Truly independent web browser
LibWeb+Meta: Move animations and their JS interfaces to Rust
Andreas Kling901cac162b35
diff --git a/Libraries/LibCompositing/Rust/src/easing.rs b/Libraries/LibCompositing/Rust/src/easing.rsindex ac0829c44c8..d4bcf20dc61 100644--- a/Libraries/LibCompositing/Rust/src/easing.rs+++ b/Libraries/LibCompositing/Rust/src/easing.rs@@ -110,6 +110,42 @@ impl Easing {}}+ /// The descriptor of the function, which borrows its control points.+ #[must_use]+ pub fn descriptor(&self) -> FfiEasingDescriptor {+ let mut descriptor = FfiEasingDescriptor {+ kind: self.kind(),+ linear_points: std::ptr::null(),+ linear_point_count: 0,+ x1: 0.0,+ y1: 0.0,+ x2: 0.0,+ y2: 0.0,+ interval_count: 0,+ step_position: 0,+ };+ match self {+ Self::Linear(points) => {+ descriptor.linear_points = points.as_ptr();+ descriptor.linear_point_count = points.len();+ }+ &Self::CubicBezier { x1, y1, x2, y2 } => {+ descriptor.x1 = x1;+ descriptor.y1 = y1;+ descriptor.x2 = x2;+ descriptor.y2 = y2;+ }+ &Self::Steps {+ interval_count,+ position,+ } => {+ descriptor.interval_count = interval_count;+ descriptor.step_position = position;+ }+ }+ descriptor+ }+pub fn kind(&self) -> FfiEasingKind {match self {Self::Linear(_) => FfiEasingKind::Linear,diff --git a/Libraries/LibWeb/Animations/Animatable.cpp b/Libraries/LibWeb/Animations/Animatable.cppindex 3b7d690dd02..75e09bc4d8d 100644--- a/Libraries/LibWeb/Animations/Animatable.cpp+++ b/Libraries/LibWeb/Animations/Animatable.cpp@@ -7,226 +7,153 @@*/#include "Animatable.h"-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/PseudoElementParsing.h>+#include <LibJS/HostClassBuilder.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/CSS/CSSAnimation.h>-#include <LibWeb/CSS/CSSAnimationProperties.h>#include <LibWeb/CSS/CSSTransition.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/CSS/StyleEngineInput.h>#include <LibWeb/DOM/AbstractElement.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/StyleValueRustFFI.h>namespace Web::Animations {-struct Animatable::Transition {- AK_ALLOC_WITH_KMALLOC;+extern "C" {- HashMap<CSS::PropertyNameAndID, GC::Ref<CSS::CSSTransition>> associated_transitions;-};--Animatable::Impl::~Impl() = default;+// Called from Bindings/Rust/src/animations/animatable.rs.+void web_animation_for_each_relevant_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*));+i32 web_animation_compare_elements_in_tree_order(void* first, void* second);+}-static WebIDL::ExceptionOr<Animatable::GetAnimationsOptions> get_animations_options_from_bindings(Bindings::GetAnimationsOptions const& options)+void Animatable::for_each_relevant_animation(IncludeSubtree include_subtree, Function<void(AnimationRef const&)> const& callback) const{- Animatable::GetAnimationsOptions converted_options;- converted_options.subtree = options.subtree;- if (options.pseudo_element.has_value())- converted_options.pseudo_element = TRY(pseudo_element_parsing(options.pseudo_element));- return converted_options;+ for (auto const& record : associated_animations_unordered()) {+ // AD-HOC: SVG animation elements drive their animations with their own timing model, which script must not+ // be able to play, pause or cancel. Like other engines, do not expose them.+ if (record.timing_state().kind == RustFFI::FfiAnimationKind::Smil)+ continue;+ if (record.is_relevant())+ callback(record);+ }++ if (include_subtree == IncludeSubtree::Yes) {+ static_cast<DOM::Element const*>(this)->for_each_child_of_type<DOM::Element>([&](auto const& child) {+ child.for_each_relevant_animation(IncludeSubtree::Yes, callback);+ return IterationDecision::Continue;+ });+ }}-static WebIDL::ExceptionOr<Animatable::KeyframeAnimationOptions> keyframe_animation_options_from_bindings(Bindings::KeyframeAnimationOptions const& options)+// NB: The Rust implementations of getAnimations() collect the relevant animations of an element, or of the subtree of a+// node where `subtree` is set, with this, after the pending style changes are applied, and sort them themselves.+void web_animation_for_each_relevant_animation(JSObject* node_wrapper, bool subtree, void* context, void (*on_animation)(void* context, RustFFI::AnimationCell const*)){- auto effect_options = TRY(keyframe_effect_options_from_bindings(options));- Animatable::KeyframeAnimationOptions converted_options;- static_cast<KeyframeEffect::Options&>(converted_options) = move(effect_options);- converted_options.id = options.id;- converted_options.timeline = options.timeline;- return converted_options;+ auto& node = *Bindings::impl_from<DOM::Node>(JS::HostABI::object_from_abi(node_wrapper));+ node.document().update_style();+ auto include_subtree = subtree ? Animatable::IncludeSubtree::Yes : Animatable::IncludeSubtree::No;+ Function<void(AnimationRef const&)> push = [&](AnimationRef const& animation) { on_animation(context, &animation.record()); };+ if (auto const* element = as_if<DOM::Element>(node)) {+ element->for_each_relevant_animation(include_subtree, push);+ return;+ }+ VERIFY(include_subtree == Animatable::IncludeSubtree::Yes);+ as<DOM::ParentNode>(node).for_each_child_of_type<DOM::Element>([&](auto const& child) {+ child.for_each_relevant_animation(Animatable::IncludeSubtree::Yes, push);+ return IterationDecision::Continue;+ });}-static WebIDL::ExceptionOr<Variant<double, Animatable::KeyframeAnimationOptions>> keyframe_animation_options_from_bindings(Variant<double, Bindings::KeyframeAnimationOptions> const& options)+i32 web_animation_compare_elements_in_tree_order(void* first, void* second){- if (options.has<double>())- return options.get<double>();- return TRY(keyframe_animation_options_from_bindings(options.get<Bindings::KeyframeAnimationOptions>()));+ return compare_elements_in_tree_order_for_composite_order(first, second);}-// https://www.w3.org/TR/web-animations-1/#dom-animatable-animate-WebIDL::ExceptionOr<GC::Ref<Animation>> Animatable::animate(Vector<BaseKeyframe> keyframes, Variant<double, KeyframeAnimationOptions> const& options)+// The list of the element, or of one of its known pseudo-elements, of the CSS animations and transitions it owns.+static Optional<RustFFI::AnimationOwnerSlot> owner_slot(Optional<CSS::PseudoElement> pseudo_element){- // 1. Let target be the object on which this method was called.- GC::Ref target { *static_cast<DOM::Element*>(this) };-- // 2. Construct a new KeyframeEffect object, effect, in the relevant Realm of target by using the same procedure as- // the KeyframeEffect(target, keyframes, options) constructor, passing target as the target argument, and the- // keyframes and options arguments as supplied.- //- // If the above procedure causes an exception to be thrown, propagate the exception and abort this procedure.- auto effect = TRY(options.visit(- [&](auto const& value) { return KeyframeEffect::create_from_processed_keyframes(target, move(keyframes), value); }));-- // 3. If options is a KeyframeAnimationOptions object, let timeline be the timeline member of options or, if- // timeline member of options is missing, be the default document timeline of the node document of the element- // on which this method was called.- Optional<GC::Ptr<AnimationTimeline>> timeline;- if (options.has<KeyframeAnimationOptions>() && options.get<KeyframeAnimationOptions>().timeline.has_value())- timeline = options.get<KeyframeAnimationOptions>().timeline.value();- if (!timeline.has_value())- timeline = target->document().timeline();-- // 4. Construct a new Animation object, animation, in the relevant Realm of target by using the same procedure as- // the Animation() constructor, passing effect and timeline as arguments of the same name.- auto animation = Animation::create(target->document().relevant_settings_object(), effect, timeline.release_value());-- // 5. If options is a KeyframeAnimationOptions object, assign the value of the id member of options to animation’s- // id attribute.- if (options.has<KeyframeAnimationOptions>())- animation->set_id(options.get<KeyframeAnimationOptions>().id);-- // 6. Run the procedure to play an animation for animation with the auto-rewind flag set to true.- TRY(animation->play_an_animation(Animation::AutoRewind::Yes));-- // 7. Return animation.- return animation;+ if (!pseudo_element.has_value())+ return RustFFI::AnimationOwnerSlot { 0 };+ if (!CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(*pseudo_element))+ return {};+ return RustFFI::AnimationOwnerSlot { static_cast<u8>(to_underlying(*pseudo_element) + 1) };}-WebIDL::ExceptionOr<GC::Ref<Animation>> Animatable::animate(JS::Realm& realm, GC::Ptr<JS::Object> keyframes, Variant<double, Bindings::KeyframeAnimationOptions> const& options)+static RustFFI::FfiTransitionProperty transition_property(CSS::PropertyNameAndID const& property){- auto processed_keyframes = TRY(process_keyframes(realm, keyframes));-- // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart- // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend- // INTEROP: Like Chrome, the keyframes are processed before the range is parsed, so the keyframes' getters run first.- Optional<AnimationAttachmentRange> range;- if (auto const* animation_options = options.get_pointer<Bindings::KeyframeAnimationOptions>()) {- auto& document = static_cast<DOM::Element*>(this)->document();- range = AnimationAttachmentRange {- .start = TRY(parse_timeline_range_edge(document, animation_options->range_start, TimelineRangeEdgeSide::Start)),- .end = TRY(parse_timeline_range_edge(document, animation_options->range_end, TimelineRangeEdgeSide::End)),- };- }-- auto animation = TRY(animate(move(processed_keyframes), TRY(keyframe_animation_options_from_bindings(options))));- if (range.has_value())- animation->set_range(*range);-- return animation;+ return {+ .property_id = to_underlying(property.id()),+ .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,+ };}-// https://drafts.csswg.org/web-animations-1/#dom-animatable-getanimations-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> Animatable::get_animations(GetAnimationsOptions const& options)+Animatable::~Animatable(){- as<DOM::Element>(*this).document().update_style();-- return get_animations_internal(GetAnimationsSorted::Yes, options);+ finalize_animations();}-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> Animatable::get_animations(Bindings::GetAnimationsOptions const& options)+void Animatable::finalize_animations(){- return get_animations(TRY(get_animations_options_from_bindings(options)));+ if (auto* animations = exchange(m_animations, nullptr))+ RustFFI::animations_element_animations_destroy(animations);}-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> Animatable::get_animations_internal(GetAnimationsSorted sorted, GetAnimationsOptions const& options)+RustFFI::ElementAnimations& Animatable::ensure_animations(){- // 1. Let object be the object on which this method was called.-- // 3. If pseudoElement is not null, then let target be the pseudo-element identified by pseudoElement with object as the originating element.- // Otherwise, let target be object.- // FIXME: We can't refer to pseudo-elements directly, and they also can't be animated yet.- (void)options.pseudo_element;- GC::Ref target { *static_cast<DOM::Element*>(this) };-- // 4. If options is passed with subtree set to true, then return the set of relevant animations for a subtree of target.- // Otherwise, return the set of relevant animations for target.- GC::RootVector<GC::Ref<Animation>> relevant_animations;- if (m_impl) {- auto& associated_animations = m_impl->associated_animations;- for (auto const& animation : associated_animations) {- // AD-HOC: SVG animation elements drive their animations with their own timing model, which script must not- // be able to play, pause or cancel. Like other engines, do not expose them.- if (animation->is_relevant() && !animation->is_smil_animation())- relevant_animations.append(*animation);- }- }-- if (options.subtree) {- TRY(target->for_each_child_of_type_fallible<DOM::Element>([&](auto& child) -> WebIDL::ExceptionOr<IterationDecision> {- relevant_animations.extend(TRY(child.get_animations_internal(GetAnimationsSorted::No, options)));- return IterationDecision::Continue;- }));- }-- // The returned list is sorted using the composite order described for the associated animations of effects in- // §5.4.2 The effect stack.- if (sorted == GetAnimationsSorted::Yes) {- quick_sort(relevant_animations, [](GC::Ref<Animation>& a, GC::Ref<Animation>& b) {- auto& a_effect = as<KeyframeEffect>(*a->effect());- auto& b_effect = as<KeyframeEffect>(*b->effect());- return KeyframeEffect::composite_order(a_effect, b_effect) < 0;- });- }-- return relevant_animations;+ if (!m_animations)+ m_animations = RustFFI::animations_element_animations_create();+ return *m_animations;}-ReadonlySpan<GC::Ref<Animation>> Animatable::associated_animations_in_composite_order()+void Animatable::forget_published_effect_descriptions(){- if (!m_impl)- return {};+ if (m_animations)+ RustFFI::animations_element_animations_forget_published_effect_descriptions(m_animations);+}- if (!m_impl->is_sorted_by_composite_order) {- quick_sort(m_impl->associated_animations, [](auto const& a, auto const& b) {- auto a_effect = a->effect();- auto b_effect = b->effect();- bool a_is_keyframe_effect = a_effect && is<KeyframeEffect>(*a_effect);- bool b_is_keyframe_effect = b_effect && is<KeyframeEffect>(*b_effect);- if (a_is_keyframe_effect && b_is_keyframe_effect)- return KeyframeEffect::composite_order(static_cast<KeyframeEffect&>(*a_effect), static_cast<KeyframeEffect&>(*b_effect)) < 0;- if (a_is_keyframe_effect != b_is_keyframe_effect)- return !a_is_keyframe_effect;- return a->global_animation_list_order() < b->global_animation_list_order();- });- m_impl->is_sorted_by_composite_order = true;- }+ElementAnimationList Animatable::associated_animations_in_composite_order()+{+ if (m_animations)+ RustFFI::animations_element_animations_sort_in_composite_order(m_animations, compare_elements_in_tree_order_for_composite_order);+ return associated_animations_unordered();+}- return m_impl->associated_animations.span();+ElementAnimationList Animatable::associated_animations_unordered() const+{+ return { m_animations, RustFFI::ElementAnimationListKind::Associated, RustFFI::AnimationOwnerSlot { 0 } };}void Animatable::invalidate_associated_animation_composite_order(){- if (m_impl)- m_impl->is_sorted_by_composite_order = false;+ if (m_animations)+ RustFFI::animations_element_animations_invalidate_composite_order(m_animations);}bool Animatable::has_associated_animations() const{- return m_impl && !m_impl->associated_animations.is_empty();+ return !associated_animations_unordered().is_empty();}-bool Animatable::has_relevant_animations() const+size_t Animatable::animation_lists_memory_size() const{- if (!m_impl)- return false;+ return m_animations ? RustFFI::animations_element_animations_memory_size(m_animations) : 0;+}- for (auto const& animation : m_impl->associated_animations) {- if (animation->is_relevant())+bool Animatable::has_relevant_animations() const+{+ for (auto const& animation : associated_animations_unordered()) {+ if (animation.is_relevant())return true;}-return false;}-void Animatable::associate_with_animation(GC::Ref<Animation> animation)+void Animatable::associate_with_animation(AnimationRef const& animation){- auto& impl = ensure_impl();- if (impl.associated_animations.contains_slow(animation))+ if (!RustFFI::animations_element_animations_associate(&ensure_animations(), &animation.record()))return;- impl.associated_animations.append(animation);- impl.is_sorted_by_composite_order = false;// The style engine computes no record for an element whose animations compose its style.CSS::record_element_animations_changed(as<DOM::Element>(*this));@@ -234,79 +161,76 @@ void Animatable::associate_with_animation(GC::Ref<Animation> animation)CSS::record_element_associated_with_animation(as<DOM::Element>(*this));as<DOM::Element>(*this).document().associate_with_animation(animation);- animation->did_associate_with_target();}-void Animatable::disassociate_with_animation(GC::Ref<Animation> animation)+void Animatable::disassociate_with_animation(AnimationRef const& animation, Optional<EffectRef> const& effect){- auto& impl = *m_impl;- auto was_associated = impl.associated_animations.remove_first_matching([&](auto element) { return animation == element; });- impl.is_sorted_by_composite_order = false;+ auto was_associated = m_animations && RustFFI::animations_element_animations_disassociate(m_animations, &animation.record());CSS::record_element_animations_changed(as<DOM::Element>(*this));if (was_associated)as<DOM::Element>(*this).change_associated_animation_count_in_subtree(-1);- as<DOM::Element>(*this).document().disassociate_with_animation(animation);+ as<DOM::Element>(*this).document().disassociate_with_animation(animation, effect);}void Animatable::on_document_changed(DOM::Document& old_document, DOM::Document& new_document){- if (!m_impl)- return;-- for (auto const& animation : m_impl->associated_animations) {- old_document.disassociate_with_animation(animation);+ for (auto const& animation : associated_animations_unordered()) {+ old_document.disassociate_with_animation(animation, animation.effect());new_document.associate_with_animation(animation);}}-// The computation of an element's animation definitions matches them against the animations the-// element already has, so the names of those animations are an input to it, and so is the definition-// each one last had applied: a plan that would apply the same again changes nothing.-static void publish_css_defined_animations(Animatable& animatable, size_t index, Vector<GC::Ref<CSS::CSSAnimation>> const& animations)+// The computation of an element's animation definitions matches them against the animations the element already has,+// so the lists publish the name of each and the definition it last had applied to the style engine, which knows the+// element by its identity there, as they change.+static Layout::RustFFI::DocumentHost const* style_engine_host_of(Animatable& animatable){auto* element = as_if<DOM::Element>(animatable);- if (!element)- return;+ return element ? CSS::style_engine_host_for_identified(*element) : nullptr;+}- Vector<Utf16FlyString> names;- Vector<CSS::StyleEngineFFI::FfiAppliedAnimationDefinition> definitions;- names.ensure_capacity(animations.size());- definitions.ensure_capacity(animations.size());- for (auto const& animation : animations) {- names.unchecked_append(animation->animation_name());- definitions.unchecked_append(animation->applied_definition());- }- CSS::record_element_css_defined_animations(*element, static_cast<u8>(index), names, definitions);+static u32 style_node_of(Animatable& animatable)+{+ auto* element = as_if<DOM::Element>(animatable);+ return element ? element->style_node_id().value() : 0;}void Animatable::cancel_css_animations_and_transitions(){- if (!m_impl)+ if (!m_animations)return;- GC::RootVector<GC::Ref<Animation>> animations_to_cancel;- for (size_t index = 0; index < m_impl->css_defined_animations.size(); ++index) {- auto& animations = m_impl->css_defined_animations[index];- if (!animations || animations->is_empty())- continue;- for (auto& animation : *animations)- animations_to_cancel.append(animation);- animations->clear();- publish_css_defined_animations(*this, index, *animations);- }- for (auto& transition : m_impl->transitions) {- if (!transition)- continue;- for (auto& animation : transition->associated_transitions)- animations_to_cancel.append(animation.value);- transition->associated_transitions.clear();- }- m_impl->has_css_defined_animations = false;+ GC::RootVector<AnimationRef> animations;+ RustFFI::animations_element_animations_cancel_css_animations_and_transitions(+ m_animations, style_engine_host_of(*this), style_node_of(*this), keep_animation_alive_in,+ [](void*, RustFFI::AnimationCell const* animation, void (*run)(void*), void* run_context) {+ HTML::TemporaryExecutionContext execution_context { HTML::relevant_realm(relevant_global_object_of(AnimationRef { *animation })) };+ run(run_context);+ },+ &animations, perform_host_effect);+}++void Animatable::play_or_pause_css_animations_as_their_play_state_asks()+{+ if (!m_animations)+ return;- for (auto& animation : animations_to_cancel)- animation->cancel(Animation::ShouldInvalidate::No);+ struct Context {+ GC::RootVector<AnimationRef> animations;+ GC::Ref<DOM::Element> element;+ } context { {}, as<DOM::Element>(*this) };+ RustFFI::animations_element_animations_play_or_pause_css_animations(+ m_animations,+ [](void* context, RustFFI::AnimationCell const* animation) {+ keep_animation_alive_in(&static_cast<Context*>(context)->animations, animation);+ },+ [](void* context, RustFFI::AnimationCell const*, void (*run)(void*), void* run_context) {+ HTML::TemporaryExecutionContext execution_context { static_cast<Context*>(context)->element->document().relevant_settings_object() };+ run(run_context);+ },+ &context, perform_host_effect);}bool Animatable::has_matching_transition_property_entry(Optional<CSS::PseudoElement> pseudo_element) const@@ -320,168 +244,89 @@ bool Animatable::has_matching_transition_property_entry(Optional<CSS::PseudoElembool Animatable::has_existing_transitions(Optional<CSS::PseudoElement> pseudo_element) const{- auto const* transition = transition_if_exists(pseudo_element);- return transition && !transition->associated_transitions.is_empty();+ return !existing_transitions(pseudo_element).is_empty();}-HashMap<CSS::PropertyNameAndID, GC::Ref<CSS::CSSTransition>> const* Animatable::existing_transitions(Optional<CSS::PseudoElement> pseudo_element) const+ElementAnimationList Animatable::existing_transitions(Optional<CSS::PseudoElement> pseudo_element) const{- auto const* transition = transition_if_exists(pseudo_element);- return transition ? &transition->associated_transitions : nullptr;+ auto slot = owner_slot(pseudo_element);+ return { slot.has_value() ? m_animations : nullptr, RustFFI::ElementAnimationListKind::Transitions, slot.value_or(0) };}-GC::Ptr<CSS::CSSTransition> Animatable::property_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property) const+Optional<AnimationRef> Animatable::property_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property) const{- auto const* maybe_transition = transition_if_exists(pseudo_element);- if (!maybe_transition)+ auto slot = owner_slot(pseudo_element);+ if (!m_animations || !slot.has_value())+ return {};+ auto const* transition = RustFFI::animations_element_animations_transition(m_animations, *slot, transition_property(property));+ if (!transition)return {};- auto& transition = *maybe_transition;- if (auto maybe_animation = transition.associated_transitions.get(property); maybe_animation.has_value())- return maybe_animation.value();- return {};+ return AnimationRef { *transition };}-void Animatable::set_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property, GC::Ref<CSS::CSSTransition> animation)+void Animatable::commit_provisional_transition(Optional<CSS::PseudoElement> pseudo_element, AnimationRef const& transition, RustFFI::TransitionOrigin origin){- auto maybe_transition = ensure_transition(pseudo_element);- if (!maybe_transition)- return;- auto& transition = *maybe_transition;- VERIFY(!transition.associated_transitions.contains(property));- transition.associated_transitions.set(property, animation);+ // NB: The record associates the transition with this element, its target, and holds it here where this element or+ // pseudo-element can own transitions.+ auto slot = owner_slot(pseudo_element);+ RustFFI::animations_css_transition_commit_provisional(&transition.record(), slot.has_value() ? &ensure_animations() : nullptr, slot.value_or(RustFFI::AnimationOwnerSlot { 0 }), origin, perform_host_effect);}void Animatable::remove_transition(Optional<CSS::PseudoElement> pseudo_element, CSS::PropertyNameAndID const& property){- auto maybe_transition = ensure_transition(pseudo_element);- if (!maybe_transition)- return;- auto& transition = *maybe_transition;- auto removed_transition = transition.associated_transitions.get(property);- VERIFY(removed_transition.has_value());- transition.associated_transitions.remove(property);- removed_transition.value()->schedule_disassociation_from_target();+ if (auto slot = owner_slot(pseudo_element); slot.has_value())+ RustFFI::animations_element_animations_remove_transition(&ensure_animations(), *slot, transition_property(property));}void Animatable::visit_edges(JS::Cell::Visitor& visitor){- if (m_impl)- m_impl->visit_edges(visitor);-}--void Animatable::Impl::visit_edges(JS::Cell::Visitor& visitor)-{- visitor.visit(associated_animations);- for (auto const& css_animation : css_defined_animations) {- if (css_animation)- visitor.visit(*css_animation);- }-- for (auto const& transition : transitions) {- if (transition)- visitor.visit(transition->associated_transitions);- }+ if (!m_animations)+ return;+ RustFFI::animations_element_animations_for_each_host_cell(m_animations, &visitor, visit_host_cell);}-bool Animatable::has_css_defined_animations() const+bool Animatable::can_own_css_animations_and_transitions(Optional<CSS::PseudoElement> pseudo_element){- if (!m_impl)- return false;-- return m_impl->has_css_defined_animations;+ return owner_slot(pseudo_element).has_value();}bool Animatable::has_css_animations_or_transitions() const{- if (!m_impl)- return false;- if (m_impl->has_css_defined_animations)- return true;- for (auto const& transition : m_impl->transitions) {- if (transition && !transition->associated_transitions.is_empty())- return true;- }- return false;-}--Vector<GC::Ref<CSS::CSSAnimation>> const* Animatable::css_defined_animations(Optional<CSS::PseudoElement> pseudo_element)-{- auto& impl = ensure_impl();-- if (pseudo_element.has_value() && !CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(pseudo_element.value()))- return nullptr;-- auto index = pseudo_element- .map([](CSS::PseudoElement pseudo_element_value) { return to_underlying(pseudo_element_value) + 1; })- .value_or(0);-- if (!impl.css_defined_animations[index])- impl.css_defined_animations[index] = make<Vector<GC::Ref<CSS::CSSAnimation>>>();-- return impl.css_defined_animations[index];-}--void Animatable::set_css_defined_animations(Optional<CSS::PseudoElement> pseudo_element, Vector<GC::Ref<CSS::CSSAnimation>>&& animations)-{- auto& impl = ensure_impl();-- if (pseudo_element.has_value() && !CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(pseudo_element.value()))- return;-- auto index = pseudo_element- .map([](CSS::PseudoElement pseudo_element_value) { return to_underlying(pseudo_element_value) + 1; })- .value_or(0);-- // NB: The flag says the element has animations to play or cancel, not that it has been through- // the step that would have registered some. Every element goes through that step, so setting- // it here unconditionally made it true of every element that had computed a style once.- // It stays set once any list is non-empty, since the lists are per pseudo-element and this- // is one flag for all of them.- if (!animations.is_empty())- impl.has_css_defined_animations = true;- // NB: Every element goes through this step; one that had no animations and still has none has nothing to publish.- bool had_animations = impl.css_defined_animations[index] && !impl.css_defined_animations[index]->is_empty();- impl.css_defined_animations[index] = make<Vector<GC::Ref<CSS::CSSAnimation>>>(move(animations));- if (had_animations || !impl.css_defined_animations[index]->is_empty())- publish_css_defined_animations(*this, index, *impl.css_defined_animations[index]);+ return m_animations && RustFFI::animations_element_animations_has_css_animations_or_transitions(m_animations);}-Animatable::Impl& Animatable::ensure_impl() const+bool Animatable::has_css_defined_animations(Optional<CSS::PseudoElement> pseudo_element) const{- if (!m_impl)- m_impl = make<Impl>();- return *m_impl;+ auto slot = owner_slot(pseudo_element);+ return m_animations && slot.has_value() && RustFFI::animations_element_animations_count(m_animations, RustFFI::ElementAnimationListKind::CssAnimations, *slot) != 0;}-static Optional<size_t> transition_index_for_pseudo_element(Optional<CSS::PseudoElement> pseudo_element)+GC::RootVector<AnimationRef> Animatable::css_defined_animations(Optional<CSS::PseudoElement> pseudo_element) const{- if (!pseudo_element.has_value())- return 0;- if (!CSS::Selector::PseudoElementSelector::is_known_pseudo_element_type(pseudo_element.value()))- return {};- return to_underlying(pseudo_element.value()) + 1;+ GC::RootVector<AnimationRef> animations;+ auto slot = owner_slot(pseudo_element);+ if (!slot.has_value())+ return animations;+ for (auto const& animation : ElementAnimationList { m_animations, RustFFI::ElementAnimationListKind::CssAnimations, *slot })+ animations.append(animation);+ return animations;}-Animatable::Transition* Animatable::ensure_transition(Optional<CSS::PseudoElement> pseudo_element) const+void Animatable::set_css_defined_animations(Optional<CSS::PseudoElement> pseudo_element, ReadonlySpan<AnimationRef> animations){- auto pseudo_element_index = transition_index_for_pseudo_element(pseudo_element);- if (!pseudo_element_index.has_value())- return nullptr;-- auto& impl = ensure_impl();- if (!impl.transitions[*pseudo_element_index])- impl.transitions[*pseudo_element_index] = make<Transition>();- return impl.transitions[*pseudo_element_index];-}+ auto slot = owner_slot(pseudo_element);+ if (!slot.has_value())+ return;+ // NB: Every element goes through this step; one that had no animations and still has none has nothing to hold or+ // publish.+ if (!m_animations && animations.is_empty())+ return;-Animatable::Transition const* Animatable::transition_if_exists(Optional<CSS::PseudoElement> pseudo_element) const-{- if (!m_impl)- return nullptr;- auto pseudo_element_index = transition_index_for_pseudo_element(pseudo_element);- if (!pseudo_element_index.has_value())- return nullptr;- return m_impl->transitions[*pseudo_element_index];+ Vector<RustFFI::AnimationCell const*, 1> records;+ records.ensure_capacity(animations.size());+ for (auto const& animation : animations)+ records.unchecked_append(&animation.record());+ RustFFI::animations_element_animations_set_css_animations(&ensure_animations(), *slot, records.span(), style_engine_host_of(*this), style_node_of(*this));}}diff --git a/Libraries/LibWeb/Animations/Animatable.h b/Libraries/LibWeb/Animations/Animatable.hindex 3f530f80160..8d9bafd171b 100644--- a/Libraries/LibWeb/Animations/Animatable.h+++ b/Libraries/LibWeb/Animations/Animatable.h@@ -9,97 +9,131 @@#pragma once#include <AK/FlyString.h>-#include <AK/HashMap.h>#include <AK/Utf16FlyString.h>#include <LibGC/RootVector.h>-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/AnimationEffect.h>+#include <LibWeb/Animations/RecordHandles.h>+#include <LibWeb/Animations/RustFFI.h>#include <LibWeb/Bindings/Animatable.h>#include <LibWeb/CSS/PropertyNameAndID.h>#include <LibWeb/Export.h>namespace Web::CSS {+class CSSAnimation;class CSSTransition;}namespace Web::Animations {+// One of the lists of animations an element holds, which a loop over it reads entry by entry as it goes, so the loop+// may change the list.+class ElementAnimationList {+public:+ ElementAnimationList(RustFFI::ElementAnimations const* animations, RustFFI::ElementAnimationListKind kind, RustFFI::AnimationOwnerSlot slot)+ : m_animations(animations)+ , m_kind(kind)+ , m_slot(slot)+ {+ }++ size_t size() const { return m_animations ? RustFFI::animations_element_animations_count(m_animations, m_kind, m_slot) : 0; }+ bool is_empty() const { return size() == 0; }+ AnimationRef at(size_t index) const { return AnimationRef { *RustFFI::animations_element_animations_get(m_animations, m_kind, m_slot, index) }; }++ struct End { };+ class Iterator {+ public:+ Iterator(ElementAnimationList const& list)+ : m_list(list)+ {+ }+ AnimationRef operator*() const { return m_list.at(m_index); }+ Iterator& operator++()+ {+ ++m_index;+ return *this;+ }+ bool operator!=(End) const { return m_index < m_list.size(); }++ private:+ ElementAnimationList const& m_list;+ size_t m_index { 0 };+ };+ Iterator begin() const { return Iterator { *this }; }+ End end() const { return {}; }++private:+ RustFFI::ElementAnimations const* m_animations;+ RustFFI::ElementAnimationListKind m_kind;+ RustFFI::AnimationOwnerSlot m_slot;+};+// https://drafts.csswg.org/web-animations-1/#animatableclass WEB_API Animatable {public:- virtual ~Animatable() = default;+ virtual ~Animatable();- enum class GetAnimationsSorted {+ enum class IncludeSubtree {No,Yes};- struct GetAnimationsOptions {- bool subtree { false };- Optional<CSS::Selector::PseudoElementSelector> pseudo_element;- };-- struct KeyframeAnimationOptions : public KeyframeEffect::Options {- Utf16FlyString id;- Optional<GC::Ptr<AnimationTimeline>> timeline;- };-- WebIDL::ExceptionOr<GC::Ref<Animation>> animate(Vector<BaseKeyframe> keyframes, Variant<double, KeyframeAnimationOptions> const& options);- WebIDL::ExceptionOr<GC::Ref<Animation>> animate(JS::Realm&, GC::Ptr<JS::Object> keyframes, Variant<double, Bindings::KeyframeAnimationOptions> const& options);- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> get_animations(GetAnimationsOptions const& options);- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> get_animations(Bindings::GetAnimationsOptions const& options);- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animation>>> get_animations_internal(GetAnimationsSorted sorted, GetAnimationsOptions const& options);- ReadonlySpan<GC::Ref<Animation>> associated_animations_in_composite_order();- ReadonlySpan<GC::Ref<Animation>> associated_animations_unordered() const { return m_impl ? m_impl->associated_animations.span() : ReadonlySpan<GC::Ref<Animation>> {}; }+ // The relevant animations of the element, and of its descendants with IncludeSubtree::Yes, in no particular order.+ void for_each_relevant_animation(IncludeSubtree, Function<void(AnimationRef const&)> const&) const;+ ElementAnimationList associated_animations_in_composite_order();+ ElementAnimationList associated_animations_unordered() const;void invalidate_associated_animation_composite_order();bool has_relevant_animations() const;bool has_associated_animations() const;-- void associate_with_animation(GC::Ref<Animation>);- void disassociate_with_animation(GC::Ref<Animation>);+ // The element's lists of its animations, created where it holds none yet, which also follow what the element+ // published of the effects that target it to the style engine.+ RustFFI::ElementAnimations& ensure_animations();+ // Forgets what the element published to the style engine of the effects that target it, as its identity there+ // changes.+ void forget_published_effect_descriptions();+ // The bytes of the element's lists of its animations and transitions, beside the animations themselves.+ size_t animation_lists_memory_size() const;++ void associate_with_animation(AnimationRef const&);+ // Disassociates the animation from the element, which `effect`, the animation's associated effect, targeted.+ void disassociate_with_animation(AnimationRef const&, Optional<EffectRef> const& effect);void on_document_changed(DOM::Document& old_document, DOM::Document& new_document);void cancel_css_animations_and_transitions();+ // Plays or pauses the CSS animations the element and its pseudo-elements own as their animation-play-state last+ // computed.+ void play_or_pause_css_animations_as_their_play_state_asks();++ // Whether the element or the pseudo-element can own CSS animations and transitions, which only the known+ // pseudo-elements can.+ static bool can_own_css_animations_and_transitions(Optional<CSS::PseudoElement>);- bool has_css_defined_animations() const;bool has_css_animations_or_transitions() const;- Vector<GC::Ref<CSS::CSSAnimation>> const* css_defined_animations(Optional<CSS::PseudoElement>);- void set_css_defined_animations(Optional<CSS::PseudoElement>, Vector<GC::Ref<CSS::CSSAnimation>>&&);+ bool has_css_defined_animations(Optional<CSS::PseudoElement>) const;+ GC::RootVector<AnimationRef> css_defined_animations(Optional<CSS::PseudoElement>) const;+ void set_css_defined_animations(Optional<CSS::PseudoElement>, ReadonlySpan<AnimationRef>);// Whether the installed style gives any longhand a matching transition-property entry, answered without listing them.bool has_matching_transition_property_entry(Optional<CSS::PseudoElement>) const;- void set_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&, GC::Ref<CSS::CSSTransition>);+ // Commits a transition started provisionally, whose target is now associated with it, as the transition of its+ // property the element or pseudo-element holds.+ void commit_provisional_transition(Optional<CSS::PseudoElement>, AnimationRef const&, RustFFI::TransitionOrigin);void remove_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&);bool has_existing_transitions(Optional<CSS::PseudoElement>) const;- // The running or completed transition for each property, if the element holds any.- HashMap<CSS::PropertyNameAndID, GC::Ref<CSS::CSSTransition>> const* existing_transitions(Optional<CSS::PseudoElement>) const;- GC::Ptr<CSS::CSSTransition> property_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&) const;+ // The running or completed transition of each property the element or pseudo-element has.+ ElementAnimationList existing_transitions(Optional<CSS::PseudoElement>) const;+ Optional<AnimationRef> property_transition(Optional<CSS::PseudoElement>, CSS::PropertyNameAndID const&) const;protected:void visit_edges(JS::Cell::Visitor&);+ // Lets go of the animations as the GC finalizes the element, so that an animation that only the lists held is no+ // longer alive to the host before anything else runs.+ void finalize_animations();private:- struct Transition;-- struct Impl {- AK_ALLOC_WITH_KMALLOC;-- Vector<GC::Ref<Animation>> associated_animations;- bool is_sorted_by_composite_order { true };- bool has_css_defined_animations { false };-- mutable Array<OwnPtr<Vector<GC::Ref<CSS::CSSAnimation>>>, to_underlying(CSS::PseudoElement::KnownPseudoElementCount) + 1> css_defined_animations;- mutable Array<OwnPtr<Transition>, to_underlying(CSS::PseudoElement::KnownPseudoElementCount) + 1> transitions;-- ~Impl();-- void visit_edges(JS::Cell::Visitor&);- };- Impl& ensure_impl() const;- Transition* ensure_transition(Optional<CSS::PseudoElement>) const;- Transition const* transition_if_exists(Optional<CSS::PseudoElement>) const;-- mutable OwnPtr<Impl> m_impl;+ // The lists, created as the element first holds an animation, which the element owns.+ RustFFI::ElementAnimations* m_animations { nullptr };};}diff --git a/Libraries/LibWeb/Animations/Animatable.idl b/Libraries/LibWeb/Animations/Animatable.idlindex 9bef3c8a9c9..25985988307 100644--- a/Libraries/LibWeb/Animations/Animatable.idl+++ b/Libraries/LibWeb/Animations/Animatable.idl@@ -1,7 +1,7 @@// https://drafts.csswg.org/web-animations-1/#the-animatable-interface-mixininterface mixin Animatable {- Animation animate(object? keyframes, optional (unrestricted double or KeyframeAnimationOptions) options = {});- sequence<Animation> getAnimations(optional GetAnimationsOptions options = {});+ [ImplementedIn=Rust] Animation animate(object? keyframes, optional (unrestricted double or KeyframeAnimationOptions) options = {});+ [ImplementedIn=Rust] sequence<Animation> getAnimations(optional GetAnimationsOptions options = {});};// https://drafts.csswg.org/web-animations-1/#dictdef-keyframeanimationoptions@@ -10,9 +10,9 @@ dictionary KeyframeAnimationOptions : KeyframeEffectOptions {AnimationTimeline? timeline;// https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart- (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeStart = "normal";+ TimelineRangeValue rangeStart = "normal";// https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend- (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeEnd = "normal";+ TimelineRangeValue rangeEnd = "normal";};// https://drafts.csswg.org/web-animations-1/#dictdef-getanimationsoptionsdiff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cppdeleted file mode 100644index 1805b4dc83d..00000000000--- a/Libraries/LibWeb/Animations/Animation.cpp+++ /dev/null@@ -1,2096 +0,0 @@-/*- * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>.- * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/TemporaryChange.h>-#include <AK/Utf16StringBuilder.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Realm.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/AnimationEffect.h>-#include <LibWeb/Animations/AnimationPlaybackEvent.h>-#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Animations/BindingsGlue.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/Bindings/Wrappable.h>-#include <LibWeb/Bindings/WrapperWorld.h>-#include <LibWeb/CSS/CSSAnimation.h>-#include <LibWeb/CSS/CSSKeywordValue.h>-#include <LibWeb/CSS/CSSNumericValue.h>-#include <LibWeb/CSS/CSSStyleProperties.h>-#include <LibWeb/CSS/CSSTransition.h>-#include <LibWeb/CSS/CSSUnitValue.h>-#include <LibWeb/CSS/ComputedStyleWorkingSet.h>-#include <LibWeb/CSS/CustomPropertyData.h>-#include <LibWeb/CSS/CustomPropertyRegistration.h>-#include <LibWeb/CSS/Length.h>-#include <LibWeb/CSS/Parser/Parser.h>-#include <LibWeb/CSS/StyleComputer.h>-#include <LibWeb/CSS/StyleValues/CalculatedStyleValue.h>-#include <LibWeb/CSS/StyleValues/ComputationContext.h>-#include <LibWeb/CSS/Zoom.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/HighResolutionTime/Performance.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/Layout/LayoutRustFFI.h>-#include <LibWeb/Layout/NodeArena.h>-#include <LibWeb/Layout/RenderDocument.h>-#include <LibWeb/Namespace.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(Animation);--// https://drafts.csswg.org/web-animations-1/#commit-computed-styles-WebIDL::ExceptionOr<void> Animation::commit_styles()-{- // 1. Let targets be the set of all effect targets for animation effects associated with animation.- auto* effect = as_if<KeyframeEffect>(m_effect.ptr());- if (!effect || !effect->target())- return {};- GC::Ref<DOM::Element> target = *effect->target();-- // 2. For each target in targets:- // 1. If target is not an element capable of having a style attribute (for example, it is a pseudo-element or is- // an element in a document format for which style attributes are not defined) throw a- // "NoModificationAllowedError" DOMException and abort these steps.- auto const& namespace_uri = target->namespace_uri();- if (effect->pseudo_element().has_value() || (namespace_uri != Namespace::HTML && namespace_uri != Namespace::SVG && namespace_uri != Namespace::MathML))- return WebIDL::NoModificationAllowedError::create("The animation target cannot have an inline style"_utf16);-- OrderedHashMap<CSS::PropertyNameAndID, NonnullRefPtr<CSS::StyleValue const>> declarations;- {- // 2. If, after applying any pending style changes, target is not being rendered, throw an "InvalidStateError"- // DOMException and abort these steps.- auto& document = target->document();- Layout::ForcedReadScope read { document };- document.update_layout(DOM::UpdateLayoutReason::AnimationCommitStyles);- if (!target->is_connected() || !target->has_style())- return WebIDL::InvalidStateError::create("The animation target is not being rendered"_utf16);- auto computed_style = target->computed_style();- if (!target->unsafe_layout_node(read) && (!computed_style->display().is_contents() || computed_style->in_display_none_subtree()))- return WebIDL::InvalidStateError::create("The animation target is not being rendered"_utf16);-- // 4. Let targeted properties be the set of physical longhand properties that are a target property for at- // least one animation effect associated with animation whose effect target is target.- HashTable<CSS::PropertyNameAndID> targeted_properties;- auto add_longhand = [&](CSS::PropertyID property) {- auto physical_property = CSS::map_logical_alias_to_physical_property(property, { computed_style->writing_mode(), computed_style->direction() });- targeted_properties.set(CSS::PropertyNameAndID::from_id(physical_property));- };- for (auto const& property : effect->target_properties()) {- if (property.is_custom_property())- targeted_properties.set(property);- else if (CSS::property_is_shorthand(property.id())) {- for (auto longhand : CSS::expanded_longhands_for_shorthand(property.id()))- add_longhand(longhand);- } else {- add_longhand(property.id());- }- }-- // 5. For each property, property, in targeted properties:- // 1. Let partialEffectStack be a copy of the effect stack for property on target.- // 2. If animation's replace state is removed, add all animation effects associated with animation whose- // effect target is target and that include property as a target property to partialEffectStack.- // 3. Remove from partialEffectStack any animation effects whose associated animation has a higher composite- // order than animation.- GC::RootVector<GC::Ref<KeyframeEffect>> effects;- for (auto animation : target->associated_animations_in_composite_order()) {- auto* other_effect = as_if<KeyframeEffect>(animation->effect().ptr());- if (other_effect && !other_effect->pseudo_element().has_value() && KeyframeEffect::composite_order(*other_effect, *effect) < 0)- effects.append(*other_effect);- }- effects.append(*effect);-- // 4. Let effect value be the result of calculating the result of partialEffectStack for property using- // target's computed style (see §5.4.3 Calculating the result of an effect stack) and setting the- // endpoint-inclusive active interval flag to true when calculating the animation effect phase- // (see §4.6.6 Animation effect phases and states).- DOM::AbstractElement element { target, {} };- // NB: A timeline script observed ahead of its current time in this task is sampled at that time, as the style- // update above was, so the committed values are those of the time script read.- RefPtr<CSS::ComputedStyleWorkingSet> committed_style;- AnimationTimeline::at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), [&] {- committed_style = document.style_computer().compute_style_for_animation_commit(read, element, effects.span());- });- auto style = committed_style.release_nonnull();- auto custom_properties = element.custom_property_data();- if (custom_properties && element.custom_property_data_is_animation_overlay())- custom_properties = custom_properties->parent();- for (auto const& property : targeted_properties) {- if (property.is_custom_property()) {- RefPtr<CSS::StyleValue const> value;- if (auto animated_value = style->animated_custom_properties().get(property.name()); animated_value.has_value())- value = **animated_value;- else if (custom_properties) {- if (auto base_value = custom_properties->get(property.name()); base_value.has_value())- value = base_value->value;- }- if (!value) {- if (auto registration = document.get_registered_custom_property(property.name()); registration.has_value() && registration->initial_value)- value = CSS::compute_registered_custom_property_initial_value(document, *registration);- }- if (value)- declarations.set(property, value.release_nonnull());- } else {- declarations.set(property, CSS::unscaled_by_zoom(property.id(), style->property(property.id()), computed_style->effective_zoom()));- }- }- }-- // 3. Let inline style be the result of getting the CSS declaration block corresponding to target's style- // attribute. If target does not have a style attribute, let inline style be a new empty CSS declaration block- // with the owner node set to target.- auto inline_style = target->style();- // 5.5. Set a CSS declaration of property for effect value in inline style.- // 6. Update style attribute for inline style.- inline_style->set_computed_properties(declarations);- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-animation-GC::Ref<Animation> Animation::create(HTML::EnvironmentSettingsObject& environment, GC::Ptr<AnimationEffect> effect, GC::Ptr<AnimationTimeline> timeline)-{- // 1. Let animation be a new Animation object.- auto animation = GC::Heap::the().allocate<Animation>(environment);-- // 2. Run the procedure to set the timeline of an animation on animation passing timeline as the new timeline.- animation->set_timeline(timeline);-- // 3. Run the procedure to set the associated effect of an animation on animation passing source as the new effect.- animation->set_effect(effect);-- return animation;-}--// https://www.w3.org/TR/web-animations-1/#animation-set-the-associated-effect-of-an-animation-void Animation::set_effect(GC::Ptr<AnimationEffect> new_effect, ShouldInvalidate should_invalidate)-{- // Setting this attribute updates the object’s associated effect using the procedure to set the associated effect of- // an animation.-- // 1. Let old effect be the current associated effect of animation, if any.- auto old_effect = m_effect;-- // 2. If new effect is the same object as old effect, abort this procedure.- if (new_effect == old_effect)- return;-- // 3. If animation has a pending pause task, reschedule that task to run as soon as animation is ready.- // 4. If animation has a pending play task, reschedule that task to run as soon as animation is ready to play ne- // effect.- // Note: There is no real difference between "pending" and "as soon as possible", so this step is a no-op.-- // 5. If new effect is not null and if new effect is the associated effect of another animation, previous animation,- // run the procedure to set the associated effect of an animation (this procedure) on previous animation passing- // null as new effect.- if (new_effect && new_effect->associated_animation() != GC::Ptr<Animation> { *this }) {- if (auto animation = new_effect->associated_animation())- animation->set_effect({});- }-- // 6. Let the associated effect of animation be new effect.- auto old_target = m_effect ? m_effect->target() : nullptr;- auto new_target = new_effect ? new_effect->target() : nullptr;- if (old_target != new_target) {- if (old_target)- old_target->disassociate_with_animation(*this);- if (new_target)- new_target->associate_with_animation(*this);- }- if (new_effect)- new_effect->set_associated_animation(this);- if (m_effect)- m_effect->set_associated_animation({});- m_effect = new_effect;-- // Once animated properties of the old effect no longer apply, we need to ensure appropriate invalidations are scheduled- if (old_effect) {- AnimationUpdateContext context;- old_effect->update_computed_properties(context);- }-- // 7. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No, should_invalidate);-}--GC::Ptr<AnimationTimeline> Animation::timeline_for_bindings() const-{- update_style_if_needed();- return m_timeline;-}--// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation-// https://drafts.csswg.org/web-animations-2/#setting-the-timeline-void Animation::set_timeline(GC::Ptr<AnimationTimeline> new_timeline)-{- // 1. Let old timeline be the current timeline of animation, if any.- auto old_timeline = m_timeline;-- // 2. If new timeline is the same object as old timeline, abort this procedure.- if (new_timeline == old_timeline)- return;-- // 3. Let previous play state be animation’s play state.- auto previous_play_state = play_state();-- // 4. Let previous current time be the animation’s current time.- auto previous_current_time = current_time();-- // 5. Set previous progress based in the first condition that applies:- auto previous_progress = [&]() -> Optional<double> {- // If previous current time is unresolved:- // Set previous progress to unresolved.- if (!previous_current_time.has_value())- return {};-- // If end time is zero:- // Set previous progress to zero.- if (m_effect && m_effect->end_time().value == 0)- return 0;-- // Otherwise- // Set previous progress = previous current time / end time- return previous_current_time.value() / m_effect->end_time();- }();-- // 6. Let from finite timeline be true if old timeline is not null and not monotonically increasing.- auto from_finite_timeline = old_timeline && !old_timeline->is_monotonically_increasing();-- // 7. Let to finite timeline be true if timeline is not null and not monotonically increasing.- auto to_finite_timeline = new_timeline && !new_timeline->is_monotonically_increasing();-- // 8. Let the timeline of animation be new timeline.- if (m_timeline)- m_timeline->disassociate_with_animation(*this);- m_timeline = new_timeline;- if (m_timeline)- m_timeline->associate_with_animation(*this);-- auto const previous_progress_multiplied_by_end_time = [&]() -> TimeValue {- // AD-HOC: The spec doesn't say what to do if we have no effect so we just assume an end time of 0- if (!m_effect)- return TimeValue::create_zero(m_timeline);-- return TimeValue {- m_timeline && m_timeline->is_progress_based() ? TimeValue::Type::Percentage : TimeValue::Type::Milliseconds,- m_effect->end_time().value * previous_progress.value()- };- };-- // AD-HOC: The normalization of the specified timing of the associated effect depends on the associated timeline.- // This must be done before calling set_current_time_for_bindings() to ensure consistent units- m_normalized_attachment_interval = attachment_interval();- if (m_effect)- m_effect->normalize_specified_timing();-- // 9. Perform the steps corresponding to the first matching condition from the following, if any:- // If to finite timeline,- if (to_finite_timeline) {- // 1. Apply any pending playback rate on animation- apply_any_pending_playback_rate();-- // 2. set auto align start time to true.- m_auto_align_start_time = true;-- // 3. Set start time to unresolved.- m_start_time = {};-- // 4. Set hold time to unresolved.- m_hold_time = {};-- // 5. If previous play state is "finished" or "running"- if (first_is_one_of(previous_play_state, AnimationPlayState::Finished, AnimationPlayState::Running)) {- // 1. Schedule a pending play task- m_pending_play_task = TaskState::Scheduled;- }-- // 6. If previous play state is "paused" and previous progress is resolved:- if (previous_play_state == AnimationPlayState::Paused && previous_progress.has_value()) {- // 1. Set hold time to previous progress * end time.- m_hold_time = previous_progress_multiplied_by_end_time();- }- // NOTE: This step ensures that previous progress is preserved even in the case of a pause-pending animation with a resolved start time.- }- // If from finite timeline and previous progress is resolved,- else if (from_finite_timeline && previous_progress.has_value()) {- // Run the procedure to set the current time to previous progress * end time.- // NB: We know that the time we are passing is valid so we can wrap this in a MUST() to avoid error handling.- // This is the procedure itself, not script setting the current time of a CSS animation. Until it is done,- // the start time is still in the units of the old timeline.- MUST(Animation::set_current_time_for_bindings(previous_progress_multiplied_by_end_time().as_css_numberish()));- }-- // 10. If the start time of animation is resolved, make animation’s hold time unresolved.- if (m_start_time.has_value()) {- // AD-HOC: A finished animation holds a time beside its start time, and setting its current time as it leaves a- // finite timeline sets the hold time alone, which leaves the start time in the units of the old- // timeline. See https://github.com/w3c/csswg-drafts/issues/11761. Like WebKit, the start time takes- // the hold time.- if (m_hold_time.has_value() && m_hold_time->type != m_start_time->type)- m_start_time = m_hold_time;- m_hold_time = {};- }-- // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No);-}--// https://drafts.csswg.org/web-animations-2/#validating-a-css-numberish-time-WebIDL::ExceptionOr<Optional<TimeValue>> Animation::validate_a_css_numberish_time(NullableCSSNumberish const& time) const-{- // The procedure to validate a CSSNumberish time for an input value of time is based on the first condition that matches:-- // If all of the following conditions are true:- if (- // The animation is associated with a progress-based timeline, and- m_timeline && m_timeline->is_progress_based() &&-- // time is not a CSSNumeric value with percent units:- (!time.has<GC::Ref<CSS::CSSNumericValue>>() || !time.get<GC::Ref<CSS::CSSNumericValue>>()->type().matches_percentage())) {- // throw a TypeError.- // return false;- return WebIDL::SimpleException {- WebIDL::SimpleExceptionType::TypeError,- "CSSNumberish must be a percentage for progress-based animations"_utf16- };- }-- // If all of the following conditions are true:- if (- // The animation is not associated with a progress-based timeline, and- (!m_timeline || !m_timeline->is_progress_based()) &&-- // time is a CSSNumericValue, and- time.has<GC::Ref<CSS::CSSNumericValue>>() &&-- // the units of time are not duration units:- !time.get<GC::Ref<CSS::CSSNumericValue>>()->type().matches_time({}) &&-- // AD-HOC: While it's not mentioned in the spec WPT also expects us to support CSSNumericValue number value, see- // https://github.com/w3c/csswg-drafts/issues/13196- !time.get<GC::Ref<CSS::CSSNumericValue>>()->type().matches_number({})) {- // throw a TypeError.- // return false.- return WebIDL::SimpleException {- WebIDL::SimpleExceptionType::TypeError,- "CSSNumericValue must be a time for non-progress based animations"_utf16- };- }-- // Otherwise- // return true.-- // AD-HOC: The spec doesn't say when we should absolutize the validated value so we do it here and return the- // absolutized value instead of a boolean- if (time.has<Empty>())- return OptionalNone {};-- // FIXME: Figure out which element we should use for this, for now we just use the document element of the current- // window- auto& document = HTML::relevant_window(relevant_global_object()).associated_document();- CSS::ComputationContext computation_context {- .length_resolution_context = CSS::Length::ResolutionContext::for_document(document),- };- if (auto const* document_element = document.document_element())- computation_context.abstract_element = DOM::AbstractElement { *document_element };- return TimeValue::from_css_numberish(time.downcast<double, GC::Ref<CSS::CSSNumericValue>>(), computation_context);-- VERIFY_NOT_REACHED();-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-starttime-// https://www.w3.org/TR/web-animations-1/#set-the-start-time-WebIDL::ExceptionOr<void> Animation::set_start_time_for_bindings(NullableCSSNumberish const& raw_new_start_time)-{- // Setting this attribute updates the start time using the procedure to set the start time of this object to the new- // value.-- // 1. Let valid start time be the result of running the validate a CSSNumberish time procedure with new start time- // as the input.- // 2. If valid start time is false, abort this procedure.- // AD-HOC: The validate_a_css_numberish_time throws on validation failure which is handled by the TRY() macro so- // there is no need to assign the `valid start time` variable here.- auto new_start_time = TRY(validate_a_css_numberish_time(raw_new_start_time));-- // 3. Set auto align start time to false.- m_auto_align_start_time = false;-- // 4. Let timeline time be the current time value of the timeline that animation is associated with. If there is no- // timeline associated with animation or the associated timeline is inactive, let the timeline time be- // unresolved.- auto timeline_time = m_timeline && !m_timeline->is_inactive() ? m_timeline->current_time() : Optional<TimeValue> {};-- // 5. If timeline time is unresolved and new start time is resolved, make animation’s hold time unresolved.- if (!timeline_time.has_value() && new_start_time.has_value())- m_hold_time = {};-- // 6. Let previous current time be animation’s current time.- auto previous_current_time = current_time();-- // 7. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // 8. Set animation’s start time to new start time.- m_start_time = new_start_time;-- // 9. Update animation’s hold time based on the first matching condition from the following,-- // -> If new start time is resolved,- if (new_start_time.has_value()) {- // If animation’s playback rate is not zero, make animation’s hold time unresolved.- if (m_playback_rate != 0.0)- m_hold_time = {};- }- // -> Otherwise (new start time is unresolved),- else {- // Set animation’s hold time to previous current time even if previous current time is unresolved.- m_hold_time = previous_current_time;- }-- // 10. If animation has a pending play task or a pending pause task, cancel that task and resolve animation’s current- // ready promise with animation.- if (pending()) {- m_pending_play_task = TaskState::None;- m_pending_pause_task = TaskState::None;- Bindings::resolve_animation_promise(current_ready_promise(), *this);- }-- // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to true,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::Yes, SynchronouslyNotify::No);-- return {};-}--// https://drafts.csswg.org/web-animations-2/#auto-aligning-start-time-// NB: The effect's timing is normalized against the attachment interval, which moves with the timeline's scroll-// container and subject. That holds whether or not the start time is auto-aligned, e.g. for a paused animation.-void Animation::normalize_timing_against_attachment_interval()-{- auto interval = attachment_interval();- if (!interval.has_value() || m_normalized_attachment_interval == *interval)- return;- m_normalized_attachment_interval = *interval;- if (m_effect)- m_effect->normalize_specified_timing();- invalidate_effect();-}--void Animation::calculate_auto_aligned_start_time()-{- VERIFY(m_timeline && m_timeline->is_progress_based());-- // 1. If the auto-align start time flag is false, abort this procedure.- if (!m_auto_align_start_time)- return;-- // 2. If the timeline is inactive, abort this procedure.- if (!m_timeline || m_timeline->is_inactive())- return;-- // 3. If play state is idle, abort this procedure.- if (is_idle())- return;-- // 4. If play state is paused, and hold time is resolved, abort this procedure.- if (play_state() == AnimationPlayState::Paused && m_hold_time.has_value())- return;-- normalize_timing_against_attachment_interval();- auto interval = attachment_interval().value();-- // 5. Let start offset be the resolved timeline time corresponding to the start of the animation attachment range.- // In the case of view timelines, it requires a calculation based on the proportion of the cover range.- auto start_offset = interval.start;-- // 6. Let end offset be the resolved timeline time corresponding to the end of the animation attachment range. In- // the case of view timelines, it requires a calculation based on the proportion of the cover range.- auto end_offset = interval.end;-- // 7. Set start time to start offset if effective playback rate ≥ 0, and end offset otherwise.- if (effective_playback_rate() >= 0.0)- m_start_time = start_offset;- else- m_start_time = end_offset;-- // 8. Clear hold time.- m_hold_time = {};-}--// https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart-WebIDL::ExceptionOr<TimelineRangeEdge> parse_timeline_range_edge(DOM::Document& document, TimelineRangeBindingValue const& value, TimelineRangeEdgeSide side)-{- auto property = side == TimelineRangeEdgeSide::Start ? CSS::PropertyID::AnimationRangeStart : CSS::PropertyID::AnimationRangeEnd;- // A DOMString value is parsed as an 'animation-range-start' (or 'animation-range-end') value to yield a- // TimelineRangeOffset rangeName and offset or alternatively a CSSKeywordValue with the value of "normal"; a- // CSSNumericValue is interpreted as a TimelineRangeOffset with that offset and a null rangeName.- auto parse = [&](Utf16String const& string) -> WebIDL::ExceptionOr<TimelineRangeEdge> {- auto parsed = parse_css_value(CSS::Parser::ParsingParams { document }, string, property);- // NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.- if (!parsed || parsed->is_css_wide_keyword() || parsed->is_unresolved() || parsed->is_pending_substitution())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };- auto computed = parsed->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(document) });- CSS::ComputedValuesFFI::FfiAnimationRangeEdge edge {};- if (!CSS::ComputedValuesFFI::rust_animation_range_edge(computed->rust_style_value_data(), side == TimelineRangeEdgeSide::End, &edge))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };- return TimelineRangeEdge { static_cast<TimelineRangeName>(edge.name), edge.offset_px, edge.offset_percentage, retain_calculated_offset(edge.offset_calculated) };- };- return value.visit(- [&](Bindings::TimelineRangeOffset const& offset) -> WebIDL::ExceptionOr<TimelineRangeEdge> {- Utf16StringBuilder builder;- if (offset.range_name.has_value() && offset.range_name->has_value())- builder.append(**offset.range_name);- if (offset.offset) {- builder.append_ascii(' ');- builder.append(offset.offset->to_string());- }- // NB: A TimelineRangeOffset that gives neither a range name nor an offset is the default edge.- if (builder.is_empty())- return parse("normal"_utf16);- return parse(builder.to_string());- },- [&](GC::Ref<CSS::CSSNumericValue> const& offset) { return parse(offset->to_string()); },- // Passing a CSSKeywordValue with a value other than "normal" as the rangeStart or rangeEnd value to any API- // defined to accept KeyframeAnimationOptions throws a TypeError.- [&](GC::Ref<CSS::CSSKeywordValue> const& keyword) -> WebIDL::ExceptionOr<TimelineRangeEdge> {- if (!keyword->value().equals_ignoring_ascii_case("normal"sv))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };- return parse("normal"_utf16);- },- [&](Utf16String const& string) { return parse(string); });-}--// When reading the attribute, the returned value is either a TimelineRangeOffset or the DOMString "normal".-static TimelineRangeBindingValue timeline_range_edge_to_bindings(TimelineRangeEdge const& edge, TimelineRangeEdge const& normal)-{- if (edge == normal)- return "normal"_utf16;-- auto px = CSS::CSSUnitValue::create(edge.offset_px, "px"_utf16_fly_string);- auto percentage = CSS::CSSUnitValue::create(edge.offset_percentage, "percent"_utf16_fly_string);- GC::Ref<CSS::CSSNumericValue> offset = edge.offset_px == 0 ? GC::Ref<CSS::CSSNumericValue> { percentage } : GC::Ref<CSS::CSSNumericValue> { px };- if (edge.offset_px != 0 && edge.offset_percentage != 0)- offset = CSS::CSSNumericValue::create_sum(px, percentage);- if (edge.calculated_offset) {- auto calculated = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(edge.calculated_offset.data()));- offset = as<CSS::CSSNumericValue>(*CSS::CSSStyleValue::reify(*calculated, {}));- }-- Bindings::TimelineRangeOffset range_offset {};- range_offset.range_name = edge.name == TimelineRangeName::None ? Optional<Utf16String> {} : Utf16String::from_utf8_without_validation(timeline_range_name_to_string(edge.name).bytes());- range_offset.offset = offset;- return range_offset;-}--TimelineRangeBindingValue Animation::range_start_for_bindings() const-{- update_style_if_needed();- return timeline_range_edge_to_bindings(m_range.start, AnimationAttachmentRange {}.start);-}--TimelineRangeBindingValue Animation::range_end_for_bindings() const-{- update_style_if_needed();- return timeline_range_edge_to_bindings(m_range.end, AnimationAttachmentRange {}.end);-}--WebIDL::ExceptionOr<void> Animation::set_range_start_for_bindings(TimelineRangeBindingValue const& value)-{- auto range = m_range;- range.start = TRY(parse_timeline_range_edge(HTML::relevant_window(relevant_global_object()).associated_document(), value, TimelineRangeEdgeSide::Start));- set_range(range);- return {};-}--WebIDL::ExceptionOr<void> Animation::set_range_end_for_bindings(TimelineRangeBindingValue const& value)-{- auto range = m_range;- range.end = TRY(parse_timeline_range_edge(HTML::relevant_window(relevant_global_object()).associated_document(), value, TimelineRangeEdgeSide::End));- set_range(range);- return {};-}--void Animation::set_range(AnimationAttachmentRange const& range)-{- if (m_range == range)- return;- m_range = range;- if (!m_timeline || !m_timeline->is_progress_based())- return;- m_normalized_attachment_interval = attachment_interval();- if (m_effect)- m_effect->normalize_specified_timing();- calculate_auto_aligned_start_time();- invalidate_effect();-}--Optional<AttachmentInterval> Animation::attachment_interval() const-{- if (!m_timeline || !m_timeline->is_progress_based())- return {};- return m_timeline->interval_for_attachment_range(m_range);-}--// https://www.w3.org/TR/web-animations-1/#animation-current-time-Optional<TimeValue> Animation::current_time() const-{- return current_time_at(m_timeline ? m_timeline->current_time() : Optional<TimeValue> {});-}--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-{- 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-{- update_style_if_needed();- return NullableCSSNumberish::from_optional_css_numberish_time(current_time_for_observation());-}--// https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time-WebIDL::ExceptionOr<void> Animation::set_current_time_for_bindings(NullableCSSNumberish const& raw_seek_time)-{- // AD-HOC: We validate here instead of within silently_set_current_time so we have access to the `TimeValue`- // value within this function.- auto seek_time = TRY(validate_a_css_numberish_time(raw_seek_time));-- // 1. Run the steps to silently set the current time of animation to seek time.- TRY(silently_set_current_time(seek_time));-- // 2. If animation has a pending pause task, synchronously complete the pause operation by performing the following- // steps:- if (m_pending_pause_task == TaskState::Scheduled) {- // 1. Set animation’s hold time to seek time.- m_hold_time = seek_time;-- // 2. Apply any pending playback rate to animation.- apply_any_pending_playback_rate();-- // 3. Make animation’s start time unresolved.- m_start_time = {};-- // 4. Cancel the pending pause task.- m_pending_pause_task = TaskState::None;-- // 5 Resolve animation’s current ready promise with animation.- Bindings::resolve_animation_promise(current_ready_promise(), *this);- }-- // 3. Run the procedure to update an animation’s finished state for animation with the did seek flag set to true,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::Yes, SynchronouslyNotify::No);-- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-playbackrate-// https://www.w3.org/TR/web-animations-1/#set-the-playback-rate-WebIDL::ExceptionOr<void> Animation::set_playback_rate(double new_playback_rate)-{- // Setting this attribute follows the procedure to set the playback rate of this object to the new value.-- // 1. Clear any pending playback rate on animation.- m_pending_playback_rate = {};-- // 2. Let previous time be the value of the current time of animation before changing the playback rate.- auto previous_time = current_time();-- // 3. Let previous playback rate be the current effective playback rate of animation.- auto previous_playback_rate = playback_rate();-- // 4. Set the playback rate to new playback rate.- m_playback_rate = new_playback_rate;-- // 5. Perform the steps corresponding to the first matching condition from the following, if any:-- // -> If animation is associated with a monotonically increasing timeline and the previous time is resolved,- if (m_timeline && m_timeline->is_monotonically_increasing() && previous_time.has_value()) {- // set the current time of animation to previous time.- TRY(set_current_time_for_bindings(previous_time->as_css_numberish()));- }- // -> If animation is associated with a non-null timeline that is not monotonically increasing, the start time of- // animation is resolved, associated effect end is not infinity, and either:- // - the previous playback rate < 0 and the new playback rate ≥ 0, or- // - the previous playback rate ≥ 0 and the new playback rate < 0,- else if (m_timeline && !m_timeline->is_monotonically_increasing() && m_start_time.has_value() && !isinf(associated_effect_end().value) && ((previous_playback_rate < 0.0 && new_playback_rate >= 0.0) || (previous_playback_rate >= 0 && new_playback_rate < 0))) {- // Set animation’s start time to the result of evaluating associated effect end - start time for animation.- m_start_time = associated_effect_end() - m_start_time.value();- }-- return {};-}--void Animation::update_style_if_needed() const-{- if (m_owning_element.has_value())- m_owning_element->document().update_style_for_element(*m_owning_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);-}--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-{- 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()-{- if (auto owning_element = this->owning_element(); owning_element.has_value())- owning_element->document().update_style();-- return play_state_at(current_time_for_observation());-}--bool Animation::pending_for_bindings() const-{- update_style_if_needed();- return pending();-}--GC::Ref<WebIDL::Promise> Animation::ready_for_bindings() const-{- update_style_if_needed();- return ready();-}--GC::Ref<WebIDL::Promise> Animation::finished_for_bindings()-{- update_style_if_needed();- auto observed_timeline_time = m_timeline ? m_timeline->current_time_for_observation() : Optional<TimeValue> {};- auto observed_current_time = current_time_at(observed_timeline_time);- if (m_timeline- && !m_is_finished- && play_state_at(current_time()) != AnimationPlayState::Finished- && play_state_at(observed_current_time) == AnimationPlayState::Finished) {- AnimationTimeline::CurrentTimeOverrideScope current_time_override_scope { *m_timeline, observed_timeline_time };- update_finished_state(DidSeek::No, SynchronouslyNotify::Yes, ShouldInvalidate::No, observed_current_time);- }- return finished();-}--// https://www.w3.org/TR/web-animations-1/#animation-relevant-bool Animation::is_relevant() const-{- 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-bool Animation::is_replaceable() const-{- // An animation is replaceable if all of the following conditions are true:-- // - The existence of the animation is not prescribed by markup. That is, it is not a CSS animation with an owning- // element, nor a CSS transition with an owning element.- if ((is_css_animation() || is_css_transition()) && owning_element().has_value())- return false;- // AD-HOC: Like a CSS animation with an owning element, an SVG animation element prescribes its animation in markup.- if (is_smil_animation())- return false;-- // - The animation's play state is finished.- if (play_state() != AnimationPlayState::Finished)- return false;-- // - The animation's replace state is not removed.- if (replace_state() == AnimationReplaceState::Removed)- return false;-- // - The animation is associated with a monotonically increasing timeline.- if (!m_timeline || !m_timeline->is_monotonically_increasing())- return false;-- // - The animation has an associated effect.- if (!m_effect)- return false;-- // - The animation's associated effect is in effect.- if (!m_effect->is_in_effect())- return false;-- // - The animation's associated effect has an effect target.- if (!m_effect->target())- return false;-- return true;-}--void Animation::set_replace_state(AnimationReplaceState value)-{- if (value == AnimationReplaceState::Removed) {- // Remove the associated effect from its target, if applicable- if (m_effect && m_effect->target())- m_effect->target()->disassociate_with_animation(*this);-- // Remove this animation from its timeline- m_timeline->disassociate_with_animation(*this);- } else if (value == AnimationReplaceState::Persisted && m_replace_state == AnimationReplaceState::Removed) {- // This animation was removed, but is now being "unremoved"; undo the effects from the if-statement above- if (m_effect && m_effect->target())- m_effect->target()->associate_with_animation(*this);- m_timeline->associate_with_animation(*this);- }-- m_replace_state = value;-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-onfinish-GC::Ptr<WebIDL::CallbackType> Animation::onfinish()-{- return event_handler_attribute(HTML::EventNames::finish);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-onfinish-void Animation::set_onfinish(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::finish, event_handler);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-oncancel-GC::Ptr<WebIDL::CallbackType> Animation::oncancel()-{- return event_handler_attribute(HTML::EventNames::cancel);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-oncancel-void Animation::set_oncancel(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::cancel, event_handler);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-onremove-GC::Ptr<WebIDL::CallbackType> Animation::onremove()-{- return event_handler_attribute(HTML::EventNames::remove);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-onremove-void Animation::set_onremove(GC::Ptr<WebIDL::CallbackType> event_handler)-{- set_event_handler_attribute(HTML::EventNames::remove, event_handler);-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel-void Animation::cancel(ShouldInvalidate should_invalidate)-{- // Note: When called from JS, we always want to invalidate the animation target's style. However, this method is- // also called from the StyleComputer when the animation-name CSS property changes. That happens in the- // middle of a cascade, and importantly, _before_ computing the animation effect stack, so there is no- // need for another invalidation. It would also schedule a redundant follow-up reaction while the current- // style computation is already updating the animation effect stack.-- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. If animation’s play state is not idle, perform the following steps:- if (play_state() != AnimationPlayState::Idle) {- HTML::TemporaryExecutionContext execution_context { realm };-- // 1. Run the procedure to reset an animation’s pending tasks on animation.- reset_an_animations_pending_tasks();-- // OPTIMIZATION: A current finished promise that was never created is a pending promise nothing can observe,- // and the new promise of step 4 is just like it, so steps 2 to 4 only matter for a created one.- if (m_current_finished_promise) {- // 2. Reject the current finished promise with a DOMException named "AbortError".- auto dom_exception = WebIDL::AbortError::create("Animation was cancelled"_utf16);- WebIDL::reject_promise(*m_current_finished_promise, dom_exception);-- // 3. Set the [[PromiseIsHandled]] internal slot of the current finished promise to true.- WebIDL::mark_promise_as_handled(*m_current_finished_promise);-- // 4. Let current finished promise be a new promise in the relevant Realm of animation.- m_current_finished_promise = nullptr;- }- m_is_finished = false;-- // 5. Create an AnimationPlaybackEvent, cancelEvent.- // 6. Set cancelEvent’s type attribute to cancel.- // 7. Set cancelEvent’s currentTime to null.- // 8. Let timeline time be the current time of the timeline with which animation is associated. If animation is- // not associated with an active timeline, let timeline time be an unresolved time value.- // 9. Set cancelEvent’s timelineTime to timeline time. If timeline time is unresolved, set it to null.- AnimationPlaybackEventInit init;- init.timeline_time = m_timeline && !m_timeline->is_inactive() ? NullableCSSNumberish { m_timeline->current_time()->as_css_numberish() } : NullableCSSNumberish { Empty {} };- auto cancel_event = AnimationPlaybackEvent::create(HTML::EventNames::cancel, init, HighResolutionTime::current_high_resolution_time(realm.global_object()));-- // 10. If animation has a document for timing, then append cancelEvent to its document for timing's pending- // animation event queue along with its target, animation. If animation is associated with an active- // timeline that defines a procedure to convert timeline times to origin-relative time, let the scheduled- // event time be the result of applying that procedure to timeline time. Otherwise, the scheduled event time- // is an unresolved time value.- // Otherwise, queue a task to dispatch cancelEvent at animation. The task source for this task is the DOM- // manipulation task source.- if (auto document = document_for_timing()) {- Optional<double> scheduled_event_time;- if (m_timeline && !m_timeline->is_inactive() && m_timeline->can_convert_a_timeline_time_to_an_origin_relative_time())- scheduled_event_time = m_timeline->convert_a_timeline_time_to_an_origin_relative_time(m_timeline->current_time());- document->append_pending_animation_event({ cancel_event, *this, *this, scheduled_event_time });- } else {- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(*this, cancel_event), [](auto& self, auto& cancel_event) {- self.dispatch_event(cancel_event);- }));- }- }-- // 2. Make animation’s hold time unresolved.- m_hold_time = {};-- // 3. Make animation’s start time unresolved.- m_start_time = {};-- // This time is needed for dispatching the animationcancel DOM event- if (auto effect = m_effect)- m_saved_cancel_time = effect->active_time_using_fill(FillMode::Both);-- // AD-HOC: The target's animation list is our own cache of the animations whose effect targets it, and holding a- // cancelled animation there keeps it alive and walked every frame. It is reassociated if revived.- schedule_disassociation_from_target();-- if (should_invalidate == ShouldInvalidate::Yes)- invalidate_effect();-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-finish-WebIDL::ExceptionOr<void> Animation::finish()-{- // 1. If animation’s effective playback rate is zero, or if animation’s effective playback rate > 0 and associated- // effect end is infinity, throw an "InvalidStateError" DOMException and abort these steps.- auto effective_playback_rate = this->effective_playback_rate();- if (effective_playback_rate == 0.0)- return WebIDL::InvalidStateError::create("Animation with a playback rate of 0 cannot be finished"_utf16);- if (effective_playback_rate > 0.0 && isinf(associated_effect_end().value))- return WebIDL::InvalidStateError::create("Animation with no end cannot be finished"_utf16);-- // 2. Apply any pending playback rate to animation.- apply_any_pending_playback_rate();-- // 3. Set limit as follows:- // -> If playback rate > 0,- // Let limit be associated effect end.- // -> Otherwise,- // Let limit be zero.- auto playback_rate = this->playback_rate();- auto limit = playback_rate > 0.0 ? associated_effect_end() : TimeValue::create_zero(m_timeline);-- // 4. Silently set the current time to limit.- TRY(silently_set_current_time(limit));-- // 5. If animation’s start time is unresolved and animation has an associated active timeline, let the start time be- // the result of evaluating timeline time - (limit / playback rate) where timeline time is the current time value- // of the associated timeline.- if (!m_start_time.has_value() && m_timeline && !m_timeline->is_inactive())- m_start_time = m_timeline->current_time().value() - (limit / playback_rate);-- // 6. If there is a pending pause task and start time is resolved,- auto should_resolve_ready_promise = false;- if (m_pending_pause_task == TaskState::Scheduled && m_start_time.has_value()) {- // 1. Let the hold time be unresolved.- // Note: Typically the hold time will already be unresolved except in the case when the animation was previously- // idle.- m_hold_time = {};-- // 2. Cancel the pending pause task.- m_pending_pause_task = TaskState::None;-- // 3. Resolve the current ready promise of animation with animation.- should_resolve_ready_promise = true;- }-- // 7. If there is a pending play task and start time is resolved, cancel that task and resolve the current ready- // promise of animation with animation.- if (m_pending_play_task == TaskState::Scheduled && m_start_time.has_value()) {- m_pending_play_task = TaskState::None;- should_resolve_ready_promise = true;- }-- if (should_resolve_ready_promise) {- HTML::TemporaryExecutionContext execution_context { relevant_settings_object() };- Bindings::resolve_animation_promise(current_ready_promise(), *this);- }-- // 8. Run the procedure to update an animation’s finished state for animation with the did seek flag set to true,- // and the synchronously notify flag set to true.- update_finished_state(DidSeek::Yes, SynchronouslyNotify::Yes);-- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-play-WebIDL::ExceptionOr<void> Animation::play(ShouldInvalidate should_invalidate)-{- // Begins or resumes playback of the animation by running the procedure to play an animation passing true as the- // value of the auto-rewind flag.- return play_an_animation(AutoRewind::Yes, should_invalidate);-}--// https://drafts.csswg.org/web-animations-1/#playing-an-animation-section-// https://drafts.csswg.org/web-animations-2/#play-an-animation-WebIDL::ExceptionOr<void> Animation::play_an_animation(AutoRewind auto_rewind, ShouldInvalidate should_invalidate)-{- // 1. Let aborted pause be a boolean flag that is true if animation has a pending pause task, and false otherwise.- auto aborted_pause = m_pending_pause_task == TaskState::Scheduled;-- // 2. Let has pending ready promise be a boolean flag that is initially false.- auto has_pending_ready_promise = false;-- // 3. Let has finite timeline be true if animation has an associated timeline that is not monotonically increasing.- auto has_finite_timeline = m_timeline && !m_timeline->is_monotonically_increasing();-- // 4. Let previous current time be the animation’s current time- auto previous_current_time = current_time();-- // 5. Let enable seek be true if the auto-rewind flag is true and has finite timeline is false. Otherwise,- // initialize to false.- auto enable_seek = (auto_rewind == AutoRewind::Yes) && !has_finite_timeline;-- // 6. Perform the steps corresponding to the first matching condition from the following, if any:- auto const& effective_playback_rate = this->effective_playback_rate();- auto const& associated_effect_end = this->associated_effect_end();-- // -> If animation’s effective playback rate > 0, enable seek is true and either animation’s:- // - previous current time is unresolved, or- // - previous current time < zero, or- // - previous current time ≥ associated effect end,- if (effective_playback_rate > 0.0 && enable_seek && (!previous_current_time.has_value() || previous_current_time->value < 0 || previous_current_time.value() >= associated_effect_end)) {- // Set the animation’s hold time to zero.- m_hold_time = TimeValue::create_zero(m_timeline);- }-- // -> If animation’s effective playback rate < 0, enable seek is true and either animation’s:- // - previous current time is unresolved, or- // - previous current time ≤ zero, or- // - previous current time > associated effect end,- else if (effective_playback_rate < 0 && enable_seek && (!previous_current_time.has_value() || previous_current_time->value <= 0 || previous_current_time.value() > associated_effect_end)) {- // -> If associated effect end is positive infinity,- if (isinf(associated_effect_end.value) && associated_effect_end.value > 0) {- // throw an "InvalidStateError" DOMException and abort these steps.- return WebIDL::InvalidStateError::create("Cannot rewind an animation with an infinite effect end"_utf16);- }-- // -> Otherwise,- // Set the animation’s hold time to the animation’s associated effect end.- m_hold_time = associated_effect_end;- }-- // -> If animation’s effective playback rate = 0 and animation’s current time is unresolved,- else if (effective_playback_rate == 0.0 && !previous_current_time.has_value()) {- // Set the animation’s hold time to zero.- m_hold_time = TimeValue::create_zero(m_timeline);- }-- // 7. If has finite timeline and previous current time is unresolved:- if (has_finite_timeline && !previous_current_time.has_value()) {- // Set the flag auto align start time to true.- m_auto_align_start_time = true;- }-- // 8. If animation’s hold time is resolved, let its start time be unresolved.- if (m_hold_time.has_value())- m_start_time = {};-- // 9. If animation has a pending play task or a pending pause task,- if (pending()) {- // 1. Cancel that task.- m_pending_play_task = TaskState::None;- m_pending_pause_task = TaskState::None;-- // 2. Set has pending ready promise to true.- has_pending_ready_promise = true;- }-- // 10. If the following three conditions are all satisfied:- // - animation’s hold time is unresolved, and- // - aborted pause is false, and- // - animation does not have a pending playback rate,- // AD-HOC: We also don't abort if we have a pending auto-alignment of the start time, see- // https://github.com/w3c/csswg-drafts/issues/13236- auto pending_auto_aligned_start_time = m_auto_align_start_time && !m_start_time.has_value();- if (!m_hold_time.has_value() && !aborted_pause && !m_pending_playback_rate.has_value() && !pending_auto_aligned_start_time) {- // abort this procedure.- return {};- }-- // 11. If has pending ready promise is false, let animation’s current ready promise be a new promise in the relevant- // Realm of animation.- if (!has_pending_ready_promise)- m_current_ready_promise = WebIDL::create_promise_for(relevant_global_object());-- // 12. Schedule a task to run as soon as animation is ready. The task shall perform the following steps:- //- // Note: Steps omitted, see run_pending_play_task()- //- // So long as the above task is scheduled but has yet to run, animation is described as having a pending play- // task. While the task is running, however, animation does not have a pending play task.- //- // If a user agent determines that animation is immediately ready, it may schedule the above task as a microtask- // such that it runs at the next microtask checkpoint, but it must not perform the task synchronously.- m_pending_play_task = TaskState::Scheduled;-- // 13. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No, should_invalidate);-- return {};-}--void Animation::disassociate_from_target_if_inert()-{- m_disassociation_from_target_pending = false;- // Script may have revived the animation since the disassociation was scheduled.- if (!m_effect || !m_effect->target() || pending() || is_relevant())- return;- m_effect->target()->disassociate_with_animation(*this);- m_play_state_when_disassociated_from_target = play_state();- // The target's animated style keeps this effect's values until they are recomputed without it.- AnimationUpdateContext context;- m_effect->update_computed_properties(context);-}--void Animation::did_associate_with_target()-{- if (!m_play_state_when_disassociated_from_target.has_value())- return;- m_play_state_when_disassociated_from_target.clear();- // Joining a target does not make the animation relevant, so check again whether it is inert.- schedule_disassociation_from_target();-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-pause-WebIDL::ExceptionOr<void> Animation::pause()-{- // 1. If animation has a pending pause task, abort these steps.- if (m_pending_pause_task == TaskState::Scheduled)- return {};-- // 2. If the play state of animation is paused, abort these steps.- if (play_state() == AnimationPlayState::Paused)- return {};-- // 3. Let seek time be a time value that is initially unresolved.- Optional<TimeValue> seek_time;-- // 4. Let has finite timeline be true if animation has an associated timeline that is not monotonically increasing.- auto has_finite_timeline = m_timeline && !m_timeline->is_monotonically_increasing();-- // 5. If the animation’s current time is unresolved, perform the steps according to the first matching condition- // from below:- if (!current_time().has_value()) {- // -> If animation’s playback rate is ≥ 0,- if (playback_rate() >= 0.0) {- // Set seek time to zero.- seek_time = TimeValue::create_zero(m_timeline);- }- // -> Otherwise- else {- // If associated effect end for animation is positive infinity,- auto associated_effect_end = this->associated_effect_end();- if (isinf(associated_effect_end.value) && associated_effect_end.value > 0) {- // throw an "InvalidStateError" DOMException and abort these steps.- return WebIDL::InvalidStateError::create("Cannot pause an animation with an infinite effect end"_utf16);- }-- // Otherwise,- // Set seek time to animation’s associated effect end.- seek_time = associated_effect_end;- }- }-- // 6. If seek time is resolved,- if (seek_time.has_value()) {- // If has finite timeline is true,- if (has_finite_timeline) {- // Set animation’s start time to seek time.- m_start_time = seek_time;- }- // Otherwise,- else {- // Set animation’s hold time to seek time.- m_hold_time = seek_time;- }- }-- // 7. Let has pending ready promise be a boolean flag that is initially false.- auto has_pending_ready_promise = false;-- // 8. If animation has a pending play task, cancel that task and let has pending ready promise be true.- if (m_pending_play_task == TaskState::Scheduled) {- m_pending_play_task = TaskState::None;- has_pending_ready_promise = true;- }-- // 9. If has pending ready promise is false, set animation’s current ready promise to a new promise in the relevant- // Realm of animation.- if (!has_pending_ready_promise)- m_current_ready_promise = WebIDL::create_promise_for(relevant_global_object());-- // 10. Schedule a task to be executed at the first possible moment where both of the following conditions are true:- // NB: Criteria has been listed out in is_ready_to_run_pending_pause_task()- // NB: This is run_pending_pause_task()- m_pending_pause_task = TaskState::Scheduled;-- // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No);-- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-updateplaybackrate-WebIDL::ExceptionOr<void> Animation::update_playback_rate(double new_playback_rate)-{- // 1. Let previous play state be animation’s play state.- // Note: It is necessary to record the play state before updating animation’s effective playback rate since, in the- // following logic, we want to immediately apply the pending playback rate of animation if it is currently- // finished regardless of whether or not it will still be finished after we apply the pending playback rate.- auto previous_play_state = play_state();-- // 2. Let animation’s pending playback rate be new playback rate.- m_pending_playback_rate = new_playback_rate;-- // 3. Perform the steps corresponding to the first matching condition from below:-- // -> If animation has a pending play task or a pending pause task,- if (pending()) {- // Abort these steps.- // Note: The different types of pending tasks will apply the pending playback rate when they run so there is no- // further action required in this case.- return {};- }-- // -> If previous play state is idle or paused, or animation’s current time is unresolved,- if (previous_play_state == AnimationPlayState::Idle || previous_play_state == AnimationPlayState::Paused || !current_time().has_value()) {- // Apply any pending playback rate on animation.- // Note: the second condition above is required so that if we have a running animation with an unresolved- // current time and no pending play task, we do not attempt to play it below.- apply_any_pending_playback_rate();- }- // -> If previous play state is finished,- else if (previous_play_state == AnimationPlayState::Finished) {- // 1. Let the unconstrained current time be the result of calculating the current time of animation- // substituting an unresolved time value for the hold time.- Optional<TimeValue> unconstrained_current_time;- {- TemporaryChange change(m_hold_time, {});- unconstrained_current_time = current_time();- }-- // 2. Let animation’s start time be the result of evaluating the following expression:- // timeline time - (unconstrained current time / pending playback rate)- // Where timeline time is the current time value of the timeline associated with animation.- // If pending playback rate is zero, let animation’s start time be timeline time.- if (m_pending_playback_rate.value() == 0.0) {- m_start_time = m_timeline->current_time().value();- } else {- m_start_time = m_timeline->current_time().value() - (unconstrained_current_time.value() / m_pending_playback_rate.value());- }-- // 3. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // 4. Run the procedure to update an animation’s finished state for animation with the did seek flag set to- // false, and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No);- }- // -> Otherwise,- else {- // Run the procedure to play an animation for animation with the auto-rewind flag set to false.- TRY(play_an_animation(AutoRewind::No));- }-- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-reverse-WebIDL::ExceptionOr<void> Animation::reverse()-{- // 1. If there is no timeline associated with animation, or the associated timeline is inactive throw an- // "InvalidStateError" DOMException and abort these steps.- if (!m_timeline || m_timeline->is_inactive())- return WebIDL::InvalidStateError::create("Cannot reverse an animation with an inactive timeline"_utf16);-- // 2. Let original pending playback rate be animation’s pending playback rate.- auto original_pending_playback_rate = m_pending_playback_rate;-- // 3. Let animation’s pending playback rate be the additive inverse of its effective playback rate (i.e.- // -effective playback rate).- m_pending_playback_rate = -effective_playback_rate();-- // 4. Run the steps to play an animation for animation with the auto-rewind flag set to true.- // If the steps to play an animation throw an exception, set animation’s pending playback rate to original- // pending playback rate and propagate the exception.- auto result = play_an_animation(AutoRewind::Yes);- if (result.is_error()) {- m_pending_playback_rate = original_pending_playback_rate;- return result;- }-- return {};-}--// https://www.w3.org/TR/web-animations-1/#dom-animation-persist-void Animation::persist()-{- // Sets this animation’s replace state to persisted.- set_replace_state(AnimationReplaceState::Persisted);-}--// https://www.w3.org/TR/web-animations-1/#animation-time-to-timeline-time-Optional<TimeValue> Animation::convert_an_animation_time_to_timeline_time(Optional<TimeValue> time) const-{- // 1. If time is unresolved, return time.- if (!time.has_value())- return time;-- // 2. If time is infinity, return an unresolved time value.- if (isinf(time->value))- return {};-- // 3. If animation’s playback rate is zero, return an unresolved time value.- if (m_playback_rate == 0.0)- return {};-- // 4. If animation’s start time is unresolved, return an unresolved time value.- if (!m_start_time.has_value())- return {};-- // 5. Return the result of calculating: time × (1 / playback rate) + start time (where playback rate and start time- // are the playback rate and start time of animation, respectively).- return (time.value() * (1.0 / m_playback_rate)) + m_start_time.value();-}--// https://www.w3.org/TR/web-animations-1/#animation-time-to-origin-relative-time-Optional<double> Animation::convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue> time) const-{- // 1. Let timeline time be the result of converting time from an animation time to a timeline time.- auto timeline_time = convert_an_animation_time_to_timeline_time(time);-- // 2. If timeline time is unresolved, return time.- if (!timeline_time.has_value())- return {};-- // 3. If animation is not associated with a timeline, return an unresolved time value.- if (!m_timeline)- return {};-- // 4. If animation is associated with an inactive timeline, return an unresolved time value.- if (m_timeline->is_inactive())- return {};-- // 5. If there is no procedure to convert a timeline time to an origin-relative time for the timeline associated- // with animation, return an unresolved time value.- if (!m_timeline->can_convert_a_timeline_time_to_an_origin_relative_time())- return {};-- // 6. Return the result of converting timeline time to an origin-relative time using the procedure defined for the- // timeline associated with animation.- return m_timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline_time);-}--// https://www.w3.org/TR/web-animations-1/#animation-document-for-timing-GC::Ptr<DOM::Document> Animation::document_for_timing() const-{- // An animation’s document for timing is the Document with which its timeline is associated. If an animation is not- // associated with a timeline, or its timeline is not associated with a document, then it has no document for- // timing.- if (!m_timeline)- return {};- return m_timeline->associated_document();-}--void Animation::update()-{- // https://drafts.csswg.org/scroll-animations-1/#event-loop- // When updating timeline current time, the start time of any attached animation is conditionally updated. For each- // attached animation, run the procedure for calculating an auto-aligned start time.- if (m_timeline && m_timeline->is_progress_based()) {- normalize_timing_against_attachment_interval();- calculate_auto_aligned_start_time();- }-- // Prevent unnecessary work if the animation is already finished and can't exit the finished state due to timeline- // changes- if (!m_is_finished || !m_timeline->is_monotonically_increasing()) {- bool was_finished = m_is_finished;- update_finished_state(DidSeek::No, SynchronouslyNotify::Yes, ShouldInvalidate::No);- if (play_state() == AnimationPlayState::Running && m_effect && is<KeyframeEffect>(*m_effect)) {- auto& effect = static_cast<KeyframeEffect&>(*m_effect);- bool output_is_constant_before_active_start = !pending()- && effect.phase() == AnimationEffect::Phase::Before- && m_timeline- && m_timeline->is_monotonically_increasing()- && playback_rate() > 0;- if (effect.can_skip_per_frame_style_update()) {- if (auto target = effect.target())- target->document().note_throttled_animation_style_update();- } else if (!pending() && !output_is_constant_before_active_start) {- invalidate_effect(ChangesPlan::No);- }- } else if (m_is_finished != was_finished) {- invalidate_effect(ChangesPlan::No);- }- }-- // Act on the pending play or pause task- run_pending_play_task_if_ready();-- if (m_pending_pause_task == TaskState::Scheduled && is_ready_to_run_pending_pause_task()) {- m_pending_pause_task = TaskState::None;- run_pending_pause_task();- }-- if (play_state() == AnimationPlayState::Running && !pending() && m_effect && is<KeyframeEffect>(*m_effect)) {- auto& effect = static_cast<KeyframeEffect&>(*m_effect);- if (effect.phase() == AnimationEffect::Phase::Before- && m_timeline && m_timeline->is_monotonically_increasing()- && playback_rate() > 0- && effect.start_delay().type == TimeValue::Type::Milliseconds) {- auto animation_current_time = current_time();- if (animation_current_time.has_value() && animation_current_time->type == TimeValue::Type::Milliseconds) {- auto delay = (effect.start_delay().value - animation_current_time->value) / playback_rate();- if (delay > 0) {- if (auto target = effect.target())- target->document().schedule_compositor_animation_wakeup(delay);- }- }- }- }-}--void Animation::run_pending_play_task_if_ready()-{- if (m_pending_play_task != TaskState::Scheduled || !is_ready())- return;- m_pending_play_task = TaskState::None;- run_pending_play_task();-}--void Animation::effect_timing_changed(Badge<AnimationEffect>)-{- update_finished_state(DidSeek::No, SynchronouslyNotify::Yes);-}--void Animation::effect_timing_changed_by_style()-{- update_finished_state(DidSeek::No, SynchronouslyNotify::No);-}--// https://www.w3.org/TR/web-animations-1/#associated-effect-end-TimeValue Animation::associated_effect_end() const-{- // The associated effect end of an animation is equal to the end time of the animation’s associated effect. If the- // animation has no associated effect, the associated effect end is zero.- 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-{- // The effective playback rate of an animation is its pending playback rate, if set, otherwise it is the animation’s- // playback rate.- return m_pending_playback_rate.has_value() ? m_pending_playback_rate.value() : m_playback_rate;-}--// https://www.w3.org/TR/web-animations-1/#apply-any-pending-playback-rate-void Animation::apply_any_pending_playback_rate()-{- // 1. If animation does not have a pending playback rate, abort these steps.- if (!m_pending_playback_rate.has_value())- return;-- // 2. Set animation’s playback rate to its pending playback rate.- m_playback_rate = m_pending_playback_rate.value();-- // 3. Clear animation’s pending playback rate.- m_pending_playback_rate = {};-}--// https://www.w3.org/TR/web-animations-1/#animation-silently-set-the-current-time-WebIDL::ExceptionOr<void> Animation::silently_set_current_time(Optional<TimeValue> valid_seek_time)-{- // 1. If seek time is an unresolved time value, then perform the following steps.- if (!valid_seek_time.has_value()) {- // 1. If the current time is resolved, then throw a TypeError.- if (current_time().has_value()) {- return WebIDL::SimpleException {- WebIDL::SimpleExceptionType::TypeError,- "Cannot change an animation's current time from a resolve value to an unresolved value"_utf16- };- }-- // 2. Abort these steps.- return {};- }-- // 2. Let valid seek time be the result of running the validate a CSSNumberish time procedure with seek time as the input.- // 3. If valid seek time is false, abort this procedure.- // AD-HOC: We have already validated in the caller.-- // 4. Set auto align start time to false.- m_auto_align_start_time = false;-- // 5. Update either animation’s hold time or start time as follows:-- // -> If any of the following conditions are true:- // - animation’s hold time is resolved, or- // - animation’s start time is unresolved, or- // - animation has no associated timeline or the associated timeline is inactive, or- // - animation’s playback rate is 0,- if (m_hold_time.has_value() || !m_start_time.has_value() || !m_timeline || m_timeline->is_inactive() || m_playback_rate == 0.0) {- // Set animation’s hold time to seek time.- m_hold_time = valid_seek_time;- }- // -> Otherwise,- else {- // Set animation’s start time to the result of evaluating timeline time - (seek time / playback rate) where- // timeline time is the current time value of timeline associated with animation.- m_start_time = m_timeline->current_time().value() - (valid_seek_time.value() / m_playback_rate);- }-- // 6. If animation has no associated timeline or the associated timeline is inactive, make animation’s start time- // unresolved.- if (!m_timeline || m_timeline->is_inactive())- m_start_time = {};-- // 7. Make animation’s previous current time unresolved.- m_previous_current_time = {};-- return {};-}--// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state-void Animation::update_finished_state(DidSeek did_seek, SynchronouslyNotify synchronously_notify, ShouldInvalidate should_invalidate, Optional<TimeValue> observed_current_time)-{- auto& realm = HTML::relevant_realm(relevant_global_object());-- // 1. Let the unconstrained current time be the result of calculating the current time substituting an unresolved- // time value for the hold time if did seek is false. If did seek is true, the unconstrained current time is- // equal to the current time.- //- // Note: This is required to accommodate timelines that may change direction. Without this definition, a once-- // finished animation would remain finished even when its timeline progresses in the opposite direction.- Optional<TimeValue> unconstrained_current_time = observed_current_time;- if (!unconstrained_current_time.has_value() && did_seek == DidSeek::No) {- TemporaryChange change(m_hold_time, {});- unconstrained_current_time = current_time();- } else if (!unconstrained_current_time.has_value()) {- unconstrained_current_time = current_time();- }-- // 2. If all three of the following conditions are true,- // - the unconstrained current time is resolved, and- // - animation’s start time is resolved, and- // - animation does not have a pending play task or a pending pause task,- if (unconstrained_current_time.has_value() && m_start_time.has_value() && !pending()) {- // then update animation’s hold time based on the first matching condition for animation from below, if any:-- // -> If playback rate > 0 and unconstrained current time is greater than or equal to associated effect end,- auto associated_effect_end = this->associated_effect_end();- if (m_playback_rate > 0.0 && unconstrained_current_time.value() >= associated_effect_end) {- // If did seek is true, let the hold time be the value of unconstrained current time.- if (did_seek == DidSeek::Yes) {- m_hold_time = unconstrained_current_time;- }- // If did seek is false, let the hold time be the maximum value of previous current time and associated- // effect end. If the previous current time is unresolved, let the hold time be associated effect end.- else if (m_previous_current_time.has_value()) {- m_hold_time = max(m_previous_current_time.value(), associated_effect_end);- } else {- m_hold_time = associated_effect_end;- }- }- // -> If playback rate < 0 and unconstrained current time is less than or equal to 0,- else if (m_playback_rate < 0.0 && unconstrained_current_time->value <= 0) {- // If did seek is true, let the hold time be the value of unconstrained current time.- if (did_seek == DidSeek::Yes) {- m_hold_time = unconstrained_current_time;- }- // If did seek is false, let the hold time be the minimum value of previous current time and zero. If the- // previous current time is unresolved, let the hold time be zero.- else if (m_previous_current_time.has_value()) {- m_hold_time = min(m_previous_current_time.value(), TimeValue::create_zero(m_timeline));- } else {- m_hold_time = TimeValue::create_zero(m_timeline);- }- }- // -> If playback rate ≠ 0, and animation is associated with an active timeline,- else if (m_playback_rate != 0.0 && m_timeline && !m_timeline->is_inactive()) {- // Perform the following steps:-- // 1. If did seek is true and the hold time is resolved, let animation’s start time be equal to the result- // of evaluating timeline time - (hold time / playback rate) where timeline time is the current time- // value of timeline associated with animation.- if (did_seek == DidSeek::Yes && m_hold_time.has_value())- m_start_time = m_timeline->current_time().value() - (m_hold_time.value() / m_playback_rate);-- // 2. Let the hold time be unresolved.- m_hold_time = {};- }- }-- // 3. Set the previous current time of animation be the result of calculating its current time.- m_previous_current_time = current_time();-- // 4. Let current finished state be true if the play state of animation is finished. Otherwise, let it be false.- auto current_finished_state = play_state() == AnimationPlayState::Finished;-- // 5. If current finished state is true and the current finished promise is not yet resolved, perform the following- // steps:- if (current_finished_state && !m_is_finished) {- // 1. Let finish notification steps refer to the following procedure:- auto finish_notification_steps = GC::create_function<void()>(GC::Heap::the(), GC::captures(*this, realm), [](Animation& self, auto& realm) {- // 1. If animation’s play state is not equal to finished, abort these steps.- if (self.play_state() != AnimationPlayState::Finished)- return;-- // 2. Resolve animation’s current finished promise object with animation.- Bindings::resolve_animation_promise(self.current_finished_promise(), self);- self.m_is_finished = true;-- // 3. Create an AnimationPlaybackEvent, finishEvent.- // 4. Set finishEvent’s type attribute to finish.- // 5. Set finishEvent’s currentTime attribute to the current time of animation.- // 6. Set finishEvent’s timelineTime attribute to the current time of the timeline with which animation is- // associated. If animation is not associated with a timeline, or the timeline is inactive, let- // timelineTime be null.- AnimationPlaybackEventInit init;- init.current_time = self.current_time()->as_css_numberish();- if (self.m_timeline && !self.m_timeline->is_inactive())- init.timeline_time = self.m_timeline->current_time()->as_css_numberish();-- auto finish_event = AnimationPlaybackEvent::create(HTML::EventNames::finish, init, HighResolutionTime::current_high_resolution_time(realm.global_object()));-- // 7. If animation has a document for timing, then append finishEvent to its document for timing's pending- // animation event queue along with its target, animation. For the scheduled event time, use the result- // of converting animation’s associated effect end to an origin-relative time.- if (auto document_for_timing = self.document_for_timing()) {- document_for_timing->append_pending_animation_event({- .event = finish_event,- .animation = self,- .target = self,- .scheduled_event_time = self.convert_a_timeline_time_to_an_origin_relative_time(self.associated_effect_end()),- });- }- // Otherwise, queue a task to dispatch finishEvent at animation. The task source for this task is the DOM- // manipulation task source.- else {- // Manually create a task so its ID can be saved- auto& document = HTML::relevant_window(realm.global_object()).associated_document();- auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document,- GC::create_function(GC::Heap::the(), GC::captures(self, finish_event), [](auto& self, auto& finish_event) {- self.dispatch_event(finish_event);- }));- self.m_pending_finish_microtask_id = task->id();- (void)HTML::main_thread_event_loop().task_queue().add(task);- }- });-- // 2. If synchronously notify is true, cancel any queued microtask to run the finish notification steps for this- // animation, and run the finish notification steps immediately.- if (synchronously_notify == SynchronouslyNotify::Yes) {- if (m_pending_finish_microtask_id.has_value()) {- HTML::main_thread_event_loop().task_queue().remove_tasks_matching([id = move(m_pending_finish_microtask_id)](auto const& task) {- return task.id() == id;- });- }- finish_notification_steps->function()();- }- // Otherwise, if synchronously notify is false, queue a microtask to run finish notification steps for- // animation unless there is already a microtask queued to run those steps for animation.- else if (!m_pending_finish_microtask_id.has_value()) {- auto& document = HTML::relevant_window(realm.global_object()).associated_document();-- auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document, GC::create_function(GC::Heap::the(), GC::captures(finish_notification_steps, realm), [](auto& finish_notification_steps, auto& realm) {- HTML::TemporaryExecutionContext context { realm };- finish_notification_steps->function()();- }));-- m_pending_finish_microtask_id = task->id();- (void)HTML::main_thread_event_loop().task_queue().add(move(task));- }- }-- // 6. If current finished state is false and animation’s current finished promise is already resolved, set- // animation’s current finished promise to a new promise in the relevant Realm of animation.- if (!current_finished_state && m_is_finished) {- m_current_finished_promise = WebIDL::create_promise_for(relevant_global_object());- m_is_finished = false;- }-- // AD-HOC: An animation disassociated from its target while inert can only be revived through here.- if (m_play_state_when_disassociated_from_target.has_value()- && (pending() || is_relevant() || play_state() != *m_play_state_when_disassociated_from_target)) {- if (auto target = m_effect ? m_effect->target() : nullptr)- target->associate_with_animation(*this);- }-- // AD-HOC: An animation that has finished without filling produces nothing more, so it leaves its target's list.- if (current_finished_state && !pending() && !is_relevant())- schedule_disassociation_from_target();-- if (should_invalidate == ShouldInvalidate::Yes)- invalidate_effect();-}--// https://www.w3.org/TR/web-animations-1/#animation-reset-an-animations-pending-tasks-void Animation::reset_an_animations_pending_tasks()-{- // 1. If animation does not have a pending play task or a pending pause task, abort this procedure.- if (!pending())- return;-- // 2. If animation has a pending play task, cancel that task.- m_pending_play_task = TaskState::None;-- // 3. If animation has a pending pause task, cancel that task.- m_pending_pause_task = TaskState::None;-- // 4. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // OPTIMIZATION: A current ready promise that was never created is a resolved promise nothing can observe. Rejecting- // it does nothing, and the new resolved promise of step 7 is just like it, so steps 5 to 7 only- // matter for a created one.- if (!m_current_ready_promise)- return;-- // 5. Reject animation’s current ready promise with a DOMException named "AbortError".- auto dom_exception = WebIDL::AbortError::create("Animation was cancelled"_utf16);- WebIDL::reject_promise(*m_current_ready_promise, dom_exception);-- // 6. Set the [[PromiseIsHandled]] internal slot of animation’s current ready promise to true.- WebIDL::mark_promise_as_handled(*m_current_ready_promise);-- // 7. Let animation’s current ready promise be the result of creating a new resolved Promise object with value- // animation in the relevant Realm of animation.- m_current_ready_promise = nullptr;-}--// https://drafts.csswg.org/web-animations-2/#ready-bool Animation::is_ready() const-{- // An animation is ready at the first moment where all of the following conditions are true:-- // FIXME: - the user agent has completed any setup required to begin the playback of each inclusive descendant of- // the animation’s associated effect including rendering the first frame of any keyframe effect or- // executing any custom effects associated with an animation effect-- // - the animation is associated with a timeline that is not inactive.- if (!m_timeline || m_timeline->is_inactive())- return false;-- // - the animation’s hold time or start time is resolved.- if (!m_hold_time.has_value() && !m_start_time.has_value())- return false;-- return true;-}--// Step 12 of https://www.w3.org/TR/web-animations-1/#playing-an-animation-section-void Animation::run_pending_play_task()-{- // 1. Assert that at least one of animation’s start time or hold time is resolved.- VERIFY(m_start_time.has_value() || m_hold_time.has_value());-- // 2. Let ready time be the time value of the timeline associated with animation at the moment when animation became- // ready.- // FIXME: We can get a more accurate time here if we record the actual instant we became ready rather than waiting- // to try and run this task- auto ready_time = m_timeline->current_time().value();- // AD-HOC: A new CSS transition of properties the compositor may run stays pending past the rendering update of its- // style change event, which already rendered it, on the compositor or here. It became ready at the time of- // its style change event, from which the compositor runs it, so that a style change a frame later starts- // the next transition from the value on the screen rather than from this transition's start value.- if (auto const* keyframe_effect = as_if<KeyframeEffect>(m_effect.ptr());- is_css_transition() && keyframe_effect && keyframe_effect->may_run_on_the_compositor()- && as<CSS::CSSTransition>(*this).previous_phase() == CSS::CSSTransition::Phase::Idle)- ready_time = { TimeValue::Type::Milliseconds, as<CSS::CSSTransition>(*this).style_change_event_time() };-- // 3. Perform the steps corresponding to the first matching condition below, if any:-- // -> If animation’s hold time is resolved,- if (m_hold_time.has_value()) {- // 1. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // 2. Let new start time be the result of evaluating ready time - hold time / playback rate for animation. If- // the playback rate is zero, let new start time be simply ready time.- auto new_start_time = m_playback_rate != 0.0 ? ready_time - (m_hold_time.value() / m_playback_rate) : ready_time;-- // 3. Set the start time of animation to new start time.- m_start_time = new_start_time;-- // 4. If animation’s playback rate is not 0, make animation’s hold time unresolved.- if (m_playback_rate != 0.0)- m_hold_time = {};- }- // -> If animation’s start time is resolved and animation has a pending playback rate,- else if (m_start_time.has_value() && m_pending_playback_rate.has_value()) {- // 1. Let current time to match be the result of evaluating (ready time - start time) × playback rate for- // animation.- auto current_time_to_match = (ready_time - m_start_time.value()) * m_playback_rate;-- // 2. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // 3. If animation’s playback rate is zero, let animation’s hold time be current time to match.- if (m_playback_rate == 0.0)- m_hold_time = current_time_to_match;-- // 4. Let new start time be the result of evaluating ready time - current time to match / playback rate for- // animation. If the playback rate is zero, let new start time be simply ready time.- auto new_start_time = m_playback_rate != 0.0 ? ready_time - (current_time_to_match / m_playback_rate) : ready_time;-- // 5. Set the start time of animation to new start time.- m_start_time = new_start_time;- }-- // 4. Resolve animation’s current ready promise with animation.- Bindings::resolve_animation_promise(current_ready_promise(), *this);-- // 5. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- // OPTIMIZATION: A new CSS transition can already have a provisional compositor descriptor anchored to its style- // change event time. Keep that descriptor so resolving this task does not restart its visual time.- auto should_invalidate = is_css_transition() && m_effect && is<KeyframeEffect>(*m_effect) && static_cast<KeyframeEffect&>(*m_effect).is_compositor_driven()- ? ShouldInvalidate::No- : ShouldInvalidate::Yes;- update_finished_state(DidSeek::No, SynchronouslyNotify::No, should_invalidate);-- // AD-HOC: A pending animation is not handed to the compositor, and the frame that hands it over once it is no- // longer pending is recorded only if something needs a repaint. Its output may not change, so ask for one.- if (auto target = m_effect ? m_effect->target() : nullptr)- target->set_needs_repaint(InvalidateDisplayList::No);-}--bool Animation::is_ready_to_run_pending_pause_task() const-{- // NB: Step 10 of the procedure to "pause an animation" requires us to schedule the pending pause task to run when- // the following conditions are true:-- // https://www.w3.org/TR/web-animations-1/#pause-an-animation- // https://drafts.csswg.org/web-animations-2/#pausing-an-animation-section- // FIXME: - the user agent has performed any processing necessary to suspend the playback of animation’s associated- // effect, if any.-- // - the animation is associated with a timeline that is not inactive.- if (!m_timeline || m_timeline->is_inactive())- return false;-- // - the animation has a resolved hold time or start time.- if (!m_hold_time.has_value() && !m_start_time.has_value())- return false;-- return true;-}--// Step 10 of https://www.w3.org/TR/web-animations-1/#pause-an-animation-void Animation::run_pending_pause_task()-{- // 1. Let ready time be the time value of the timeline associated with animation at the moment when the user agent- // completed processing necessary to suspend playback of animation’s associated effect.- // FIXME: We can get a more accurate time here if we record the actual instant the above is true rather than waiting- // for this task to run- auto ready_time = m_timeline->current_time().value();-- // 2. If animation’s start time is resolved and its hold time is not resolved, let animation’s hold time be the- // result of evaluating (ready time - start time) × playback rate.- // Note: The hold time might be already set if the animation is finished, or if the animation has a pending play- // task. In either case we want to preserve the hold time as we enter the paused state.- if (m_start_time.has_value() && !m_hold_time.has_value())- m_hold_time = (ready_time - m_start_time.value()) * m_playback_rate;-- // 3. Apply any pending playback rate on animation.- apply_any_pending_playback_rate();-- // 4. Make animation’s start time unresolved.- m_start_time = {};-- // 5. Resolve animation’s current ready promise with animation.- Bindings::resolve_animation_promise(current_ready_promise(), *this);-- // 6. Run the procedure to update an animation’s finished state for animation with the did seek flag set to false,- // and the synchronously notify flag set to false.- update_finished_state(DidSeek::No, SynchronouslyNotify::No);-}--JS::Object& Animation::relevant_global_object() const-{- return m_environment->global_object();-}--GC::Ref<WebIDL::Promise> Animation::current_ready_promise() const-{- if (!m_current_ready_promise) {- // The current ready promise is initially a resolved Promise created using the procedure to create a new- // resolved Promise with the animation itself as its value and created in the relevant Realm of the animation.- m_current_ready_promise = Bindings::create_resolved_animation_promise(*this);- }-- return *m_current_ready_promise;-}--GC::Ref<WebIDL::Promise> Animation::current_finished_promise() const-{- if (!m_current_finished_promise) {- // The current finished promise is initially a pending Promise object.- m_current_finished_promise = WebIDL::create_promise_for(relevant_global_object());- }-- return *m_current_finished_promise;-}--void Animation::invalidate_effect(ChangesPlan changes_plan)-{- if (!m_effect)- return;-- if (!is<KeyframeEffect>(*m_effect))- return;-- auto& effect = static_cast<KeyframeEffect&>(*m_effect);- // The render clock's lanes tick the document's animations as the last rendering update planned them.- if (auto target = effect.target(); changes_plan == ChangesPlan::Yes && target && target->document().layout_node_arena_if_created())- Layout::RustFFI::document_host_note_animation_change(target->document().layout_node_arena_if_created()->host());- effect.invalidate_effect();-}--Animation::Animation(HTML::EnvironmentSettingsObject& environment)- : DOM::EventTarget()- , m_environment(environment)-{- static unsigned int next_animation_list_order = 0;- m_global_animation_list_order = next_animation_list_order++;-}--void Animation::set_provisional_effect(GC::Ref<AnimationEffect> effect)-{- VERIFY(!m_effect);- VERIFY(!effect->associated_animation());- effect->set_associated_animation(this);- m_effect = effect;-}--void Animation::discard_provisional_effect()-{- VERIFY(m_effect);- VERIFY(m_effect->associated_animation() == GC::Ptr<Animation> { *this });- m_effect->set_associated_animation({});- m_effect = nullptr;-}--GC::Ptr<Bindings::Wrappable> Animation::relevant_global_impl() const-{- return HTML::relevant_window_or_worker_global_scope(m_environment->global_object()).this_impl();-}--void Animation::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_environment);- visitor.visit(m_effect);- visitor.visit(m_timeline);- visitor.visit(m_current_ready_promise);- visitor.visit(m_current_finished_promise);- if (m_owning_element.has_value())- m_owning_element->visit(visitor);-}--void Animation::finalize()-{- Base::finalize();- if (m_timeline)- m_timeline->disassociate_with_animation(*this);-}--}--namespace Web::Bindings {--static JS::Value animation_wrapper_value(JS::Realm& realm, Animations::Animation const& animation)-{- return wrap(host_defined_wrapper_world(realm), realm, GC::Ref { const_cast<Animations::Animation&>(animation) }).ptr();-}--GC::Ref<Animations::Animation> construct_animation(JS::Realm& realm, GC::Ptr<Animations::AnimationEffect> effect, Optional<GC::Ptr<Animations::AnimationTimeline>> timeline, size_t argument_count)-{- auto& window = HTML::relevant_window(realm.global_object());- auto selected_timeline = argument_count < 2 ? GC::Ptr<Animations::AnimationTimeline> { window.associated_document().timeline() } : timeline.value();- return Animations::Animation::create(window.associated_document().relevant_settings_object(), effect, selected_timeline);-}--void resolve_animation_promise(WebIDL::Promise& promise, Animations::Animation const& animation)-{- auto& realm = WebIDL::promise_realm(promise);- WebIDL::resolve_promise(promise, animation_wrapper_value(realm, animation));-}--GC::Ref<WebIDL::Promise> create_resolved_animation_promise(Animations::Animation const& animation)-{- auto& realm = HTML::relevant_realm(animation.relevant_global_object());- return WebIDL::create_resolved_promise(realm, animation_wrapper_value(realm, animation));-}--}diff --git a/Libraries/LibWeb/Animations/Animation.h b/Libraries/LibWeb/Animations/Animation.hdeleted file mode 100644index 3ecc34b1e7f..00000000000--- a/Libraries/LibWeb/Animations/Animation.h+++ /dev/null@@ -1,316 +0,0 @@-/*- * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#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>-#include <LibWeb/DOM/AbstractElement.h>-#include <LibWeb/DOM/EventTarget.h>-#include <LibWeb/Forward.h>--namespace Web::Animations {--// Sorted by composite order:-// https://www.w3.org/TR/css-animations-2/#animation-composite-order-enum class AnimationClass {- SMILAnimation,- CSSAnimationWithOwningElement,- CSSTransition,- CSSAnimationWithoutOwningElement,- None,-};--using AnimationReplaceState = Bindings::AnimationReplaceState;-using AnimationPlayState = Bindings::AnimationPlayState;--// https://www.w3.org/TR/web-animations-1/#the-animation-interface-// (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString)-using TimelineRangeBindingValue = Variant<Bindings::TimelineRangeOffset, GC::Ref<CSS::CSSNumericValue>, GC::Ref<CSS::CSSKeywordValue>, Utf16String>;--// Parses an attachment range edge script gives, as KeyframeAnimationOptions's rangeStart and rangeEnd take it.-enum class TimelineRangeEdgeSide : u8 {- Start,- End,-};-WebIDL::ExceptionOr<TimelineRangeEdge> parse_timeline_range_edge(DOM::Document&, TimelineRangeBindingValue const&, TimelineRangeEdgeSide);--class Animation : public DOM::EventTarget {- WEB_WRAPPABLE(Animation, DOM::EventTarget);- GC_DECLARE_ALLOCATOR(Animation);--public:- static constexpr size_t effect_offset() { return offsetof(Animation, m_effect); }- enum class ShouldInvalidate {- Yes,- No,- };-- static GC::Ref<Animation> create(HTML::EnvironmentSettingsObject&, GC::Ptr<AnimationEffect>, GC::Ptr<AnimationTimeline>);-- Utf16FlyString const& id() const { return m_id; }- void set_id(Utf16FlyString value) { m_id = move(value); }-- GC::Ptr<AnimationEffect> effect() const { return m_effect; }- void set_effect(GC::Ptr<AnimationEffect>, ShouldInvalidate = ShouldInvalidate::Yes);-- GC::Ptr<AnimationTimeline> timeline() const { return m_timeline; }- void set_timeline(GC::Ptr<AnimationTimeline>);-- virtual GC::Ptr<AnimationTimeline> timeline_for_bindings() const;- virtual void set_timeline_for_bindings(GC::Ptr<AnimationTimeline> timeline) { set_timeline(timeline); }-- // https://drafts.csswg.org/web-animations-2/#dom-animation-starttime- NullableCSSNumberish start_time_for_bindings() const- {- update_style_if_needed();- return NullableCSSNumberish::from_optional_css_numberish_time(start_time());- }- Optional<TimeValue> start_time() const { return m_start_time; }- Optional<TimeValue> hold_time() const { return m_hold_time; }- virtual WebIDL::ExceptionOr<void> set_start_time_for_bindings(NullableCSSNumberish const&);-- void calculate_auto_aligned_start_time();- void normalize_timing_against_attachment_interval();-- // https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range- AnimationAttachmentRange const& range() const { return m_range; }- void set_range(AnimationAttachmentRange const&);-- // https://drafts.csswg.org/web-animations-2/#dom-animation-rangestart- TimelineRangeBindingValue range_start_for_bindings() const;- virtual WebIDL::ExceptionOr<void> set_range_start_for_bindings(TimelineRangeBindingValue const&);- // https://drafts.csswg.org/web-animations-2/#dom-animation-rangeend- TimelineRangeBindingValue range_end_for_bindings() const;- virtual WebIDL::ExceptionOr<void> set_range_end_for_bindings(TimelineRangeBindingValue const&);- // The start and the end of the attachment range on a progress-based timeline, as timeline times.- Optional<AttachmentInterval> attachment_interval() const;-- // https://drafts.csswg.org/web-animations-2/#dom-animation-currenttime- NullableCSSNumberish current_time_for_bindings() const;- Optional<TimeValue> current_time() const;- Optional<TimeValue> current_time_for_observation() const;- Optional<TimeValue> current_time_at(Optional<TimeValue> timeline_time) const;- virtual WebIDL::ExceptionOr<void> set_current_time_for_bindings(NullableCSSNumberish const&);-- double playback_rate() const { return m_playback_rate; }- virtual WebIDL::ExceptionOr<void> set_playback_rate(double value);-- AnimationPlayState play_state() const;- AnimationPlayState play_state_for_bindings();-- bool is_relevant() const;-- bool is_replaceable() const;- AnimationReplaceState replace_state() const { return m_replace_state; }- void set_replace_state(AnimationReplaceState value);-- // https://www.w3.org/TR/web-animations-1/#dom-animation-pending- bool pending_for_bindings() const;- bool pending() const { return m_pending_play_task == TaskState::Scheduled || m_pending_pause_task == TaskState::Scheduled; }- bool has_pending_play_task() const { return m_pending_play_task == TaskState::Scheduled; }-- // https://www.w3.org/TR/web-animations-1/#dom-animation-ready- GC::Ref<WebIDL::Promise> ready_for_bindings() const;- GC::Ref<WebIDL::Promise> ready() const- {- update_style_if_needed();- return current_ready_promise();- }-- // https://www.w3.org/TR/web-animations-1/#dom-animation-finished- GC::Ref<WebIDL::Promise> finished_for_bindings();- 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();- void set_onfinish(GC::Ptr<WebIDL::CallbackType>);- GC::Ptr<WebIDL::CallbackType> oncancel();- void set_oncancel(GC::Ptr<WebIDL::CallbackType>);- GC::Ptr<WebIDL::CallbackType> onremove();- void set_onremove(GC::Ptr<WebIDL::CallbackType>);-- enum class AutoRewind {- Yes,- No,- };- virtual void cancel(ShouldInvalidate = ShouldInvalidate::Yes);- WebIDL::ExceptionOr<void> finish();- virtual WebIDL::ExceptionOr<void> play(ShouldInvalidate = ShouldInvalidate::Yes);- WebIDL::ExceptionOr<void> play_an_animation(AutoRewind, ShouldInvalidate = ShouldInvalidate::Yes);- virtual WebIDL::ExceptionOr<void> pause();- virtual WebIDL::ExceptionOr<void> update_playback_rate(double);- virtual WebIDL::ExceptionOr<void> reverse();- void persist();- WebIDL::ExceptionOr<void> commit_styles();-- Optional<TimeValue> convert_an_animation_time_to_timeline_time(Optional<TimeValue>) const;- Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue>) const;-- GC::Ptr<DOM::Document> document_for_timing() const;- void update();- // Runs the pending play task of the animation if it is ready.- void run_pending_play_task_if_ready();-- void effect_timing_changed(Badge<AnimationEffect>);-- virtual bool is_css_animation() const { return false; }- virtual bool is_css_transition() const { return false; }- virtual bool is_smil_animation() const { return false; }-- Optional<DOM::AbstractElement> owning_element() const { return m_owning_element; }- void set_owning_element(Optional<DOM::AbstractElement>&& value) { m_owning_element = move(value); }- void schedule_disassociation_from_target() { m_disassociation_from_target_pending = true; }- bool disassociation_from_target_pending() const { return m_disassociation_from_target_pending; }- void disassociate_from_target_if_inert();- void did_associate_with_target();- void update_style_if_needed() const;-- virtual AnimationClass animation_class() const { return AnimationClass::None; }- virtual int class_specific_composite_order(GC::Ref<Animation>) const { return 0; }-- unsigned int global_animation_list_order() const { return m_global_animation_list_order; }-- auto release_saved_cancel_time() { return move(m_saved_cancel_time); }-- TimeValue associated_effect_end() const;- JS::Object& relevant_global_object() const;--protected:- Animation(HTML::EnvironmentSettingsObject&);-- HTML::EnvironmentSettingsObject& relevant_settings_object() const { return *m_environment; }-- // Install an effect whose target must not observe this animation until a surrounding style- // stabilization epoch commits it.- void set_provisional_effect(GC::Ref<AnimationEffect>);- void discard_provisional_effect();-- void effect_timing_changed_by_style();-- virtual void visit_edges(Cell::Visitor&) override;- virtual void finalize() override;--private:- AnimationPlayState play_state_at(Optional<TimeValue> current_time) const;-- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;-- enum class TaskState {- None,- Scheduled,- };-- enum class DidSeek {- Yes,- No,- };-- enum class SynchronouslyNotify {- Yes,- No,- };-- double effective_playback_rate() const;-- WebIDL::ExceptionOr<Optional<TimeValue>> validate_a_css_numberish_time(NullableCSSNumberish const&) const;-- void apply_any_pending_playback_rate();- WebIDL::ExceptionOr<void> silently_set_current_time(Optional<TimeValue>);- void update_finished_state(DidSeek, SynchronouslyNotify, ShouldInvalidate = ShouldInvalidate::Yes, Optional<TimeValue> observed_current_time = {});- void reset_an_animations_pending_tasks();-- bool is_ready() const;- void run_pending_play_task();-- bool is_ready_to_run_pending_pause_task() const;- void run_pending_pause_task();-- GC::Ref<WebIDL::Promise> current_ready_promise() const;- GC::Ref<WebIDL::Promise> current_finished_promise() const;-- // Whether an invalidation changes the animation as the last rendering update planned it for the render clock, rather- // than move it on in time, as a rendering update does.- enum class ChangesPlan : bool {- No,- Yes,- };- void invalidate_effect(ChangesPlan = ChangesPlan::Yes);-- // https://www.w3.org/TR/web-animations-1/#dom-animation-id- Utf16FlyString m_id;-- // https://www.w3.org/TR/web-animations-1/#global-animation-list- unsigned int m_global_animation_list_order { 0 };-- GC::Ref<HTML::EnvironmentSettingsObject> m_environment;-- // https://www.w3.org/TR/web-animations-1/#dom-animation-effect- GC::Ptr<AnimationEffect> m_effect;-- // https://www.w3.org/TR/web-animations-1/#dom-animation-timeline- GC::Ptr<AnimationTimeline> m_timeline;-- // https://www.w3.org/TR/web-animations-1/#animation-start-time- Optional<TimeValue> m_start_time {};-- bool m_auto_align_start_time { false };-- AnimationAttachmentRange m_range;-- // The attachment interval the effect's timing was last normalized against.- Optional<AttachmentInterval> m_normalized_attachment_interval;-- // https://www.w3.org/TR/web-animations-1/#animation-hold-time- Optional<TimeValue> m_hold_time {};-- // https://www.w3.org/TR/web-animations-1/#previous-current-time- Optional<TimeValue> m_previous_current_time {};-- // https://www.w3.org/TR/web-animations-1/#playback-rate- double m_playback_rate { 1.0 };-- // https://www.w3.org/TR/web-animations-1/#pending-playback-rate- Optional<double> m_pending_playback_rate {};-- // https://www.w3.org/TR/web-animations-1/#dom-animation-replacestate- AnimationReplaceState m_replace_state { AnimationReplaceState::Active };-- // Note: The following promises are initialized lazily to avoid constructing them outside of an execution context- // https://www.w3.org/TR/web-animations-1/#current-ready-promise- mutable GC::Ptr<WebIDL::Promise> m_current_ready_promise;-- // https://www.w3.org/TR/web-animations-1/#current-finished-promise- mutable GC::Ptr<WebIDL::Promise> m_current_finished_promise;- bool m_is_finished { false };-- // https://www.w3.org/TR/web-animations-1/#pending-play-task- TaskState m_pending_play_task { TaskState::None };-- // https://www.w3.org/TR/web-animations-1/#pending-pause-task- TaskState m_pending_pause_task { TaskState::None };-- // https://www.w3.org/TR/css-animations-2/#owning-element-section- Optional<DOM::AbstractElement> m_owning_element;-- bool m_disassociation_from_target_pending { false };- Optional<AnimationPlayState> m_play_state_when_disassociated_from_target;-- Optional<HTML::TaskID> m_pending_finish_microtask_id;-- Optional<TimeValue> m_saved_cancel_time;-};--}diff --git a/Libraries/LibWeb/Animations/Animation.idl b/Libraries/LibWeb/Animations/Animation.idlindex f0b7db432ca..6ffdcb91327 100644--- a/Libraries/LibWeb/Animations/Animation.idl+++ b/Libraries/LibWeb/Animations/Animation.idl@@ -1,22 +1,21 @@// https://drafts.csswg.org/web-animations-1/#the-animation-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface Animation : EventTarget {- [ImplementedInBindings, NeedsArgumentCount] constructor(optional AnimationEffect? effect = null,- optional AnimationTimeline? timeline);-- attribute [FlyString] DOMString id;- [DirectGetter] attribute AnimationEffect? effect;- [ImplementedAs=timeline_for_bindings] attribute AnimationTimeline? timeline;- [ImplementedAs=start_time_for_bindings] attribute CSSNumberish? startTime;- [ImplementedAs=current_time_for_bindings] attribute CSSNumberish? currentTime;+ constructor(optional AnimationEffect? effect = null, optional AnimationTimeline? timeline);++ attribute DOMString id;+ attribute AnimationEffect? effect;+ attribute AnimationTimeline? timeline;+ attribute CSSNumberish? startTime;+ attribute CSSNumberish? currentTime;attribute double playbackRate;- [ImplementedAs=range_start_for_bindings] attribute (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeStart;- [ImplementedAs=range_end_for_bindings] attribute (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeEnd;- [ImplementedAs=play_state_for_bindings] readonly attribute AnimationPlayState playState;+ attribute TimelineRangeValue rangeStart;+ attribute TimelineRangeValue rangeEnd;+ readonly attribute AnimationPlayState playState;readonly attribute AnimationReplaceState replaceState;- [ImplementedAs=pending_for_bindings] readonly attribute boolean pending;- [ImplementedAs=ready_for_bindings] readonly attribute Promise<Animation> ready;- [ImplementedAs=finished_for_bindings] readonly attribute Promise<Animation> finished;+ readonly attribute boolean pending;+ readonly attribute Promise<Animation> ready;+ readonly attribute Promise<Animation> finished;attribute EventHandler onfinish;attribute EventHandler oncancel;@@ -32,6 +31,9 @@ interface Animation : EventTarget {[CEReactions] undefined commitStyles();};+// AD-HOC: The union of the edges of an attachment range that script sets, which the spec names no typedef of.+typedef (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) TimelineRangeValue;+// https://drafts.csswg.org/web-animations-2/#dictdef-timelinerangeoffsetdictionary TimelineRangeOffset {CSSOMString? rangeName;@@ -46,10 +48,10 @@ enum AnimationReplaceState { "active", "removed", "persisted" };// https://drafts.csswg.org/web-animations-1/#extensions-to-the-document-interfacepartial interface Document {- readonly attribute DocumentTimeline timeline;+ [ImplementedIn=Rust] readonly attribute DocumentTimeline timeline;};// https://drafts.csswg.org/web-animations-1/#extensions-to-the-documentorshadowroot-interface-mixinpartial interface mixin DocumentOrShadowRoot {- sequence<Animation> getAnimations();+ [ImplementedIn=Rust] sequence<Animation> getAnimations();};diff --git a/Libraries/LibWeb/Animations/AnimationEffect.cpp b/Libraries/LibWeb/Animations/AnimationEffect.cppindex 31b773dc4a8..ee19b408def 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.cpp+++ b/Libraries/LibWeb/Animations/AnimationEffect.cpp@@ -4,15 +4,13 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/ScopeGuard.h>#include <LibGC/RootVector.h>+#include <LibJS/HostClassBuilder.h>#include <LibJS/Runtime/VM.h>-#include <LibWeb/Animations/Animation.h>#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/Bindings/AnimationEffect.h>-#include <LibWeb/CSS/CSSNumericValue.h>+#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/CSS/ComputedStyleWorkingSet.h>#include <LibWeb/CSS/ComputedValues.h>#include <LibWeb/CSS/Parser/Parser.h>@@ -31,8 +29,6 @@namespace Web::Animations {-GC_DEFINE_ALLOCATOR(AnimationEffect);-AnimationUpdateContext::ElementData::ElementData() = default;AnimationUpdateContext::ElementData::ElementData(CSS::InstalledStyle style_before_update, RefPtr<CSS::ComputedStyleWorkingSet> target_style)@@ -47,472 +43,107 @@ AnimationUpdateContext::ElementData& AnimationUpdateContext::ElementData::operatAnimationUpdateContext::ElementData::~ElementData() = default;-AnimationUpdateContext::AnimationUpdateContext() = default;--Bindings::FillMode css_fill_mode_to_bindings_fill_mode(CSS::AnimationFillMode mode)-{- switch (mode) {- case CSS::AnimationFillMode::Backwards:- return Bindings::FillMode::Backwards;- case CSS::AnimationFillMode::Both:- return Bindings::FillMode::Both;- case CSS::AnimationFillMode::Forwards:- return Bindings::FillMode::Forwards;- case CSS::AnimationFillMode::None:- return Bindings::FillMode::None;- default:- VERIFY_NOT_REACHED();- }-}--Bindings::PlaybackDirection css_animation_direction_to_bindings_playback_direction(CSS::AnimationDirection direction)-{- switch (direction) {- case CSS::AnimationDirection::Alternate:- return Bindings::PlaybackDirection::Alternate;- case CSS::AnimationDirection::AlternateReverse:- return Bindings::PlaybackDirection::AlternateReverse;- case CSS::AnimationDirection::Normal:- return Bindings::PlaybackDirection::Normal;- case CSS::AnimationDirection::Reverse:- return Bindings::PlaybackDirection::Reverse;- default:- VERIFY_NOT_REACHED();- }-}--Bindings::OptionalEffectTiming to_optional_effect_timing(Bindings::EffectTiming const& effect_timing)-{- return {- .delay = effect_timing.delay,- .direction = effect_timing.direction,- .duration = effect_timing.duration.visit(- [](double const& value) -> Variant<double, Utf16String> { return value; },- [](Utf16String const& value) -> Variant<double, Utf16String> { return value; },- // NB: We check that this isn't the case in the caller- [](GC::Ref<CSS::CSSNumericValue>) -> Variant<double, Utf16String> { VERIFY_NOT_REACHED(); }),- .easing = effect_timing.easing,- .end_delay = effect_timing.end_delay,- .fill = effect_timing.fill,- .iteration_start = effect_timing.iteration_start,- .iterations = effect_timing.iterations,- };-}--// https://www.w3.org/TR/web-animations-1/#dom-animationeffect-gettiming-Bindings::EffectTiming AnimationEffect::get_timing() const-{- update_style_if_needed();-- // 1. Returns the specified timing properties for this animation effect.- return {- .delay = m_specified_start_delay,- .direction = m_playback_direction,- .duration = m_specified_iteration_duration,- .easing = m_timing_function.to_utf16_string(),- .end_delay = m_specified_end_delay,- .fill = m_fill_mode,- .iteration_start = m_iteration_start,- .iterations = m_iteration_count,- };-}--// https://www.w3.org/TR/web-animations-1/#dom-animationeffect-getcomputedtiming-// https://drafts.csswg.org/web-animations-2/#dom-animationeffect-getcomputedtiming-Bindings::ComputedEffectTiming AnimationEffect::get_computed_timing() const-{- update_style_if_needed();-- if (m_associated_animation) {- // NB: Observing the current time can ask for the phase of this effect, which must not read the time it observed- // last.- auto observed_local_time = m_associated_animation->current_time_for_observation();- m_has_local_time_override_for_observation = true;- m_local_time_override_for_observation = observed_local_time;- }- ScopeGuard clear_local_time_override = [&] {- m_has_local_time_override_for_observation = false;- };-- // 1. Returns the calculated timing properties for this animation effect.-- // Note: Although some of the attributes of the object returned by getTiming() and getComputedTiming() are common,- // their values may differ in the following ways:-- // - duration: while getTiming() may return the string auto, getComputedTiming() must return a number- // corresponding to the calculated value of the iteration duration as defined in the description of the- // duration member of the EffectTiming interface.- //- // If duration is the string auto, this attribute will return the current calculated value of the intrinsic- // iteration duration, which may be a expressed as a double representing the duration in milliseconds or a- // percentage when the effect is associated with a progress-based timeline.- auto duration = m_iteration_duration.as_css_numberish();-- // - fill: likewise, while getTiming() may return the string auto, getComputedTiming() must return the specific- // FillMode used for timing calculations as defined in the description of the fill member of the EffectTiming- // interface.- //- // In this level of the specification, that simply means that an auto value is replaced by the none FillMode.- auto fill = m_fill_mode == Bindings::FillMode::Auto ? Bindings::FillMode::None : m_fill_mode;-- Bindings::ComputedEffectTiming computed_timing {};- computed_timing.delay = m_specified_start_delay;- computed_timing.end_delay = m_specified_end_delay;- computed_timing.fill = fill;- computed_timing.iteration_start = m_iteration_start;- computed_timing.iterations = m_iteration_count;- computed_timing.duration = duration;- computed_timing.direction = m_playback_direction;- computed_timing.easing = m_timing_function.to_utf16_string();- 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;-}--GC::Ptr<AnimationTimeline> AnimationEffect::associated_timeline() const-{- if (!m_associated_animation)- return {};-- return m_associated_animation->timeline();-}--Optional<TimeValue> AnimationEffect::timeline_duration() const-{- auto timeline = associated_timeline();- if (!timeline)- return {};-- // AD-HOC: The duration of a progress-based timeline, as an animation attached to a range of it sees it, is the- // length of its attachment range. This matches WebKit.- // An attachment range whose end comes before its start is empty.- if (auto interval = m_associated_animation->attachment_interval(); interval.has_value())- return max(interval->end - interval->start, TimeValue { TimeValue::Type::Percentage, 0 });-- return timeline->duration();-}--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()+void AnimationUpdateContext::ElementData::visit_edges(GC::Cell::Visitor& visitor){- 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;+ for (auto const& effect : effects)+ effect.visit_edges(visitor);}-// https://www.w3.org/TR/web-animations-1/#dom-animationeffect-updatetiming-// https://www.w3.org/TR/web-animations-1/#update-the-timing-properties-of-an-animation-effect-// https://drafts.csswg.org/web-animations-2/#updating-animationeffect-timing-WebIDL::ExceptionOr<void> AnimationEffect::update_timing(Bindings::OptionalEffectTiming const& timing)+void AnimationUpdateContext::add_effect(DOM::AbstractElement abstract_element, EffectRef const& effect){- // 1. If the iterationStart member of input exists and is less than zero, throw a TypeError and abort this- // procedure.- if (timing.iteration_start.has_value() && timing.iteration_start.value() < 0.0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid iteration start value"_utf16 };-- // 2. If the iterations member of input exists, and is less than zero or is the value NaN, throw a TypeError and- // abort this procedure.- if (timing.iterations.has_value() && (timing.iterations.value() < 0.0 || isnan(timing.iterations.value())))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid iteration count value"_utf16 };-- // 3. If the duration member of input exists, and is less than zero or is the value NaN, throw a TypeError and- // abort this procedure.- // Note: "auto", the only valid string value, is treated as 0.- auto& duration = timing.duration;- auto has_valid_duration_value = [&] {- if (!duration.has_value())- return true;- if (duration->has<double>() && (duration->get<double>() < 0.0 || isnan(duration->get<double>())))- return false;- if (duration->has<Utf16String>() && (duration->get<Utf16String>() != "auto"sv))- return false;- return true;- }();- if (!has_valid_duration_value)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid duration value"_utf16 };-- // 4. If the easing member of input exists but cannot be parsed using the <easing-function> production- // [CSS-EASING-1], throw a TypeError and abort this procedure.- Optional<CSS::EasingFunction> easing_value;- if (timing.easing.has_value()) {- easing_value = parse_easing_string(timing.easing.value());- if (!easing_value.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid easing function"_utf16 };- }-- // 5. Assign each member that exists in input to the corresponding timing property of effect as follows:-- // - delay → specified start delay- if (timing.delay.has_value())- m_specified_start_delay = timing.delay.value();-- // - endDelay → specified end delay- if (timing.end_delay.has_value())- m_specified_end_delay = timing.end_delay.value();-- // - fill → fill mode- if (timing.fill.has_value())- m_fill_mode = timing.fill.value();-- // - iterationStart → iteration start- if (timing.iteration_start.has_value())- m_iteration_start = timing.iteration_start.value();-- // - iterations → iteration count- if (timing.iterations.has_value())- m_iteration_count = timing.iterations.value();-- // - duration → specified iteration duration- if (timing.duration.has_value())- m_specified_iteration_duration = timing.duration.value();-- // - direction → playback direction- if (timing.direction.has_value())- m_playback_direction = timing.direction.value();-- // - easing → timing function- if (easing_value.has_value())- m_timing_function = easing_value.value();-- // 6. Follow the procedure to normalize specified timing.- normalize_specified_timing();-- if (auto* keyframe_effect = as_if<KeyframeEffect>(*this))- keyframe_effect->clear_per_frame_style_update_cache();-- // AD-HOC: Notify the associated animation that the effect timing has changed.- if (auto animation = m_associated_animation)- animation->effect_timing_changed({});+ auto& style_computer = abstract_element.element().document().style_computer();+ auto& element_data = elements.ensure(abstract_element, [&abstract_element, &style_computer] {+ auto const& style = abstract_element.installed_style();+ if (!style)+ return ElementData {};+ auto computed_properties = style_computer.reconstruct_computed_properties_for_animation(style);+ return ElementData { style, move(computed_properties) };+ });- return {};+ if (!element_data.target_style)+ return;+ element_data.effects.append(effect);}-void AnimationEffect::set_associated_animation(GC::Ptr<Animation> value)-{- m_associated_animation = value;- if (auto* keyframe_effect = as_if<KeyframeEffect>(*this))- keyframe_effect->invalidate_animation_preparation();-- // NB: The normalization of the specified timing depends on the timeline of the associated animation.- normalize_specified_timing();-}--GC::Ptr<Bindings::Wrappable> AnimationEffect::relevant_global_impl() const-{- if (m_associated_animation)- return static_cast<Bindings::Wrappable&>(*m_associated_animation).relevant_global_impl();- return nullptr;-}--void AnimationEffect::update_style_if_needed() const-{- if (m_associated_animation)- m_associated_animation->update_style_if_needed();-}--// https://www.w3.org/TR/web-animations-1/#local-time-Optional<TimeValue> AnimationEffect::local_time() const-{- if (m_has_local_time_override_for_observation)- return m_local_time_override_for_observation;-- // The local time of an animation effect at a given moment is based on the first matching condition from the- // following:-- // -> If the animation effect is associated with an animation,- if (m_associated_animation) {- // the local time is the current time of the animation.- return m_associated_animation->current_time();- }+AnimationUpdateContext::AnimationUpdateContext() = default;- // -> Otherwise,- // the local time is unresolved.- return {};-}+extern "C" {-RustFFI::AnimationEffectTiming AnimationEffect::effect_timing(Bindings::FillMode fill_mode) const-{- 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)),- };+// Declared in Bindings/Rust/src/animations/animation_effect.rs and keyframe_effect.rs.+void web_animation_effect_visit_host_cells(RustFFI::AnimationEffectCell const*, void* visitor);+void web_animation_effect_set_target(RustFFI::AnimationEffectCell const*, DOM::Element*, bool update);+void web_animation_effect_invalidate(RustFFI::AnimationEffectCell const*);+void web_animation_effect_set_composite(RustFFI::AnimationEffectCell const*, CSS::StyleValueFFI::FfiCompositeOperation);+void web_animation_effect_set_keyframe_set(RustFFI::AnimationEffectCell const*, RustFFI::KeyframeSet const*);+DOM::Element* web_animation_element_of_wrapper(JSObject*);+JSObject* web_animation_wrap_element(void* realm, DOM::Element*);+void* web_animation_document_timeline(JSObject* document_wrapper);}-RustFFI::EffectTimingSnapshot AnimationEffect::timing_snapshot() const+EffectRef EffectRef::create_keyframe_effect(){- 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 },- };+ return EffectRef::adopt(*RustFFI::animations_effect_create());}-AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing_at(Optional<TimeValue> const& local_time, Bindings::FillMode fill_mode, WithTransformedProgress with_transformed_progress, EndpointInclusiveActiveInterval endpoint_inclusive) const+void EffectRef::visit_edges(GC::Cell::Visitor& visitor) const{- 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();+ if (auto* effect = static_cast<GC::Cell*>(RustFFI::animations_effect_facade(&record()))) {+ visitor.visit(effect);+ return;}- 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);-}--// What follows from the effect's timing alone, without a local time.-AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing_alone() const-{- auto timing = effect_timing(m_fill_mode);- return RustFFI::animations_resolve_effect_timing(&timing, to_ffi({}), nullptr, nullptr, nullptr, false);+ visitor.visit(target());}-AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing() const+void web_animation_effect_visit_host_cells(RustFFI::AnimationEffectCell const* record, void* visitor){- return resolve_timing_at(local_time(), m_fill_mode);+ auto& cell_visitor = *static_cast<GC::Cell::Visitor*>(visitor);+ EffectRef effect { *record };+ if (auto animation = effect.associated_animation(); animation.has_value())+ animation->visit_edges(cell_visitor);+ cell_visitor.visit(effect.target());}-// https://www.w3.org/TR/web-animations-1/#end-time-TimeValue AnimationEffect::end_time() const+void web_animation_effect_set_target(RustFFI::AnimationEffectCell const* record, DOM::Element* target, bool update){- return resolve_timing_alone().end_time;+ EffectRef { *record }.set_target(target, update ? EffectRef::InvalidateEffect::Yes : EffectRef::InvalidateEffect::No);}-// https://www.w3.org/TR/web-animations-1/#active-duration-TimeValue AnimationEffect::active_duration() const+void web_animation_effect_invalidate(RustFFI::AnimationEffectCell const* record){- return resolve_timing_alone().active_duration;+ EffectRef { *record }.invalidate();}-// https://www.w3.org/TR/web-animations-1/#before-active-boundary-time-TimeValue AnimationEffect::before_active_boundary_time() const+void web_animation_effect_set_composite(RustFFI::AnimationEffectCell const* record, CSS::StyleValueFFI::FfiCompositeOperation composite){- return resolve_timing_alone().before_active_boundary_time;+ EffectRef { *record }.set_composite(composite);}-// https://www.w3.org/TR/web-animations-1/#active-after-boundary-time-TimeValue AnimationEffect::after_active_boundary_time() const+void web_animation_effect_set_keyframe_set(RustFFI::AnimationEffectCell const* record, RustFFI::KeyframeSet const* keyframe_set){- return resolve_timing_alone().after_active_boundary_time;+ EffectRef { *record }.set_keyframe_set(KeyframeSetHandle::adopt(keyframe_set));}-// https://www.w3.org/TR/web-animations-1/#calculating-the-active-time-Optional<TimeValue> AnimationEffect::active_time() const+DOM::Element* web_animation_element_of_wrapper(JSObject* wrapper){- return from_ffi(resolve_timing().active_time);+ return Bindings::impl_from<DOM::Element>(JS::HostABI::object_from_abi(wrapper));}-Optional<TimeValue> AnimationEffect::active_time_using_fill(Bindings::FillMode fill_mode) const+static JSObject* wrap_in_realm(void* realm, GC::Ref<Bindings::Wrappable> object){- return from_ffi(resolve_timing_at(local_time(), fill_mode).active_time);+ auto& js_realm = *static_cast<JS::Realm*>(realm);+ auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(js_realm), js_realm, object);+ return JS::HostABI::object_to_abi(wrapper.ptr());}-// https://www.w3.org/TR/web-animations-1/#current-bool AnimationEffect::is_current() const+JSObject* web_animation_wrap_element(void* realm, DOM::Element* element){- return resolve_timing().is_current;+ return wrap_in_realm(realm, *element);}-// https://www.w3.org/TR/web-animations-1/#in-effect-bool AnimationEffect::is_in_effect() const+void* web_animation_document_timeline(JSObject* document_wrapper){- return resolve_timing().is_in_effect;-}--AnimationEffect::Phase AnimationEffect::phase() const-{- return resolve_timing().phase;-}--Optional<double> AnimationEffect::current_iteration() const-{- return current_iteration(resolve_timing());-}--// https://www.w3.org/TR/web-animations-1/#current-iteration-Optional<double> AnimationEffect::current_iteration(ResolvedTiming const& timing) const-{- 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-{- 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)-{- if (auto style_value = parse_css_value(CSS::Parser::ParsingParams(), value, CSS::PropertyID::AnimationTimingFunction)) {- if (style_value->is_unresolved() || style_value->is_css_wide_keyword())- return {};-- auto easing_values = style_value->as_value_list().values();-- if (easing_values.size() != 1)- return {};-- // FIXME: We should absolutize the style value to resolve relative lengths within calcs- return CSS::EasingFunction::from_style_value(easing_values[0]);- }-- return {};-}--AnimationEffect::AnimationEffect() = default;--void AnimationEffect::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_associated_animation);+ auto& document = *Bindings::impl_from<DOM::Document>(JS::HostABI::object_from_abi(document_wrapper));+ return document.timeline().ptr();}AnimationUpdateContext::~AnimationUpdateContext()@@ -526,12 +157,13 @@ void AnimationUpdateContext::publish()struct Sample {DOM::AbstractElement element;ElementData const& data;- Vector<GC::Ref<KeyframeEffect>> effects;+ Vector<EffectRef> effects;void visit_edges(GC::Cell::Visitor& visitor){element.visit_edges(visitor);- visitor.visit(effects);+ for (auto const& effect : effects)+ effect.visit_edges(visitor);}};GC::RootVector<Sample> samples;@@ -548,17 +180,17 @@ void AnimationUpdateContext::publish()// never among the collected effects, but their values are already part of the published// style. Collect them first, in composite order below every associated effect, or this// update would rebuild the style without them.- GC::RootVector<GC::Ref<KeyframeEffect>> effects_to_collect;- target->document().style_computer().for_each_provisional_transition_effect(element, [&](KeyframeEffect& effect) {+ Vector<EffectRef> effects_to_collect;+ target->document().style_computer().for_each_provisional_transition_effect(element, [&](EffectRef const& effect) {effects_to_collect.append(effect);});- for (auto& animation : target->associated_animations_in_composite_order()) {- if (animation->is_idle() || !animation->effect() || !is<KeyframeEffect>(*animation->effect()))+ for (auto const& animation : target->associated_animations_in_composite_order()) {+ auto effect = animation.effect();+ if (!effect.has_value() || animation.timing_state().play_state == RustFFI::AnimationPlayState::Idle)continue;- auto& effect = static_cast<KeyframeEffect&>(*animation->effect());- if (effect.target() != target || effect.pseudo_element_type() != element.pseudo_element())+ if (effect->target() != target.ptr() || effect->pseudo_element_type() != element.pseudo_element())continue;- effects_to_collect.append(effect);+ effects_to_collect.append(*effect);}// A dirty effect may have just become irrelevant. Include it once so rebuilding the// animated overlay removes its terminal contribution.diff --git a/Libraries/LibWeb/Animations/AnimationEffect.h b/Libraries/LibWeb/Animations/AnimationEffect.hindex a6e82b9b23c..b2feab93a9f 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.h+++ b/Libraries/LibWeb/Animations/AnimationEffect.h@@ -12,27 +12,16 @@#include <AK/Variant.h>#include <LibGC/RootHashMap.h>#include <LibGC/RootVector.h>+#include <LibWeb/Animations/KeyframeSetHandle.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/Animations/RustFFI.h>#include <LibWeb/Animations/TimeValue.h>-#include <LibWeb/Bindings/AnimationEffect.h>-#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/CSS/EasingFunction.h>#include <LibWeb/CSS/InstalledStyle.h>#include <LibWeb/CSS/PropertyNameAndID.h>namespace Web::Animations {-using FillMode = Bindings::FillMode;-using PlaybackDirection = Bindings::PlaybackDirection;-using EffectTiming = Bindings::EffectTiming;-using ComputedEffectTiming = Bindings::ComputedEffectTiming;-using OptionalEffectTiming = Bindings::OptionalEffectTiming;-using EffectTimingDuration = Variant<double, Utf16String>;--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() };@@ -52,6 +41,11 @@ inline Optional<double> from_ffi(RustFFI::OptionalNumber const& number)return number.value;}+inline RustFFI::OptionalNumber to_ffi(Optional<double> const& number)+{+ return { .value = number.value_or(0), .has_value = number.has_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 {@@ -61,9 +55,12 @@ struct AnimationUpdateContext {ElementData& operator=(ElementData&&);~ElementData();+ // NB: The effects keep their AnimationEffects alive while the update holds them.+ void visit_edges(GC::Cell::Visitor&);+CSS::InstalledStyle style_before_update;RefPtr<CSS::ComputedStyleWorkingSet> target_style;- GC::RootVector<GC::Ref<KeyframeEffect>> effects;+ Vector<EffectRef> effects;// Whether the record the update samples over was computed by this style update, so that the base// adjustments the sampled values feed into were made over the values the element holds now.bool base_is_current { false };@@ -77,167 +74,11 @@ struct AnimationUpdateContext {// otherwise does.void publish();+ // Notes that the update samples `effect` over the style `abstract_element` holds.+ void add_effect(DOM::AbstractElement, EffectRef const& effect);+// NOTE: This is lazily populated by KeyframeEffects as their respective animations are applied to an element.GC::RootHashMap<DOM::AbstractElement, ElementData> elements;};-// https://www.w3.org/TR/web-animations-1/#the-animationeffect-interface-class AnimationEffect : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(AnimationEffect, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(AnimationEffect);--public:- static Optional<CSS::EasingFunction> parse_easing_string(Utf16View value);-- Bindings::EffectTiming get_timing() const;- Bindings::ComputedEffectTiming get_computed_timing() const;- WebIDL::ExceptionOr<void> update_timing(Bindings::OptionalEffectTiming const& timing = {});-- TimeValue start_delay() const { return m_start_delay; }- void set_specified_start_delay(double start_delay) { m_specified_start_delay = start_delay; }-- TimeValue end_delay() const { return m_end_delay; }- void set_specified_end_delay(double end_delay) { m_specified_end_delay = end_delay; }-- Bindings::FillMode fill_mode() const { return m_fill_mode; }- void set_fill_mode(Bindings::FillMode fill_mode) { m_fill_mode = fill_mode; }-- double iteration_start() const { return m_iteration_start; }- void set_iteration_start(double iteration_start) { m_iteration_start = iteration_start; }-- double iteration_count() const { return m_iteration_count; }- void set_iteration_count(double iteration_count) { m_iteration_count = iteration_count; }-- TimeValue const& iteration_duration() const { return m_iteration_duration; }- void set_specified_iteration_duration(Variant<double, Utf16String> iteration_duration) { m_specified_iteration_duration = move(iteration_duration); }-- Bindings::PlaybackDirection playback_direction() const { return m_playback_direction; }- void set_playback_direction(Bindings::PlaybackDirection playback_direction) { m_playback_direction = playback_direction; }-- CSS::EasingFunction const& timing_function() const { return m_timing_function; }- void set_timing_function(CSS::EasingFunction value) { m_timing_function = move(value); }-- GC::Ptr<Animation> associated_animation() const { return m_associated_animation; }- void set_associated_animation(GC::Ptr<Animation> value);-- TimeValue end_time() const;- Optional<TimeValue> local_time() const;- TimeValue active_duration() const;- Optional<TimeValue> active_time() const;- Optional<TimeValue> active_time_using_fill(Bindings::FillMode) const;-- bool is_current() const;- bool is_in_effect() const;-- TimeValue before_active_boundary_time() const;- TimeValue after_active_boundary_time() const;-- // Keep this enum up to date with CSSTransition::Phase.- using Phase = RustFFI::AnimationEffectPhase;- Phase phase() const;-- // Everything a progress calculation needs, resolved together from one local time.- using ResolvedTiming = RustFFI::FfiResolvedEffectTiming;- enum class EndpointInclusiveActiveInterval : bool {- No,- Yes,- };- 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; }- double previous_current_iteration() const { return m_previous_current_iteration; }- void set_previous_current_iteration(double value) { m_previous_current_iteration = value; }-- Optional<double> current_iteration() const;- Optional<double> current_iteration(ResolvedTiming const&) const;- Optional<double> transformed_progress(EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;-- void normalize_specified_timing();-- HashTable<CSS::PropertyNameAndID> const& target_properties() const { return m_target_properties; }-- virtual GC::Ptr<DOM::Element> target() const { return {}; }- virtual bool is_keyframe_effect() const { return false; }-- virtual void update_computed_properties(AnimationUpdateContext&) = 0;--protected:- AnimationEffect();- virtual ~AnimationEffect() = default;-- void update_style_if_needed() const;- void invalidate_effect();-- virtual void visit_edges(GC::Cell::Visitor&) override;- virtual GC::Ptr<Bindings::Wrappable> relevant_global_impl() const override;-- GC::Ptr<AnimationTimeline> associated_timeline() const;- Optional<TimeValue> timeline_duration() 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 };-- // https://www.w3.org/TR/web-animations-1/#start-delay- TimeValue m_start_delay { TimeValue::Type::Milliseconds, 0.0 };-- // https://drafts.csswg.org/web-animations-2/#specified-end-delay- double m_specified_end_delay { 0.0 };-- // https://www.w3.org/TR/web-animations-1/#end-delay- TimeValue m_end_delay { TimeValue::Type::Milliseconds, 0.0 };-- // https://www.w3.org/TR/web-animations-1/#fill-mode- Bindings::FillMode m_fill_mode { Bindings::FillMode::Auto };-- // https://www.w3.org/TR/web-animations-1/#iteration-start- double m_iteration_start { 0.0 };-- // https://www.w3.org/TR/web-animations-1/#iteration-count- double m_iteration_count { 1.0 };-- // https://drafts.csswg.org/web-animations-2/#specified-iteration-duration- Variant<double, Utf16String> m_specified_iteration_duration { "auto"_utf16 };-- // https://www.w3.org/TR/web-animations-1/#iteration-duration- // https://drafts.csswg.org/web-animations-2/#iteration-intervals- // The initial iteration duration of an animation effect is simply its intrinsic iteration duration- // NB: 0ms is the intrinsic iteration duration of an effect with no associated animation - we then update this value- // when an animation is associated for the first time.- TimeValue m_iteration_duration = { TimeValue::Type::Milliseconds, 0.0 };-- // https://www.w3.org/TR/web-animations-1/#playback-direction- Bindings::PlaybackDirection m_playback_direction { Bindings::PlaybackDirection::Normal };-- // https://www.w3.org/TR/web-animations-1/#animation-associated-effect- GC::Ptr<Animation> m_associated_animation {};-- // https://www.w3.org/TR/web-animations-1/#time-transformations- CSS::EasingFunction m_timing_function { CSS::EasingFunction::linear() };-- mutable bool m_has_local_time_override_for_observation { false };- mutable Optional<TimeValue> m_local_time_override_for_observation;-- // Used for calculating transitions in StyleComputer- Phase m_previous_phase { Phase::Idle };- double m_previous_current_iteration { 0.0 };-- // https://www.w3.org/TR/web-animations-1/#target-property- // Note: Only modified by child classes- HashTable<CSS::PropertyNameAndID> m_target_properties;-};-}diff --git a/Libraries/LibWeb/Animations/AnimationEffect.idl b/Libraries/LibWeb/Animations/AnimationEffect.idlindex b20bc76f56e..a2f7f36e448 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.idl+++ b/Libraries/LibWeb/Animations/AnimationEffect.idl@@ -42,7 +42,7 @@ dictionary ComputedEffectTiming : EffectTiming {};// https://drafts.csswg.org/web-animations-1/#the-animationeffect-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface AnimationEffect {EffectTiming getTiming();ComputedEffectTiming getComputedTiming();diff --git a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp b/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cppdeleted file mode 100644index 7e9e7f51d66..00000000000--- a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.cpp+++ /dev/null@@ -1,53 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2026, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Animations/AnimationPlaybackEvent.h>-#include <LibWeb/CSS/CSSNumericValue.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(AnimationPlaybackEvent);--GC::Ref<AnimationPlaybackEvent> AnimationPlaybackEvent::create(Utf16FlyString const& type, AnimationPlaybackEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- return GC::Heap::the().allocate<AnimationPlaybackEvent>(type, event_init, time_stamp);-}--GC::Ref<AnimationPlaybackEvent> AnimationPlaybackEvent::create(Utf16FlyString const& type, NullableCSSNumberish current_time, NullableCSSNumberish timeline_time, HighResolutionTime::DOMHighResTimeStamp time_stamp)-{- AnimationPlaybackEventInit event_init;- event_init.current_time = move(current_time);- event_init.timeline_time = move(timeline_time);- return create(type, event_init, time_stamp);-}--AnimationPlaybackEvent::AnimationPlaybackEvent(Utf16FlyString const& type, AnimationPlaybackEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp time_stamp)- : DOM::Event(FlyString { type.view().to_utf8_but_should_be_ported_to_utf16() }, event_init, time_stamp)- , m_current_time(event_init.current_time)- , m_timeline_time(event_init.timeline_time)-{-}--void AnimationPlaybackEvent::visit_edges(Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_current_time);- visitor.visit(m_timeline_time);-}--NullableCSSNumberish AnimationPlaybackEvent::current_time() const-{- return m_current_time;-}--NullableCSSNumberish AnimationPlaybackEvent::timeline_time() const-{- return m_timeline_time;-}--}diff --git a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h b/Libraries/LibWeb/Animations/AnimationPlaybackEvent.hdeleted file mode 100644index 140f9a1baea..00000000000--- a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.h+++ /dev/null@@ -1,51 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>- * Copyright (c) 2026, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Animations/TimeValue.h>-#include <LibWeb/Bindings/AnimationPlaybackEvent.h>-#include <LibWeb/DOM/Event.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::HTML {--class Window;--}--namespace Web::Animations {--using AnimationPlaybackEventInit = Bindings::AnimationPlaybackEventInit;--// https://www.w3.org/TR/web-animations-1/#animationplaybackevent-class AnimationPlaybackEvent : public DOM::Event {- WEB_WRAPPABLE(AnimationPlaybackEvent, DOM::Event);- GC_DECLARE_ALLOCATOR(AnimationPlaybackEvent);--public:- [[nodiscard]] static GC::Ref<AnimationPlaybackEvent> create(Utf16FlyString const& type, AnimationPlaybackEventInit const&, HighResolutionTime::DOMHighResTimeStamp);- [[nodiscard]] static GC::Ref<AnimationPlaybackEvent> create(Utf16FlyString const& type, NullableCSSNumberish current_time, NullableCSSNumberish timeline_time, HighResolutionTime::DOMHighResTimeStamp);-- virtual ~AnimationPlaybackEvent() override = default;-- NullableCSSNumberish current_time() const;- NullableCSSNumberish timeline_time() const;--private:- AnimationPlaybackEvent(Utf16FlyString const& type, AnimationPlaybackEventInit const& event_init, HighResolutionTime::DOMHighResTimeStamp);-- virtual void visit_edges(Visitor&) override;-- // https://drafts.csswg.org/web-animations-2/#dom-animationplaybackevent-currenttime- NullableCSSNumberish m_current_time;-- // https://drafts.csswg.org/web-animations-2/#dom-animationplaybackevent-timelinetime- NullableCSSNumberish m_timeline_time;-};--}diff --git a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.idl b/Libraries/LibWeb/Animations/AnimationPlaybackEvent.idlindex fb1813222c6..f8cacc4e82c 100644--- a/Libraries/LibWeb/Animations/AnimationPlaybackEvent.idl+++ b/Libraries/LibWeb/Animations/AnimationPlaybackEvent.idl@@ -1,5 +1,5 @@// https://drafts.csswg.org/web-animations-2/#animationplaybackevent-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface AnimationPlaybackEvent : Event {constructor(DOMString type, optional AnimationPlaybackEventInit eventInitDict = {});readonly attribute CSSNumberish? currentTime;diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.cpp b/Libraries/LibWeb/Animations/AnimationTimeline.cppindex 56e4aaece7e..8ea74f180f1 100644--- a/Libraries/LibWeb/Animations/AnimationTimeline.cpp+++ b/Libraries/LibWeb/Animations/AnimationTimeline.cpp@@ -1,129 +1,227 @@/** Copyright (c) 2023-2024, Matthew Olsson <[email protected]>.+ * Copyright (c) 2026, Callum Law <[email protected]>.** SPDX-License-Identifier: BSD-2-Clause*/#include <LibGC/RootVector.h>-#include <LibWeb/Animations/Animation.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/VM.h>#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/Animations/ScrollTimeline.h>+#include <LibWeb/Animations/RecordHandles.h>+#include <LibWeb/CSS/Parser/Parser.h>+#include <LibWeb/CSS/StyleValues/ComputationContext.h>#include <LibWeb/DOM/Document.h>+#include <LibWeb/DOM/Element.h>#include <LibWeb/HTML/EventLoop/EventLoop.h>#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/Layout/RenderDocument.h>+#include <LibWeb/Layout/Viewport.h>+#include <LibWeb/Painting/Scrolling.h>namespace Web::Animations {-GC_DEFINE_ALLOCATOR(AnimationTimeline);+// Takes a reference to a calculated inset the style engine hands over, which may be null.+static CSS::RustStyleValueHandle retain_calculated_inset(void const* value)+{+ if (!value)+ return {};+ return CSS::RustStyleValueHandle::retained(static_cast<CSS::StyleValueFFI::StyleValueData const*>(value));+}-AnimationTimeline::CurrentTimeOverrideScope::CurrentTimeOverrideScope(AnimationTimeline& timeline, Optional<TimeValue> current_time)- : m_timeline(timeline)- , m_previous_current_time_override(timeline.m_current_time_override_for_style_sampling)- , m_had_previous_current_time_override(timeline.m_has_current_time_override_for_style_sampling)+extern "C" {++// Defined in Bindings/Rust/src/animations/animation_timeline.rs.+void* web_animation_timeline_create(JSVM*, DOM::Document*, RustFFI::FfiTimelineDescription const*);+RustFFI::TimelineCell const* web_animation_timeline_record(void* timeline);++// Declared in Bindings/Rust/src/animations.+void web_animation_timeline_did_create(void* timeline);+RustFFI::OptionalTimeValue web_animation_timeline_current_time_for_observation(void* timeline);+DOM::Element* web_scroll_timeline_source(void* timeline);+DOM::Element* web_animation_document_scrolling_element(DOM::Document*);+void web_internal_animation_timeline_set_time(void* timeline, RustFFI::OptionalNumber, bool for_observation);+CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document*, CSS::StyleValueFFI::StyleValueData const*);+}++static RustFFI::FfiScrollTimelineSource source_to_ffi(AnimationTimeline::ScrollSource const& source){- m_timeline->set_current_time_override_for_style_sampling(move(current_time));+ return source.visit(+ [](GC::Ptr<DOM::Element const> const& element) -> RustFFI::FfiScrollTimelineSource {+ return { .element = const_cast<DOM::Element*>(element.ptr()), .is_anonymous = false, .scroller = 0, .target = nullptr, .pseudo_element = 0, .has_pseudo_element = false };+ },+ [](AnimationTimeline::AnonymousScrollSource const& anonymous_source) -> RustFFI::FfiScrollTimelineSource {+ auto pseudo_element = anonymous_source.target.pseudo_element();+ return {+ .element = nullptr,+ .is_anonymous = true,+ .scroller = to_underlying(anonymous_source.scroller),+ .target = const_cast<DOM::Element*>(&anonymous_source.target.element()),+ .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },+ .has_pseudo_element = pseudo_element.has_value(),+ };+ });}-AnimationTimeline::CurrentTimeOverrideScope::~CurrentTimeOverrideScope()+static RustFFI::FfiViewTimelineInset inset_to_ffi(ViewTimelineInset const& inset){- m_timeline->m_current_time_override_for_style_sampling = move(m_previous_current_time_override);- m_timeline->m_has_current_time_override_for_style_sampling = m_had_previous_current_time_override;+ auto edge = [](ViewTimelineInsetEdge const& edge) -> RustFFI::FfiViewTimelineInsetEdge {+ return { .is_auto = edge.is_auto, .px = edge.px, .percentage = edge.percentage, .calculated = edge.calculated.data() };+ };+ return { .start = edge(inset.start), .end = edge(inset.end) };}-RustFFI::TimelineSample AnimationTimeline::sample() const+ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const& inset){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(),+ .start = { inset.start_is_auto, inset.start_px, inset.start_percentage, retain_calculated_inset(inset.start_calculated) },+ .end = { inset.end_is_auto, inset.end_px, inset.end_percentage, retain_calculated_inset(inset.end_calculated) },};}-RustFFI::TimelineClock AnimationTimeline::clock()+GC::Ref<AnimationTimeline> AnimationTimeline::create(DOM::Document& document, RustFFI::FfiTimelineDescription const& description){- // 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 };+ return *static_cast<AnimationTimeline*>(web_animation_timeline_create(JS::HostABI::vm_to_abi(JS::VM::the()), &document, &description));+}++GC::Ref<AnimationTimeline> AnimationTimeline::create_document_timeline(DOM::Document& document, double origin_time)+{+ return create(document, { .kind = RustFFI::FfiTimelineKind::Document, .origin_time = origin_time, .source = {}, .axis = 0, .inset = {} });+}++GC::Ref<AnimationTimeline> AnimationTimeline::create_scroll_timeline(DOM::Document& document, ScrollSource const& source, ScrollAxis axis)+{+ return create(document, { .kind = RustFFI::FfiTimelineKind::Scroll, .origin_time = 0, .source = source_to_ffi(source), .axis = to_underlying(axis), .inset = {} });+}++GC::Ref<AnimationTimeline> AnimationTimeline::create_view_timeline(DOM::Document& document, DOM::AbstractElement subject, ScrollAxis axis, ViewTimelineInset const& inset)+{+ return create(document,+ {+ .kind = RustFFI::FfiTimelineKind::View,+ .origin_time = 0,+ .source = source_to_ffi(AnonymousScrollSource { .scroller = CSS::Scroller::Nearest, .target = subject }),+ .axis = to_underlying(axis),+ .inset = inset_to_ffi(inset),+ });+}++GC::Ref<AnimationTimeline> AnimationTimeline::create_internal_timeline(DOM::Document& document)+{+ return create(document, { .kind = RustFFI::FfiTimelineKind::Internal, .origin_time = 0, .source = {}, .axis = 0, .inset = {} });+}++RustFFI::TimelineCell const& AnimationTimeline::record() const+{+ return *web_animation_timeline_record(const_cast<AnimationTimeline*>(this));+}++GC::Ref<DOM::Document> AnimationTimeline::associated_document() const+{+ return *static_cast<DOM::Document*>(RustFFI::animations_timeline_document(&record()));+}++bool AnimationTimeline::is_scroll_timeline() const+{+ auto kind = read().kind;+ return kind == RustFFI::FfiTimelineKind::Scroll || kind == RustFFI::FfiTimelineKind::View;+}++AnimationTimeline::CurrentTimeOverrideScope::CurrentTimeOverrideScope(AnimationTimeline& timeline, Optional<TimeValue> current_time)+ : m_timeline(timeline)+{+ auto read = timeline.read();+ m_had_previous_current_time_override = read.has_style_sampling_override;+ m_previous_current_time_override = read.style_sampling_override;+ m_timeline->set_current_time_override_for_style_sampling(move(current_time));+}++AnimationTimeline::CurrentTimeOverrideScope::~CurrentTimeOverrideScope()+{+ RustFFI::animations_timeline_set_style_sampling_override(&m_timeline->record(), m_had_previous_current_time_override, m_previous_current_time_override);}// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttimeOptional<TimeValue> AnimationTimeline::current_time() const{- // Returns the current time for this timeline or null if this timeline is inactive.- if (is_inactive())- return {};- return effective_current_time();+ // NB: The record returns the current time for this timeline or null if this timeline is inactive.+ return from_ffi(read().sample.current_time);}-NullableCSSNumberish AnimationTimeline::current_time_for_bindings()+u64 AnimationTimeline::task_generation() const{- return NullableCSSNumberish::from_optional_css_numberish_time(current_time_for_observation());+ return associated_document()->relevant_settings_object().responsible_event_loop().task_generation();}Optional<TimeValue> AnimationTimeline::current_time_for_observation(){- if (!m_is_monotonically_increasing || !can_sample_current_time_at_timestamp())- return current_time();+ auto read = this->read();+ if (!read.sample.is_monotonically_increasing || !read.can_sample_current_time_at_timestamp)+ return from_ffi(read.sample.current_time);bool has_animation_without_per_frame_tick = false;- for (auto const& animation : m_associated_animations) {+ for (auto const& animation : associated_animations()) {auto effect = animation.effect();- if (!effect || !is<KeyframeEffect>(*effect))+ if (!effect.has_value())continue;- auto& keyframe_effect = static_cast<KeyframeEffect&>(*effect);- if (keyframe_effect.per_frame_animation_tick_was_skipped() || keyframe_effect.can_skip_per_frame_animation_tick()) {+ if (effect->per_frame_animation_tick_was_skipped() || effect->can_skip_per_frame_animation_tick()) {has_animation_without_per_frame_tick = true;break;}}if (!has_animation_without_per_frame_tick)- return current_time();+ return from_ffi(read.sample.current_time);auto& settings = associated_document()->relevant_settings_object();auto task_generation = settings.responsible_event_loop().task_generation();- if (m_last_current_time_update_task_generation == task_generation)- return m_observed_current_time;+ if (read.has_observation_task_generation && read.observation_task_generation == task_generation)+ return from_ffi(read.observed_current_time);// OPTIMIZATION: An animation skipped by the per-frame sampler does not keep the rendering update loop alive.// Sample document timelines only when script observes them, and at most once per event-loop task// so all reads within a stable state agree.auto timestamp = HighResolutionTime::relative_high_resolution_time(HighResolutionTime::unsafe_shared_current_time(), settings.global_object());- m_observed_current_time = current_time_at_timestamp(timestamp);- m_last_current_time_update_task_generation = task_generation;+ auto observed_current_time = RustFFI::animations_timeline_current_time_at_timestamp(&record(), timestamp, true, task_generation);HTML::note_rendering_trace_event("animation timeline synchronized"sv);- return m_observed_current_time;+ return from_ffi(observed_current_time);}bool AnimationTimeline::was_observed_ahead_in_current_task() const{- return m_observed_current_time != m_current_time- && m_last_current_time_update_task_generation == associated_document()->relevant_settings_object().responsible_event_loop().task_generation();+ auto read = this->read();+ return read.was_observed_ahead && read.observed_ahead_task_generation == task_generation();}-void AnimationTimeline::set_current_time(Optional<TimeValue> value)+Optional<TimeValue> AnimationTimeline::current_time_at_timestamp(double timestamp) const{- if (m_is_monotonically_increasing && m_current_time.has_value() && (!value.has_value() || *value < *m_current_time)) {- dbgln("AnimationTimeline::set_current_time({}): monotonically increasing timeline can only move forward", value);+ return from_ffi(RustFFI::animations_timeline_current_time_at_timestamp(&record(), timestamp, false, 0));+}++void AnimationTimeline::update_current_time(double timestamp)+{+ // https://drafts.csswg.org/scroll-animations-1/#ref-for-dom-animationtimeline-currenttime+ // NB: The record calculates the scroll progress from the layout of the scroller. The passed timestamp is ignored.+ if (is_scroll_timeline()) {+ // NB: Called during animation timeline update, which runs before layout is up to date.+ update_current_time_from_layout(false);return;}+ RustFFI::animations_timeline_update_current_time(&record(), timestamp, nullptr, task_generation(), false, update_associated_animations_of);+}- m_current_time = value;- m_observed_current_time = value;- m_last_current_time_update_task_generation = associated_document()->relevant_settings_object().responsible_event_loop().task_generation();+// https://drafts.csswg.org/scroll-animations-1/#stale-timelines+bool AnimationTimeline::update_current_time_if_stale()+{+ return update_current_time_from_layout(true);+}- update_associated_animations();+void AnimationTimeline::update_associated_animations_of(void* timeline)+{+ static_cast<AnimationTimeline*>(timeline)->update_associated_animations();}void AnimationTimeline::update_associated_animations()@@ -137,61 +235,254 @@ void AnimationTimeline::update_associated_animations()// NB: Since we dispatch events for all animations regardless of whether they have a timeline we handle them all together in Document::update_animations_and_send_events()HTML::note_rendering_trace_event("animation timeline updated its animations"sv);// NB: Updating an animation can run script that changes which animations are associated with this timeline. Skip- // the ones it disassociates.- GC::RootVector<GC::Ref<Animation>> animations;- for (auto& animation : m_associated_animations)+ // the ones it disassociates. The animations stay alive through it.+ GC::RootVector<AnimationRef> animations;+ auto associated_animations = this->associated_animations();+ for (auto const& animation : associated_animations)animations.append(animation);- for (auto& animation : animations) {- if (m_associated_animations.contains(*animation))- animation->update();+ for (auto const& animation : animations) {+ if (associated_animations.contains(animation.record()))+ animation.update();}}-Optional<TimeValue> AnimationTimeline::effective_current_time() const+// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time+Optional<double> AnimationTimeline::convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue> timeline_time){- if (m_has_current_time_override_for_style_sampling)- return m_current_time_override_for_style_sampling;- return m_current_time;+ return from_ffi(RustFFI::animations_timeline_convert_to_origin_relative_time(&record(), to_ffi(timeline_time)));}// https://drafts.csswg.org/web-animations-2/#timeline-duration-NullableCSSNumberish AnimationTimeline::duration_for_bindings() const+Optional<TimeValue> AnimationTimeline::duration() const{- // The duration of a timeline gives the maximum value a timeline may generate for its current time. This value is- // used to calculate the intrinsic iteration duration for the target effect of an animation that is associated with- // the timeline when the effect’s iteration duration is "auto". The value is computed such that the effect fills the- // available time. For a monotonic timeline, there is no upper bound on current time, and timeline duration is- // unresolved. For a non-monotonic (e.g. scroll) timeline, the duration has a fixed upper bound. In this case, the- // timeline is a progress-based timeline, and its timeline duration is 100%.- return NullableCSSNumberish::from_optional_css_numberish_time(duration());+ return from_ffi(read().duration);}-// https://drafts.csswg.org/web-animations-1/#timeline-bool AnimationTimeline::is_inactive() const+AnimationTimeline::ScrollSource AnimationTimeline::scroll_source() const{- // A timeline is considered to be inactive when its time value is unresolved, and active otherwise.- return !effective_current_time().has_value();+ auto source = read().source;+ if (!source.is_anonymous)+ return GC::Ptr<DOM::Element const> { static_cast<DOM::Element const*>(source.element) };+ Optional<CSS::PseudoElement> pseudo_element;+ if (source.has_pseudo_element)+ pseudo_element = static_cast<CSS::PseudoElement>(source.pseudo_element);+ return AnonymousScrollSource {+ .scroller = static_cast<CSS::Scroller>(source.scroller),+ .target = DOM::AbstractElement { *static_cast<DOM::Element*>(source.target), pseudo_element },+ };}-AnimationTimeline::AnimationTimeline(GC::Ref<DOM::Document> document)- : m_associated_document(document)+GC::Ptr<DOM::Element const> AnimationTimeline::source() const{- m_associated_document->associate_with_timeline(*this);+ return scroll_source().visit(+ [](GC::Ptr<DOM::Element const> const& source) -> GC::Ptr<DOM::Element const> {+ return source;+ },+ [](AnonymousScrollSource const& anonymous_source) -> GC::Ptr<DOM::Element const> {+ switch (anonymous_source.scroller) {+ case CSS::Scroller::Root:+ return anonymous_source.target.document().document_element();+ case CSS::Scroller::Nearest: {+ GC::Ptr<DOM::Element const> ancestor = anonymous_source.target.parent_element();++ // Whether a box is a scroll container depends on its used overflow, which is visible for a body whose+ // overflow is propagated to the viewport. The document element stands for the viewport.+ Layout::ForcedReadScope read { anonymous_source.target.document() };+ while (ancestor && !ancestor->is_document_element()) {+ auto const* layout_node = ancestor->unsafe_layout_node(read);+ if (layout_node && layout_node->is_scroll_container())+ break;+ ancestor = ancestor->parent_element();+ }++ return ancestor;+ }+ case CSS::Scroller::Self:+ return anonymous_source.target.element();+ }+ VERIFY_NOT_REACHED();+ });}-void AnimationTimeline::finalize()+void AnimationTimeline::set_axis(ScrollAxis axis){- Base::finalize();- m_associated_document->disassociate_with_timeline(*this);+ if (RustFFI::animations_scroll_timeline_set_axis_and_inset(&record(), to_underlying(axis), nullptr))+ update_current_time(0);}-void AnimationTimeline::visit_edges(GC::Cell::Visitor& visitor)+DOM::AbstractElement AnimationTimeline::view_subject() const{- Base::visit_edges(visitor);- visitor.visit(m_associated_document);- // We intentionally don't visit m_associated_animations here to avoid keeping Animations alive solely because they- // are associated with a timeline. Animations are disassociated from timelines in Animation::finalize() so we don't- // need to worry about dangling references.+ return scroll_source().get<AnonymousScrollSource>().target;}+ViewTimelineInset AnimationTimeline::view_inset() const+{+ auto inset = read().inset;+ auto edge = [](RustFFI::FfiViewTimelineInsetEdge const& edge) -> ViewTimelineInsetEdge {+ return { edge.is_auto, edge.px, edge.percentage, retain_calculated_inset(edge.calculated) };+ };+ return { edge(inset.start), edge(inset.end) };+}++void AnimationTimeline::set_axis_and_inset(ScrollAxis axis, ViewTimelineInset const& inset)+{+ auto ffi_inset = inset_to_ffi(inset);+ if (RustFFI::animations_scroll_timeline_set_axis_and_inset(&record(), to_underlying(axis), &ffi_inset))+ update_current_time(0);+}++void AnimationTimeline::set_internal_time(Optional<double> time, bool for_observation)+{+ RustFFI::animations_internal_timeline_set_time(&record(), to_ffi(time), for_observation, task_generation(), update_associated_animations_of);+}++bool AnimationTimeline::update_current_time_from_layout(bool only_if_stale)+{+ // NB: The record measures the boxes the timeline follows where the render state of the document whose viewport or+ // element the source propagates to lays them out.+ RustFFI::FfiScrollTimelineBoxes boxes {+ .host = nullptr,+ .read = nullptr,+ .scroller = Compositing::RustFFI::NodeSlotId_INVALID,+ .has_scroll_node = false,+ .scroll_node = {},+ .scroller_style_node = 0,+ .subject = Compositing::RustFFI::NodeSlotId_INVALID,+ .subject_style_node = 0,+ };+ auto update = [&] {+ return RustFFI::animations_timeline_update_current_time(&record(), 0, &boxes, task_generation(), only_if_stale, update_associated_animations_of);+ };++ // https://drafts.csswg.org/scroll-animations-1/#scroll-notation+ // References to the root element propagate to the document viewport (which functions as its scroll container).+ auto const source = this->source();+ Variant<GC::Ptr<DOM::Element const>, GC::Ptr<DOM::Document>> propagated_source = source;+ if (source && source.ptr() == source->document().document_element())+ propagated_source = source->owner_document();+ if (propagated_source.visit([](auto const& source) { return source == nullptr; }))+ return update();++ Layout::ForcedReadScope read { propagated_source.visit([](auto const& source) -> DOM::Document const& { return source->document(); }) };+ auto const* layout_node = propagated_source.visit([&read](auto const& source) -> Layout::NodeWithStyle const* { return source->unsafe_layout_node(read); });+ if (!layout_node)+ return update();++ boxes.host = layout_node->document_host();+ boxes.read = read;+ boxes.scroller = Layout::Node::slot_id(layout_node);+ if (auto scroll_node = Painting::async_scroll_node_stable_id(*layout_node); scroll_node.has_value()) {+ boxes.has_scroll_node = true;+ boxes.scroll_node = { .node_id = scroll_node->node_id.value(), .kind = to_underlying(scroll_node->kind), .pseudo_element_type = scroll_node->pseudo_element_type };+ }+ boxes.scroller_style_node = propagated_source.visit(+ [](GC::Ptr<DOM::Element const> const& element) { return element->style_node_id().value(); },+ [](GC::Ptr<DOM::Document> const&) -> u32 { return 0; });+ // NB: A view timeline follows the box of its subject besides its scroller's.+ if (is_view_timeline()) {+ auto subject = view_subject();+ boxes.subject = Layout::Node::slot_id(subject.unsafe_layout_node(read));+ // NB: A clock tick finds the subject by its style node, which a pseudo-element does not name.+ if (!subject.pseudo_element().has_value())+ boxes.subject_style_node = subject.element().style_node_id().value();+ }+ return update();+}++ScrollAxis scroll_axis_from_css_axis(CSS::Axis axis)+{+ switch (axis) {+ case CSS::Axis::Block:+ return ScrollAxis::Block;+ case CSS::Axis::Inline:+ return ScrollAxis::Inline;+ case CSS::Axis::X:+ return ScrollAxis::X;+ case CSS::Axis::Y:+ return ScrollAxis::Y;+ }++ VERIFY_NOT_REACHED();+}++// NB: What the Rust timelines ask of the host.+void web_animation_timeline_did_create(void* cell)+{+ auto& timeline = *static_cast<AnimationTimeline*>(cell);+ auto document = timeline.associated_document();+ document->associate_with_timeline(timeline);+ Optional<double> current_time;+ if (timeline.is_document_timeline()) {+ current_time = document->last_animation_frame_timestamp();+ if (!current_time.has_value()) {+ // The document hasn't processed an animation frame yet, we use the navigation start time, which is either+ // the time that the previous document started to be unloaded or the creation time of the current document.+ current_time = HighResolutionTime::relative_high_resolution_time(document->load_timing_info().navigation_start_time, document->relevant_settings_object().global_object());+ }+ } else if (timeline.is_scroll_timeline()) {+ // NB: The passed timestamp is ignored for ScrollTimelines so we can just pass 0 here.+ current_time = 0;+ }+ if (current_time.has_value())+ timeline.update_current_time(*current_time);+}++RustFFI::OptionalTimeValue web_animation_timeline_current_time_for_observation(void* cell)+{+ return to_ffi(static_cast<AnimationTimeline*>(cell)->current_time_for_observation());+}++DOM::Element* web_scroll_timeline_source(void* cell)+{+ auto& timeline = *static_cast<AnimationTimeline*>(cell);+ if (timeline.is_view_timeline()) {+ // The values of subject, source, and currentTime are all computed when any of them is requested or updated.+ auto subject = timeline.view_subject();+ subject.document().update_layout(DOM::UpdateLayoutReason::ViewTimelineSource);++ // If the source or subject of a ViewTimeline is an element whose principal box does not exist, [...] then the+ // ViewTimeline is inactive.+ // INTEROP: Its source is then null, as WebKit and Blink have it.+ for (GC::Ptr<DOM::Element const> element = &subject.element(); element; element = element->flat_tree_parent_element()) {+ if (!element->has_style() || element->installed_style().display_is_none())+ return nullptr;+ }+ } else {+ // The nearest scroll container is the nearest one by used overflow, which layout decides.+ auto scroll_source = timeline.scroll_source();+ if (auto const* anonymous_source = scroll_source.get_pointer<AnimationTimeline::AnonymousScrollSource>(); anonymous_source && anonymous_source->scroller == CSS::Scroller::Nearest)+ anonymous_source->target.document().update_layout(DOM::UpdateLayoutReason::ScrollTimelineSource);+ }+ return const_cast<DOM::Element*>(timeline.source().ptr());+}++DOM::Element* web_animation_document_scrolling_element(DOM::Document* document)+{+ return const_cast<DOM::Element*>(document->scrolling_element().ptr());+}++void web_internal_animation_timeline_set_time(void* cell, RustFFI::OptionalNumber time, bool for_observation)+{+ static_cast<AnimationTimeline*>(cell)->set_internal_time(from_ffi(time), for_observation);+}++// NB: Absolutizes a style value that script gave, as the document's values are.+CSS::StyleValueFFI::StyleValueData const* web_animation_absolutize_style_value(DOM::Document* document, CSS::StyleValueFFI::StyleValueData const* value)+{+ auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));+ auto computed = style_value->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(*document) });+ return CSS::StyleValueFFI::rust_style_value_retain(computed->rust_style_value_data());+}++}++// NB: What the timeline records ask of the document a timeline is associated with.+extern "C" WEB_API bool ladybird_animations_document_is_active(void* document)+{+ return static_cast<Web::DOM::Document const*>(document)->is_active();+}++extern "C" WEB_API void* ladybird_animations_element_node_document(void* element)+{+ return &static_cast<Web::DOM::Element*>(element)->document();}diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.h b/Libraries/LibWeb/Animations/AnimationTimeline.hindex d9fe31d89dc..1217b1da3e2 100644--- a/Libraries/LibWeb/Animations/AnimationTimeline.h+++ b/Libraries/LibWeb/Animations/AnimationTimeline.h@@ -6,19 +6,69 @@#pragma once-#include <LibGC/WeakHashSet.h>-#include <LibWeb/Animations/Animation.h>+#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/Animations/TimeValue.h>-#include <LibWeb/Bindings/Wrappable.h>+#include <LibWeb/Bindings/AnimationTimeline.h>+#include <LibWeb/Bindings/RustInterface.h>+#include <LibWeb/CSS/Enums.h>+#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>+#include <LibWeb/ComputedValuesRustFFI.h>+#include <LibWeb/DOM/AbstractElement.h>namespace Web::Animations {-// https://www.w3.org/TR/web-animations-1/#animationtimeline-class AnimationTimeline : public Bindings::GCAllocatedWrappable {- WEB_WRAPPABLE(AnimationTimeline, Bindings::GCAllocatedWrappable);- GC_DECLARE_ALLOCATOR(AnimationTimeline);+// https://drafts.csswg.org/scroll-animations-1/#enumdef-scrollaxis+enum class ScrollAxis : u8 {+ Block,+ Inline,+ X,+ Y,+};++ScrollAxis scroll_axis_from_css_axis(CSS::Axis);++// One side of the view progress visibility range: auto takes the scroll container's scroll padding, otherwise a length+// plus a percentage of the scrollport.+// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset+struct ViewTimelineInsetEdge {+ bool is_auto { true };+ double px { 0 };+ double percentage { 0 };+ // NB: An inset only a calculation can describe, such as min(50%, 10px), resolves against the scrollport size.+ CSS::RustStyleValueHandle calculated {};++ bool operator==(ViewTimelineInsetEdge const&) const = default;+};++struct ViewTimelineInset {+ ViewTimelineInsetEdge start;+ ViewTimelineInsetEdge end;++ bool operator==(ViewTimelineInset const&) const = default;+};++// https://drafts.csswg.org/web-animations-2/#the-animationtimeline-interface+// The cell of an AnimationTimeline, which Bindings/Rust/src/animations implements, of any of the interfaces that+// inherit from it. The state of the timeline is its record.+class WEB_API AnimationTimeline final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(AnimationTimeline, animation_timeline)public:+ // The source of an anonymous scroll timeline: the scroller it finds from its target.+ // https://drafts.csswg.org/scroll-animations-1/#scroll-notation+ struct AnonymousScrollSource {+ CSS::Scroller scroller;+ DOM::AbstractElement target;++ bool operator==(AnonymousScrollSource const& other) const = default;+ };+ using ScrollSource = Variant<GC::Ptr<DOM::Element const>, AnonymousScrollSource>;++ static GC::Ref<AnimationTimeline> create_document_timeline(DOM::Document&, double origin_time);+ static GC::Ref<AnimationTimeline> create_scroll_timeline(DOM::Document&, ScrollSource const&, ScrollAxis);+ static GC::Ref<AnimationTimeline> create_view_timeline(DOM::Document&, DOM::AbstractElement subject, ScrollAxis, ViewTimelineInset const&);+ static GC::Ref<AnimationTimeline> create_internal_timeline(DOM::Document&);+class CurrentTimeOverrideScope {public:CurrentTimeOverrideScope(AnimationTimeline&, Optional<TimeValue>);@@ -29,98 +79,92 @@ public:private:GC::Ref<AnimationTimeline> m_timeline;- Optional<TimeValue> m_previous_current_time_override;bool m_had_previous_current_time_override { false };+ RustFFI::OptionalTimeValue m_previous_current_time_override;};- NullableCSSNumberish current_time_for_bindings();+ // The timeline's state, which lives as long as the timeline.+ RustFFI::TimelineCell const& record() const;+Optional<TimeValue> current_time() const;// What the timing model reads of the timeline now.- RustFFI::TimelineSample sample() const;+ RustFFI::TimelineSample sample() const { return read().sample; }// What moves the timeline as a clock tick samples it.- RustFFI::TimelineClock clock();+ RustFFI::TimelineClock clock() const { return read().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;+ // The current time at a timestamp, where the timeline can sample it there, and its current time otherwise.+ Optional<TimeValue> current_time_at_timestamp(double timestamp) const;// Runs the callback with every timeline in [timelines, end) that script observed ahead of its current time in the// current task sampled at the time script observed, so that what the callback samples agrees with what script read.template<typename Iterator, typename Callback>static void at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback);- virtual void update_current_time(double timestamp) = 0;-- NullableCSSNumberish duration_for_bindings() const;- virtual Optional<TimeValue> duration() const = 0;+ // Updates the current time: a document timeline's from the timestamp, and a scroll timeline's from the layout of+ // its scroller, which ignores the timestamp.+ void update_current_time(double timestamp);+ // Updates the current time of a scroll timeline from the layout of its scroller where that changed it since its+ // last update, answering whether it did.+ bool update_current_time_if_stale();- GC::Ref<DOM::Document> associated_document() const { return m_associated_document; }+ Optional<TimeValue> duration() const;- virtual bool is_inactive() const;- bool is_monotonically_increasing() const { return m_is_monotonically_increasing; }- virtual bool is_progress_based() const { return false; }+ GC::Ref<DOM::Document> associated_document() const;- // https://drafts.csswg.org/web-animations-2/#minimum-timeline-time- // NB: Empty for a monotonically increasing timeline, whose minimum timeline time is -infinity.- virtual Optional<TimeValue> minimum_timeline_time() const { return {}; }- // https://drafts.csswg.org/web-animations-2/#maximum-timeline-time- // NB: Empty for a monotonically increasing timeline, whose maximum timeline time is +infinity.- virtual Optional<TimeValue> maximum_timeline_time() const { return {}; }-- // The timeline times of the start and the end of an attachment range on a progress-based timeline.- // https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range- virtual AttachmentInterval interval_for_attachment_range(AnimationAttachmentRange const&) const- {- return { { TimeValue::Type::Percentage, 0 }, { TimeValue::Type::Percentage, 100 } };- }+ bool is_inactive() const { return read().is_inactive; }+ bool is_monotonically_increasing() const { return read().sample.is_monotonically_increasing; }+ bool is_document_timeline() const { return read().kind == RustFFI::FfiTimelineKind::Document; }+ // A scroll timeline, or a view timeline, which is one.+ bool is_scroll_timeline() const;+ bool is_view_timeline() const { return read().kind == RustFFI::FfiTimelineKind::View; }+ bool is_progress_based() const { return is_scroll_timeline(); }// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time- virtual Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue>) { VERIFY_NOT_REACHED(); }- virtual bool can_convert_a_timeline_time_to_an_origin_relative_time() const { return false; }-- void associate_with_animation(GC::Ref<Animation> value) { m_associated_animations.set(*value); }- void disassociate_with_animation(GC::Ref<Animation> value) { m_associated_animations.remove(*value); }- GC::WeakHashSet<Animation> const& associated_animations() const { return m_associated_animations; }+ Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue>);+ bool can_convert_a_timeline_time_to_an_origin_relative_time() const { return is_document_timeline(); }-protected:- explicit AnimationTimeline(GC::Ref<DOM::Document>);+ // NB: The animations associated with the timeline, none of which it keeps alive.+ WeakAnimationSetView associated_animations() const { return WeakAnimationSetView { *RustFFI::animations_timeline_associated_animations(&record()) }; }- virtual void visit_edges(GC::Cell::Visitor&) override;- virtual void finalize() override;+ // The source, axis and inset of a scroll or view timeline.+ ScrollSource scroll_source() const;+ // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source+ GC::Ptr<DOM::Element const> source() const;+ ScrollAxis axis() const { return static_cast<ScrollAxis>(read().axis); }+ void set_axis(ScrollAxis);+ DOM::AbstractElement view_subject() const;+ ViewTimelineInset view_inset() const;+ void set_axis_and_inset(ScrollAxis, ViewTimelineInset const&);- void set_current_time(Optional<TimeValue> value);- void update_associated_animations();- virtual bool can_sample_current_time_at_timestamp() const { return false; }- virtual Optional<TimeValue> current_time_at_timestamp(double) const { return current_time(); }-- // https://www.w3.org/TR/web-animations-1/#dom-animationtimeline-currenttime- Optional<TimeValue> m_current_time {};+ // Sets the time of the Internals interface's timeline, or the time a read of it observes.+ void set_internal_time(Optional<double>, bool for_observation);- // https://drafts.csswg.org/web-animations-1/#monotonically-increasing-timeline- bool m_is_monotonically_increasing { false };+private:+ friend class DOM::Document;- // https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document- GC::Ref<DOM::Document> m_associated_document;+ static GC::Ref<AnimationTimeline> create(DOM::Document&, RustFFI::FfiTimelineDescription const&);- GC::WeakHashSet<Animation> m_associated_animations;- Optional<u64> m_last_current_time_update_task_generation;- Optional<TimeValue> m_observed_current_time;+ RustFFI::FfiTimeline read() const { return RustFFI::animations_timeline_read(&record()); }+ u64 task_generation() const;+ void update_associated_animations();+ // The host's function through which the record has the timeline update its associated animations.+ static void update_associated_animations_of(void* timeline);-private:- friend class DOM::Document;+ // Updates the current time of a scroll timeline from where the render state lays out the boxes the timeline+ // follows, unless that leaves it as it was where `only_if_stale`, answering whether it updated it.+ bool update_current_time_from_layout(bool only_if_stale);void set_current_time_override_for_style_sampling(Optional<TimeValue> value){- m_current_time_override_for_style_sampling = move(value);- m_has_current_time_override_for_style_sampling = true;+ RustFFI::animations_timeline_set_style_sampling_override(&record(), true, to_ffi(value));}- void clear_current_time_override_for_style_sampling() { m_has_current_time_override_for_style_sampling = false; }-- Optional<TimeValue> effective_current_time() const;-- Optional<TimeValue> m_current_time_override_for_style_sampling;- bool m_has_current_time_override_for_style_sampling { false };+ void clear_current_time_override_for_style_sampling() { RustFFI::animations_timeline_set_style_sampling_override(&record(), false, to_ffi(Optional<TimeValue> {})); }};+ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const&);+template<typename Iterator, typename Callback>void AnimationTimeline::at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback){@@ -135,3 +179,7 @@ void AnimationTimeline::at_times_observed_ahead(Iterator timelines, Iterator end}}++// NB: What the timeline records ask of the document a timeline is associated with.+extern "C" WEB_API bool ladybird_animations_document_is_active(void* document);+extern "C" WEB_API void* ladybird_animations_element_node_document(void* element);diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.idl b/Libraries/LibWeb/Animations/AnimationTimeline.idlindex 7a9cefb7905..ae94fe5a14f 100644--- a/Libraries/LibWeb/Animations/AnimationTimeline.idl+++ b/Libraries/LibWeb/Animations/AnimationTimeline.idl@@ -1,7 +1,7 @@// https://drafts.csswg.org/web-animations-2/#the-animationtimeline-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface AnimationTimeline {- [ImplementedAs=current_time_for_bindings] readonly attribute CSSNumberish? currentTime;- [ImplementedAs=duration_for_bindings] readonly attribute CSSNumberish? duration;+ readonly attribute CSSNumberish? currentTime;+ readonly attribute CSSNumberish? duration;[FIXME] Animation play (optional AnimationEffect? effect = null);};diff --git a/Libraries/LibWeb/Animations/BindingsGlue.h b/Libraries/LibWeb/Animations/BindingsGlue.hdeleted file mode 100644index 0133f7ab1dc..00000000000--- a/Libraries/LibWeb/Animations/BindingsGlue.h+++ /dev/null@@ -1,30 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <LibGC/Forward.h>-#include <LibJS/Forward.h>-#include <LibWeb/Export.h>-#include <LibWeb/Forward.h>-#include <LibWeb/WebIDL/Promise.h>--namespace Web::Animations {--class Animation;-class AnimationEffect;-class AnimationTimeline;--}--namespace Web::Bindings {--WEB_API GC::Ref<Animations::Animation> construct_animation(JS::Realm&, GC::Ptr<Animations::AnimationEffect>, Optional<GC::Ptr<Animations::AnimationTimeline>>, size_t argument_count);-WEB_API void resolve_animation_promise(WebIDL::Promise&, Animations::Animation const&);-WEB_API GC::Ref<WebIDL::Promise> create_resolved_animation_promise(Animations::Animation const&);--}diff --git a/Libraries/LibWeb/Animations/DocumentTimeline.cpp b/Libraries/LibWeb/Animations/DocumentTimeline.cppdeleted file mode 100644index 4f4bb23c6ad..00000000000--- a/Libraries/LibWeb/Animations/DocumentTimeline.cpp+++ /dev/null@@ -1,90 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Bindings/DocumentTimeline.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/HighResolutionTime/Performance.h>-#include <LibWeb/HighResolutionTime/TimeOrigin.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(DocumentTimeline);--GC::Ref<DocumentTimeline> DocumentTimeline::create(DOM::Document& document, HighResolutionTime::DOMHighResTimeStamp origin_time)-{- auto timeline = GC::Heap::the().allocate<DocumentTimeline>(document, origin_time);- auto current_time = document.last_animation_frame_timestamp();- if (!current_time.has_value()) {- // The document hasn't processed an animation frame yet, we use the navigation start time, which is either the time- // that the previous document started to be unloaded or the creation time of the current document.- current_time = HighResolutionTime::relative_high_resolution_time(document.load_timing_info().navigation_start_time, document.relevant_settings_object().global_object());- }- timeline->update_current_time(current_time.value());- return timeline;-}--WebIDL::ExceptionOr<GC::Ref<DocumentTimeline>> DocumentTimeline::create_for_constructor(JS::Object& relevant_global_object, Bindings::DocumentTimelineOptions const& options)-{- return create(HTML::relevant_window(relevant_global_object).associated_document(), options.origin_time);-}--// https://www.w3.org/TR/web-animations-1/#ref-for-timeline-time-to-origin-relative-time-Optional<double> DocumentTimeline::convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue> timeline_time)-{- // To convert a timeline time, timeline time, to an origin-relative time for a document timeline, timeline, return- // the sum of the timeline time and timeline’s origin time. If timeline is inactive, return an unresolved time- // value.- if (is_inactive() || !timeline_time.has_value())- return {};-- // NB: We know the timeline time of a DocumentTimeline is always in milliseconds because it's only ever set from- // update_current_time()- VERIFY(timeline_time->type == TimeValue::Type::Milliseconds);- return timeline_time->value + m_origin_time;-}--// https://drafts.csswg.org/web-animations-1/#document-timeline-void DocumentTimeline::update_current_time(double timestamp)-{- // A document timeline is a type of timeline that is associated with a document and whose current time is calculated- // as a fixed offset from the now timestamp provided each time the update animations and send events procedure is- // run. This fixed offset is equal to the current time of the default document timeline when this timeline’s current- // time was zero, and is thus referred to as the document timeline’s origin time.- set_current_time(TimeValue { TimeValue::Type::Milliseconds, timestamp - m_origin_time });-- // https://drafts.csswg.org/web-animations-1/#ref-for-active-timeline- // After a document timeline becomes active, it is monotonically increasing.- if (!m_is_monotonically_increasing && !is_inactive())- m_is_monotonically_increasing = true;-}--Optional<TimeValue> DocumentTimeline::current_time_at_timestamp(double timestamp) const-{- if (is_inactive())- return {};- return TimeValue { TimeValue::Type::Milliseconds, timestamp - m_origin_time };-}--// https://www.w3.org/TR/web-animations-1/#document-timelines-bool DocumentTimeline::is_inactive() const-{- // A document timeline that is associated with a Document which is not an active document is also considered to be- // inactive.- return Base::is_inactive() || !associated_document()->is_active();-}--DocumentTimeline::DocumentTimeline(DOM::Document& document, HighResolutionTime::DOMHighResTimeStamp origin_time)- : AnimationTimeline(document)- , m_origin_time(origin_time)-{-}--}diff --git a/Libraries/LibWeb/Animations/DocumentTimeline.h b/Libraries/LibWeb/Animations/DocumentTimeline.hdeleted file mode 100644index 64990d2098a..00000000000--- a/Libraries/LibWeb/Animations/DocumentTimeline.h+++ /dev/null@@ -1,56 +0,0 @@-/*- * Copyright (c) 2023, Matthew Olsson <[email protected]>.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibJS/Forward.h>-#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/WebIDL/ExceptionOr.h>-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>--namespace Web::Bindings {--struct DocumentTimelineOptions;--}--namespace Web::HTML {--class Window;--}--namespace Web::Animations {--// https://www.w3.org/TR/web-animations-1/#the-documenttimeline-interface-class DocumentTimeline : public AnimationTimeline {- WEB_WRAPPABLE(DocumentTimeline, AnimationTimeline);- GC_DECLARE_ALLOCATOR(DocumentTimeline);--public:- static GC::Ref<DocumentTimeline> create(DOM::Document&, HighResolutionTime::DOMHighResTimeStamp origin_time);- static WebIDL::ExceptionOr<GC::Ref<DocumentTimeline>> create_for_constructor(JS::Object&, Bindings::DocumentTimelineOptions const&);-- virtual Optional<TimeValue> duration() const override { return {}; }-- virtual void update_current_time(double timestamp) override;- virtual bool is_inactive() const override;-- virtual Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<TimeValue>) override;- virtual bool can_convert_a_timeline_time_to_an_origin_relative_time() const override { return true; }--protected:- virtual bool can_sample_current_time_at_timestamp() const override { return true; }- virtual Optional<TimeValue> current_time_at_timestamp(double) const override;--private:- DocumentTimeline(DOM::Document&, HighResolutionTime::DOMHighResTimeStamp origin_time);- virtual ~DocumentTimeline() override = default;-- HighResolutionTime::DOMHighResTimeStamp m_origin_time;-};--}diff --git a/Libraries/LibWeb/Animations/DocumentTimeline.idl b/Libraries/LibWeb/Animations/DocumentTimeline.idlindex 02ad81696a9..4ab7be2c818 100644--- a/Libraries/LibWeb/Animations/DocumentTimeline.idl+++ b/Libraries/LibWeb/Animations/DocumentTimeline.idl@@ -4,7 +4,7 @@ dictionary DocumentTimelineOptions {};// https://drafts.csswg.org/web-animations-1/#documenttimeline-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface DocumentTimeline : AnimationTimeline {constructor(optional DocumentTimelineOptions options = {});};diff --git a/Libraries/LibWeb/Animations/KeyframeEffect.cpp b/Libraries/LibWeb/Animations/KeyframeEffect.cppdeleted file mode 100644index ef064ca1237..00000000000--- a/Libraries/LibWeb/Animations/KeyframeEffect.cpp+++ /dev/null@@ -1,1570 +0,0 @@-/*- * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <AK/Atomic.h>-#include <AK/InsertionSort.h>-#include <AK/QuickSort.h>-#include <LibGC/Heap.h>-#include <LibJS/Runtime/Iterator.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/Animations/PseudoElementParsing.h>-#include <LibWeb/Bindings/KeyframeEffect.h>-#include <LibWeb/CSS/CSSAnimation.h>-#include <LibWeb/CSS/ComputedStyleWorkingSet.h>-#include <LibWeb/CSS/Parser/Parser.h>-#include <LibWeb/CSS/PropertyID.h>-#include <LibWeb/CSS/StyleComputer.h>-#include <LibWeb/CSS/StyleEngineInput.h>-#include <LibWeb/CSS/StyleValues/KeywordStyleValue.h>-#include <LibWeb/CSS/Zoom.h>-#include <LibWeb/ComputedValuesRustFFI.h>-#include <LibWeb/DOM/AbstractElement.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/Slot.h>-#include <LibWeb/HTML/EventLoop/EventLoop.h>-#include <LibWeb/HTML/EventNames.h>-#include <LibWeb/HTML/HTMLSlotElement.h>-#include <LibWeb/HTML/LocalNavigable.h>-#include <LibWeb/HTML/NavigableContainer.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Layout/Node.h>-#include <LibWeb/SVG/SMILAnimation.h>-#include <LibWeb/SVG/SVGAnimationElement.h>-#include <LibWeb/SVG/SVGElement.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(KeyframeEffect);--static Atomic<u64> s_next_animation_preparation_identity { 1 };--template<typename T>-WebIDL::ExceptionOr<Variant<T, Vector<T>>> convert_value_to_maybe_list(JS::Realm& realm, JS::Value value, Function<WebIDL::ExceptionOr<T>(JS::Value)>& value_converter)-{- auto& vm = realm.vm();-- if (TRY(value.is_array(vm))) {- Vector<T> offsets;-- auto iterator = TRY(JS::get_iterator(vm, value, JS::IteratorHint::Sync));- auto values = TRY(JS::iterator_to_list(vm, iterator));- for (auto const& element : values) {- if (element.is_undefined()) {- offsets.append({});- } else {- offsets.append(TRY(value_converter(element)));- }- }-- return offsets;- }-- return TRY(value_converter(value));-}--enum class AllowLists {- Yes,- No,-};--template<AllowLists AL>-using KeyframeType = Conditional<AL == AllowLists::Yes, BasePropertyIndexedKeyframe, BaseKeyframe>;--// https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object-template<AllowLists AL>-static WebIDL::ExceptionOr<KeyframeType<AL>> process_a_keyframe_like_object(JS::Realm& realm, JS::Value keyframe_input)-{- auto& vm = realm.vm();-- Function<WebIDL::ExceptionOr<Optional<double>>(JS::Value)> to_offset = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Optional<double>> {- if (value.is_nullish())- return Optional<double> {};- auto double_value = TRY(value.to_double(vm));- if (isnan(double_value) || isinf(double_value))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Invalid offset value: {}", TRY(value.to_utf16_string(vm))) };- return double_value;- };-- Function<WebIDL::ExceptionOr<Utf16String>(JS::Value)> to_string = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Utf16String> {- return TRY(value.to_utf16_string(vm));- };-- Function<WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto>(JS::Value)> to_composite_operation = [&vm](JS::Value value) -> WebIDL::ExceptionOr<Bindings::CompositeOperationOrAuto> {- if (value.is_undefined())- return Bindings::CompositeOperationOrAuto::Auto;-- auto string_value = TRY(value.to_utf16_string(vm));- if (string_value == "replace"sv)- return Bindings::CompositeOperationOrAuto::Replace;- if (string_value == "add"sv)- return Bindings::CompositeOperationOrAuto::Add;- if (string_value == "accumulate"sv)- return Bindings::CompositeOperationOrAuto::Accumulate;- if (string_value == "auto"sv)- return Bindings::CompositeOperationOrAuto::Auto;-- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid composite value"_utf16 };- };-- // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript- // value, and the dictionary type depending on the value of the allow lists flag as follows:- //- // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.- // -> Otherwise, use the following dictionary type: <BaseKeyframe>.- //- // Store the result of this procedure as keyframe output.-- KeyframeType<AL> keyframe_output;- if (keyframe_input.is_nullish())- return keyframe_output;-- auto& keyframe_object = keyframe_input.as_object();- auto composite = TRY(keyframe_object.get("composite"_utf16_fly_string));- if (composite.is_undefined())- composite = JS::PrimitiveString::create(vm, "auto"_utf16_fly_string);- auto easing = TRY(keyframe_object.get("easing"_utf16_fly_string));- if (easing.is_undefined())- easing = JS::PrimitiveString::create(vm, "linear"_utf16_fly_string);- auto offset = TRY(keyframe_object.get("offset"_utf16_fly_string));-- if constexpr (AL == AllowLists::Yes) {- keyframe_output.composite = TRY(convert_value_to_maybe_list(realm, composite, to_composite_operation));-- auto easing_maybe_list = TRY(convert_value_to_maybe_list(realm, easing, to_string));- easing_maybe_list.visit(- [&](Utf16String const& value) {- keyframe_output.easing = EasingValue { value };- },- [&](Vector<Utf16String> const& values) {- Vector<EasingValue> easing_values;- for (auto& easing_value : values)- easing_values.append(easing_value);- keyframe_output.easing = move(easing_values);- });-- keyframe_output.offset = TRY(convert_value_to_maybe_list(realm, offset, to_offset));- } else {- keyframe_output.composite = TRY(to_composite_operation(composite));- keyframe_output.easing = TRY(to_string(easing));- keyframe_output.offset = TRY(to_offset(offset));- }-- // 2. Build up a list of animatable properties as follows:- //- // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand- // sub-properties that are animatable) that can be animated by the implementation.- // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the- // animation property name to IDL attribute name algorithm.-- // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the- // object.-- // 4. Make up a new list animation properties that consists of all of the properties that are in both input- // properties and animatable properties, or which are in input properties and conform to the- // <custom-property-name> production.- auto input_properties = TRY(keyframe_object.enumerable_own_property_names(JS::Object::PropertyKind::Key));-- Vector<Utf16FlyString> animation_properties;-- for (auto const& input_property : input_properties) {- if (!input_property.is_string())- continue;-- auto name = Utf16FlyString::from_utf16(input_property.as_string().utf16_string_view());-- // Handle the two special cases- if (name == "cssFloat"sv || name == "cssOffset"sv) {- animation_properties.append(name);- } else if (name == "float"sv || name == "offset"sv) {- // Ignore these property names- } else if (CSS::is_a_custom_property_name_string(name)) {- animation_properties.append(name);- } else if (auto property = CSS::property_id_from_camel_case_string(name); property.has_value()) {- if (CSS::is_animatable_property(property.value()))- animation_properties.append(name);- }- }-- // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.- quick_sort(animation_properties);-- // 6. For each property name in animation properties,- for (auto const& property_name : animation_properties) {- // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name- // as the property key and keyframe input as the receiver.- // 2. Check the completion record of raw value.- JS::PropertyKey key { property_name, JS::PropertyKey::StringMayBeNumber::No };- auto raw_value = TRY(keyframe_object.get(key));-- using PropertyValuesType = Conditional<AL == AllowLists::Yes, Vector<Utf16String>, Utf16String>;- PropertyValuesType property_values;-- // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:-- // -> If allow lists is true,- if constexpr (AL == AllowLists::Yes) {- // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)- // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].- auto intermediate_property_values = TRY(convert_value_to_maybe_list(realm, raw_value, to_string));-- // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the- // original value of property values as the only element.- if (intermediate_property_values.has<Utf16String>())- property_values = Vector { intermediate_property_values.get<Utf16String>() };- else- property_values = intermediate_property_values.get<Vector<Utf16String>>();- }- // -> Otherwise,- else {- // Let property values be the result of converting raw value to a DOMString using the procedure for- // converting an ECMAScript value to a DOMString [WEBIDL].- property_values = TRY(raw_value.to_utf16_string(vm));- }-- // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation- // property name algorithm to property name.- // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL- // attribute name) in the steps above.-- // 5. Add a property to keyframe output with normalized property name as the property name, and property values- // as the property value.- if constexpr (AL == AllowLists::Yes) {- keyframe_output.properties.set(property_name, property_values);- } else {- keyframe_output.unparsed_properties().set(property_name, property_values);- }- }-- return keyframe_output;-}--WebIDL::ExceptionOr<KeyframeEffect::Options> keyframe_effect_options_from_bindings(Bindings::KeyframeEffectOptions const& options)-{- if (options.duration.has<GC::Ref<CSS::CSSNumericValue>>())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Setting duration as a CSSNumericValue is not supported"_utf16 };-- KeyframeEffect::Options converted_options {- .timing = to_optional_effect_timing(options),- .composite = options.composite,- .pseudo_element = {},- };- if (options.pseudo_element.has_value())- converted_options.pseudo_element = TRY(pseudo_element_parsing(options.pseudo_element));- return converted_options;-}--// https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets-void compute_missing_keyframe_offsets(Vector<BaseKeyframe>& keyframes)-{- // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe- // offset value.- for (auto& keyframe : keyframes)- keyframe.computed_offset = keyframe.offset;-- // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in- // keyframes is null, set the computed keyframe offset of the first keyframe to 0.- if (keyframes.size() > 1 && !keyframes[0].computed_offset.has_value())- keyframes[0].computed_offset = 0.0;-- // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset- // to 1.- if (!keyframes.is_empty() && !keyframes.last().computed_offset.has_value())- keyframes.last().computed_offset = 1.0;-- // 4. For each pair of keyframes A and B where:- // - A appears before B in keyframes, and- // - A and B have a computed keyframe offset that is not null, and- // - all keyframes between A and B have a null computed keyframe offset,- auto find_next_index_of_keyframe_with_computed_offset = [&](size_t starting_index) -> Optional<size_t> {- for (size_t index = starting_index; index < keyframes.size(); index++) {- if (keyframes[index].computed_offset.has_value())- return index;- }-- return {};- };-- auto maybe_index_a = find_next_index_of_keyframe_with_computed_offset(0);- if (!maybe_index_a.has_value())- return;-- auto index_a = maybe_index_a.value();- auto maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_a + 1);-- while (maybe_index_b.has_value()) {- auto index_b = maybe_index_b.value();-- // calculate the computed keyframe offset of each keyframe between A and B as follows:- for (size_t keyframe_index = index_a + 1; keyframe_index < index_b; keyframe_index++) {- // 1. Let offsetk be the computed keyframe offset of a keyframe k.- auto offset_a = keyframes[index_a].computed_offset.value();- auto offset_b = keyframes[index_b].computed_offset.value();-- // 2. Let n be the number of keyframes between and including A and B minus 1.- auto n = static_cast<double>(index_b - index_a);-- // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the- // first keyframe after A has an index of 1.- auto index = static_cast<double>(keyframe_index - index_a);-- // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.- keyframes[keyframe_index].computed_offset = offset_a + (offset_b - offset_a) * index / n;- }-- index_a = index_b;- maybe_index_b = find_next_index_of_keyframe_with_computed_offset(index_b + 1);- }-}--// https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset-static bool is_loosely_sorted_by_offset(Vector<BaseKeyframe> const& keyframes)-{- // The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe- // in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the- // previous keyframe in the list with a keyframe offset that is not null, if any.-- Optional<double> last_offset;- for (auto const& keyframe : keyframes) {- if (!keyframe.offset.has_value())- continue;-- if (last_offset.has_value() && keyframe.offset.value() < last_offset.value())- return false;-- last_offset = keyframe.offset;- }-- return true;-}--// https://www.w3.org/TR/web-animations-1/#process-a-keyframes-argument-static WebIDL::ExceptionOr<Vector<BaseKeyframe>> process_a_keyframes_argument(JS::Realm& realm, GC::Ptr<JS::Object> object)-{- auto& vm = realm.vm();-- // 1. If object is null, return an empty sequence of keyframes.- if (!object)- return Vector<BaseKeyframe> {};-- // 2. Let processed keyframes be an empty sequence of keyframes.- Vector<BaseKeyframe> processed_keyframes;- Vector<EasingValue> unused_easings;-- // 3. Let method be the result of GetMethod(object, @@iterator).- // 4. Check the completion record of method.- auto method = TRY(JS::Value(object).get_method(vm, vm.well_known_symbol_iterator()));-- // 5. Perform the steps corresponding to the first matching condition from below,-- // -> If method is not undefined,- if (method) {- // 1. Let iter be GetIterator(object, method).- // 2. Check the completion record of iter.- auto iter = TRY(JS::get_iterator_from_method(vm, object, *method));-- // 3. Repeat:- while (true) {- // 1. Let next be IteratorStep(iter).- // 2. Check the completion record of next.- // 3. If next is false abort this loop.- // 4. Let nextItem be IteratorValue(next).- // 5. Check the completion record of nextItem.- // FIXME: The spec should be updated to use IteratorStepValue instead.- auto maybe_next_item = TRY(JS::iterator_step_value(vm, iter));- if (!maybe_next_item.has_value())- break;- auto next_item = maybe_next_item.release_value();-- // 6. If Type(nextItem) is not Undefined, Null or Object, then throw a TypeError and abort these steps.- if (!next_item.is_nullish() && !next_item.is_object())- return vm.throw_completion<JS::TypeError>(JS::ErrorType::NotAnObjectOrNull, next_item);-- // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object- // passing nextItem as the keyframe input and with the allow lists flag set to false.- processed_keyframes.append(TRY(process_a_keyframe_like_object<AllowLists::No>(realm, next_item)));- }- }- // -> Otherwise,- else {- // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object- // passing object as the keyframe input and with the allow lists flag set to true.- auto property_indexed_keyframe = TRY(process_a_keyframe_like_object<AllowLists::Yes>(realm, object));-- // 2. For each member, m, in property-indexed keyframe, perform the following steps:- for (auto const& [property_name, property_values] : property_indexed_keyframe.properties) {- // 1. Let property name be the key for m.-- // 2. If property name is "composite", or "easing", or "offset", skip the remaining steps in this loop and- // continue from the next member in property-indexed keyframe after m.- // Note: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe-- // 3. Let property values be the value for m.-- // 4. Let property keyframes be an empty sequence of keyframes.- Vector<BaseKeyframe> property_keyframes;-- // 5. For each value, v, in property values perform the following steps:- for (auto const& value : property_values) {- // 1. Let k be a new keyframe with a null keyframe offset.- BaseKeyframe keyframe;-- // 2. Add the property-value pair, property name → v, to k.- keyframe.unparsed_properties().set(property_name, value);-- // 3. Append k to property keyframes.- property_keyframes.append(keyframe);- }-- // 6. Apply the procedure to compute missing keyframe offsets to property keyframes.- compute_missing_keyframe_offsets(property_keyframes);-- // 7. Add keyframes in property keyframes to processed keyframes.- processed_keyframes.extend(move(property_keyframes));- }-- // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order.- quick_sort(processed_keyframes, [](auto const& a, auto const& b) {- return a.computed_offset.value() < b.computed_offset.value();- });-- // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.- // Note: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the- // earlier keyframe with the properties of the later keyframe.- for (int i = 0; i < static_cast<int>(processed_keyframes.size() - 1); i++) {- auto& keyframe_a = processed_keyframes[i];- auto& keyframe_b = processed_keyframes[i + 1];-- if (keyframe_a.computed_offset.value() == keyframe_b.computed_offset.value()) {- keyframe_a.easing = keyframe_b.easing;- keyframe_a.composite = keyframe_b.composite;- keyframe_a.unparsed_properties().update(keyframe_b.unparsed_properties());- processed_keyframes.remove(i + 1);- i--;- }- }-- // 5. Let offsets be a sequence of nullable double values assigned based on the type of the "offset" member- // of the property-indexed keyframe as follows:- //- // -> sequence<double?>,- // The value of "offset" as-is.- // -> double?,- // A sequence of length one with the value of "offset" as its single item, i.e. « offset »,- auto offsets = property_indexed_keyframe.offset.has<Optional<double>>()- ? Vector { property_indexed_keyframe.offset.get<Optional<double>>() }- : property_indexed_keyframe.offset.get<Vector<Optional<double>>>();-- // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in- // processed keyframes until the end of either sequence is reached.- for (size_t i = 0; i < offsets.size() && i < processed_keyframes.size(); i++)- processed_keyframes[i].offset = offsets[i];-- // 7. Let easings be a sequence of DOMString values assigned based on the type of the "easing" member of the- // property-indexed keyframe as follows:- //- // -> sequence<DOMString>,- // The value of "easing" as-is.- // -> DOMString,- // A sequence of length one with the value of "easing" as its single item, i.e. « easing »,- auto easings = property_indexed_keyframe.easing.has<EasingValue>()- ? Vector { property_indexed_keyframe.easing.get<EasingValue>() }- : property_indexed_keyframe.easing.get<Vector<EasingValue>>();-- // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value "linear",- // i.e. « "linear" ».- if (easings.is_empty())- easings.append("linear"_utf16);-- // 9. If easings has fewer items than processed keyframes, repeat the elements in easings successively starting- // from the beginning of the list until easings has as many items as processed keyframes.- //- // For example, if processed keyframes has five items, and easings is the sequence « "ease-in", "ease-out" »,- // easings would be repeated to become « "ease-in", "ease-out", "ease-in", "ease-out", "ease-in" ».- size_t num_easings = easings.size();- size_t index = 0;- while (easings.size() < processed_keyframes.size())- easings.append(easings[index++ % num_easings]);-- // 10. If easings has more items than processed keyframes, store the excess items as unused easings.- while (easings.size() > processed_keyframes.size())- unused_easings.append(easings.take_last());-- // 11. Assign each value in easings to a property named "easing" on the keyframe with the corresponding position- // in processed keyframes until the end of processed keyframes is reached.- for (size_t i = 0; i < processed_keyframes.size(); i++)- processed_keyframes[i].easing = easings[i];-- // 12. If the "composite" member of the property-indexed keyframe is not an empty sequence:- auto composite_value = property_indexed_keyframe.composite;- if (!composite_value.has<Vector<Bindings::CompositeOperationOrAuto>>() || !composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>().is_empty()) {- // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the "composite"- // member of property-indexed keyframe. If that member is a single CompositeOperationOrAuto value- // operation, let composite modes be a sequence of length one, with the value of the "composite" as its- // single item.- auto composite_modes = composite_value.has<Bindings::CompositeOperationOrAuto>()- ? Vector { composite_value.get<Bindings::CompositeOperationOrAuto>() }- : composite_value.get<Vector<Bindings::CompositeOperationOrAuto>>();-- // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in- // composite modes successively starting from the beginning of the list until composite modes has as- // many items as processed keyframes.- size_t num_composite_modes = composite_modes.size();- index = 0;- while (composite_modes.size() < processed_keyframes.size())- composite_modes.append(composite_modes[index++ % num_composite_modes]);-- // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on- // the keyframe with the corresponding position in processed keyframes until the end of processed- // keyframes is reached.- for (size_t i = 0; i < processed_keyframes.size(); i++) {- if (composite_modes[i] != Bindings::CompositeOperationOrAuto::Auto)- processed_keyframes[i].composite = composite_modes[i];- }- }- }-- // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps.- if (!is_loosely_sorted_by_offset(processed_keyframes))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Keyframes are not in ascending order based on offset"_utf16 };-- // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than zero or- // greater than one, throw a TypeError and abort these steps.- for (size_t i = 0; i < processed_keyframes.size(); i++) {- auto const& keyframe = processed_keyframes[i];- if (!keyframe.offset.has_value())- continue;-- auto offset = keyframe.offset.value();- if (offset < 0.0 || offset > 1.0)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Keyframe {} has invalid offset value {}", i, offset) };- }-- // 8. For each frame in processed keyframes, perform the following steps:- for (auto& keyframe : processed_keyframes) {- // 1. For each property-value pair in frame, parse the property value using the syntax specified for that- // property.- //- // If the property value is invalid according to the syntax for the property, discard the property-value pair.- // User agents that provide support for diagnosing errors in content SHOULD produce an appropriate warning- // highlight- BaseKeyframe::ParsedProperties parsed_properties;- for (auto& [property_string, value_string] : keyframe.unparsed_properties()) {- Optional<CSS::PropertyNameAndID> property;-- // Handle some special cases- if (property_string == "cssFloat"sv) {- property = CSS::PropertyNameAndID::from_id(CSS::PropertyID::Float);- } else if (property_string == "cssOffset"sv) {- property = CSS::PropertyNameAndID::from_id(CSS::PropertyID::Offset);- } else if (property_string == "float"sv || property_string == "offset"sv) {- // Ignore these properties- } else if (CSS::is_a_custom_property_name_string(property_string)) {- property = CSS::PropertyNameAndID::from_name(property_string);- } else if (auto property_id = CSS::property_id_from_camel_case_string(property_string); property_id.has_value()) {- property = CSS::PropertyNameAndID::from_id(*property_id);- }-- if (!property.has_value())- continue;-- if (auto style_value = parse_css_value(CSS::Parser::ParsingParams(), value_string, property->id()))- parsed_properties.set(*property, CSS::RustStyleValueHandle::retained(style_value->rust_style_value_data()));- }- keyframe.properties.set(move(parsed_properties));-- // 2. Let the timing function of frame be the result of parsing the "easing" property on frame using the CSS- // syntax defined for the easing member of the EffectTiming dictionary.- //- // If parsing the "easing" property fails, throw a TypeError and abort this procedure.- auto easing_string = keyframe.easing.get<Utf16String>();- auto easing_value = AnimationEffect::parse_easing_string(easing_string);-- if (!easing_value.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Invalid animation easing value: \"{}\"", easing_string) };-- keyframe.easing.set(easing_value.value());- }-- // 9. Parse each of the values in unused easings using the CSS syntax defined for easing member of the EffectTiming- // interface, and if any of the values fail to parse, throw a TypeError and abort this procedure.- for (auto& unused_easing : unused_easings) {- auto easing_string = unused_easing.get<Utf16String>();- auto easing_value = AnimationEffect::parse_easing_string(easing_string);- if (!easing_value.has_value())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, Utf16String::formatted("Invalid animation easing value: \"{}\"", easing_string) };- }-- return processed_keyframes;-}--WebIDL::ExceptionOr<Vector<BaseKeyframe>> process_keyframes(JS::Realm& realm, GC::Ptr<JS::Object> object)-{- return process_a_keyframes_argument(realm, object);-}--// https://www.w3.org/TR/css-animations-2/#keyframe-processing-void KeyframeEffect::generate_initial_and_final_frames(RefPtr<KeyFrameSet> keyframe_set, HashTable<CSS::PropertyNameAndID> const& animated_properties)-{- // 1. Find or create the initial keyframe, a keyframe with a keyframe offset of 0%, default timing function- // as its keyframe timing function, and default composite as its keyframe composite.- KeyFrameSet::ResolvedKeyFrame* initial_keyframe;- if (auto existing_keyframe = keyframe_set->keyframes_by_key.find(0)) {- initial_keyframe = existing_keyframe;- } else {- keyframe_set->keyframes_by_key.insert(0, {});- initial_keyframe = keyframe_set->keyframes_by_key.find(0);- }-- auto expanded_properties_at_offset = [&](u64 offset) {- HashTable<CSS::PropertyNameAndID> result;-- for (auto it = keyframe_set->keyframes_by_key.begin(); it != keyframe_set->keyframes_by_key.end(); ++it) {- if (it.key() != offset)- continue;- for (auto const& property : it->properties) {- if (!property.key.is_custom_property() && property_is_shorthand(property.key.id())) {- for (auto longhand : expanded_longhands_for_shorthand(property.key.id()))- result.set(CSS::PropertyNameAndID::from_id(longhand));- } else {- result.set(property.key);- }- }- }-- return result;- };-- // 2. For any property in animated properties that is not otherwise present in a keyframe with an offset of- // 0% or one that would be positioned earlier in the used keyframe order, add the computed value of that- // property on element to initial keyframe’s keyframe values.- auto initial_properties = expanded_properties_at_offset(0);- for (auto property : animated_properties) {- if (!initial_properties.contains(property))- initial_keyframe->properties.set(property, KeyFrameSet::UseInitial {});- }-- // 3. If initial keyframe’s keyframe values is not empty, prepend initial keyframe to keyframes.-- // 4. Repeat for final keyframe, using an offset of 100%, considering keyframes positioned later in the used- // keyframe order, and appending to keyframes.- KeyFrameSet::ResolvedKeyFrame* final_keyframe;- if (auto existing_keyframe = keyframe_set->keyframes_by_key.find(100 * AnimationKeyFrameKeyScaleFactor)) {- final_keyframe = existing_keyframe;- } else {- keyframe_set->keyframes_by_key.insert(100 * AnimationKeyFrameKeyScaleFactor, {});- final_keyframe = keyframe_set->keyframes_by_key.find(100 * AnimationKeyFrameKeyScaleFactor);- }-- auto final_properties = expanded_properties_at_offset(100 * AnimationKeyFrameKeyScaleFactor);- for (auto property : animated_properties) {- if (!final_properties.contains(property))- final_keyframe->properties.set(property, KeyFrameSet::UseInitial {});- }-}--// https://www.w3.org/TR/web-animations-1/#animation-composite-order-int KeyframeEffect::composite_order(GC::Ref<KeyframeEffect> a, GC::Ref<KeyframeEffect> b)-{- // The relative composite order of any two keyframe effects A and B within an effect stack is established by- // comparing their properties as follows:- auto a_animation = a->associated_animation();- auto b_animation = b->associated_animation();-- // 1. Sort A and B by applying the following conditions in turn until the order is resolved,-- // 1. If A and B’s associated animations differ by class, sort by any inter-class composite order defined for- // the corresponding classes.- auto a_class = a_animation->animation_class();- auto b_class = b_animation->animation_class();-- // From https://www.w3.org/TR/css-animations-2/#animation-composite-order:- // "CSS Animations with an owning element have a later composite order than CSS Transitions but an earlier- // composite order than animations without a specific animation class."- if (a_class != b_class)- return to_underlying(a_class) - to_underlying(b_class);-- // 2. If A and B are still not sorted, sort by any class-specific composite order defined by the common class of- // A and B’s associated animations.- if (auto order = a_animation->class_specific_composite_order(*b_animation); order != 0)- return order;-- // 3. If A and B are still not sorted, sort by the position of their associated animations in the global- // animation list.- return a_animation->global_animation_list_order() - b_animation->global_animation_list_order();-}--GC::Ref<KeyframeEffect> KeyframeEffect::create()-{- return GC::Heap::the().allocate<KeyframeEffect>();-}--WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> KeyframeEffect::create_from_processed_keyframes(- GC::Ptr<DOM::Element> target,- Vector<BaseKeyframe> keyframes,- Variant<double, Options> options)-{- auto effect = create();- effect->set_target(target);- if (options.has<Options>()) {- auto const& effect_options = options.get<Options>();- effect->m_target_pseudo_selector = effect_options.pseudo_element;- TRY(effect->update_timing(effect_options.timing));- effect->set_composite(effect_options.composite);- } else {- Bindings::OptionalEffectTiming timing;- timing.duration = options.get<double>();- TRY(effect->update_timing(timing));- }- effect->set_keyframes(move(keyframes));- return effect;-}--// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect-WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> KeyframeEffect::construct_impl(- JS::Realm& realm,- GC::Ptr<DOM::Element> target,- GC::Ptr<JS::Object> keyframes,- Variant<double, Bindings::KeyframeEffectOptions> const& options)-{- // 1. Create a new KeyframeEffect object, effect.- auto effect = create();-- // 2. Set the target element of effect to target.- effect->set_target(target);-- // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.-- // If options is a KeyframeEffectOptions object with a pseudoElement property,- if (options.has<Bindings::KeyframeEffectOptions>()) {- // Set the target pseudo-selector to the value of the pseudoElement property.- //- // When assigning this property, the error-handling defined for the pseudoElement setter on the interface is- // applied. If the setter requires an exception to be thrown, this procedure must throw the same exception and- // abort all further steps.- TRY(effect->set_pseudo_element(options.get<Bindings::KeyframeEffectOptions>().pseudo_element));- }- // Otherwise,- else {- // Set the target pseudo-selector to null.- // Note: This is the default when constructed- }-- // 4. Let timing input be the result corresponding to the first matching condition from below.- Bindings::KeyframeEffectOptions timing_input;-- // If options is a KeyframeEffectOptions object,- if (options.has<Bindings::KeyframeEffectOptions>()) {- // Let timing input be options.- timing_input = options.get<Bindings::KeyframeEffectOptions>();- }- // Otherwise (if options is a double),- else {- // Let timing input be a new EffectTiming object with all members set to their default values and duration set- // to options.- timing_input.duration = options.get<double>();- }-- // https://drafts.csswg.org/web-animations-2/#the-effecttiming-dictionaries- // Note: In this version of the spec, duration is not settable as a CSSNumericValue; however, duration may be- // returned as a CSSNumericValue when resolving the duration in getComputedTiming(). Future versions of- // the spec may enable setting the duration as a CSSNumeric value, where the unit is a valid time unit or- // percent.- if (timing_input.duration.has<GC::Ref<CSS::CSSNumericValue>>())- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Setting duration as a CSSNumericValue is not supported"_utf16 };-- // 5. Call the procedure to update the timing properties of an animation effect of effect from timing input.- // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.- TRY(effect->update_timing(to_optional_effect_timing(timing_input)));-- // 6. If options is a KeyframeEffectOptions object, assign the composite property of effect to the corresponding- // value from options.- //- // When assigning this property, the error-handling defined for the corresponding setter on the KeyframeEffect- // interface is applied. If the setter requires an exception to be thrown for the value specified by options,- // this procedure must throw the same exception and abort all further steps.- if (options.has<Bindings::KeyframeEffectOptions>())- effect->set_composite(options.get<Bindings::KeyframeEffectOptions>().composite);-- // 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes() passing keyframes as- // the input.- TRY(effect->set_keyframes_from_js(realm, keyframes));-- return effect;-}--// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect-source-WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> KeyframeEffect::construct_impl(GC::Ref<KeyframeEffect> source)-{- // 1. Create a new KeyframeEffect object, effect.- auto effect = create();-- // 2. Set the following properties of effect using the corresponding values of source:-- // - effect target,- effect->m_target_element = source->target();- effect->m_target_pseudo_selector = source->m_target_pseudo_selector;-- // - keyframes,- auto keyframes = source->m_keyframes_from_css ? source->declared_css_keyframes() : source->m_keyframes;- if (source->m_keyframes_from_css)- insertion_sort(keyframes, [](auto const& a, auto const& b) { return *a.offset < *b.offset; });- if (source->m_key_frame_set && source->m_key_frame_set->computed_value_zoom.has_value()) {- for (auto& frame : keyframes) {- for (auto& [property, value] : frame.parsed_properties()) {- if (!property.is_custom_property()) {- auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value.data()));- auto unscaled = CSS::unscaled_by_zoom(property.id(), move(style_value), *source->m_key_frame_set->computed_value_zoom);- value = CSS::RustStyleValueHandle::retained(unscaled->rust_style_value_data());- }- }- }- }- effect->set_keyframes(move(keyframes), source->m_key_frame_set ? source->m_key_frame_set->style_sheet_resource_context : Optional<KeyFrameSet::StyleSheetResourceContext> {});-- // - composite operation, and- effect->set_composite(source->composite());-- // - all specified timing properties:-- // AD-HOC: This is defined in the web-animations level 1 spec so doesn't explicitly mention the level 2 properties- // (specified start delay, specified end delay, specified iteration duration) but it is required that we- // copy these and then normalize them as opposed to copying the already normalized values which may be- // invalid in this context i.e. if the existing effect was associated with a progress-based timeline-- // - specified start delay,- effect->m_specified_start_delay = source->m_specified_start_delay;-- // - specified end delay,- effect->m_specified_end_delay = source->m_specified_end_delay;-- // - fill mode,- effect->m_fill_mode = source->m_fill_mode;-- // - iteration start,- effect->m_iteration_start = source->m_iteration_start;-- // - iteration count,- effect->m_iteration_count = source->m_iteration_count;-- // - specified iteration duration,- effect->m_specified_iteration_duration = source->m_specified_iteration_duration;-- // - playback direction, and- effect->m_playback_direction = source->m_playback_direction;-- // - timing function.- effect->m_timing_function = source->m_timing_function;-- effect->normalize_specified_timing();-- return effect;-}--void KeyframeEffect::set_target(GC::Ptr<DOM::Element> target)-{- if (auto animation = this->associated_animation()) {- if (m_target_element)- m_target_element->disassociate_with_animation(*animation);- if (target)- target->associate_with_animation(*animation);- }- m_target_element = target;-- invalidate_animation_preparation();- if (m_target_element)- CSS::record_attr_names_read_by_keyframes(*m_target_element, *this);- invalidate_effect();- // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and- // it will remain "stuck" until it's style is fully invalidated for some other reason.-}--Optional<Utf16String> KeyframeEffect::pseudo_element() const-{- if (!m_target_pseudo_selector.has_value())- return {};- return m_target_pseudo_selector->serialize();-}--// https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudoelement-WebIDL::ExceptionOr<void> KeyframeEffect::set_pseudo_element(Optional<Utf16String> value)-{- // On setting, sets the target pseudo-selector of the animation effect to the result of- // pseudo-element parsing on the provided value, defined as the following:- // NOTE: The actual definition is in pseudo_element_parsing().- m_target_pseudo_selector = TRY(pseudo_element_parsing(value));-- invalidate_animation_preparation();- invalidate_effect();- // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and- // it will remain "stuck" until it's style is fully invalidated for some other reason.-- return {};-}--Optional<DOM::AbstractElement> KeyframeEffect::target_abstract_element() const-{- if (m_target_element)- return DOM::AbstractElement { *m_target_element, pseudo_element_type() };- return {};-}--void KeyframeEffect::set_target(DOM::AbstractElement abstract_element, InvalidateEffect invalidate)-{- if (invalidate == InvalidateEffect::Yes) {- set_target(&abstract_element.element());- } else {- VERIFY(!associated_animation());- m_target_element = &abstract_element.element();- CSS::record_attr_names_read_by_keyframes(*m_target_element, *this);- }- m_target_pseudo_selector = abstract_element.pseudo_element().map([](auto it) { return CSS::Selector::PseudoElementSelector { it }; });-}--Optional<CSS::PseudoElement> KeyframeEffect::pseudo_element_type() const-{- if (!m_target_pseudo_selector.has_value())- return {};- return m_target_pseudo_selector->type();-}--void KeyframeEffect::set_composite(Bindings::CompositeOperation value)-{- m_composite = value;- invalidate_animation_preparation();- invalidate_effect();-}--void KeyframeEffect::set_key_frame_set(RefPtr<KeyFrameSet const> key_frame_set)-{- if (m_ignore_css_keyframes || m_key_frame_set == key_frame_set)- return;- m_keyframes_from_css = true;-- m_target_properties.clear();- if (key_frame_set) {- for (auto const& keyframe : key_frame_set->keyframes_by_key) {- for (auto const& property : keyframe.properties)- m_target_properties.set(property.key);- }- }- m_key_frame_set = move(key_frame_set);- if (m_target_element)- CSS::record_attr_names_read_by_keyframes(*m_target_element, *this);- invalidate_animation_preparation();- invalidate_effect();-}--Bindings::CompositeOperation KeyframeEffect::composite_for_bindings() const-{- update_style_if_needed();- return composite();-}--// https://drafts.csswg.org/css-animations-2/#keyframes-CSS::EasingFunction KeyframeEffect::default_keyframe_easing() const-{- if (auto animation = associated_animation(); animation && is<CSS::CSSAnimation>(*animation))- return static_cast<CSS::CSSAnimation const&>(*animation).default_easing();- return CSS::EasingFunction::linear();-}--Vector<BaseKeyframe> KeyframeEffect::declared_css_keyframes() const-{- Vector<BaseKeyframe> frames;- if (!m_key_frame_set)- return frames;-- auto default_easing = default_keyframe_easing();-- auto append_frame = [&](u64 key, KeyFrameSet::ResolvedKeyFrame const& source) {- auto offset = static_cast<double>(key) / (100 * AnimationKeyFrameKeyScaleFactor);- // AD-HOC: Step 2.2 uses the computed timing function. Substitution-dependent keyframe easings use the- // animation-wide easing for web compatibility.- auto easing = source.easing.has<CSS::EasingFunction>() ? source.easing.get<CSS::EasingFunction>() : default_easing;- auto matching_frame = frames.find_if([&](BaseKeyframe const& frame) {- return frame.offset == offset && frame.easing.get<CSS::EasingFunction>() == easing && frame.composite == source.composite;- });- if (matching_frame == frames.end()) {- frames.append(BaseKeyframe {- .offset = offset,- .easing = easing,- .composite = source.composite,- .computed_offset = offset,- .properties = BaseKeyframe::ParsedProperties {},- });- matching_frame = frames.end() - 1;- }- for (auto const& [property, value] : source.properties) {- if (auto const* declared = value.get_pointer<CSS::RustStyleValueHandle>())- matching_frame->parsed_properties().set(property, *declared);- }- };- if (m_key_frame_set->css_keyframes.has_value()) {- // 2.3.1. Cascade together all of its declaration blocks such that for each CSS property (except those that are- // "not animatable", which must be ignored) the last declaration among all its <keyframe-block>- // declarations takes precedence.- for (auto const& frame : *m_key_frame_set->css_keyframes)- append_frame(frame.key, frame.values);- } else {- for (auto it = m_key_frame_set->keyframes_by_key.begin(); it != m_key_frame_set->keyframes_by_key.end(); ++it)- append_frame(it.key(), *it);- }- return frames;-}--// https://drafts.csswg.org/css-animations-2/#keyframes-Vector<BaseKeyframe> KeyframeEffect::computed_css_keyframes() const-{- auto frames = declared_css_keyframes();- if (!m_key_frame_set || !m_key_frame_set->css_keyframes.has_value())- return frames;- bool has_custom_properties = false;- for (auto& frame : frames)- frame.parsed_properties().remove_all_matching([&](auto const& property, auto const&) {- has_custom_properties |= property.is_custom_property();- return property.is_custom_property();- });- auto default_easing = default_keyframe_easing();- if (!has_custom_properties && !frames.contains([](auto const& frame) { return !frame.parsed_properties().is_empty(); }))- return {};-- auto target = target_abstract_element();- if (target.has_value() && target->installed_style()) {- auto underlying_values = target->element().document().style_computer().compute_css_keyframe_values(*target, frames, m_key_frame_set->style_sheet_resource_context);- for (auto offset : { 0.0, 1.0 }) {- HashTable<CSS::PropertyNameAndID> present;- Optional<size_t> destination;- for (size_t i = 0; i < frames.size(); ++i) {- auto const& frame = frames[i];- if (frame.offset != offset)- continue;- for (auto const& property : frame.parsed_properties())- present.set(property.key);- // AD-HOC: Step 3.1 uses the default composite. Underlying-value endpoints use "replace", even for an- // additive effect, so their values aren't added to themselves.- if (!destination.has_value() && frame.easing.get<CSS::EasingFunction>() == default_easing- && (frame.composite == CompositeOperationOrAuto::Auto || frame.composite == CompositeOperationOrAuto::Replace))- destination = i;- }- BaseKeyframe::ParsedProperties missing;- for (auto const& [property, value] : underlying_values) {- if (!present.contains(property))- missing.set(property, value);- }- // AD-HOC: Custom properties contribute keyframe offsets and implicit endpoints, but their values are- // omitted from CSS keyframe reflection for web compatibility.- if (missing.is_empty() && !has_custom_properties)- continue;- // 3.2. For any property in animated properties that is not otherwise present in a keyframe with an offset- // of 0% or one that would be positioned earlier in the used keyframe order, add the computed value of- // that property on element to initial keyframe's keyframe values.- if (destination.has_value()) {- for (auto const& [property, value] : missing)- frames[*destination].parsed_properties().set(property, value);- } else {- BaseKeyframe frame {- .offset = offset,- .easing = default_easing,- .composite = CompositeOperationOrAuto::Replace,- .computed_offset = offset,- .properties = move(missing),- };- // AD-HOC: Step 3.3 prepends the initial keyframe. For web compatibility, reflected synthetic endpoints- // follow explicitly declared frames at the same offset.- frames.append(move(frame));- }- }- }- // 4. The computed order of keyframes—which is the order returned by getKeyframes()—is found by shifting any- // keyframes whose offset was specified as a <percentage>, from keyword, or to keyword to the front of the list- // (after the generated initial keyframe, if any), and performing a stable sort on these keyframes by their- // keyframe offsets.- insertion_sort(frames, [](auto const& a, auto const& b) { return *a.offset < *b.offset; });- return frames;-}--// https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-getkeyframes-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<JS::Object>>> KeyframeEffect::get_keyframes(JS::Object& relevant_global_object)-{- update_style_if_needed();- auto css_keyframes = m_keyframes_from_css ? computed_css_keyframes() : Vector<BaseKeyframe> {};- auto const& reflected_keyframes = m_keyframes_from_css ? css_keyframes : m_keyframes;- double zoom = 1;- if (m_keyframes_from_css) {- if (m_key_frame_set && m_key_frame_set->computed_value_zoom.has_value()) {- zoom = *m_key_frame_set->computed_value_zoom;- } else if (auto target = target_abstract_element(); target.has_value()) {- if (auto style = target->computed_style())- zoom = style->effective_zoom();- }- }-- // The getKeyframes() algorithm returns a fresh sequence of fresh objects on- // every invocation. Do not expose the previous result as a mutable cache:- // callers are allowed to modify the returned dictionaries without changing- // the effect.- m_keyframe_objects_cache.clear();-- {- auto& realm = HTML::relevant_realm(relevant_global_object);- auto& vm = realm.vm();-- for (auto const& keyframe : reflected_keyframes) {- auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());- TRY(object->set(vm.names.offset, keyframe.offset.has_value() ? JS::Value(keyframe.offset.value()) : JS::js_null(), JS::Object::ShouldThrowExceptions::Yes));- TRY(object->set(vm.names.computedOffset, JS::Value(keyframe.computed_offset.value()), JS::Object::ShouldThrowExceptions::Yes));- auto easing_value = keyframe.easing.get<CSS::EasingFunction>();- TRY(object->set(vm.names.easing, JS::PrimitiveString::create(vm, easing_value.to_utf16_string()), JS::Object::ShouldThrowExceptions::Yes));-- if (keyframe.composite == Bindings::CompositeOperationOrAuto::Replace) {- TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "replace"sv), JS::Object::ShouldThrowExceptions::Yes));- } else if (keyframe.composite == Bindings::CompositeOperationOrAuto::Add) {- TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "add"sv), JS::Object::ShouldThrowExceptions::Yes));- } else if (keyframe.composite == Bindings::CompositeOperationOrAuto::Accumulate) {- TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "accumulate"sv), JS::Object::ShouldThrowExceptions::Yes));- } else {- TRY(object->set(vm.names.composite, JS::PrimitiveString::create(vm, "auto"sv), JS::Object::ShouldThrowExceptions::Yes));- }-- for (auto const& [property, value] : keyframe.parsed_properties()) {- // https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name- // 1. If property follows the <custom-property-name> production, return property.- // 2. If property refers to the CSS float property, return the string "cssFloat".- // 3. If property refers to the CSS offset property, return the string "cssOffset".- // 4. Otherwise, return the result of applying the CSS property to IDL attribute algorithm [CSSOM] to- // property.- Utf16FlyString key;- if (property.is_custom_property())- key = property.name();- else if (property.id() == CSS::PropertyID::Float)- key = "cssFloat"_utf16_fly_string;- else if (property.id() == CSS::PropertyID::Offset)- key = "cssOffset"_utf16_fly_string;- else- key = CSS::camel_case_string_from_property_id(property.id());- // Serialization can still fall back to C++, which needs the typed facade; reflection is cold, so- // wrap on demand.- NonnullRefPtr<CSS::StyleValue const> style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value.data()));- if (m_keyframes_from_css && !property.is_custom_property())- style_value = CSS::unscaled_by_zoom(property.id(), move(style_value), zoom);- auto value_string = JS::PrimitiveString::create(vm, style_value->to_utf16_string(CSS::SerializationMode::Normal));- TRY(object->set(JS::PropertyKey { move(key), JS::PropertyKey::StringMayBeNumber::No }, value_string, JS::Object::ShouldThrowExceptions::Yes));- }-- m_keyframe_objects_cache.append(object);- }- }-- GC::RootVector<GC::Ref<JS::Object>> keyframes;- for (auto const& keyframe : m_keyframe_objects_cache)- keyframes.append(keyframe);- return keyframes;-}--// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes-WebIDL::ExceptionOr<void> KeyframeEffect::set_keyframes_from_js(JS::Realm& realm, GC::Ptr<JS::Object> keyframe_object)-{- auto keyframes = TRY(process_a_keyframes_argument(realm, keyframe_object));- set_keyframes(move(keyframes));- return {};-}--void KeyframeEffect::set_keyframes(Vector<BaseKeyframe> keyframes, Optional<KeyFrameSet::StyleSheetResourceContext> resource_context)-{- m_keyframe_objects_cache.clear();- m_ignore_css_keyframes |= m_keyframes_from_css;- m_keyframes_from_css = false;- m_keyframes = move(keyframes);- // FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed- // keyframes using the procedure outlined in the second half of- // https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the- // missing keyframe offsets- compute_missing_keyframe_offsets(m_keyframes);-- auto keyframe_set = adopt_ref(*new KeyFrameSet);- keyframe_set->style_sheet_resource_context = move(resource_context);- m_target_properties.clear();-- for (auto& keyframe : m_keyframes) {- Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame resolved_keyframe;- resolved_keyframe.composite = keyframe.composite;- if (auto const* easing = keyframe.easing.get_pointer<CSS::EasingFunction>())- resolved_keyframe.easing = *easing;-- auto key = static_cast<u64>(keyframe.computed_offset.value() * 100 * AnimationKeyFrameKeyScaleFactor);-- for (auto const& [property, property_value] : keyframe.parsed_properties()) {- resolved_keyframe.properties.set(property, property_value);- if (property.is_custom_property()) {- m_target_properties.set(property);- continue;- }- auto expansion = CSS::ComputedValuesFFI::rust_expand_property_shorthands(- to_underlying(property.id()), property_value.data());- for (size_t i = 0; i < expansion.count; ++i)- m_target_properties.set(CSS::PropertyNameAndID::from_id(static_cast<CSS::PropertyID>(expansion.properties[i].property_id)));- CSS::ComputedValuesFFI::rust_shorthand_expansion_destroy(expansion.storage);- }-- keyframe_set->keyframes_by_key.insert(key, resolved_keyframe);- }-- generate_initial_and_final_frames(keyframe_set, m_target_properties);- m_key_frame_set = keyframe_set;- if (m_target_element)- CSS::record_attr_names_read_by_keyframes(*m_target_element, *this);-- invalidate_animation_preparation();- invalidate_effect();-}--KeyframeEffect::KeyframeEffect()- : m_animation_preparation_identity(s_next_animation_preparation_identity.fetch_add(1, AK::MemoryOrder::memory_order_relaxed))-{-}--Painting::CompositorAnimationEffectState& KeyframeEffect::compositor_animation_state()-{- if (!m_compositor_animation_state)- m_compositor_animation_state = make<Painting::CompositorAnimationEffectState>();- return *m_compositor_animation_state;-}--void KeyframeEffect::invalidate_effect()-{- if (m_compositor_animation_state)- m_compositor_animation_state->reset();- m_is_compositor_driven = false;- m_is_compositor_replaced = false;- m_is_offscreen_throttled = false;- m_is_observation_relevant_compositor_animation = false;- m_can_skip_per_frame_style_update_cache.clear();- if (m_target_element)- m_target_element->document().set_needs_animated_style_update(*this);-}--void KeyframeEffect::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_target_element);- visitor.visit(m_keyframe_objects_cache);-}--// Whether nothing shows the target's style, as a display: none ancestor leaves the target without a box.-// NB: SVG resources keep their style under display: none, where boxes elsewhere in the document can reference them.-static bool target_is_unseen_in_display_none_subtree(DOM::Element const& target)-{- if (target.has_layout_box() || !target.has_inclusive_ancestor_with_display_none_ignoring_animations())- return false;- bool has_referenceable_svg_element = false;- target.for_each_in_inclusive_subtree_of_type<SVG::SVGElement>([&](SVG::SVGElement const& element) {- if (!element.is_referenceable_in_display_none_subtree())- return TraversalDecision::Continue;- has_referenceable_svg_element = true;- return TraversalDecision::Break;- });- return !has_referenceable_svg_element;-}--// NB: A custom property can feed the display of the target through var().-bool KeyframeEffect::may_animate_display() const-{- return any_of(target_properties(), [](auto const& property) {- return property.id() == CSS::PropertyID::Display || property.is_custom_property();- });-}--bool KeyframeEffect::can_skip_per_frame_style_update() const-{- if (m_is_compositor_driven || m_is_compositor_replaced)- return true;- if (m_is_offscreen_throttled && all_of(target_properties(), [](auto const& property) {- return !first_is_one_of(property.id(), CSS::PropertyID::Transform, CSS::PropertyID::Translate, CSS::PropertyID::Rotate, CSS::PropertyID::Scale);- }))- return true;-- auto target = this->target();- if (!target)- return false;-- // An animation inside a box-less iframe can't affect its embedding document's rendering. Check the containers- // before the target-local cache, since their layout can change without changing the target's style or layout box.- // Reverse playback and effects with a finite end time need ticks to finish, even with an infinite iteration count.- if (auto animation = associated_animation(); animation && animation->playback_rate() > 0 && isinf(iteration_count()) && isinf(end_time().value)) {- for (auto navigable = target->document().navigable(); navigable;) {- auto container = navigable->container();- if (!container)- break;- if (container->document().layout_is_up_to_date() && !container->has_layout_box())- return true;- navigable = container->document().navigable();- }- }-- Layout::ForcedReadScope read { target->document() };- auto cache_result = [&](bool result) {- if (target->document().layout_is_up_to_date()) {- m_can_skip_per_frame_style_update_cache = CanSkipPerFrameStyleUpdateCache {- .target_style_generation = target->animation_style_generation(),- .target_subtree_style_generation = target->animation_subtree_style_generation(),- .target_is_connected = target->is_connected(),- .layout_node = target->unsafe_layout_node(read),- .result = result,- };- }- return result;- };- if (target->document().layout_is_up_to_date()) {- auto const* layout_node = target->unsafe_layout_node(read);- if (m_can_skip_per_frame_style_update_cache.has_value()- && m_can_skip_per_frame_style_update_cache->target_style_generation == target->animation_style_generation()- && m_can_skip_per_frame_style_update_cache->target_subtree_style_generation == target->animation_subtree_style_generation()- && m_can_skip_per_frame_style_update_cache->target_is_connected == target->is_connected()- && m_can_skip_per_frame_style_update_cache->layout_node == layout_node) {- HTML::note_rendering_trace_event("animation style skip cache hit"sv);- return m_can_skip_per_frame_style_update_cache->result;- }- if (m_can_skip_per_frame_style_update_cache.has_value())- HTML::note_rendering_trace_event("animation style skip cache miss"sv);- }-- // Restrict throttling within a rendered document to infinite transform-only effects until animation overflow- // updates can also be throttled safely.- if (!isinf(iteration_count()) || pseudo_element_type().has_value())- return cache_result(false);-- if (!target->is_connected())- return cache_result(true);- if (target->document().layout_is_up_to_date() && !may_animate_display() && target_is_unseen_in_display_none_subtree(*target))- return cache_result(true);- bool has_animated_property = false;- auto const* key_frame_set = m_key_frame_set.ptr();- if (!key_frame_set)- return false;- for (auto const& keyframe : key_frame_set->keyframes_by_key) {- for (auto const& property : keyframe.properties) {- has_animated_property = true;- if (!first_is_one_of(property.key.id(),- CSS::PropertyID::Transform,- CSS::PropertyID::Translate,- CSS::PropertyID::Rotate,- CSS::PropertyID::Scale))- return cache_result(false);- }- }- if (!has_animated_property)- return cache_result(false);-- // NB: Transforms cannot affect rendering without a layout box. This also covers SVG content inside- // display-none subtrees and closed details elements.- if (target->document().layout_is_up_to_date() && !target->has_layout_box())- return cache_result(true);- if (target->namespace_uri() == Namespace::SVG)- return cache_result(false);-- if (m_is_offscreen_throttled)- return cache_result(true);-- if (!target->document().layout_is_up_to_date())- return false;- auto const* layout_node = target->unsafe_layout_node(read);- if (!layout_node || layout_node->visibility() != CSS::Visibility::Hidden)- return cache_result(false);-- bool has_visible_descendant = false;- layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {- if (descendant.visibility() != CSS::Visibility::Visible)- return TraversalDecision::Continue;- has_visible_descendant = true;- return TraversalDecision::Break;- });- if (has_visible_descendant)- return cache_result(false);-- return cache_result(true);-}--void KeyframeEffect::request_observation_sample()-{- if (m_needs_observation_sample)- return;- m_needs_observation_sample = true;- if (m_target_element)- m_target_element->document().set_needs_animated_style_update(*this);-}--bool KeyframeEffect::can_skip_per_frame_animation_tick() const-{- auto phase = this->phase();-- if (auto animation = associated_animation(); animation && !animation->pending()- && animation->play_state() == Bindings::AnimationPlayState::Running- && animation->playback_rate() > 0- && animation->timeline() && animation->timeline()->is_monotonically_increasing()- && phase == Phase::Before)- return true;-- if (!m_is_compositor_driven && !m_is_compositor_replaced && !can_skip_per_frame_style_update())- return false;-- // NB: Playing backward, an effect with an infinite iteration count finishes at time zero, and with a zero iteration- // duration it finishes at its end time. No timer wakes the main thread for either.- if (auto animation = associated_animation(); animation && isinf(iteration_count()) && (animation->playback_rate() < 0 || !isinf(end_time().value)))- return false;-- // A compositor-handled one-iteration effect has a document timer that wakes the main thread at its active end.- if ((m_is_compositor_driven || m_is_compositor_replaced) && (!isinf(iteration_count()) || m_is_observation_relevant_compositor_animation))- return true;-- // NB: Infinite effects cannot reach their natural end, and finite offscreen paint effects have an end timer.- // Neither needs a continuous tick for animationend listeners.- // NB: Starting or cancelling an active animation requests an update independently of playback.- // Only iteration events require future updates while a visually throttled effect runs.- return !css_animation_events_are_heard(phase == Phase::Active);-}--bool KeyframeEffect::may_run_on_the_compositor() const-{- return all_of(target_properties(), [](auto const& property) {- return first_is_one_of(property.id(), CSS::PropertyID::Opacity, CSS::PropertyID::BackgroundColor, CSS::PropertyID::Filter,- CSS::PropertyID::Translate, CSS::PropertyID::Rotate, CSS::PropertyID::Scale, CSS::PropertyID::Transform);- });-}--// Whether a listener on `target`, the nodes its events bubble to or its window hears an event `hears` names.-template<typename Hears>-static bool event_is_heard_at(DOM::Element& target, Hears const& hears)-{- for (auto* node = static_cast<DOM::Node*>(&target); node;) {- if (hears(*node))- return true;- if (auto assigned_slot = DOM::assigned_slot_for_node(*node))- node = assigned_slot.ptr();- else- node = node->parent_or_shadow_host();- }- auto window = target.document().window();- return window && hears(*window);-}--// Whether a listener hears the CSS animation events of the effect that need a tick: only its iteration events if-// `only_iteration_events`.-bool KeyframeEffect::css_animation_events_are_heard(bool only_iteration_events) const-{- // NB: SMIL animations raise time events at their animation element instead, which do not bubble.- if (auto animation = associated_animation(); animation && animation->is_smil_animation()) {- auto& animation_element = as<SVG::SMILAnimation>(*animation).animation_element();- if (only_iteration_events)- return animation_element.has_event_listener(HTML::EventNames::repeatEvent);- return animation_element.has_event_listener(HTML::EventNames::beginEvent)- || animation_element.has_event_listener(HTML::EventNames::endEvent)- || animation_element.has_event_listener(HTML::EventNames::repeatEvent);- }-- // Script animations do not dispatch CSS animation events, even when an ancestor listens for them.- if (auto animation = associated_animation(); animation && !animation->is_css_animation())- return false;-- auto target = this->target();- VERIFY(target);- return event_is_heard_at(*target, [only_iteration_events](DOM::EventTarget const& event_target) {- if (only_iteration_events)- return event_target.has_event_listener(HTML::EventNames::animationiteration)- || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration);-- return event_target.has_event_listener(HTML::EventNames::animationcancel)- || event_target.has_event_listener(HTML::EventNames::animationiteration)- || event_target.has_event_listener(HTML::EventNames::animationstart)- || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration)- || event_target.has_event_listener(HTML::EventNames::webkitAnimationStart);- });-}--static bool is_in_display_none_subtree_ignoring_animations(DOM::AbstractElement abstract_element)-{- if (abstract_element.pseudo_element().has_value() && abstract_element.element().installed_style(abstract_element.pseudo_element()).display_is_none_ignoring_animations())- return true;- return abstract_element.element().has_inclusive_ancestor_with_display_none_ignoring_animations();-}--void KeyframeEffect::update_computed_properties(AnimationUpdateContext& context)-{- auto target = this->target();- if (!target || !target->is_connected())- return;-- // An effect that animates `display` can be the very thing holding its `display: none` target visible, and- // the update being skipped is the one that applies or removes that override, so it must always run.- // NB: A descendant's retained style can still describe a display-none subtree while ancestor visibility- // reactions are propagating, so inspect the current target and ancestor styles before skipping its update.- // NB: Only a pseudo-element can skip it. What an element animates reaches the SVG paint servers below it, which- // keep their style under display: none.- DOM::AbstractElement abstract_element { *target, pseudo_element_type() };- if (abstract_element.pseudo_element().has_value()- && !target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Display))- && is_in_display_none_subtree_ignoring_animations(abstract_element))- return;-- target->update_animated_properties({}, pseudo_element_type(), *this, context);-}--void KeyframeEffect::update_computed_properties_for_style(AnimationUpdateContext& context, DOM::AbstractElement abstract_element)-{- auto& style_computer = abstract_element.element().document().style_computer();- auto& element_data = context.elements.ensure(abstract_element, [&abstract_element, &style_computer] {- auto const& style = abstract_element.installed_style();- if (!style)- return AnimationUpdateContext::ElementData {};- auto computed_properties = style_computer.reconstruct_computed_properties_for_animation(style);- return AnimationUpdateContext::ElementData { style, move(computed_properties) };- });-- if (!element_data.target_style)- return;- element_data.effects.append(*this);-}--Bindings::CompositeOperation css_animation_composition_to_bindings_composite_operation(CSS::AnimationComposition composition)-{- switch (composition) {- case CSS::AnimationComposition::Accumulate:- return Bindings::CompositeOperation::Accumulate;- case CSS::AnimationComposition::Add:- return Bindings::CompositeOperation::Add;- case CSS::AnimationComposition::Replace:- return Bindings::CompositeOperation::Replace;- }- VERIFY_NOT_REACHED();-}--Bindings::CompositeOperationOrAuto css_animation_composition_to_bindings_composite_operation_or_auto(CSS::AnimationComposition composition)-{- switch (composition) {- case CSS::AnimationComposition::Accumulate:- return Bindings::CompositeOperationOrAuto::Accumulate;- case CSS::AnimationComposition::Add:- return Bindings::CompositeOperationOrAuto::Add;- case CSS::AnimationComposition::Replace:- return Bindings::CompositeOperationOrAuto::Replace;- }- VERIFY_NOT_REACHED();-}--CompositeOperation css_animation_composition_to_composite_operation(CSS::AnimationComposition composition)-{- return css_animation_composition_to_bindings_composite_operation(composition);-}--CompositeOperationOrAuto css_animation_composition_to_composite_operation_or_auto(CSS::AnimationComposition composition)-{- return css_animation_composition_to_bindings_composite_operation_or_auto(composition);-}--}diff --git a/Libraries/LibWeb/Animations/KeyframeEffect.h b/Libraries/LibWeb/Animations/KeyframeEffect.hdeleted file mode 100644index 9279d8ec9ab..00000000000--- a/Libraries/LibWeb/Animations/KeyframeEffect.h+++ /dev/null@@ -1,277 +0,0 @@-/*- * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/OwnPtr.h>-#include <AK/RedBlackTree.h>-#include <AK/String.h>-#include <AK/Types.h>-#include <LibGC/Ptr.h>-#include <LibGC/RootVector.h>-#include <LibJS/Forward.h>-#include <LibJS/Runtime/Value.h>-#include <LibWeb/Animations/AnimationEffect.h>-#include <LibWeb/Bindings/KeyframeEffect.h>-#include <LibWeb/CSS/PropertyNameAndID.h>-#include <LibWeb/CSS/Selector.h>-#include <LibWeb/CSS/StyleValues/StyleValue.h>-#include <LibWeb/Painting/CompositorAnimationEffectState.h>--namespace Web::Animations {--using EasingValue = Variant<Utf16String, CSS::EasingFunction>;-using CompositeOperation = Bindings::CompositeOperation;-using CompositeOperationOrAuto = Bindings::CompositeOperationOrAuto;--Bindings::CompositeOperation css_animation_composition_to_bindings_composite_operation(CSS::AnimationComposition composition);-Bindings::CompositeOperationOrAuto css_animation_composition_to_bindings_composite_operation_or_auto(CSS::AnimationComposition composition);--// https://www.w3.org/TR/web-animations-1/#dictdef-basepropertyindexedkeyframe-// Note: This is an intermediate structure used only when parsing Keyframes provided by the caller in a slightly-// different format. It is converted to BaseKeyframe, which is why it doesn't need to store the parsed properties-struct BasePropertyIndexedKeyframe {- Variant<Optional<double>, Vector<Optional<double>>> offset { Vector<Optional<double>> {} };- Variant<EasingValue, Vector<EasingValue>> easing { Vector<EasingValue> {} };- Variant<Bindings::CompositeOperationOrAuto, Vector<Bindings::CompositeOperationOrAuto>> composite { Vector<Bindings::CompositeOperationOrAuto> {} };-- HashMap<Utf16FlyString, Vector<Utf16String>> properties {};-};--CompositeOperation css_animation_composition_to_composite_operation(CSS::AnimationComposition composition);-CompositeOperationOrAuto css_animation_composition_to_composite_operation_or_auto(CSS::AnimationComposition composition);--// https://www.w3.org/TR/web-animations-1/#dictdef-basekeyframe-struct BaseKeyframe {- using UnparsedProperties = HashMap<Utf16FlyString, Utf16String>;- using ParsedProperties = HashMap<CSS::PropertyNameAndID, CSS::RustStyleValueHandle>;-- Optional<double> offset {};- EasingValue easing { "linear"_utf16 };- Bindings::CompositeOperationOrAuto composite { Bindings::CompositeOperationOrAuto::Auto };-- Optional<double> computed_offset {};-- Variant<UnparsedProperties, ParsedProperties> properties { UnparsedProperties {} };-- UnparsedProperties& unparsed_properties() { return properties.get<UnparsedProperties>(); }- UnparsedProperties const& unparsed_properties() const { return properties.get<UnparsedProperties>(); }- ParsedProperties& parsed_properties() { return properties.get<ParsedProperties>(); }- ParsedProperties const& parsed_properties() const { return properties.get<ParsedProperties>(); }-};--void compute_missing_keyframe_offsets(Vector<BaseKeyframe>&);--// https://www.w3.org/TR/web-animations-1/#the-keyframeeffect-interface-class KeyframeEffect final : public AnimationEffect {- WEB_WRAPPABLE(KeyframeEffect, AnimationEffect);- GC_DECLARE_ALLOCATOR(KeyframeEffect);--public:- constexpr static double AnimationKeyFrameKeyScaleFactor = 1000.0; // 0..100000-- struct Options {- OptionalEffectTiming timing {};- CompositeOperation composite { CompositeOperation::Replace };- Optional<CSS::Selector::PseudoElementSelector> pseudo_element;- };-- struct KeyFrameSet : public RefCounted<KeyFrameSet> {- struct StyleSheetResourceContext {- String base_url;- bool origin_clean { false };- };- struct UseInitial { };- struct ResolvedKeyFrame {- // These style values can be unresolved, as they may be generated from a @keyframes rule, well- // before they are applied to an element- HashMap<CSS::PropertyNameAndID, Variant<UseInitial, CSS::RustStyleValueHandle>> properties {};- CompositeOperationOrAuto composite { CompositeOperationOrAuto::Auto };- Variant<Empty, CSS::EasingFunction, CSS::RustStyleValueHandle> easing {};- };- struct CSSKeyframe {- u64 key;- ResolvedKeyFrame values;- };- Optional<Vector<CSSKeyframe>> css_keyframes;- Optional<double> computed_value_zoom;- RedBlackTree<u64, ResolvedKeyFrame> keyframes_by_key;- Optional<StyleSheetResourceContext> style_sheet_resource_context;- };- static void generate_initial_and_final_frames(RefPtr<KeyFrameSet>, HashTable<CSS::PropertyNameAndID> const& animated_properties);-- static int composite_order(GC::Ref<KeyframeEffect>, GC::Ref<KeyframeEffect>);-- static GC::Ref<KeyframeEffect> create();-- static WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> create_from_processed_keyframes(- GC::Ptr<DOM::Element> target,- Vector<BaseKeyframe> keyframes,- Variant<double, Options> options);-- static WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> construct_impl(- JS::Realm&,- GC::Ptr<DOM::Element> target,- GC::Ptr<JS::Object> keyframes,- Variant<double, Bindings::KeyframeEffectOptions> const& options);- static WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> construct_impl(GC::Ref<KeyframeEffect> source);- static WebIDL::ExceptionOr<GC::Ref<KeyframeEffect>> create_copy(GC::Ref<KeyframeEffect> source);-- virtual GC::Ptr<DOM::Element> target() const override { return m_target_element; }- void set_target(GC::Ptr<DOM::Element> target);-- // JS bindings- Optional<Utf16String> pseudo_element() const;- WebIDL::ExceptionOr<void> set_pseudo_element(Optional<Utf16String>);-- Optional<DOM::AbstractElement> target_abstract_element() const;- enum class InvalidateEffect {- No,- Yes,- };- void set_target(DOM::AbstractElement, InvalidateEffect = InvalidateEffect::Yes);-- Optional<CSS::PseudoElement> pseudo_element_type() const;- void set_pseudo_element(Optional<CSS::Selector::PseudoElementSelector> pseudo_element) { m_target_pseudo_selector = pseudo_element; }-- Bindings::CompositeOperation composite_for_bindings() const;- void set_composite_for_bindings(Bindings::CompositeOperation value) { set_composite(value); }- Bindings::CompositeOperation composite() const { return m_composite; }- void set_composite(Bindings::CompositeOperation value);-- Vector<BaseKeyframe> const& keyframes() const { return m_keyframes; }- void set_keyframes(Vector<BaseKeyframe>, Optional<KeyFrameSet::StyleSheetResourceContext> = {});- WebIDL::ExceptionOr<void> set_keyframes_from_js(JS::Realm&, GC::Ptr<JS::Object>);- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<JS::Object>>> get_keyframes(JS::Object& relevant_global_object);-- KeyFrameSet const* key_frame_set() const { return m_key_frame_set; }- void set_key_frame_set(RefPtr<KeyFrameSet const>);-- virtual bool is_keyframe_effect() const override { return true; }-- bool can_skip_per_frame_style_update() const;- void clear_per_frame_style_update_cache() { m_can_skip_per_frame_style_update_cache.clear(); }- bool can_skip_per_frame_animation_tick() const;- // Whether a compositor animation may run every property the effect targets.- bool may_run_on_the_compositor() const;- bool is_compositor_driven() const { return m_is_compositor_driven; }- void set_is_compositor_driven(bool value)- {- if (m_is_compositor_driven == value)- return;- m_is_compositor_driven = value;- m_can_skip_per_frame_style_update_cache.clear();- }- bool is_compositor_replaced() const { return m_is_compositor_replaced; }- void set_is_compositor_replaced(bool value)- {- if (m_is_compositor_replaced == value)- return;- m_is_compositor_replaced = value;- m_can_skip_per_frame_style_update_cache.clear();- }- // The compositor animations built from this effect live in Rust; the state is made when first needed.- Painting::CompositorAnimationEffectState& compositor_animation_state();- bool has_retained_compositor_animations() const { return m_compositor_animation_state && m_compositor_animation_state->has_retained(); }- void clear_retained_compositor_animations()- {- if (m_compositor_animation_state)- m_compositor_animation_state->clear_retained();- }- void clear_pending_compositor_animations()- {- if (m_compositor_animation_state)- m_compositor_animation_state->clear_pending();- }- void set_is_offscreen_throttled(bool value)- {- if (m_is_offscreen_throttled == value)- return;- m_is_offscreen_throttled = value;- m_can_skip_per_frame_style_update_cache.clear();- }- bool is_offscreen_throttled() const { return m_is_offscreen_throttled; }- void set_is_observation_relevant_compositor_animation(bool value) { m_is_observation_relevant_compositor_animation = value; }- bool is_observation_relevant_compositor_animation() const { return m_is_observation_relevant_compositor_animation; }- void request_observation_sample();- u64 animation_preparation_identity() const { return m_animation_preparation_identity; }- u64 animation_preparation_generation() const { return m_animation_preparation_generation; }- void invalidate_animation_preparation() { ++m_animation_preparation_generation; }- bool request_element_scoped_observation_sample(u64 task_generation)- {- if (m_last_element_scoped_observation_sample_task_generation == task_generation)- return false;- m_last_element_scoped_observation_sample_task_generation = task_generation;- request_observation_sample();- return true;- }- bool observation_sample_requested() const { return m_needs_observation_sample; }- bool consume_observation_sample_request() { return exchange(m_needs_observation_sample, false); }- bool per_frame_animation_tick_was_skipped() const { return m_per_frame_animation_tick_was_skipped; }- void note_per_frame_animation_tick_was_skipped() { m_per_frame_animation_tick_was_skipped = true; }- void clear_per_frame_animation_tick_was_skipped() { m_per_frame_animation_tick_was_skipped = false; }- virtual void update_computed_properties(AnimationUpdateContext&) override;- void update_computed_properties_for_style(AnimationUpdateContext&, DOM::AbstractElement);--private:- bool may_animate_display() const;- bool css_animation_events_are_heard(bool only_iteration_events) const;-- friend class Animation;-- KeyframeEffect();- virtual ~KeyframeEffect() override = default;-- void invalidate_effect();-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // https://www.w3.org/TR/web-animations-1/#effect-target-target-element- GC::Ptr<DOM::Element> m_target_element {};-- // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-pseudoelement- Optional<CSS::Selector::PseudoElementSelector> m_target_pseudo_selector {};-- // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-composite- CompositeOperation m_composite { CompositeOperation::Replace };-- // https://www.w3.org/TR/web-animations-1/#keyframe- Vector<BaseKeyframe> m_keyframes {};-- // A cached version of m_keyframes suitable for returning from get_keyframes()- Vector<GC::Ref<JS::Object>> m_keyframe_objects_cache {};-- CSS::EasingFunction default_keyframe_easing() const;- Vector<BaseKeyframe> declared_css_keyframes() const;- Vector<BaseKeyframe> computed_css_keyframes() const;- bool m_keyframes_from_css { false };- bool m_ignore_css_keyframes { false };- RefPtr<KeyFrameSet const> m_key_frame_set {};- u64 m_animation_preparation_identity { 0 };- u64 m_animation_preparation_generation { 0 };- OwnPtr<Painting::CompositorAnimationEffectState> m_compositor_animation_state;- bool m_is_compositor_driven { false };- bool m_is_compositor_replaced { false };- bool m_is_offscreen_throttled { false };- bool m_is_observation_relevant_compositor_animation { false };- bool m_needs_observation_sample { false };- struct CanSkipPerFrameStyleUpdateCache {- u64 target_style_generation { 0 };- u64 target_subtree_style_generation { 0 };- bool target_is_connected { false };- Layout::Node const* layout_node { nullptr };- bool result { false };- };- mutable Optional<CanSkipPerFrameStyleUpdateCache> m_can_skip_per_frame_style_update_cache;- Optional<u64> m_last_element_scoped_observation_sample_task_generation;- bool m_per_frame_animation_tick_was_skipped { false };-};--WebIDL::ExceptionOr<Vector<BaseKeyframe>> process_keyframes(JS::Realm&, GC::Ptr<JS::Object>);-WebIDL::ExceptionOr<KeyframeEffect::Options> keyframe_effect_options_from_bindings(Bindings::KeyframeEffectOptions const&);--}diff --git a/Libraries/LibWeb/Animations/KeyframeEffect.idl b/Libraries/LibWeb/Animations/KeyframeEffect.idlindex 20200983c32..40b59431d86 100644--- a/Libraries/LibWeb/Animations/KeyframeEffect.idl+++ b/Libraries/LibWeb/Animations/KeyframeEffect.idl@@ -11,14 +11,14 @@ dictionary KeyframeEffectOptions : EffectTiming {};// https://drafts.csswg.org/web-animations-1/#the-keyframeeffect-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface KeyframeEffect : AnimationEffect {- constructor(Element? target, object? keyframes, optional (unrestricted double or KeyframeEffectOptions) options = {});- constructor(KeyframeEffect source);+ [ImplementedAs=construct] constructor(Element? target, object? keyframes, optional (unrestricted double or KeyframeEffectOptions) options = {});+ [ImplementedAs=construct_from_source] constructor(KeyframeEffect source);attribute Element? target;attribute CSSOMString? pseudoElement;- [ImplementedAs=composite_for_bindings] attribute CompositeOperation composite;+ attribute CompositeOperation composite;sequence<object> getKeyframes();- [ImplementedAs=set_keyframes_from_js, NeedsCallerRealm] undefined setKeyframes(object? keyframes);+ undefined setKeyframes(object? keyframes);};diff --git a/Libraries/LibWeb/Animations/KeyframeSetHandle.h b/Libraries/LibWeb/Animations/KeyframeSetHandle.hnew file mode 100644index 00000000000..e540f1eb726--- /dev/null+++ b/Libraries/LibWeb/Animations/KeyframeSetHandle.h@@ -0,0 +1,155 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/AnyOf.h>+#include <AK/BinarySearch.h>+#include <AK/StdLibExtras.h>+#include <LibWeb/Animations/RustFFI.h>+#include <LibWeb/CSS/PropertyNameAndID.h>++namespace Web::Animations {++// https://www.w3.org/TR/web-animations-1/#target-property+// The properties the keyframes of a set animate, borrowed from the set for as long as what lent it holds it.+class TargetProperties {+public:+ TargetProperties() = default;+ explicit TargetProperties(RustFFI::FfiKeyframeSetFacts const& facts)+ : m_properties(facts.target_properties, facts.target_property_count)+ , m_custom_properties(facts.target_custom_properties, facts.target_custom_property_count)+ {+ }++ bool is_empty() const { return size() == 0; }+ size_t size() const { return m_properties.size() + m_custom_properties.size(); }++ bool contains(CSS::PropertyNameAndID const& property) const+ {+ if (!property.is_custom_property())+ return binary_search(m_properties, static_cast<u16>(property.id())) != nullptr;+ return any_of(m_custom_properties, [&](size_t name) { return Utf16FlyString::from_raw(name) == property.name(); });+ }++ class Iterator {+ public:+ CSS::PropertyNameAndID operator*() const+ {+ if (m_index < m_properties->m_properties.size())+ return CSS::PropertyNameAndID::from_id(static_cast<CSS::PropertyID>(m_properties->m_properties[m_index]));+ return CSS::PropertyNameAndID::from_name(Utf16FlyString::from_raw(m_properties->m_custom_properties[m_index - m_properties->m_properties.size()])).release_value();+ }++ Iterator& operator++()+ {+ ++m_index;+ return *this;+ }++ bool operator==(Iterator const& other) const { return m_index == other.m_index; }++ private:+ friend class TargetProperties;++ Iterator(TargetProperties const& properties, size_t index)+ : m_properties(&properties)+ , m_index(index)+ {+ }++ TargetProperties const* m_properties { nullptr };+ size_t m_index { 0 };+ };++ Iterator begin() const { return { *this, 0 }; }+ Iterator end() const { return { *this, size() }; }++private:+ ReadonlySpan<u16> m_properties;+ ReadonlySpan<size_t> m_custom_properties;+};++// A borrowed view of an immutable keyframe set, valid for as long as what lent it holds the set.+class KeyframeSetView {+public:+ KeyframeSetView() = default;+ explicit KeyframeSetView(RustFFI::KeyframeSet const* set)+ : m_set(set)+ {+ }++ RustFFI::KeyframeSet const* ptr() const { return m_set; }+ explicit operator bool() const { return m_set; }+ bool operator==(KeyframeSetView const& other) const { return m_set == other.m_set; }++ size_t keyframe_count() const { return RustFFI::animations_keyframe_set_facts(m_set).keyframe_count; }+ RustFFI::FfiKeyframeValue value(size_t index, u16 property_id) const { return RustFFI::animations_keyframe_set_value(m_set, index, property_id); }+ RustFFI::FfiKeyframeSetFacts facts() const { return RustFFI::animations_keyframe_set_facts(m_set); }+ TargetProperties target_properties() const { return m_set ? TargetProperties { facts() } : TargetProperties {}; }++protected:+ RustFFI::KeyframeSet const* m_set { nullptr };+};++// A reference to an immutable keyframe set, which Rust owns and shares between everything that runs it.+class KeyframeSetHandle : public KeyframeSetView {+public:+ KeyframeSetHandle() = default;++ // Takes over the one reference a keyframe set builder handed out.+ static KeyframeSetHandle adopt(RustFFI::KeyframeSet const* set)+ {+ KeyframeSetHandle handle;+ handle.m_set = set;+ return handle;+ }++ // Takes a reference of its own to a set something else holds one to.+ static KeyframeSetHandle retained(RustFFI::KeyframeSet const* set)+ {+ if (set)+ RustFFI::animations_keyframe_set_retain(set);+ return adopt(set);+ }++ KeyframeSetHandle(KeyframeSetHandle const& other)+ : KeyframeSetHandle(retained(other.m_set))+ {+ }++ KeyframeSetHandle(KeyframeSetHandle&& other)+ : KeyframeSetView(exchange(other.m_set, nullptr))+ {+ }++ KeyframeSetHandle& operator=(KeyframeSetHandle const& other)+ {+ if (this != &other)+ *this = retained(other.m_set);+ return *this;+ }++ KeyframeSetHandle& operator=(KeyframeSetHandle&& other)+ {+ if (this != &other) {+ release();+ m_set = exchange(other.m_set, nullptr);+ }+ return *this;+ }++ ~KeyframeSetHandle() { release(); }++private:+ void release()+ {+ if (auto const* set = exchange(m_set, nullptr))+ RustFFI::animations_keyframe_set_release(set);+ }+};++}diff --git a/Libraries/LibWeb/Animations/NamedTimelines.cpp b/Libraries/LibWeb/Animations/NamedTimelines.cppindex f5e1f8e8768..e0dffd47d0a 100644--- a/Libraries/LibWeb/Animations/NamedTimelines.cpp+++ b/Libraries/LibWeb/Animations/NamedTimelines.cpp@@ -135,31 +135,31 @@ NamedTimelines::DeclaringElement const* NamedTimelines::declaring_element(DOM::Ereturn &m_declaring_elements[*index];}-GC::Ref<ScrollTimeline> NamedTimelines::timeline_for(DOM::Element& element, Declaration const& declaration)+GC::Ref<AnimationTimeline> NamedTimelines::timeline_for(DOM::Element& element, Declaration const& declaration){TimelineKey key { element, declaration.name };if (auto existing = m_timelines.get(key); existing.has_value()) {// An element may only define one timeline per name, which keeps its identity while its axis and inset change.- if (auto* view_timeline = as_if<ViewTimeline>(*existing.value()); view_timeline && declaration.is_view) {- view_timeline->set_axis_and_inset(declaration.axis, declaration.view_inset);+ if (existing.value()->is_view_timeline() && declaration.is_view) {+ existing.value()->set_axis_and_inset(declaration.axis, declaration.view_inset);return *existing;}- if (!is<ViewTimeline>(*existing.value()) && !declaration.is_view) {+ if (!existing.value()->is_view_timeline() && !declaration.is_view) {existing.value()->set_axis(declaration.axis);return *existing;}}HTML::TemporaryExecutionContext context { m_document->relevant_settings_object() };- GC::Ref<ScrollTimeline> timeline = declaration.is_view- ? GC::Ref<ScrollTimeline> { ViewTimeline::create(m_document, DOM::AbstractElement { element }, declaration.axis, declaration.view_inset) }- : ScrollTimeline::create(m_document, GC::Ptr<DOM::Element const> { &element }, declaration.axis);+ auto timeline = declaration.is_view+ ? AnimationTimeline::create_view_timeline(m_document, DOM::AbstractElement { element }, declaration.axis, declaration.view_inset)+ : AnimationTimeline::create_scroll_timeline(m_document, GC::Ptr<DOM::Element const> { &element }, declaration.axis);m_timelines.set(key, timeline);return timeline;}// https://drafts.csswg.org/scroll-animations-1/#target-timeline-GC::Ptr<ScrollTimeline> NamedTimelines::target_timeline(DOM::AbstractElement const& element, Utf16FlyString const& name)+GC::Ptr<AnimationTimeline> NamedTimelines::target_timeline(DOM::AbstractElement const& element, Utf16FlyString const& name){refresh_declarations();@@ -212,9 +212,9 @@ GC::Ptr<ScrollTimeline> NamedTimelines::target_timeline(DOM::AbstractElement conreturn nullptr;}-void NamedTimelines::track_animation(CSS::CSSAnimation& animation)+void NamedTimelines::track_animation(AnimationRef const& animation){- m_tracked_animations.set(animation);+ m_document->animations_following_named_timelines().set(animation);}bool NamedTimelines::update_tracked_animations()@@ -223,14 +223,12 @@ bool NamedTimelines::update_tracked_animations()if (!m_tracked_animations_need_update)return false;m_tracked_animations_need_update = false;- GC::RootVector<GC::Ref<CSS::CSSAnimation>> animations;- for (auto& animation : m_tracked_animations)+ GC::RootVector<AnimationRef> animations;+ for (auto const& animation : m_document->animations_following_named_timelines())animations.append(animation);bool any_timeline_changed = false;- for (auto& animation : animations) {- auto previous_timeline = animation->timeline();- animation->update_named_timeline();- if (animation->timeline() != previous_timeline)+ for (auto const& animation : animations) {+ if (CSS::CSSAnimation::update_named_timeline(animation))any_timeline_changed = true;}return any_timeline_changed;diff --git a/Libraries/LibWeb/Animations/NamedTimelines.h b/Libraries/LibWeb/Animations/NamedTimelines.hindex 934a61ddbc7..ecc2e8368e6 100644--- a/Libraries/LibWeb/Animations/NamedTimelines.h+++ b/Libraries/LibWeb/Animations/NamedTimelines.h@@ -12,8 +12,8 @@#include <LibGC/Cell.h>#include <LibGC/CellAllocator.h>#include <LibGC/Ptr.h>-#include <LibGC/WeakHashSet.h>-#include <LibWeb/Animations/ViewTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/Forward.h>namespace Web::Animations {@@ -29,11 +29,11 @@ public:[[nodiscard]] static GC::Ref<NamedTimelines> create(DOM::Document&);// https://drafts.csswg.org/scroll-animations-1/#target-timeline- GC::Ptr<ScrollTimeline> target_timeline(DOM::AbstractElement const&, Utf16FlyString const& name);+ GC::Ptr<AnimationTimeline> target_timeline(DOM::AbstractElement const&, Utf16FlyString const& name);- // Tracks an animation whose timeline is a named timeline, so that it follows the timeline its name finds as the+ // Tracks a CSS animation whose timeline is a named timeline, so that it follows the timeline its name finds as the// declarations of the document change.- void track_animation(CSS::CSSAnimation&);+ void track_animation(AnimationRef const&);// Looks the timelines of the tracked animations up again, where the declarations of the document have changed.// Returns whether any animation changed its timeline.@@ -48,7 +48,7 @@ private:Utf16FlyString name;bool is_view { false };ScrollAxis axis { ScrollAxis::Block };- ViewTimeline::Inset view_inset;+ ViewTimelineInset view_inset;};struct DeclaringElement {GC::Ref<DOM::Element> element;@@ -65,7 +65,7 @@ private:void refresh_declarations();DeclaringElement const* declaring_element(DOM::Element const&) const;- GC::Ref<ScrollTimeline> timeline_for(DOM::Element&, Declaration const&);+ GC::Ref<AnimationTimeline> timeline_for(DOM::Element&, Declaration const&);GC::Ref<DOM::Document> m_document;@@ -84,9 +84,9 @@ private:struct TimelineKeyTraits : public DefaultTraits<TimelineKey> {static unsigned hash(TimelineKey const& key) { return pair_int_hash(ptr_hash(key.element.ptr()), key.name.hash()); }};- HashMap<TimelineKey, GC::Ref<ScrollTimeline>, TimelineKeyTraits> m_timelines;+ HashMap<TimelineKey, GC::Ref<AnimationTimeline>, TimelineKeyTraits> m_timelines;- GC::WeakHashSet<CSS::CSSAnimation> m_tracked_animations;+ // NB: The document holds the tracked animations, as its animations following named timelines.bool m_tracked_animations_need_update { false };};diff --git a/Libraries/LibWeb/Animations/PseudoElementParsing.cpp b/Libraries/LibWeb/Animations/PseudoElementParsing.cppdeleted file mode 100644index 7827016cbf1..00000000000--- a/Libraries/LibWeb/Animations/PseudoElementParsing.cpp+++ /dev/null@@ -1,28 +0,0 @@-/*- * Copyright (c) 2024, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include "PseudoElementParsing.h"-#include <LibWeb/CSS/Parser/Parser.h>--namespace Web::Animations {--static WebIDL::ExceptionOr<Optional<CSS::Selector::PseudoElementSelector>> pseudo_element_parsing_impl(Optional<Utf16String> const& value)-{- Optional<CSS::Selector::PseudoElementSelector> pseudo_element;- if (value.has_value()) {- pseudo_element = parse_pseudo_element_selector(CSS::Parser::ParsingParams {}, *value);- if (!pseudo_element.has_value())- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid pseudo-element selector: \"{}\"", value.value()));- }- return pseudo_element;-}--WebIDL::ExceptionOr<Optional<CSS::Selector::PseudoElementSelector>> pseudo_element_parsing(Optional<Utf16String> const& value)-{- return pseudo_element_parsing_impl(value);-}--}diff --git a/Libraries/LibWeb/Animations/PseudoElementParsing.h b/Libraries/LibWeb/Animations/PseudoElementParsing.hdeleted file mode 100644index c76c23eef64..00000000000--- a/Libraries/LibWeb/Animations/PseudoElementParsing.h+++ /dev/null@@ -1,19 +0,0 @@-/*- * Copyright (c) 2024, Sam Atkins <[email protected]>- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Optional.h>-#include <AK/Utf16String.h>-#include <LibWeb/CSS/Selector.h>-#include <LibWeb/WebIDL/ExceptionOr.h>--namespace Web::Animations {--// https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudo-element-parsing-WebIDL::ExceptionOr<Optional<CSS::Selector::PseudoElementSelector>> pseudo_element_parsing(Optional<Utf16String> const&);--}diff --git a/Libraries/LibWeb/Animations/RecordHandles.cpp b/Libraries/LibWeb/Animations/RecordHandles.cppnew file mode 100644index 00000000000..1b3f99fb965--- /dev/null+++ b/Libraries/LibWeb/Animations/RecordHandles.cpp@@ -0,0 +1,975 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#include <LibGC/RootVector.h>+#include <LibJS/HostClassBuilder.h>+#include <LibJS/Runtime/Realm.h>+#include <LibWeb/Animations/AnimationEffect.h>+#include <LibWeb/Animations/AnimationTimeline.h>+#include <LibWeb/Animations/RecordHandles.h>+#include <LibWeb/CSS/CSSStyleProperties.h>+#include <LibWeb/CSS/ComputedStyleWorkingSet.h>+#include <LibWeb/CSS/CustomPropertyData.h>+#include <LibWeb/CSS/CustomPropertyRegistration.h>+#include <LibWeb/CSS/Selector.h>+#include <LibWeb/CSS/StyleComputer.h>+#include <LibWeb/CSS/StyleEngineInput.h>+#include <LibWeb/CSS/StyleValues/ComputationContext.h>+#include <LibWeb/CSS/StyleValues/StyleValue.h>+#include <LibWeb/CSS/Zoom.h>+#include <LibWeb/DOM/AbstractElement.h>+#include <LibWeb/DOM/Document.h>+#include <LibWeb/DOM/Element.h>+#include <LibWeb/DOM/Event.h>+#include <LibWeb/DOM/EventTarget.h>+#include <LibWeb/DOM/Slot.h>+#include <LibWeb/HTML/EventLoop/EventLoop.h>+#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/HTML/HTMLSlotElement.h>+#include <LibWeb/HTML/LocalNavigable.h>+#include <LibWeb/HTML/NavigableContainer.h>+#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>+#include <LibWeb/HTML/Window.h>+#include <LibWeb/HighResolutionTime/TimeOrigin.h>+#include <LibWeb/Layout/LayoutRustFFI.h>+#include <LibWeb/Layout/Node.h>+#include <LibWeb/Layout/NodeArena.h>+#include <LibWeb/Layout/RenderDocument.h>+#include <LibWeb/Layout/Viewport.h>+#include <LibWeb/Namespace.h>+#include <LibWeb/Painting/CompositorAnimationEffectState.h>+#include <LibWeb/Painting/Scrolling.h>+#include <LibWeb/SVG/SVGAnimationElement.h>+#include <LibWeb/SVG/SVGElement.h>++namespace Web::Animations {++void visit_host_cell(void* visitor, void* cell, RustFFI::HostCellKind kind)+{+ auto& cell_visitor = *static_cast<GC::Cell::Visitor*>(visitor);+ switch (kind) {+ case RustFFI::HostCellKind::Cell:+ cell_visitor.visit(static_cast<GC::Cell*>(cell));+ return;+ case RustFFI::HostCellKind::Element:+ cell_visitor.visit(static_cast<DOM::Element*>(cell));+ return;+ }+ VERIFY_NOT_REACHED();+}++extern "C" {++// Declared in Bindings/Rust/src/css/animation_event.rs.+void web_animation_visit_host_cells(RustFFI::AnimationCell const*, void* visitor);+}++void web_animation_visit_host_cells(RustFFI::AnimationCell const* animation, void* visitor)+{+ RustFFI::animations_animation_visit_host_cells(animation, visitor, visit_host_cell);+}++void keep_animation_alive_in(void* root_vector, RustFFI::AnimationCell const* animation)+{+ static_cast<GC::RootVector<AnimationRef>*>(root_vector)->append(AnimationRef { *animation });+}++i32 AnimationRef::composite_order(AnimationRef const& a, AnimationRef const& b)+{+ return RustFFI::animations_composite_order(&a.record(), &b.record(), compare_elements_in_tree_order_for_composite_order);+}++Optional<CSS::PseudoElement> EffectRef::pseudo_element_type() const+{+ auto pseudo_element = RustFFI::animations_effect_target(&record()).pseudo_element;+ if (!pseudo_element.serialization)+ return {};+ return static_cast<CSS::PseudoElement>(pseudo_element.kind);+}++Optional<DOM::AbstractElement> EffectRef::target_abstract_element() const+{+ if (auto* target = this->target())+ return DOM::AbstractElement { *target, pseudo_element_type() };+ return {};+}++CSS::EasingFunction::Descriptor EffectRef::timing_function_with_points_in(Vector<CSS::EasingFunction::LinearPoint>& storage) const+{+ auto descriptor = RustFFI::animations_effect_timing_function(&record()).descriptor;+ storage.append(descriptor.linear_points, descriptor.linear_point_count);+ descriptor.linear_points = storage.data();+ descriptor.linear_point_count = storage.size();+ return descriptor;+}++RustFFI::FfiResolvedEffectTiming EffectRef::resolve_timing() const+{+ auto animation = associated_animation();+ auto local_time = animation.has_value() ? animation->timing_state().current_time : to_ffi(Optional<TimeValue> {});+ return RustFFI::animations_effect_resolve_timing(&record(), local_time, timing().fill_mode, animation.has_value() ? &animation->record() : nullptr, false);+}++Painting::CompositorAnimationEffectState EffectRef::compositor_animation_state() const+{+ return Painting::CompositorAnimationEffectState { RustFFI::animations_effect_compositor_animation_state(&record(), RustFFI::CompositorAnimationStateAccess::CreateIfMissing) };+}++Optional<Painting::CompositorAnimationEffectState> EffectRef::existing_compositor_animation_state() const+{+ if (auto* state = RustFFI::animations_effect_compositor_animation_state(&record(), RustFFI::CompositorAnimationStateAccess::Existing))+ return Painting::CompositorAnimationEffectState { state };+ return {};+}++bool EffectRef::has_retained_compositor_animations() const+{+ auto state = existing_compositor_animation_state();+ return state.has_value() && state->has_retained();+}++// Whether nothing shows the target's style, as a display: none ancestor leaves the target without a box.+// NB: SVG resources keep their style under display: none, where boxes elsewhere in the document can reference them.+static bool target_is_unseen_in_display_none_subtree(DOM::Element const& target)+{+ if (target.has_layout_box() || !target.has_inclusive_ancestor_with_display_none_ignoring_animations())+ return false;+ bool has_referenceable_svg_element = false;+ target.for_each_in_inclusive_subtree_of_type<SVG::SVGElement>([&](SVG::SVGElement const& element) {+ if (!element.is_referenceable_in_display_none_subtree())+ return TraversalDecision::Continue;+ has_referenceable_svg_element = true;+ return TraversalDecision::Break;+ });+ return !has_referenceable_svg_element;+}++// NB: A custom property can feed the display of the target through var().+bool EffectRef::may_animate_display() const+{+ return any_of(target_properties(), [](auto const& property) {+ return property.id() == CSS::PropertyID::Display || property.is_custom_property();+ });+}++bool EffectRef::can_skip_per_frame_style_update() const+{+ if (is_compositor_driven() || is_compositor_replaced())+ return true;+ if (is_offscreen_throttled() && all_of(target_properties(), [](auto const& property) {+ return !first_is_one_of(property.id(), CSS::PropertyID::Transform, CSS::PropertyID::Translate, CSS::PropertyID::Rotate, CSS::PropertyID::Scale);+ }))+ return true;++ auto* target = this->target();+ if (!target)+ return false;++ // An animation inside a box-less iframe can't affect its embedding document's rendering. Check the containers+ // before the target-local cache, since their layout can change without changing the target's style or layout box.+ // Reverse playback and effects with a finite end time need ticks to finish, even with an infinite iteration count.+ auto const timing = this->timing();+ if (auto animation = associated_animation(); animation.has_value()) {+ auto const state = animation->timing_state();+ if (state.playback.playback_rate > 0 && isinf(timing.iteration_count) && isinf(state.end_time.value)) {+ for (auto navigable = target->document().navigable(); navigable;) {+ auto container = navigable->container();+ if (!container)+ break;+ if (container->document().layout_is_up_to_date() && !container->has_layout_box())+ return true;+ navigable = container->document().navigable();+ }+ }+ }++ Layout::ForcedReadScope read { target->document() };+ auto skip_key = [&] {+ return RustFFI::PerFrameStyleUpdateSkipKey {+ .target_style_generation = target->animation_style_generation(),+ .target_subtree_style_generation = target->animation_subtree_style_generation(),+ .layout_node = bit_cast<FlatPtr>(target->unsafe_layout_node(read)),+ .target_is_connected = target->is_connected(),+ };+ };+ auto cache_result = [&](bool result) {+ if (target->document().layout_is_up_to_date()) {+ auto key = skip_key();+ RustFFI::animations_effect_note_per_frame_style_update_skip_decision(&record(), &key, result);+ }+ return result;+ };+ if (target->document().layout_is_up_to_date()) {+ auto key = skip_key();+ switch (RustFFI::animations_effect_per_frame_style_update_skip_decision(&record(), &key)) {+ case RustFFI::PerFrameStyleUpdateSkipDecision::CanSkip:+ HTML::note_rendering_trace_event("animation style skip cache hit"sv);+ return true;+ case RustFFI::PerFrameStyleUpdateSkipDecision::CannotSkip:+ HTML::note_rendering_trace_event("animation style skip cache hit"sv);+ return false;+ case RustFFI::PerFrameStyleUpdateSkipDecision::Stale:+ HTML::note_rendering_trace_event("animation style skip cache miss"sv);+ break;+ case RustFFI::PerFrameStyleUpdateSkipDecision::Unknown:+ break;+ }+ }++ // Restrict throttling within a rendered document to infinite transform-only effects until animation overflow+ // updates can also be throttled safely.+ if (!isinf(timing.iteration_count) || pseudo_element_type().has_value())+ return cache_result(false);++ if (!target->is_connected())+ return cache_result(true);+ if (target->document().layout_is_up_to_date() && !may_animate_display() && target_is_unseen_in_display_none_subtree(*target))+ return cache_result(true);+ if (!keyframe_set())+ return false;+ if (target_properties().is_empty() || any_of(target_properties(), [](auto const& property) {+ return !first_is_one_of(property.id(),+ CSS::PropertyID::Transform,+ CSS::PropertyID::Translate,+ CSS::PropertyID::Rotate,+ CSS::PropertyID::Scale);+ }))+ return cache_result(false);++ // NB: Transforms cannot affect rendering without a layout box. This also covers SVG content inside+ // display-none subtrees and closed details elements.+ if (target->document().layout_is_up_to_date() && !target->has_layout_box())+ return cache_result(true);+ if (target->namespace_uri() == Namespace::SVG)+ return cache_result(false);++ if (is_offscreen_throttled())+ return cache_result(true);++ if (!target->document().layout_is_up_to_date())+ return false;+ auto const* layout_node = target->unsafe_layout_node(read);+ if (!layout_node || layout_node->visibility() != CSS::Visibility::Hidden)+ return cache_result(false);++ bool has_visible_descendant = false;+ layout_node->for_each_in_inclusive_subtree_of_type<Layout::NodeWithStyle>([&](auto const& descendant) {+ if (descendant.visibility() != CSS::Visibility::Visible)+ return TraversalDecision::Continue;+ has_visible_descendant = true;+ return TraversalDecision::Break;+ });+ if (has_visible_descendant)+ return cache_result(false);++ return cache_result(true);+}++void EffectRef::set_composite(CSS::StyleValueFFI::FfiCompositeOperation composite) const+{+ RustFFI::animations_effect_set_composite(&record(), composite);+ invalidate();+}++void EffectRef::set_keyframe_set(KeyframeSetHandle keyframe_set) const+{+ if (this->keyframe_set() == keyframe_set)+ return;++ if (!RustFFI::animations_effect_set_keyframe_set(&record(), keyframe_set.ptr()))+ return;+ if (auto* target = this->target())+ CSS::record_attr_names_read_by_keyframes(*target, this->keyframe_set());+ invalidate();+}++void EffectRef::set_target(DOM::Element* target, InvalidateEffect invalidate) const+{+ // NB: The record associates the associated animation with the new target rather than the old.+ RustFFI::animations_effect_set_target_element(&record(), target, perform_host_effect);+ if (invalidate == InvalidateEffect::No)+ return;++ if (target)+ CSS::record_attr_names_read_by_keyframes(*target, keyframe_set());+ this->invalidate();+ // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and+ // it will remain "stuck" until it's style is fully invalidated for some other reason.+}++void EffectRef::set_target(DOM::AbstractElement abstract_element, InvalidateEffect invalidate) const+{+ if (invalidate == InvalidateEffect::Yes) {+ set_target(&abstract_element.element());+ } else {+ VERIFY(!associated_animation().has_value());+ set_target(&abstract_element.element(), InvalidateEffect::No);+ CSS::record_attr_names_read_by_keyframes(abstract_element.element(), keyframe_set());+ }+ set_pseudo_element(abstract_element.pseudo_element());+}++void EffectRef::set_pseudo_element(Optional<CSS::PseudoElement> pseudo_element) const+{+ if (!pseudo_element.has_value()) {+ RustFFI::animations_effect_set_pseudo_element(&record(), { .kind = 0, .serialization = 0 });+ return;+ }+ Utf16FlyString serialization { CSS::Selector::PseudoElementSelector { *pseudo_element }.serialize() };+ RustFFI::animations_effect_set_pseudo_element(&record(), { .kind = to_underlying(*pseudo_element), .serialization = serialization.raw_identity() });+}++void EffectRef::invalidate() const+{+ RustFFI::animations_effect_forget_what_the_host_concluded(&record());+ if (auto* target = this->target())+ target->document().set_needs_animated_style_update(*this);+}++void EffectRef::request_observation_sample() const+{+ if (set_flag(RustFFI::EffectFlag::NeedsObservationSample, true))+ note_observation_sample_requested();+}++bool EffectRef::request_element_scoped_observation_sample(u64 task_generation) const+{+ switch (RustFFI::animations_effect_request_observation_sample_in_task(&record(), task_generation)) {+ case RustFFI::ObservationSampleRequest::AlreadyRequestedInTask:+ return false;+ case RustFFI::ObservationSampleRequest::Requested:+ return true;+ case RustFFI::ObservationSampleRequest::NewlyRequested:+ note_observation_sample_requested();+ return true;+ }+ VERIFY_NOT_REACHED();+}++void EffectRef::note_observation_sample_requested() const+{+ if (auto* target = this->target())+ target->document().set_needs_animated_style_update(*this);+}++bool EffectRef::can_skip_per_frame_animation_tick() const+{+ auto animation = associated_animation();+ auto const state = animation.has_value() ? animation->timing_state() : RustFFI::FfiAnimationTimingState {};+ auto const phase = animation.has_value() ? state.phase : resolve_timing().phase;+ auto const timing = this->timing();++ if (animation.has_value() && !state.playback.has_pending_play_task && !state.playback.has_pending_pause_task+ && state.play_state == RustFFI::AnimationPlayState::Running+ && state.playback.playback_rate > 0+ && state.has_monotonically_increasing_timeline+ && phase == RustFFI::AnimationEffectPhase::Before)+ return true;++ if (!is_compositor_driven() && !is_compositor_replaced() && !can_skip_per_frame_style_update())+ return false;++ // NB: Playing backward, an effect with an infinite iteration count finishes at time zero, and with a zero iteration+ // duration it finishes at its end time. No timer wakes the main thread for either.+ if (animation.has_value() && isinf(timing.iteration_count) && (state.playback.playback_rate < 0 || !isinf(state.end_time.value)))+ return false;++ // A compositor-handled one-iteration effect has a document timer that wakes the main thread at its active end.+ if ((is_compositor_driven() || is_compositor_replaced()) && (!isinf(timing.iteration_count) || is_observation_relevant_compositor_animation()))+ return true;++ // NB: Infinite effects cannot reach their natural end, and finite offscreen paint effects have an end timer.+ // Neither needs a continuous tick for animationend listeners.+ // NB: Starting or cancelling an active animation requests an update independently of playback.+ // Only iteration events require future updates while a visually throttled effect runs.+ return !css_animation_events_are_heard(state, phase == RustFFI::AnimationEffectPhase::Active);+}++// Whether a listener on `target`, the nodes its events bubble to or its window hears an event `hears` names.+template<typename Hears>+static bool event_is_heard_at(DOM::Element& target, Hears const& hears)+{+ for (auto* node = static_cast<DOM::Node*>(&target); node;) {+ if (hears(*node))+ return true;+ if (auto assigned_slot = DOM::assigned_slot_for_node(*node))+ node = assigned_slot.ptr();+ else+ node = node->parent_or_shadow_host();+ }+ auto window = target.document().window();+ return window && hears(*window);+}++// Whether a listener hears the CSS animation events of the effect, whose associated animation's timing is `state`,+// that need a tick: only its iteration events if `only_iteration_events`.+bool EffectRef::css_animation_events_are_heard(RustFFI::FfiAnimationTimingState const& state, bool only_iteration_events) const+{+ auto animation = associated_animation();++ // NB: SMIL animations raise time events at their animation element instead, which do not bubble.+ if (animation.has_value() && state.kind == RustFFI::FfiAnimationKind::Smil) {+ auto& animation_element = *static_cast<SVG::SVGAnimationElement*>(RustFFI::animations_smil_animation_element(&animation->record()));+ if (only_iteration_events)+ return animation_element.has_event_listener(HTML::EventNames::repeatEvent);+ return animation_element.has_event_listener(HTML::EventNames::beginEvent)+ || animation_element.has_event_listener(HTML::EventNames::endEvent)+ || animation_element.has_event_listener(HTML::EventNames::repeatEvent);+ }++ // Script animations do not dispatch CSS animation events, even when an ancestor listens for them.+ if (animation.has_value() && state.kind != RustFFI::FfiAnimationKind::CssAnimation)+ return false;++ auto* target = this->target();+ VERIFY(target);+ return event_is_heard_at(*target, [only_iteration_events](DOM::EventTarget const& event_target) {+ if (only_iteration_events)+ return event_target.has_event_listener(HTML::EventNames::animationiteration)+ || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration);++ return event_target.has_event_listener(HTML::EventNames::animationcancel)+ || event_target.has_event_listener(HTML::EventNames::animationiteration)+ || event_target.has_event_listener(HTML::EventNames::animationstart)+ || event_target.has_event_listener(HTML::EventNames::webkitAnimationIteration)+ || event_target.has_event_listener(HTML::EventNames::webkitAnimationStart);+ });+}++static bool is_in_display_none_subtree_ignoring_animations(DOM::AbstractElement abstract_element)+{+ if (abstract_element.pseudo_element().has_value() && abstract_element.element().installed_style(abstract_element.pseudo_element()).display_is_none_ignoring_animations())+ return true;+ return abstract_element.element().has_inclusive_ancestor_with_display_none_ignoring_animations();+}++void EffectRef::update_computed_properties(AnimationUpdateContext& context) const+{+ auto* target = this->target();+ if (!target || !target->is_connected())+ return;++ // An effect that animates `display` can be the very thing holding its `display: none` target visible, and+ // the update being skipped is the one that applies or removes that override, so it must always run.+ // NB: A descendant's retained style can still describe a display-none subtree while ancestor visibility+ // reactions are propagating, so inspect the current target and ancestor styles before skipping its update.+ // NB: Only a pseudo-element can skip it. What an element animates reaches the SVG paint servers below it, which+ // keep their style under display: none.+ DOM::AbstractElement abstract_element { *target, pseudo_element_type() };+ if (abstract_element.pseudo_element().has_value()+ && !target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Display))+ && is_in_display_none_subtree_ignoring_animations(abstract_element))+ return;++ target->update_animated_properties({}, pseudo_element_type(), *this, context);+}++extern "C" {++// Declared in Bindings/Rust/src/animations/animation.rs.+void* web_animation_object_realm(RustFFI::AnimationCell const*);+void* web_animation_object_event_target(RustFFI::AnimationCell const*);+size_t web_animation_object_memory_size(RustFFI::AnimationCell const*);+void web_animation_perform_promise_effect(JSVM*, RustFFI::FfiHostEffect const*);++// Defined in Bindings/Rust/src/animations/exports.rs.+void* web_animation_playback_event_create(JSVM*, void* realm, FlatPtr event_name, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time);++// What Bindings/Rust/src/animations asks of the host.+void web_animation_perform_host_effect(RustFFI::FfiHostEffect const*);+void web_animation_update_style_of_owning_element(RustFFI::AnimationCell const*);+void web_animation_update_style_of_owning_element_document(RustFFI::AnimationCell const*);+void* web_animation_realm_of_element(DOM::Element*);+void* web_animation_document_timeline_of_document(DOM::Document*);+void web_animation_visit_named_cells(RustFFI::AnimationCell const*, void* visitor);+}++static Optional<DOM::AbstractElement> owning_element_of(AnimationRef const& animation)+{+ auto owner = RustFFI::animations_animation_owning_element(&animation.record());+ if (!owner.element)+ return {};+ Optional<CSS::PseudoElement> pseudo_element;+ if (owner.has_pseudo_element)+ pseudo_element = static_cast<CSS::PseudoElement>(owner.pseudo_element);+ return DOM::AbstractElement { *static_cast<DOM::Element*>(owner.element), pseudo_element };+}++// NB: Script observes a CSS animation or transition with the style of its owning element computed.+void web_animation_update_style_of_owning_element(RustFFI::AnimationCell const* record)+{+ if (auto owning_element = owning_element_of(AnimationRef { *record }); owning_element.has_value())+ owning_element->document().update_style_for_element(*owning_element, DOM::Document::StyleUpdateMode::OnlyIfNeeded);+}++// NB: Script observes the play state of an animation with the style of the document of its owning element computed.+void web_animation_update_style_of_owning_element_document(RustFFI::AnimationCell const* record)+{+ if (auto owning_element = owning_element_of(AnimationRef { *record }); owning_element.has_value())+ owning_element->document().update_style();+}++void* web_animation_realm_of_element(DOM::Element* element)+{+ return &HTML::relevant_realm(element->document());+}++void* web_animation_document_timeline_of_document(DOM::Document* document)+{+ return document->timeline().ptr();+}++void web_animation_visit_named_cells(RustFFI::AnimationCell const* animation, void* visitor)+{+ RustFFI::animations_animation_visit_named_cells(animation, visitor, visit_host_cell);+}++void set_owning_element(AnimationRef const& animation, DOM::AbstractElement owner)+{+ auto pseudo_element = owner.pseudo_element();+ RustFFI::animations_animation_set_owning_element(&animation.record(), {+ .element = const_cast<DOM::Element*>(&owner.element()),+ .pseudo_element = pseudo_element.has_value() ? to_underlying(*pseudo_element) : u8 { 0 },+ .has_pseudo_element = pseudo_element.has_value(),+ });+}++size_t object_memory_size(AnimationRef const& animation)+{+ return web_animation_object_memory_size(&animation.record());+}++void AnimationRef::visit_edges(GC::Cell::Visitor& visitor) const+{+ RustFFI::animations_animation_visit_host_cells(&record(), &visitor, visit_host_cell);+}++// https://www.w3.org/TR/web-animations-1/#animation-relevant+bool AnimationRef::is_relevant() const+{+ // NB: The local time of the associated effect is the current time of the animation.+ auto state = timing_state();+ return RustFFI::animations_is_relevant(&record(), state.has_effect ? state.current_time : to_ffi(Optional<TimeValue> {}));+}++void AnimationRef::update() const+{+ RustFFI::animations_animation_update(&record(), perform_host_effect);+}++void AnimationRef::disassociate_from_target_if_inert() const+{+ RustFFI::animations_animation_disassociate_from_target_if_inert(&record(), perform_host_effect);+}++void AnimationRef::run_pending_play_task_if_ready() const+{+ RustFFI::animations_animation_run_pending_play_task_if_ready(&record(), perform_host_effect);+}++void AnimationRef::cancel(bool invalidate) const+{+ // Note: When called from JS, we always want to invalidate the animation target's style. However, this method is+ // also called from the StyleComputer when the animation-name CSS property changes. That happens in the+ // middle of a cascade, and importantly, _before_ computing the animation effect stack, so there is no+ // need for another invalidation. It would also schedule a redundant follow-up reaction while the current+ // style computation is already updating the animation effect stack.++ // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.+ Optional<HTML::TemporaryExecutionContext> execution_context;+ if (timing_state().play_state != RustFFI::AnimationPlayState::Idle)+ execution_context.emplace(HTML::relevant_realm(relevant_global_object_of(*this)));++ RustFFI::animations_animation_cancel(&record(), invalidate, perform_host_effect);+}++i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second)+{+ auto& first_element = *static_cast<DOM::Element*>(first);+ auto& second_element = *static_cast<DOM::Element*>(second);+ return first_element.document().compare_elements_in_tree_order_for_composite_order(first_element, second_element);+}++// The realm of the object of the animation, or null where it has none.+static JS::Realm* realm_of_object(AnimationRef const& animation)+{+ return static_cast<JS::Realm*>(web_animation_object_realm(&animation.record()));+}++JS::Object& relevant_global_object_of(AnimationRef const& animation)+{+ if (auto* realm = realm_of_object(animation))+ return realm->global_object();+ auto* element = static_cast<DOM::Element*>(RustFFI::animations_animation_owning_element(&animation.record()).element);+ if (!element)+ element = static_cast<DOM::Element*>(RustFFI::animations_smil_animation_element(&animation.record()));+ VERIFY(element);+ return element->document().relevant_settings_object().global_object();+}++// Whether an invalidation changes the animation as the last rendering update planned it for the render clock, rather+// than move it on in time, as a rendering update does.+enum class ChangesPlan : bool {+ No,+ Yes,+};++// Invalidates the style the associated effect of the animation produces.+static void invalidate_effect(AnimationRef const& animation, ChangesPlan changes_plan)+{+ auto effect = animation.effect();+ if (!effect.has_value())+ return;+ // The render clock's lanes tick the document's animations as the last rendering update planned them.+ if (auto* target = effect->target(); changes_plan == ChangesPlan::Yes && target && target->document().layout_node_arena_if_created())+ Layout::RustFFI::document_host_note_animation_change(target->document().layout_node_arena_if_created()->host());+ effect->invalidate();+}++// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state+// https://www.w3.org/TR/web-animations-1/#cancel-an-animation+// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations+static Utf16FlyString const& playback_event_type_name(RustFFI::PlaybackEventType type)+{+ switch (type) {+ case RustFFI::PlaybackEventType::Finish:+ return HTML::EventNames::finish;+ case RustFFI::PlaybackEventType::Cancel:+ return HTML::EventNames::cancel;+ case RustFFI::PlaybackEventType::Remove:+ return HTML::EventNames::remove;+ }+ VERIFY_NOT_REACHED();+}++// NB: A remove event is created in the realm of the document whose replaced animations are removed, which is the+// document for timing of the animation, and whose pending animation event queue it joins.+static JS::Realm& playback_event_realm(JS::Realm& realm, RustFFI::PlaybackEventType type, DOM::Document const* document_for_timing)+{+ if (type == RustFFI::PlaybackEventType::Remove && document_for_timing)+ return HTML::relevant_realm(*document_for_timing);+ return realm;+}++// A new AnimationPlaybackEvent of the type, created in the realm.+// https://drafts.csswg.org/web-animations-2/#animationplaybackevent+static GC::Ref<DOM::Event> create_animation_playback_event(JS::Realm& realm, Utf16FlyString const& type, RustFFI::OptionalTimeValue current_time, RustFFI::OptionalTimeValue timeline_time)+{+ auto* event = web_animation_playback_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), current_time, timeline_time);+ return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };+}++static DOM::EventTarget& event_target_of_object(AnimationRef const& animation)+{+ return *static_cast<DOM::EventTarget*>(static_cast<GC::Cell*>(web_animation_object_event_target(&animation.record())));+}++// https://www.w3.org/TR/web-animations-1/#animation-document-for-timing+static GC::Ptr<DOM::Document> document_for_timing(AnimationRef const& animation)+{+ // An animation’s document for timing is the Document with which its timeline is associated. If an animation is not+ // associated with a timeline, or its timeline is not associated with a document, then it has no document for+ // timing.+ auto* timeline = static_cast<AnimationTimeline*>(RustFFI::animations_animation_timeline(&animation.record()));+ if (!timeline)+ return {};+ return timeline->associated_document();+}++static void queue_playback_event(AnimationRef const& animation, JS::Realm& realm, RustFFI::FfiHostEffect const& effect)+{+ auto is_finish = effect.playback_event_type == RustFFI::PlaybackEventType::Finish;+ auto document = document_for_timing(animation);+ auto& event_realm = playback_event_realm(realm, effect.playback_event_type, document.ptr());++ // If animation has a document for timing, then append the event to its document for timing's pending animation+ // event queue along with its target, animation.+ if (document) {+ // https://www.w3.org/TR/web-animations-1/#animation-time-to-origin-relative-time+ // NB: The procedure converted the time to a timeline time.+ Optional<double> scheduled_event_time;+ auto* timeline = static_cast<AnimationTimeline*>(RustFFI::animations_animation_timeline(&animation.record()));+ if (auto timeline_time = from_ffi(effect.scheduled_timeline_time); timeline_time.has_value()+ && timeline && !timeline->is_inactive() && timeline->can_convert_a_timeline_time_to_an_origin_relative_time())+ scheduled_event_time = timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline_time);+ // NB: The queue holds what the event is, which the document creates as it dispatches it, with the time stamp+ // of now, when the event is created in the spec.+ document->append_pending_animation_event(animation, {+ .kind = RustFFI::PendingAnimationEventKind::Playback,+ .css_event_type = {},+ .playback_event_type = effect.playback_event_type,+ .time_event_type = {},+ .detail = 0,+ .elapsed_time = 0,+ .current_time = effect.current_time,+ .timeline_time = effect.timeline_time,+ .scheduled_event_time = to_ffi(scheduled_event_time),+ .time_stamp = HighResolutionTime::current_high_resolution_time(event_realm.global_object()),+ });+ return;+ }++ auto event = create_animation_playback_event(event_realm, playback_event_type_name(effect.playback_event_type), effect.current_time, effect.timeline_time);+ auto& target = event_target_of_object(animation);++ // Otherwise, queue a task to dispatch the event at animation. The task source for this task is the DOM manipulation+ // task source.+ if (!is_finish) {+ HTML::queue_global_task(HTML::Task::Source::DOMManipulation, realm.global_object(), GC::create_function(GC::Heap::the(), GC::captures(target, event), [](auto& target, auto& event) {+ target.dispatch_event(event);+ }));+ return;+ }++ // NB: The task to dispatch a finish event is created manually so its ID can be saved.+ auto& window_document = HTML::relevant_window(realm.global_object()).associated_document();+ auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &window_document, GC::create_function(GC::Heap::the(), GC::captures(target, event), [](auto& target, auto& event) {+ target.dispatch_event(event);+ }));+ RustFFI::animations_animation_set_finish_notification_task(&animation.record(), task->id().value());+ (void)HTML::main_thread_event_loop().task_queue().add(task);+}++void dispatch_pending_playback_event(AnimationRef const& animation, DOM::Document const& document, RustFFI::FfiPendingAnimationEvent const& pending_event)+{+ auto* realm = realm_of_object(animation);+ VERIFY(realm);+ auto event = create_animation_playback_event(playback_event_realm(*realm, pending_event.playback_event_type, &document), playback_event_type_name(pending_event.playback_event_type), pending_event.current_time, pending_event.timeline_time);+ event->set_time_stamp(pending_event.time_stamp);+ event_target_of_object(animation).dispatch_event(event);+}++void web_animation_perform_host_effect(RustFFI::FfiHostEffect const* host_effect)+{+ perform_host_effect(host_effect);+}++void perform_host_effect(RustFFI::FfiHostEffect const* host_effect)+{+ auto const& effect = *host_effect;+ AnimationRef animation { *effect.animation };+ auto effect_target = [&] -> DOM::Element* {+ auto associated_effect = animation.effect();+ return associated_effect.has_value() ? associated_effect->target() : nullptr;+ };+ using Kind = RustFFI::FfiHostEffectKind;+ switch (effect.kind) {+ case Kind::ReplaceReadyPromise:+ case Kind::ResolveReadyPromise:+ case Kind::RejectReadyPromise:+ case Kind::ReplaceFinishedPromise:+ case Kind::ResolveFinishedPromise:+ case Kind::RejectFinishedPromise:+ // NB: Only an animation with an object has promises script can observe.+ web_animation_perform_promise_effect(JS::HostABI::vm_to_abi(JS::VM::the()), host_effect);+ return;+ case Kind::QueuePlaybackEvent:+ // NB: Only an animation with an object can hear its playback events.+ if (auto* realm = realm_of_object(animation))+ queue_playback_event(animation, *realm, effect);+ return;+ case Kind::QueueFinishNotificationTask: {+ // NB: The task runs whether or not the animation has an object, as the finish notification steps note that the+ // animation finished.+ auto& global = relevant_global_object_of(animation);+ auto& document = HTML::relevant_window(global).associated_document();+ auto task = HTML::Task::create(HTML::Task::Source::DOMManipulation, &document, GC::create_function(GC::Heap::the(), GC::captures(animation, global), [](AnimationRef const& animation, JS::Object& global) {+ HTML::TemporaryExecutionContext context { HTML::relevant_realm(global) };+ RustFFI::animations_animation_run_finish_notification_steps(&animation.record(), perform_host_effect);+ }));+ RustFFI::animations_animation_set_finish_notification_task(&animation.record(), task->id().value());+ (void)HTML::main_thread_event_loop().task_queue().add(move(task));+ return;+ }+ case Kind::CancelFinishNotificationTask:+ HTML::main_thread_event_loop().task_queue().remove_tasks_matching([id = HTML::TaskID { effect.task }](auto const& task) {+ return task.id() == id;+ });+ return;+ case Kind::InvalidateEffect:+ invalidate_effect(animation, effect.changes_plan ? ChangesPlan::Yes : ChangesPlan::No);+ return;+ case Kind::InvalidateUnlessThrottled: {+ auto keyframe_effect = animation.effect();+ if (!keyframe_effect.has_value())+ return;+ if (keyframe_effect->can_skip_per_frame_style_update()) {+ if (auto* target = keyframe_effect->target())+ target->document().note_throttled_animation_style_update();+ } else if (effect.invalidate) {+ invalidate_effect(animation, ChangesPlan::No);+ }+ return;+ }+ case Kind::AssociateWithTarget:+ static_cast<DOM::Element*>(effect.element)->associate_with_animation(animation);+ return;+ case Kind::DisassociateFromTarget:+ static_cast<DOM::Element*>(effect.element)->disassociate_with_animation(animation, EffectRef { *effect.effect });+ return;+ case Kind::RecomputeEffectStyle: {+ AnimationUpdateContext context;+ EffectRef { *effect.effect }.update_computed_properties(context);+ return;+ }+ case Kind::RequestRepaint:+ if (auto* target = effect_target())+ target->set_needs_repaint(InvalidateDisplayList::No);+ return;+ case Kind::ScheduleWakeup:+ if (auto* target = effect_target())+ target->document().schedule_compositor_animation_wakeup(effect.delay);+ return;+ }+ VERIFY_NOT_REACHED();+}++// NB: What committing the computed styles of an animation answers its bindings.+enum class CommitStylesResult : u8 {+ Committed,+ TargetCannotHaveInlineStyle,+ TargetIsNotBeingRendered,+};++extern "C" WEB_API CommitStylesResult web_animation_commit_styles(RustFFI::AnimationCell const* animation_cell);++// https://drafts.csswg.org/web-animations-1/#commit-computed-styles+extern "C" WEB_API CommitStylesResult web_animation_commit_styles(RustFFI::AnimationCell const* animation_cell)+{+ AnimationRef animation { *animation_cell };++ // 1. Let targets be the set of all effect targets for animation effects associated with animation.+ auto effect = animation.effect();+ if (!effect.has_value() || !effect->target())+ return CommitStylesResult::Committed;+ GC::Ref<DOM::Element> target = *effect->target();++ // 2. For each target in targets:+ // 1. If target is not an element capable of having a style attribute (for example, it is a pseudo-element or is+ // an element in a document format for which style attributes are not defined) throw a+ // "NoModificationAllowedError" DOMException and abort these steps.+ auto const& namespace_uri = target->namespace_uri();+ if (effect->pseudo_element_type().has_value() || (namespace_uri != Namespace::HTML && namespace_uri != Namespace::SVG && namespace_uri != Namespace::MathML))+ return CommitStylesResult::TargetCannotHaveInlineStyle;++ OrderedHashMap<CSS::PropertyNameAndID, NonnullRefPtr<CSS::StyleValue const>> declarations;+ {+ // 2. If, after applying any pending style changes, target is not being rendered, throw an "InvalidStateError"+ // DOMException and abort these steps.+ auto& document = target->document();+ Layout::ForcedReadScope read { document };+ document.update_layout(DOM::UpdateLayoutReason::AnimationCommitStyles);+ if (!target->is_connected() || !target->has_style())+ return CommitStylesResult::TargetIsNotBeingRendered;+ auto computed_style = target->computed_style();+ if (!target->unsafe_layout_node(read) && (!computed_style->display().is_contents() || computed_style->in_display_none_subtree()))+ return CommitStylesResult::TargetIsNotBeingRendered;++ // 4. Let targeted properties be the set of physical longhand properties that are a target property for at+ // least one animation effect associated with animation whose effect target is target.+ HashTable<CSS::PropertyNameAndID> targeted_properties;+ auto add_longhand = [&](CSS::PropertyID property) {+ auto physical_property = CSS::map_logical_alias_to_physical_property(property, { computed_style->writing_mode(), computed_style->direction() });+ targeted_properties.set(CSS::PropertyNameAndID::from_id(physical_property));+ };+ RustFFI::FfiKeyframeSetFacts facts {};+ if (auto keyframe_set = effect->keyframe_set())+ facts = keyframe_set.facts();+ for (auto raw_property : ReadonlySpan<u16> { facts.target_properties, facts.target_property_count }) {+ auto property = static_cast<CSS::PropertyID>(raw_property);+ if (CSS::property_is_shorthand(property)) {+ for (auto longhand : CSS::expanded_longhands_for_shorthand(property))+ add_longhand(longhand);+ } else {+ add_longhand(property);+ }+ }+ for (auto name : ReadonlySpan<FlatPtr> { reinterpret_cast<FlatPtr const*>(facts.target_custom_properties), facts.target_custom_property_count })+ targeted_properties.set(CSS::PropertyNameAndID::from_name(Utf16FlyString::from_raw(name)).release_value());++ // 5. For each property, property, in targeted properties:+ // 1. Let partialEffectStack be a copy of the effect stack for property on target.+ // 2. If animation's replace state is removed, add all animation effects associated with animation whose+ // effect target is target and that include property as a target property to partialEffectStack.+ // 3. Remove from partialEffectStack any animation effects whose associated animation has a higher composite+ // order than animation.+ Vector<EffectRef> effects;+ for (auto other_animation : target->associated_animations_in_composite_order()) {+ auto other_effect = other_animation.effect();+ if (other_effect.has_value() && !other_effect->pseudo_element_type().has_value()+ && RustFFI::animations_composite_order(&other_animation.record(), animation_cell, compare_elements_in_tree_order_for_composite_order) < 0)+ effects.append(other_effect.release_value());+ }+ effects.append(*effect);++ // 4. Let effect value be the result of calculating the result of partialEffectStack for property using+ // target's computed style (see §5.4.3 Calculating the result of an effect stack) and setting the+ // endpoint-inclusive active interval flag to true when calculating the animation effect phase+ // (see §4.6.6 Animation effect phases and states).+ DOM::AbstractElement element { target, {} };+ // NB: A timeline script observed ahead of its current time in this task is sampled at that time, as the style+ // update above was, so the committed values are those of the time script read.+ RefPtr<CSS::ComputedStyleWorkingSet> committed_style;+ auto commit = [&] { committed_style = document.style_computer().compute_style_for_animation_commit(read, element, effects.span()); };+ AnimationTimeline::at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), commit);+ auto style = committed_style.release_nonnull();+ auto custom_properties = element.custom_property_data();+ if (custom_properties && element.custom_property_data_is_animation_overlay())+ custom_properties = custom_properties->parent();+ for (auto const& property : targeted_properties) {+ if (property.is_custom_property()) {+ RefPtr<CSS::StyleValue const> value;+ if (auto animated_value = style->animated_custom_properties().get(property.name()); animated_value.has_value())+ value = **animated_value;+ else if (custom_properties) {+ if (auto base_value = custom_properties->get(property.name()); base_value.has_value())+ value = base_value->value;+ }+ if (!value) {+ if (auto registration = document.get_registered_custom_property(property.name()); registration.has_value() && registration->initial_value)+ value = CSS::compute_registered_custom_property_initial_value(document, *registration);+ }+ if (value)+ declarations.set(property, value.release_nonnull());+ } else {+ declarations.set(property, CSS::unscaled_by_zoom(property.id(), style->property(property.id()), computed_style->effective_zoom()));+ }+ }+ }++ // 3. Let inline style be the result of getting the CSS declaration block corresponding to target's style+ // attribute. If target does not have a style attribute, let inline style be a new empty CSS declaration block+ // with the owner node set to target.+ auto inline_style = target->style();+ // 5.5. Set a CSS declaration of property for effect value in inline style.+ // 6. Update style attribute for inline style.+ inline_style->set_computed_properties(declarations);+ return CommitStylesResult::Committed;+}++// NB: What the reflection of the keyframes of a CSS animation or transition asks of the style of its target.+extern "C" WEB_API bool web_animation_compute_css_keyframe_values(DOM::Element* target, bool has_pseudo_element, u8 pseudo_element, CSS::ComputedValuesFFI::FfiReflectedKeyframeProperty const* properties, size_t property_count, size_t keyframe_count, CSS::ComputedValuesFFI::FfiStyleSheetResourceContext const* resource_context, void* context, CSS::StyleComputer::CSSKeyframeValueCallback emit);+extern "C" WEB_API double web_animation_effective_zoom_of_target(DOM::Element* target, bool has_pseudo_element, u8 pseudo_element);++extern "C" WEB_API bool web_animation_compute_css_keyframe_values(DOM::Element* target, bool has_pseudo_element, u8 pseudo_element, CSS::ComputedValuesFFI::FfiReflectedKeyframeProperty const* properties, size_t property_count, size_t keyframe_count, CSS::ComputedValuesFFI::FfiStyleSheetResourceContext const* resource_context, void* context, CSS::StyleComputer::CSSKeyframeValueCallback emit)+{+ DOM::AbstractElement abstract_target { *target, has_pseudo_element ? static_cast<CSS::PseudoElement>(pseudo_element) : Optional<CSS::PseudoElement> {} };+ if (!abstract_target.installed_style())+ return false;+ target->document().style_computer().compute_css_keyframe_values(abstract_target, { properties, property_count }, keyframe_count, *resource_context, context, emit);+ return true;+}++extern "C" WEB_API double web_animation_effective_zoom_of_target(DOM::Element* target, bool has_pseudo_element, u8 pseudo_element)+{+ DOM::AbstractElement abstract_target { *target, has_pseudo_element ? static_cast<CSS::PseudoElement>(pseudo_element) : Optional<CSS::PseudoElement> {} };+ if (auto style = abstract_target.computed_style())+ return style->effective_zoom();+ return 1;+}++}diff --git a/Libraries/LibWeb/Animations/RecordHandles.h b/Libraries/LibWeb/Animations/RecordHandles.hnew file mode 100644index 00000000000..023362e7fa7--- /dev/null+++ b/Libraries/LibWeb/Animations/RecordHandles.h@@ -0,0 +1,325 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++#pragma once++#include <AK/Optional.h>+#include <AK/StdLibExtras.h>+#include <LibGC/Cell.h>+#include <LibWeb/Animations/KeyframeSetHandle.h>+#include <LibWeb/Animations/RustFFI.h>+#include <LibWeb/CSS/EasingFunction.h>+#include <LibWeb/Forward.h>++namespace Web::Painting {++class CompositorAnimationEffectState;++}++namespace Web::Animations {++struct AnimationUpdateContext;++namespace Detail {++struct AdoptRecord { };++}++// A reference to a record, which Rust owns and keeps alive for as long as anything references it.+template<typename Self, typename Record, void (*retain)(Record const*), void (*release)(Record const*)>+class RecordRef {+public:+ // Takes a reference of its own to a record something else holds one to.+ explicit RecordRef(Record const& record)+ : m_record(&record)+ {+ retain(m_record);+ }++ // Takes over a reference Rust handed out.+ RecordRef(Detail::AdoptRecord, Record const& record)+ : m_record(&record)+ {+ }++ static Self adopt(Record const& record) { return Self { Detail::AdoptRecord {}, record }; }++ RecordRef(RecordRef const& other)+ : RecordRef(*other.m_record)+ {+ }++ RecordRef(RecordRef&& other)+ : m_record(exchange(other.m_record, nullptr))+ {+ }++ RecordRef& operator=(RecordRef const& other)+ {+ if (this != &other)+ *this = RecordRef { *other.m_record };+ return *this;+ }++ RecordRef& operator=(RecordRef&& other)+ {+ if (this != &other) {+ drop();+ m_record = exchange(other.m_record, nullptr);+ }+ return *this;+ }++ ~RecordRef() { drop(); }++ Record const& record() const { return *m_record; }++ bool operator==(RecordRef const& other) const { return m_record == other.m_record; }++private:+ void drop()+ {+ if (auto const* record = exchange(m_record, nullptr))+ release(record);+ }++ Record const* m_record { nullptr };+};++class EffectRef;++// A reference to the record of an animation.+class AnimationRef : public RecordRef<AnimationRef, RustFFI::AnimationCell, RustFFI::animations_animation_retain, RustFFI::animations_animation_unretain> {+public:+ using RecordRef::RecordRef;++ // Visits what keeps the elements the record names alive: the animation's Animation, or, for an animation without+ // one, those elements. A holder the GC traces visits this.+ void visit_edges(GC::Cell::Visitor&) const;++ // https://www.w3.org/TR/web-animations-1/#animation-associated-effect+ Optional<EffectRef> effect() const;++ // https://www.w3.org/TR/web-animations-1/#animation-relevant+ bool is_relevant() const;++ // What the host's per-frame decisions read of the animation now.+ RustFFI::FfiAnimationTimingState timing_state() const { return RustFFI::animations_animation_timing_state(&record(), false, 0); }+ // The same, with the current time of the animation at `timestamp` too.+ RustFFI::FfiAnimationTimingState timing_state_at_timestamp(double timestamp) const { return RustFFI::animations_animation_timing_state(&record(), true, timestamp); }++ // Updates the animation as its timeline updated its current time.+ void update() const;+ // https://www.w3.org/TR/web-animations-1/#dom-animation-cancel+ // Cancels the animation, invalidating the style of its target where `invalidate`.+ void cancel(bool invalidate = true) const;+ // Runs the pending play task of the animation if it is ready.+ void run_pending_play_task_if_ready() const;+ // Disassociates the animation from the target of its associated effect where it is inert, where a procedure+ // scheduled that.+ void disassociate_from_target_if_inert() const;++ // https://www.w3.org/TR/web-animations-1/#animation-composite-order+ static i32 composite_order(AnimationRef const&, AnimationRef const&);+};++// A reference to the record of an animation effect.+class EffectRef : public RecordRef<EffectRef, RustFFI::AnimationEffectCell, RustFFI::animations_effect_retain, RustFFI::animations_effect_release> {+public:+ using RecordRef::RecordRef;++ // A new KeyframeEffect's state, with the default timing, no keyframes and no target, as a CSS animation or+ // transition creates its associated effect.+ static EffectRef create_keyframe_effect();++ // Visits what keeps the element the record targets alive: the effect's AnimationEffect, or, for an effect without+ // one, that element. A holder the GC traces visits this.+ void visit_edges(GC::Cell::Visitor&) const;++ RustFFI::AnimationEffectId id() const { return RustFFI::animations_effect_id(&record()); }++ // https://www.w3.org/TR/web-animations-1/#animation-associated-effect+ // The animation whose associated effect this effect is.+ Optional<AnimationRef> associated_animation() const;++ // https://www.w3.org/TR/web-animations-1/#effect-target+ DOM::Element* target() const { return static_cast<DOM::Element*>(RustFFI::animations_effect_target(&record()).element); }+ enum class InvalidateEffect : bool {+ No,+ Yes,+ };+ // Sets the target element, and where `invalidate`, notes what the keyframes read of it and invalidates the style+ // the effect produces.+ void set_target(DOM::Element*, InvalidateEffect = InvalidateEffect::Yes) const;+ void set_target(DOM::AbstractElement, InvalidateEffect = InvalidateEffect::Yes) const;+ void set_pseudo_element(Optional<CSS::PseudoElement>) const;+ Optional<CSS::PseudoElement> pseudo_element_type() const;+ Optional<DOM::AbstractElement> target_abstract_element() const;++ // The keyframes the effect runs, which the view borrows until they change.+ KeyframeSetView keyframe_set() const { return KeyframeSetView { RustFFI::animations_effect_keyframe_set(&record()) }; }+ // https://www.w3.org/TR/web-animations-1/#target-property+ // The properties the effect's keyframes animate, borrowed until its keyframes change.+ TargetProperties target_properties() const { return keyframe_set().target_properties(); }+ bool composite_is_replace() const { return RustFFI::animations_effect_composite(&record()) == CSS::StyleValueFFI::FfiCompositeOperation::Replace; }+ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-composite+ void set_composite(CSS::StyleValueFFI::FfiCompositeOperation) const;+ // Sets the keyframes the effect runs, invalidating the style it produces where they change.+ void set_keyframe_set(KeyframeSetHandle) const;+ // The normalized timing the timing model reads of the effect.+ RustFFI::AnimationEffectTiming timing() const { return RustFFI::animations_effect_timing(&record()); }+ // The descriptor reads the timing function's control points from a copy in storage the caller keeps alive.+ CSS::EasingFunction::Descriptor timing_function_with_points_in(Vector<CSS::EasingFunction::LinearPoint>& storage) const;++ // The timing of the effect at its local time, the current time of its associated animation.+ RustFFI::FfiResolvedEffectTiming resolve_timing() const;+ void set_previous_phase_and_current_iteration(RustFFI::AnimationEffectPhase phase, double current_iteration) const { RustFFI::animations_effect_set_previous_phase_and_current_iteration(&record(), phase, current_iteration); }++ bool has_flag(RustFFI::EffectFlag flag) const { return RustFFI::animations_effect_has_flag(&record(), flag); }+ bool set_flag(RustFFI::EffectFlag flag, bool value) const { return RustFFI::animations_effect_set_flag(&record(), flag, value); }+ bool is_compositor_driven() const { return has_flag(RustFFI::EffectFlag::CompositorDriven); }+ bool is_compositor_replaced() const { return has_flag(RustFFI::EffectFlag::CompositorReplaced); }+ bool is_offscreen_throttled() const { return has_flag(RustFFI::EffectFlag::OffscreenThrottled); }+ bool is_observation_relevant_compositor_animation() const { return has_flag(RustFFI::EffectFlag::ObservationRelevantCompositorAnimation); }+ bool per_frame_animation_tick_was_skipped() const { return has_flag(RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped); }++ // Whether a compositor animation may run every property the effect targets.+ bool may_run_on_the_compositor() const { return RustFFI::animations_effect_may_run_on_the_compositor(&record()); }+ // The compositor animations built from this effect live in its record; the state is made when first needed.+ Painting::CompositorAnimationEffectState compositor_animation_state() const;+ Optional<Painting::CompositorAnimationEffectState> existing_compositor_animation_state() const;+ bool has_retained_compositor_animations() const;++ // Invalidates the style the effect produces, forgetting what the host concluded of it.+ void invalidate() const;++ bool can_skip_per_frame_style_update() const;+ bool can_skip_per_frame_animation_tick() const;+ void request_observation_sample() const;+ // Requests an observation sample on behalf of a read of an element, unless one was requested in the same task.+ bool request_element_scoped_observation_sample(u64 task_generation) const;+ // Samples the effect into the style of its target for the update.+ void update_computed_properties(AnimationUpdateContext&) const;++private:+ void note_observation_sample_requested() const;+ bool may_animate_display() const;+ bool css_animation_events_are_heard(RustFFI::FfiAnimationTimingState const&, bool only_iteration_events) const;+};++inline Optional<EffectRef> AnimationRef::effect() const+{+ if (auto const* effect = RustFFI::animations_animation_effect(&record()))+ return EffectRef { *effect };+ return {};+}++inline Optional<AnimationRef> EffectRef::associated_animation() const+{+ if (auto const* animation = RustFFI::animations_effect_associated_animation(&record()))+ return AnimationRef { *animation };+ return {};+}++// Visits a GC cell an animation record names, as a holder of the record the GC traces does.+void visit_host_cell(void* visitor, void* cell, RustFFI::HostCellKind);++// Keeps an animation a procedure hands the host alive, as an AnimationRef appended to the GC::RootVector<AnimationRef>+// `root_vector`, for as long as that lives.+void keep_animation_alive_in(void* root_vector, RustFFI::AnimationCell const*);++// The relevant global object of an animation: that of its object, or, for an animation that has none, that of the+// node document of the element that owns it or whose animation element it is.+JS::Object& relevant_global_object_of(AnimationRef const&);++// Performs what a procedure of an animation asked the host to do, which the host hands to the procedures to run. Only+// settling the promises of the animation and queueing its playback events need its object, and an animation that has+// none has nothing to settle them for or to dispatch them at.+void perform_host_effect(RustFFI::FfiHostEffect const*);++// Creates the playback event the pending animation event queue of `document` holds of `animation`, and dispatches it+// at the object of the animation.+void dispatch_pending_playback_event(AnimationRef const&, DOM::Document const&, RustFFI::FfiPendingAnimationEvent const&);++// https://www.w3.org/TR/css-animations-2/#owning-element-section+void set_owning_element(AnimationRef const&, DOM::AbstractElement);++// The bytes of the objects script sees of an animation and of its associated effect, beside their records.+size_t object_memory_size(AnimationRef const&);++// Compares two DOM::Elements in tree order, as the composite order of their animations does.+i32 compare_elements_in_tree_order_for_composite_order(void* first, void* second);++// A set of animation records that keeps none of them alive, which Rust owns. The record of an animation that dies+// leaves the set as the set is next enumerated.+class WeakAnimationSetView {+public:+ explicit WeakAnimationSetView(RustFFI::WeakAnimationSet& set)+ : m_set(&set)+ {+ }++ bool set(AnimationRef const& animation) { return RustFFI::animations_weak_animation_set_insert(m_set, &animation.record()); }+ bool remove(RustFFI::AnimationCell const& animation) { return RustFFI::animations_weak_animation_set_remove(m_set, &animation); }+ bool contains(RustFFI::AnimationCell const& record) const { return RustFFI::animations_weak_animation_set_contains(m_set, &record); }+ bool is_empty() const { return begin() == end(); }++ struct EndIterator { };++ class Iterator {+ public:+ AnimationRef const& operator*() const { return *m_current; }+ AnimationRef const* operator->() const { return &*m_current; }++ Iterator& operator++()+ {+ ++m_index;+ settle();+ return *this;+ }++ bool operator==(EndIterator) const { return !m_current.has_value(); }++ private:+ friend class WeakAnimationSetView;++ explicit Iterator(RustFFI::WeakAnimationSet const* set)+ : m_set(set)+ {+ settle();+ }++ // Moves on to the first entry from the current one whose animation is alive.+ void settle()+ {+ m_current.clear();+ for (; m_index < RustFFI::animations_weak_animation_set_entry_count(m_set); ++m_index) {+ if (auto const* record = RustFFI::animations_weak_animation_set_get(m_set, m_index)) {+ m_current = AnimationRef::adopt(*record);+ return;+ }+ }+ }++ RustFFI::WeakAnimationSet const* m_set { nullptr };+ size_t m_index { 0 };+ Optional<AnimationRef> m_current;+ };++ Iterator begin() const+ {+ RustFFI::animations_weak_animation_set_prune(m_set);+ return Iterator { m_set };+ }+ EndIterator end() const { return {}; }++protected:+ RustFFI::WeakAnimationSet* m_set { nullptr };+};++}diff --git a/Libraries/LibWeb/Animations/ScrollTimeline.cpp b/Libraries/LibWeb/Animations/ScrollTimeline.cppdeleted file mode 100644index aeff2c077aa..00000000000--- a/Libraries/LibWeb/Animations/ScrollTimeline.cpp+++ /dev/null@@ -1,313 +0,0 @@-/*- * Copyright (c) 2026, Callum Law <[email protected]>.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include "ScrollTimeline.h"-#include <LibGC/Heap.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/ViewTimeline.h>-#include <LibWeb/Bindings/ScrollTimeline.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Scripting/Environments.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Layout/RenderDocument.h>-#include <LibWeb/Layout/Viewport.h>-#include <LibWeb/Painting/BoxViews.h>-#include <LibWeb/Painting/Scrolling.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(ScrollTimeline);--GC::Ref<ScrollTimeline> ScrollTimeline::create(DOM::Document& document, Source source, ScrollAxis axis)-{- auto timeline = GC::Heap::the().allocate<ScrollTimeline>(document, source, axis);-- // NB: The passed timestamp is ignored for ScrollTimelines so we can just pass 0 here.- timeline->update_current_time(0);-- return timeline;-}--GC::Ref<ScrollTimeline> ScrollTimeline::create_for_constructor(JS::Object& relevant_global_object, Bindings::ScrollTimelineOptions const& options)-{- auto& document = HTML::relevant_window(relevant_global_object).associated_document();- auto source = [&]() -> GC::Ptr<DOM::Element const> {- if (options.source.has_value())- return options.source.value();- return document.scrolling_element();- }();- return create(document, source, options.axis);-}--GC::Ptr<DOM::Element const> ScrollTimeline::source() const-{- return m_source.visit(- [](GC::Ptr<DOM::Element const> const& source) -> GC::Ptr<DOM::Element const> {- return source;- },- [](AnonymousSource const& anonymous_source) -> GC::Ptr<DOM::Element const> {- switch (anonymous_source.scroller) {- case CSS::Scroller::Root:- return anonymous_source.target.document().document_element();- case CSS::Scroller::Nearest: {- GC::Ptr<DOM::Element const> ancestor = anonymous_source.target.parent_element();-- // Whether a box is a scroll container depends on its used overflow, which is visible for a body whose- // overflow is propagated to the viewport. The document element stands for the viewport.- Layout::ForcedReadScope read { anonymous_source.target.document() };- while (ancestor && !ancestor->is_document_element()) {- auto const* layout_node = ancestor->unsafe_layout_node(read);- if (layout_node && layout_node->is_scroll_container())- break;- ancestor = ancestor->parent_element();- }-- return ancestor;- }- case CSS::Scroller::Self:- return anonymous_source.target.element();- }- VERIFY_NOT_REACHED();- });-}--GC::Ptr<DOM::Element const> ScrollTimeline::source_for_bindings() const-{- // The nearest scroll container is the nearest one by used overflow, which layout decides.- if (auto const* anonymous_source = m_source.get_pointer<AnonymousSource>(); anonymous_source && anonymous_source->scroller == CSS::Scroller::Nearest)- anonymous_source->target.document().update_layout(DOM::UpdateLayoutReason::ScrollTimelineSource);- return source();-}--struct ComputedScrollAxis {- bool is_vertical;- bool is_reversed;-};-static ComputedScrollAxis computed_scroll_axis(ScrollAxis axis, CSS::WritingMode writing_mode, CSS::Direction direction)-{- // NB: This is based on the table specified here: https://drafts.csswg.org/css-writing-modes-4/#logical-to-physical-- // FIXME: Note: The used direction depends on the computed writing-mode and text-orientation: in vertical writing- // modes, a text-orientation value of upright forces the used direction to ltr.- auto used_direction = direction;-- switch (axis) {- case ScrollAxis::Block:- switch (writing_mode) {- case CSS::WritingMode::HorizontalTb:- return { true, false };- case CSS::WritingMode::VerticalRl:- case CSS::WritingMode::SidewaysRl:- return { false, true };- case CSS::WritingMode::VerticalLr:- case CSS::WritingMode::SidewaysLr:- return { false, false };- }- VERIFY_NOT_REACHED();- case ScrollAxis::Inline:- switch (writing_mode) {- case CSS::WritingMode::HorizontalTb:- return { false, used_direction == CSS::Direction::Rtl };- case CSS::WritingMode::VerticalRl:- case CSS::WritingMode::SidewaysRl:- case CSS::WritingMode::VerticalLr:- return { true, used_direction == CSS::Direction::Rtl };- case CSS::WritingMode::SidewaysLr:- return { true, used_direction == CSS::Direction::Ltr };- }- VERIFY_NOT_REACHED();- case ScrollAxis::X:- return { false, false };- case ScrollAxis::Y:- return { true, false };- }-- VERIFY_NOT_REACHED();-}--Optional<ScrollTimeline::ScrollerMetrics> ScrollTimeline::scroller_metrics() const-{- auto propagated_source = get_propagated_source();- if (propagated_source.visit([](auto const& source) { return source == nullptr; }))- return {};-- Layout::ForcedReadScope read { propagated_source.visit([](auto const& source) -> DOM::Document const& { return source->document(); }) };-- auto const& layout_node = propagated_source.visit([&read](auto const& source) -> Layout::NodeWithStyle const* { return source->unsafe_layout_node(read); });-- if (!layout_node || !layout_node->is_scroll_container())- return {};-- if (!Painting::has_committed_box(*layout_node) || !Painting::has_scrollable_overflow(*layout_node))- return {};-- auto const& scrollable_overflow_rect = Painting::scrollable_overflow_rect(*layout_node).value();- auto const& computed_axis = computed_scroll_axis(m_axis, layout_node->writing_mode(), layout_node->direction());- auto scrollport = Painting::absolute_padding_box_rect(*layout_node);- // NB: Only a view progress timeline measures its subject against the scroll padding, so a scroll progress timeline- // does not resolve it on every update.- auto snapport = is<ViewTimeline>(*this) ? Painting::scroll_snapport_rect(*layout_node, scrollport) : scrollport;-- // FIXME: Scroll offset is currently incorrect as it is always relative to the top left of the scrollable overflow- // rect when it should instead be relative to the scroll origin.-- // FIXME: Support the case where the computed scroll axis is reversed-- return ScrollerMetrics {- .scroll_node = Painting::async_scroll_node_stable_id(*layout_node),- .scroller_style_node = propagated_source.visit(- [](GC::Ptr<DOM::Element const> const& element) { return element->style_node_id().value(); },- [](GC::Ptr<DOM::Document> const&) -> u32 { return 0; }),- .is_vertical = computed_axis.is_vertical,- .scroll_offset = computed_axis.is_vertical- ? Painting::scroll_offset(*layout_node).y().to_double()- : Painting::scroll_offset(*layout_node).x().to_double(),- .max_scroll_offset = computed_axis.is_vertical- ? scrollable_overflow_rect.height().to_double() - Painting::content_height(*layout_node).to_double()- : scrollable_overflow_rect.width().to_double() - Painting::content_width(*layout_node).to_double(),- .scrollport_start = (computed_axis.is_vertical ? scrollport.y() : scrollport.x()).to_double(),- .scrollport_size = (computed_axis.is_vertical ? scrollport.height() : scrollport.width()).to_double(),- .scroll_padding_start = computed_axis.is_vertical- ? (snapport.y() - scrollport.y()).to_double()- : (snapport.x() - scrollport.x()).to_double(),- .scroll_padding_end = computed_axis.is_vertical- ? (scrollport.bottom() - snapport.bottom()).to_double()- : (scrollport.right() - snapport.right()).to_double(),- };-}--Optional<ScrollTimeline::FollowedScroller> ScrollTimeline::followed_scroller_from(ScrollerMetrics const& metrics)-{- if (!metrics.scroll_node.has_value())- return {};- return FollowedScroller { *metrics.scroll_node, metrics.scroller_style_node, metrics.is_vertical, metrics.scroll_offset, metrics.max_scroll_offset };-}--void ScrollTimeline::set_axis(ScrollAxis axis)-{- if (m_axis == axis)- return;- m_axis = axis;- update_current_time(0);-}--bool ScrollTimeline::is_stale() const-{- // FIXME: This should probably be a spec bug-- // https://drafts.csswg.org/scroll-animations-1/#stale-timelines- // AD-HOC: The spec only lists two criteria for a scroll timeline to be considered stale: a) it was newly created- // within the current frame or; b) style update and layout within the current frame changed it's associated- // named timeline ranges. However, WPT expects us to also consider the source element resizing as a cause- // for staleness, so we use a more broad definition of staleness and consider any timeline whose max scroll- // offset has changed since the last call to `update_current_time` to be stale. This matches the (admittedly- // narrow) tests in WPT and is the same behavior as is implemented by WebKit.-- // FIXME: Account for the named timeline ranges of view progress timelines once they are implemented.- auto scroll_offset_data = scroller_metrics();-- return scroll_offset_data.map([](auto const& data) { return data.max_scroll_offset; }) != m_last_max_scroll_offset;-}--void ScrollTimeline::update_current_time(double)-{- // https://drafts.csswg.org/scroll-animations-1/#ref-for-dom-animationtimeline-currenttime- // currentTime represents the scroll progress of the scroll container as a percentage CSSUnitValue, with 0%- // representing its startmost scroll position (in the writing mode of the scroll container). Null when the timeline- // is inactive.-- auto scroll_offset_data = scroller_metrics();-- m_last_max_scroll_offset = scroll_offset_data.map([](auto const& data) { return data.max_scroll_offset; });- m_followed_scroller.clear();-- // If the source of a ScrollTimeline is an element whose principal box does not exist or is not a scroll container,- // or if there is no scrollable overflow, then the ScrollTimeline is inactive.- // NB: Called during animation timeline update, which runs before layout is up to date.-- if (!scroll_offset_data.has_value()) {- set_current_time({});- return;- }-- // https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress- // If the 0% position and 100% position coincide (i.e. the denominator in the current time formula is zero), the timeline is inactive.- if (scroll_offset_data->max_scroll_offset == 0) {- set_current_time({});- return;- }-- // FIXME: In paged media, scroll progress timelines that would otherwise reference the document viewport are also inactive.-- // https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress- // Progress (the current time) for a scroll progress timeline is calculated as:- // scroll offset ÷ (scrollable overflow size − scroll container size)- auto progress = scroll_offset_data->scroll_offset / scroll_offset_data->max_scroll_offset;-- m_followed_scroller = followed_scroller_from(*scroll_offset_data);-- set_current_time(TimeValue { TimeValue::Type::Percentage, progress * 100 });-}--AttachmentInterval ScrollTimeline::interval_for_attachment_range(AnimationAttachmentRange const& range) const-{- // NB: A scroll progress timeline has no named timeline ranges, so each edge is measured along the entire timeline,- // whose length is the maximum scroll offset. This matches WebKit.- auto max_scroll_offset = m_last_max_scroll_offset.value_or(0);- auto time_of = [&](TimelineRangeEdge const& edge) {- if (max_scroll_offset == 0)- return TimeValue { TimeValue::Type::Percentage, edge.offset_percentage };- return TimeValue { TimeValue::Type::Percentage, edge.offset_along(max_scroll_offset) / max_scroll_offset * 100 };- };- return { time_of(range.start), time_of(range.end) };-}--ScrollTimeline::ScrollTimeline(DOM::Document& document, Source source, ScrollAxis axis)- : AnimationTimeline(document)- , m_source(source)- , m_axis(axis)-{- static u64 s_next_clock_identity = 1;- m_clock_identity = s_next_clock_identity++;-}--void ScrollTimeline::visit_edges(GC::Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- m_source.visit(- [&](GC::Ptr<DOM::Element const>& source) { visitor.visit(source); },- [&](AnonymousSource& anonymous_source) { anonymous_source.target.visit(visitor); });-}--Variant<GC::Ptr<DOM::Element const>, GC::Ptr<DOM::Document>> ScrollTimeline::get_propagated_source() const-{- auto const& source = this->source();-- // https://drafts.csswg.org/scroll-animations-1/#scroll-notation- // References to the root element propagate to the document viewport (which functions as its scroll container).- if (source && source.ptr() == source->document().document_element())- return source->owner_document();-- return source;-}--ScrollAxis scroll_axis_from_css_axis(CSS::Axis axis)-{- switch (axis) {- case CSS::Axis::Block:- return ScrollAxis::Block;- case CSS::Axis::Inline:- return ScrollAxis::Inline;- case CSS::Axis::X:- return ScrollAxis::X;- case CSS::Axis::Y:- return ScrollAxis::Y;- }-- VERIFY_NOT_REACHED();-}--}diff --git a/Libraries/LibWeb/Animations/ScrollTimeline.h b/Libraries/LibWeb/Animations/ScrollTimeline.hdeleted file mode 100644index b333e142950..00000000000--- a/Libraries/LibWeb/Animations/ScrollTimeline.h+++ /dev/null@@ -1,121 +0,0 @@-/*- * Copyright (c) 2026, Callum Law <[email protected]- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Types.h>-#include <LibJS/Forward.h>-#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Bindings/ScrollTimeline.h>-#include <LibWebCommon/Page/AsyncScrollNodeStableID.h>--namespace Web::HTML {--class Window;--}--namespace Web::Animations {--using ScrollAxis = Bindings::ScrollAxis;--// https://drafts.csswg.org/scroll-animations-1/#scrolltimeline-class ScrollTimeline : public AnimationTimeline {- WEB_WRAPPABLE(ScrollTimeline, AnimationTimeline);- GC_DECLARE_ALLOCATOR(ScrollTimeline);--public:- struct AnonymousSource {- CSS::Scroller scroller;- DOM::AbstractElement target;-- bool operator==(AnonymousSource const& other) const = default;- };-- using Source = Variant<GC::Ptr<DOM::Element const>, AnonymousSource>;-- static GC::Ref<ScrollTimeline> create(DOM::Document&, Source source, ScrollAxis axis);- static GC::Ref<ScrollTimeline> create_for_constructor(JS::Object&, Bindings::ScrollTimelineOptions const&);-- virtual Optional<TimeValue> duration() const override { return TimeValue { TimeValue::Type::Percentage, 100 }; }-- GC::Ptr<DOM::Element const> source() const;- virtual GC::Ptr<DOM::Element const> source_for_bindings() const;- ScrollAxis axis() const { return m_axis; }- void set_axis(ScrollAxis);-- Source source_internal() const { return m_source; }-- virtual bool is_stale() const;- virtual void update_current_time(double timestamp) override;-- // The scroll node the timeline followed at its last update, the style node of the element whose box scrolls, or 0- // for the viewport, and the scroll offset there and at 100% progress, in CSS pixels: empty while it was inactive.- struct FollowedScroller {- AsyncScrollNodeStableID scroll_node;- u32 scroller_style_node { 0 };- bool vertical { true };- double scroll_offset { 0 };- double max_scroll_offset { 0 };-- bool operator==(FollowedScroller const&) const = default;- };- Optional<FollowedScroller> const& followed_scroller() const { return m_followed_scroller; }-- // What names the timeline to the render clock, whose ticks sample its animations.- u64 clock_identity() const { return m_clock_identity; }-- virtual bool is_progress_based() const override { return true; }- virtual AttachmentInterval interval_for_attachment_range(AnimationAttachmentRange const&) const override;-- // NB: The minimum and the maximum scroll offsets.- virtual Optional<TimeValue> minimum_timeline_time() const override { return TimeValue { TimeValue::Type::Percentage, 0 }; }- virtual Optional<TimeValue> maximum_timeline_time() const override { return TimeValue { TimeValue::Type::Percentage, 100 }; }- virtual bool can_convert_a_timeline_time_to_an_origin_relative_time() const override { return false; }--protected:- ScrollTimeline(DOM::Document&, Source source, ScrollAxis axis);- virtual ~ScrollTimeline() override = default;-- virtual void visit_edges(GC::Cell::Visitor&) override;-- // The scroll container the timeline follows, along the timeline's axis, in CSS pixels.- struct ScrollerMetrics {- Optional<AsyncScrollNodeStableID> scroll_node;- u32 scroller_style_node { 0 };- bool is_vertical { true };- double scroll_offset { 0 };- double max_scroll_offset { 0 };- // Where the scrollport starts in the coordinates the boxes inside it are laid out in, and its size.- double scrollport_start { 0 };- double scrollport_size { 0 };- // The scroll padding at the start and at the end of the scrollport.- double scroll_padding_start { 0 };- double scroll_padding_end { 0 };- };- // Empty while the source has no box, is not a scroll container or has no scrollable overflow.- Optional<ScrollerMetrics> scroller_metrics() const;-- static Optional<FollowedScroller> followed_scroller_from(ScrollerMetrics const&);- void set_followed_scroller(Optional<FollowedScroller> followed_scroller) { m_followed_scroller = move(followed_scroller); }--private:- Variant<GC::Ptr<DOM::Element const>, GC::Ptr<DOM::Document>> get_propagated_source() const;-- // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source- Source m_source;-- // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-axis- ScrollAxis m_axis;-- Optional<double> m_last_max_scroll_offset;- Optional<FollowedScroller> m_followed_scroller;- u64 m_clock_identity { 0 };-};--ScrollAxis scroll_axis_from_css_axis(CSS::Axis);--}diff --git a/Libraries/LibWeb/Animations/ScrollTimeline.idl b/Libraries/LibWeb/Animations/ScrollTimeline.idlindex 939c286df27..406b0ae9545 100644--- a/Libraries/LibWeb/Animations/ScrollTimeline.idl+++ b/Libraries/LibWeb/Animations/ScrollTimeline.idl@@ -1,8 +1,8 @@// https://drafts.csswg.org/scroll-animations-1/#scrolltimeline-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface ScrollTimeline : AnimationTimeline {constructor(optional ScrollTimelineOptions options = {});- [ImplementedAs=source_for_bindings] readonly attribute Element? source;+ readonly attribute Element? source;readonly attribute ScrollAxis axis;};diff --git a/Libraries/LibWeb/Animations/TimelineRange.cpp b/Libraries/LibWeb/Animations/TimelineRange.cppdeleted file mode 100644index 7c7db4f6e7b..00000000000--- a/Libraries/LibWeb/Animations/TimelineRange.cpp+++ /dev/null@@ -1,37 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/Animations/TimelineRange.h>-#include <LibWeb/ComputedValuesRustFFI.h>--namespace Web::Animations {--static double length_percentage_px(CSS::RustStyleValueHandle const& calculated, double px, double percentage, double basis)-{- if (calculated)- return CSS::ComputedValuesFFI::rust_length_percentage_px(calculated.data(), basis);- return px + percentage / 100 * basis;-}--CSS::RustStyleValueHandle retain_calculated_offset(void const* value)-{- if (!value)- return {};- return CSS::RustStyleValueHandle::retained(static_cast<CSS::StyleValueFFI::StyleValueData const*>(value));-}--double TimelineRangeEdge::offset_along(double range_size) const-{- return length_percentage_px(calculated_offset, offset_px, offset_percentage, range_size);-}--double ViewTimelineInsetEdge::resolve(double scrollport_size) const-{- VERIFY(!is_auto);- return length_percentage_px(calculated, px, percentage, scrollport_size);-}--}diff --git a/Libraries/LibWeb/Animations/TimelineRange.h b/Libraries/LibWeb/Animations/TimelineRange.hdeleted file mode 100644index a971832549b..00000000000--- a/Libraries/LibWeb/Animations/TimelineRange.h+++ /dev/null@@ -1,113 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/StringView.h>-#include <AK/Types.h>-#include <LibWeb/Animations/TimeValue.h>-#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>--namespace Web::Animations {--// https://drafts.csswg.org/scroll-animations-1/#named-ranges-enum class TimelineRangeName : u8 {- // NB: An edge given without a range name is measured along the entire timeline.- None,- Cover,- Contain,- Entry,- Exit,- EntryCrossing,- ExitCrossing,- Scroll,-};--// https://drafts.csswg.org/scroll-animations-1/#typedef-timeline-range-name-inline StringView timeline_range_name_to_string(TimelineRangeName name)-{- switch (name) {- case TimelineRangeName::None:- return "normal"sv;- case TimelineRangeName::Cover:- return "cover"sv;- case TimelineRangeName::Contain:- return "contain"sv;- case TimelineRangeName::Entry:- return "entry"sv;- case TimelineRangeName::Exit:- return "exit"sv;- case TimelineRangeName::EntryCrossing:- return "entry-crossing"sv;- case TimelineRangeName::ExitCrossing:- return "exit-crossing"sv;- case TimelineRangeName::Scroll:- return "scroll"sv;- }- VERIFY_NOT_REACHED();-}--// One edge of an animation attachment range: a point measured from the start of a named timeline range, as a length-// plus a percentage of the range.-// https://drafts.csswg.org/scroll-animations-1/#animation-range-start-struct TimelineRangeEdge {- TimelineRangeName name { TimelineRangeName::None };- double offset_px { 0 };- double offset_percentage { 0 };- // NB: An offset only a calculation can describe, such as min(50%, 10px), resolves against the size of its range once- // that is known. offset_px and offset_percentage then describe it as it resolves against 0px and 100px.- CSS::RustStyleValueHandle calculated_offset {};-- // The offset, in pixels, along a range of the given size.- double offset_along(double range_size) const;-- bool operator==(TimelineRangeEdge const&) const = default;-};--// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range-struct AnimationAttachmentRange {- // NB: The initial edges, normal, are the start and the end of the entire timeline.- TimelineRangeEdge start { TimelineRangeName::None, 0, 0 };- TimelineRangeEdge end { TimelineRangeName::None, 0, 100 };-- bool operator==(AnimationAttachmentRange const&) const = default;-};--// The timeline times of the start and the end of an attachment range.-struct AttachmentInterval {- TimeValue start;- TimeValue end;-- bool operator==(AttachmentInterval const&) const = default;-};--// One side of the view progress visibility range: auto takes the scroll container's scroll padding, otherwise a length-// plus a percentage of the scrollport.-// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset-struct ViewTimelineInsetEdge {- bool is_auto { true };- double px { 0 };- double percentage { 0 };- // NB: An inset only a calculation can describe, such as min(50%, 10px), resolves against the scrollport size.- CSS::RustStyleValueHandle calculated {};-- // The inset, in pixels, of a side that is not auto, in a scrollport of the given size.- double resolve(double scrollport_size) const;-- bool operator==(ViewTimelineInsetEdge const&) const = default;-};--// Takes a reference to a calculated offset or inset the style engine hands over, which may be null.-CSS::RustStyleValueHandle retain_calculated_offset(void const*);--struct ViewTimelineInset {- ViewTimelineInsetEdge start;- ViewTimelineInsetEdge end;-- bool operator==(ViewTimelineInset const&) const = default;-};--}diff --git a/Libraries/LibWeb/Animations/ViewTimeline.cpp b/Libraries/LibWeb/Animations/ViewTimeline.cppdeleted file mode 100644index e4524441c55..00000000000--- a/Libraries/LibWeb/Animations/ViewTimeline.cpp+++ /dev/null@@ -1,315 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Animations/ViewTimeline.h>-#include <LibWeb/CSS/CSSKeywordValue.h>-#include <LibWeb/CSS/CSSUnitValue.h>-#include <LibWeb/CSS/Parser/Parser.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/DOM/Element.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Layout/Node.h>-#include <LibWeb/Layout/RenderDocument.h>-#include <LibWeb/Painting/BoxViews.h>--namespace Web::Animations {--GC_DEFINE_ALLOCATOR(ViewTimeline);--ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const& inset)-{- return {- .start = { inset.start_is_auto, inset.start_px, inset.start_percentage, retain_calculated_offset(inset.start_calculated) },- .end = { inset.end_is_auto, inset.end_px, inset.end_percentage, retain_calculated_offset(inset.end_calculated) },- };-}--// The insets a computed 'view-timeline-inset' value describes.-static ViewTimelineInset view_timeline_inset_from_style_value(CSS::StyleValue const& value)-{- return view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::rust_view_timeline_inset(value.rust_style_value_data()));-}--GC::Ref<ViewTimeline> ViewTimeline::create(DOM::Document& document, DOM::AbstractElement subject, ScrollAxis axis, Inset inset)-{- auto timeline = GC::Heap::the().allocate<ViewTimeline>(document, subject, axis, inset);-- // NB: The passed timestamp is ignored for ViewTimelines so we can just pass 0 here.- timeline->update_current_time(0);-- return timeline;-}--// https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-viewtimeline-WebIDL::ExceptionOr<GC::Ref<ViewTimeline>> ViewTimeline::create_for_constructor(JS::Object& relevant_global_object, Bindings::ViewTimelineOptions const& options)-{- auto& document = HTML::relevant_window(relevant_global_object).associated_document();-- // 1. Let timeline be the new ViewTimeline object.- // 2. Set the subject and axis properties of timeline to the corresponding values from options.- // 3. Set the source of timeline to the subject’s nearest ancestor scroll container element that's scrollable in- // the specified axis.- // NB: The source is found from the subject whenever it is asked for.-- // 4. If a DOMString value is provided as an inset, parse it as a <'view-timeline-inset'> value; if a sequence is- // provided, the first value represents the start inset and the second value represents the end inset. If the- // sequence has only one value, it is duplicated. If it has zero values or more than two values, or if it- // contains a CSSKeywordValue whose value is not "auto", throw a TypeError.- // AD-HOC: Relative lengths are not allowed, see https://github.com/w3c/csswg-drafts/issues/13852- auto parse_inset = [&](Utf16String const& string) -> WebIDL::ExceptionOr<Inset> {- auto value = parse_css_value(CSS::Parser::ParsingParams { document }, string, CSS::PropertyID::ViewTimelineInset);- // NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.- if (!value || value->is_css_wide_keyword() || value->is_unresolved() || value->is_pending_substitution()- || CSS::ComputedValuesFFI::rust_view_timeline_inset_has_relative_length(value->rust_style_value_data()))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid view timeline inset"_utf16 };- auto computed = value->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(document) });- return view_timeline_inset_from_style_value(*computed);- };- auto parse_auto = [&](Utf16View const& keyword) -> WebIDL::ExceptionOr<InsetEdge> {- if (!keyword.equals_ignoring_ascii_case("auto"sv))- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "A view timeline inset keyword must be auto"_utf16 };- return InsetEdge {};- };- auto inset = TRY(options.inset.visit(- [&](Utf16String const& string) { return parse_inset(string); },- [&](auto const& values) -> WebIDL::ExceptionOr<Inset> {- if (values.is_empty() || values.size() > 2)- return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "A view timeline inset takes one or two values"_utf16 };- Vector<InsetEdge, 2> edges;- for (auto const& value : values) {- auto edge = TRY(value.visit(- [&](GC::Ref<CSS::CSSNumericValue> const& numeric) -> WebIDL::ExceptionOr<InsetEdge> {- return TRY(parse_inset(numeric->to_string())).start;- },- [&](GC::Ref<CSS::CSSKeywordValue> const& keyword) { return parse_auto(keyword->value()); },- // INTEROP: Blink takes "auto" as a string in the sequence too.- [&](Utf16String const& keyword) { return parse_auto(keyword); }));- edges.append(edge);- }- return Inset { edges[0], edges.size() > 1 ? edges[1] : edges[0] };- }));-- return create(document, DOM::AbstractElement { *options.subject }, options.axis, inset);-}--ViewTimeline::ViewTimeline(DOM::Document& document, DOM::AbstractElement subject, ScrollAxis axis, Inset inset)- : ScrollTimeline(document, AnonymousSource { .scroller = CSS::Scroller::Nearest, .target = subject }, axis)- , m_inset(inset)-{-}--DOM::AbstractElement ViewTimeline::subject_internal() const-{- return source_internal().get<AnonymousSource>().target;-}--GC::Ref<DOM::Element const> ViewTimeline::subject() const-{- return subject_internal().element();-}--GC::Ptr<DOM::Element const> ViewTimeline::source_for_bindings() const-{- // The values of subject, source, and currentTime are all computed when any of them is requested or updated.- auto subject = subject_internal();- subject.document().update_layout(DOM::UpdateLayoutReason::ViewTimelineSource);-- // If the source or subject of a ViewTimeline is an element whose principal box does not exist, [...] then the- // ViewTimeline is inactive.- // INTEROP: Its source is then null, as WebKit and Blink have it.- for (GC::Ptr<DOM::Element const> element = &subject.element(); element; element = element->flat_tree_parent_element()) {- if (!element->has_style() || element->installed_style().display_is_none())- return nullptr;- }- return source();-}--void ViewTimeline::set_axis_and_inset(ScrollAxis axis, Inset inset)-{- if (this->axis() == axis && m_inset == inset)- return;- m_inset = inset;- if (this->axis() != axis)- set_axis(axis);- else- update_current_time(0);-}--Optional<ViewTimeline::Metrics> ViewTimeline::compute_metrics() const-{- // If the source or subject of a ViewTimeline is an element whose principal box does not exist, or if its nearest- // ancestor scroll container has no scrollable overflow or is not scrollable in the specified axis (or if there is no- // such ancestor, e.g. in print media), then the ViewTimeline is inactive.- auto scroller = scroller_metrics();- if (!scroller.has_value())- return {};-- auto subject = subject_internal();- Layout::ForcedReadScope read { subject.document() };- auto const* subject_layout_node = subject.unsafe_layout_node(read);- if (!subject_layout_node || !Painting::has_committed_box(*subject_layout_node))- return {};-- // NB: The border box is laid out where the scroll container's scrolled content is at its scroll origin, with- // transforms ignored and relative positioning accounted for, as the view progress timeline ranges ask.- auto subject_border_box = Painting::absolute_border_box_rect(*subject_layout_node);- auto subject_start = (scroller->is_vertical ? subject_border_box.y() : subject_border_box.x()).to_double();- auto subject_size = (scroller->is_vertical ? subject_border_box.height() : subject_border_box.width()).to_double();- auto subject_offset = subject_start - scroller->scrollport_start;-- auto inset_of = [&](InsetEdge const& edge, double scroll_padding) {- if (edge.is_auto)- return scroll_padding;- return edge.resolve(scroller->scrollport_size);- };- auto inset_start = inset_of(m_inset.start, scroller->scroll_padding_start);- auto inset_end = inset_of(m_inset.end, scroller->scroll_padding_end);-- // https://drafts.csswg.org/scroll-animations-1/#valdef-animation-timeline-range-cover- // 0% progress represents the latest position at which the start border edge of the element’s principal box- // coincides with the end edge of its view progress visibility range.- // 100% progress represents the earliest position at which the end border edge of the element’s principal box- // coincides with the start edge of its view progress visibility range.- return Metrics {- .followed_scroller = followed_scroller_from(*scroller),- .scroll_offset = scroller->scroll_offset,- .max_scroll_offset = scroller->max_scroll_offset,- .scrollport_size = scroller->scrollport_size,- .inset_start = inset_start,- .inset_end = inset_end,- .subject_offset = subject_offset,- .subject_size = subject_size,- };-}--bool ViewTimeline::is_stale() const-{- // NB: See ScrollTimeline::is_stale(). A view progress timeline's named timeline ranges move with its subject too.- return compute_metrics() != m_last_metrics;-}--void ViewTimeline::update_current_time(double)-{- m_last_metrics = compute_metrics();- set_followed_scroller({});-- if (!m_last_metrics.has_value()) {- set_current_time({});- return;- }-- // https://drafts.csswg.org/scroll-animations-1/#view-timeline-progress- // Progress (the current time) in a view progress timeline is calculated as: distance ÷ range where:- // - distance is the current scroll offset minus the scroll offset corresponding to the start of the cover range- // - range is the scroll offset corresponding to the end of the cover range minus the scroll offset corresponding- // to the start of the cover range- auto distance = m_last_metrics->scroll_offset - m_last_metrics->cover_start();- auto range = m_last_metrics->cover_end() - m_last_metrics->cover_start();-- // If the 0% position and 100% position coincide (i.e. the denominator in the current time formula is zero), the- // timeline is inactive.- if (range == 0) {- set_current_time({});- return;- }-- // FIXME: In paged media, view progress timelines that would otherwise reference the document viewport are also- // inactive.-- set_followed_scroller(m_last_metrics->followed_scroller);- set_current_time(TimeValue { TimeValue::Type::Percentage, distance / range * 100 });-}--// https://drafts.csswg.org/scroll-animations-1/#view-timelines-ranges-ViewTimeline::ScrollOffsetInterval ViewTimeline::interval_for_range_name(Metrics const& metrics, TimelineRangeName name) const-{- auto sorted = [](double start, double end) {- if (end < start)- swap(start, end);- return ScrollOffsetInterval { start, end };- };-- switch (name) {- case TimelineRangeName::None:- case TimelineRangeName::Cover:- // Represents the full range of the view progress timeline.- return { metrics.cover_start(), metrics.cover_end() };- case TimelineRangeName::Contain:- // Represents the range during which the principal box is either fully contained by, or fully covers, its view- // progress visibility range within the scrollport.- return sorted(metrics.cover_start() + metrics.subject_size, metrics.cover_end() - metrics.subject_size);- case TimelineRangeName::Entry: {- // 0% is equivalent to 0% of the cover range.- // 100% is equivalent to 0% of the contain range.- auto contain = interval_for_range_name(metrics, TimelineRangeName::Contain);- return sorted(metrics.cover_start(), contain.start);- }- case TimelineRangeName::Exit: {- // 0% is equivalent to 100% of the contain range.- // 100% is equivalent to 100% of the cover range.- auto contain = interval_for_range_name(metrics, TimelineRangeName::Contain);- return sorted(contain.end, metrics.cover_end());- }- case TimelineRangeName::EntryCrossing:- // Represents the range during which the principal box crosses the end border edge.- return sorted(metrics.cover_start(), metrics.cover_start() + metrics.subject_size);- case TimelineRangeName::ExitCrossing:- // Represents the range during which the principal box crosses the start border edge.- return sorted(metrics.cover_end() - metrics.subject_size, metrics.cover_end());- case TimelineRangeName::Scroll:- // Represents the full range of the scroll container on which the view progress timeline is defined.- return { 0, metrics.max_scroll_offset };- }- VERIFY_NOT_REACHED();-}--AttachmentInterval ViewTimeline::interval_for_attachment_range(AnimationAttachmentRange const& range) const-{- auto cover_length = m_last_metrics.has_value() ? m_last_metrics->cover_end() - m_last_metrics->cover_start() : 0;- if (cover_length == 0)- return ScrollTimeline::interval_for_attachment_range(range);-- // Each edge is measured from the start of its named timeline range, along that range, and is then placed as a- // proportion of the cover range, which spans the entire timeline.- auto time_of = [&](TimelineRangeEdge const& edge) {- auto named_range = interval_for_range_name(*m_last_metrics, edge.name);- auto position = named_range.start + edge.offset_along(named_range.end - named_range.start);- return TimeValue { TimeValue::Type::Percentage, (position - m_last_metrics->cover_start()) / cover_length * 100 };- };- return { time_of(range.start), time_of(range.end) };-}--// NB: The timeline times at the minimum and the maximum scroll offsets, which need not be 0% and 100%.-Optional<TimeValue> ViewTimeline::minimum_timeline_time() const-{- if (!m_last_metrics.has_value() || m_last_metrics->cover_end() == m_last_metrics->cover_start())- return {};- return TimeValue { TimeValue::Type::Percentage, (0 - m_last_metrics->cover_start()) / (m_last_metrics->cover_end() - m_last_metrics->cover_start()) * 100 };-}--Optional<TimeValue> ViewTimeline::maximum_timeline_time() const-{- if (!m_last_metrics.has_value() || m_last_metrics->cover_end() == m_last_metrics->cover_start())- return {};- return TimeValue { TimeValue::Type::Percentage, (m_last_metrics->max_scroll_offset - m_last_metrics->cover_start()) / (m_last_metrics->cover_end() - m_last_metrics->cover_start()) * 100 };-}--GC::Ref<CSS::CSSNumericValue> ViewTimeline::start_offset() const-{- // Represents the starting (0% progress) scroll position of the view progress timeline as a length offset (in px)- // from the scroll origin.- return CSS::CSSUnitValue::create(m_last_metrics.has_value() ? m_last_metrics->cover_start() : 0, "px"_utf16_fly_string);-}--GC::Ref<CSS::CSSNumericValue> ViewTimeline::end_offset() const-{- // Represents the ending (100% progress) scroll position of the view progress timeline as a length offset (in px)- // from the scroll origin.- return CSS::CSSUnitValue::create(m_last_metrics.has_value() ? m_last_metrics->cover_end() : 0, "px"_utf16_fly_string);-}--}diff --git a/Libraries/LibWeb/Animations/ViewTimeline.h b/Libraries/LibWeb/Animations/ViewTimeline.hdeleted file mode 100644index df30e8a54fd..00000000000--- a/Libraries/LibWeb/Animations/ViewTimeline.h+++ /dev/null@@ -1,89 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Animations/ScrollTimeline.h>-#include <LibWeb/Bindings/ViewTimeline.h>-#include <LibWeb/ComputedValuesRustFFI.h>--namespace Web::Animations {--// https://drafts.csswg.org/scroll-animations-1/#viewtimeline-class ViewTimeline final : public ScrollTimeline {- WEB_WRAPPABLE(ViewTimeline, ScrollTimeline);- GC_DECLARE_ALLOCATOR(ViewTimeline);--public:- using InsetEdge = ViewTimelineInsetEdge;- using Inset = ViewTimelineInset;-- static GC::Ref<ViewTimeline> create(DOM::Document&, DOM::AbstractElement subject, ScrollAxis, Inset);- static WebIDL::ExceptionOr<GC::Ref<ViewTimeline>> create_for_constructor(JS::Object&, Bindings::ViewTimelineOptions const&);-- // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-subject- GC::Ref<DOM::Element const> subject() const;- DOM::AbstractElement subject_internal() const;-- // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source- virtual GC::Ptr<DOM::Element const> source_for_bindings() const override;-- Inset const& inset() const { return m_inset; }- void set_axis_and_inset(ScrollAxis, Inset);-- // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-startoffset- GC::Ref<CSS::CSSNumericValue> start_offset() const;- // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-endoffset- GC::Ref<CSS::CSSNumericValue> end_offset() const;-- virtual bool is_stale() const override;- virtual void update_current_time(double timestamp) override;- virtual AttachmentInterval interval_for_attachment_range(AnimationAttachmentRange const&) const override;- virtual Optional<TimeValue> minimum_timeline_time() const override;- virtual Optional<TimeValue> maximum_timeline_time() const override;-- // What decides the progress of the timeline, along its axis, in CSS pixels.- struct Metrics {- Optional<FollowedScroller> followed_scroller;- double scroll_offset { 0 };- double max_scroll_offset { 0 };- double scrollport_size { 0 };- // The insets of the view progress visibility range, at the start and at the end of the scrollport.- double inset_start { 0 };- double inset_end { 0 };- // Where the subject's border box starts, from the start of the scrollport, and its size.- double subject_offset { 0 };- double subject_size { 0 };- // The start and the end of the cover range.- double cover_start() const { return subject_offset - (scrollport_size - inset_end); }- double cover_end() const { return subject_offset + subject_size - inset_start; }-- bool operator==(Metrics const&) const = default;- };- // What the timeline's progress was last calculated from: empty while it was inactive.- Optional<Metrics> const& last_metrics() const { return m_last_metrics; }--private:- // The scroll offsets at the start and at the end of a named timeline range, in CSS pixels.- struct ScrollOffsetInterval {- double start { 0 };- double end { 0 };- };-- ViewTimeline(DOM::Document&, DOM::AbstractElement subject, ScrollAxis, Inset);- virtual ~ViewTimeline() override = default;-- Optional<Metrics> compute_metrics() const;-- ScrollOffsetInterval interval_for_range_name(Metrics const&, TimelineRangeName) const;-- Inset m_inset;- Optional<Metrics> m_last_metrics;-};--ViewTimelineInset view_timeline_inset_from_ffi(CSS::ComputedValuesFFI::FfiViewTimelineInset const&);--}diff --git a/Libraries/LibWeb/Animations/ViewTimeline.idl b/Libraries/LibWeb/Animations/ViewTimeline.idlindex 91449726045..746dcf4a4e8 100644--- a/Libraries/LibWeb/Animations/ViewTimeline.idl+++ b/Libraries/LibWeb/Animations/ViewTimeline.idl@@ -7,7 +7,7 @@ dictionary ViewTimelineOptions {};// https://drafts.csswg.org/scroll-animations-1/#viewtimeline-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface ViewTimeline : ScrollTimeline {constructor(ViewTimelineOptions options);readonly attribute Element subject;diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rsnew file mode 100644index 00000000000..44dc34c954e--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animatable.rs@@ -0,0 +1,211 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.csswg.org/web-animations-1/#the-animatable-interface-mixin++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, MarkedVec, Object};+use libweb_rust::AnimationRecordRef;+use libweb_rust::web_animations::sort_in_composite_order;++use super::animation::{+ AnyAnimation, TimelineRangeValue, animation_object, default_document_timeline, parse_timeline_range_edge,+ perform_host_effect, realm_of_element,+};+use super::animation_timeline::{AnyAnimationTimeline, element_of_wrapper};+use super::keyframe_effect::{+ KeyframeEffect, KeyframeEffectOptions, KeyframesArgument, UnrestrictedDoubleOrKeyframeEffectOptions,+ process_a_keyframes_argument, pseudo_element_parsing,+};+use crate::bindings::conversions::CppInterface;+use crate::bindings::{CallContext, Exception, WebIdlResult};++unsafe extern "C" {+ fn web_animation_for_each_relevant_animation(+ node_wrapper: *mut c_void,+ subtree: bool,+ context: *mut c_void,+ on_animation: unsafe extern "C" fn(context: *mut c_void, animation: *const c_void),+ );+ fn web_animation_compare_elements_in_tree_order(first: *mut c_void, second: *mut c_void) -> i32;+ fn ladybird_animations_element_node_document(element: *mut c_void) -> *mut c_void;+}++// https://drafts.csswg.org/web-animations-1/#dictdef-keyframeanimationoptions+pub(crate) struct KeyframeAnimationOptions {+ pub(crate) parent: KeyframeEffectOptions,+ pub(crate) id: Utf16String,+ pub(crate) timeline: Option<Option<AnyAnimationTimeline>>,+ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+ pub(crate) range_start: TimelineRangeValue,+ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend+ pub(crate) range_end: TimelineRangeValue,+}++/// The union (unrestricted double or KeyframeAnimationOptions) of the options of Animatable.animate().+pub(crate) enum UnrestrictedDoubleOrKeyframeAnimationOptions {+ UnrestrictedDouble(f64),+ KeyframeAnimationOptions(KeyframeAnimationOptions),+}++/// https://drafts.csswg.org/web-animations-1/#dom-animatable-animate+pub(crate) fn animate(+ this: &CppInterface,+ cx: &mut CallContext,+ keyframes: Option<Gc<Object>>,+ options: UnrestrictedDoubleOrKeyframeAnimationOptions,+) -> WebIdlResult<AnyAnimation> {+ let vm = cx.vm();++ // 1. Let target be the object on which this method was called.+ let target = element_of_wrapper(*this);+ // SAFETY: The element is live, and so is its node document.+ let document = NonNull::new(unsafe { ladybird_animations_element_node_document(target.as_ptr()) })+ .expect("an element has a node document");+ let realm = realm_of_element(target);++ // INTEROP: Like Chrome, the keyframes are processed before the range is parsed, so the keyframes' getters run first.+ let keyframes = process_a_keyframes_argument(vm, keyframes)?;++ let (effect_options, animation_options) = match options {+ UnrestrictedDoubleOrKeyframeAnimationOptions::UnrestrictedDouble(duration) => (+ UnrestrictedDoubleOrKeyframeEffectOptions::UnrestrictedDouble(duration),+ None,+ ),+ UnrestrictedDoubleOrKeyframeAnimationOptions::KeyframeAnimationOptions(options) => (+ UnrestrictedDoubleOrKeyframeEffectOptions::KeyframeEffectOptions(options.parent),+ Some((options.id, options.timeline, options.range_start, options.range_end)),+ ),+ };++ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend+ let mut timeline_option = None;+ let mut id = None;+ let mut range = None;+ if let Some((options_id, options_timeline, range_start, range_end)) = animation_options {+ range = Some((+ parse_timeline_range_edge(document, range_start, false)?,+ parse_timeline_range_edge(document, range_end, true)?,+ ));+ timeline_option = options_timeline;+ id = Some(options_id);+ }++ // 2. Construct a new KeyframeEffect object, effect, in the relevant Realm of target by using the same procedure as+ // the KeyframeEffect(target, keyframes, options) constructor, passing target as the target argument, and the+ // keyframes and options arguments as supplied.+ //+ // If the above procedure causes an exception to be thrown, propagate the exception and abort this procedure.+ let mut effect_cx = CallContext::new(vm, realm);+ let effect = KeyframeEffect::construct_for_target(+ &mut effect_cx,+ target.as_ptr(),+ KeyframesArgument::Processed(keyframes),+ effect_options,+ )?;++ // 3. If options is a KeyframeAnimationOptions object, let timeline be the timeline member of options or, if+ // timeline member of options is missing, be the default document timeline of the node document of the element+ // on which this method was called.+ let timeline = match timeline_option {+ Some(timeline) => timeline.map(|timeline| timeline.record().clone()),+ None => Some(default_document_timeline(document)),+ };++ // 4. Construct a new Animation object, animation, in the relevant Realm of target by using the same procedure as+ // the Animation() constructor, passing effect and timeline as arguments of the same name.+ let animation = super::animation::Animation::create(vm, realm, Some(effect.effect().record()), timeline.as_ref());++ // 5. If options is a KeyframeAnimationOptions object, assign the value of the id member of options to animation’s+ // id attribute.+ if let Some(id) = id {+ animation.record().set_dom_id(&id);+ }++ // 6. Run the procedure to play an animation for animation with the auto-rewind flag set to true.+ animation+ .record()+ .play_an_animation(perform_host_effect)+ .map_err(|exception| match exception {+ libweb_rust::web_animations::AnimationException::InvalidState(message) => {+ Exception::Dom("InvalidStateError", Utf16String::from_utf8(message))+ }+ libweb_rust::web_animations::AnimationException::TypeError(message) => Exception::type_error(message),+ })?;++ if let Some((start, end)) = range {+ animation.record().set_range_edge(false, start, perform_host_effect);+ animation.record().set_range_edge(true, end, perform_host_effect);+ }++ // 7. Return animation.+ Ok(AnyAnimation::Animation(animation))+}++// https://drafts.csswg.org/web-animations-1/#dictdef-getanimationsoptions+pub(crate) struct GetAnimationsOptions {+ pub(crate) subtree: bool,+ pub(crate) pseudo_element: Option<Utf16String>,+}++/// https://drafts.csswg.org/web-animations-1/#dom-animatable-getanimations+pub(crate) fn get_animations<'vm>(+ this: &CppInterface,+ cx: &mut CallContext<'vm>,+ options: GetAnimationsOptions,+) -> WebIdlResult<MarkedVec<'vm, AnyAnimation>> {+ // 1. Let object be the object on which this method was called.+ // 2. Let pseudoElement be the result of pseudo-element parsing applied to pseudoElement of options, or null if+ // options is not passed.+ let _pseudo_element = pseudo_element_parsing(options.pseudo_element.as_ref())?;++ // 3. If pseudoElement is not null, then let target be the pseudo-element identified by pseudoElement with object+ // as the originating element. Otherwise, let target be object.+ // FIXME: We can't refer to pseudo-elements directly, and they also can't be animated yet.++ // 4. If options is passed with subtree set to true, then return the set of relevant animations for a subtree of+ // target. Otherwise, return the set of relevant animations for target.+ // The returned list is sorted using the composite order described for the associated animations of effects in+ // §5.4.2 The effect stack.+ Ok(sorted_relevant_animations(this, options.subtree, cx))+}++/// The relevant animations of the element or the document or shadow root `node`, and those of its subtree where+/// `subtree` is set, after the pending style changes are applied, sorted in composite order.+pub(super) fn sorted_relevant_animations<'vm>(+ node: &CppInterface,+ subtree: bool,+ cx: &mut CallContext<'vm>,+) -> MarkedVec<'vm, AnyAnimation> {+ unsafe extern "C" fn on_animation(context: *mut c_void, animation: *const c_void) {+ // SAFETY: The context is the list below, and LibWeb passes animations that it holds references to.+ let animations = unsafe { &mut *context.cast::<Vec<AnimationRecordRef>>() };+ animations.push(unsafe { AnimationRecordRef::retained_from_host(animation) });+ }+ let mut relevant_animations: Vec<AnimationRecordRef> = Vec::new();+ // SAFETY: The wrapper is live, and the callback receives the list for as long as the call runs.+ unsafe {+ web_animation_for_each_relevant_animation(+ node.wrapper().as_ptr().cast(),+ subtree,+ (&raw mut relevant_animations).cast(),+ on_animation,+ );+ }++ sort_in_composite_order(&mut relevant_animations, web_animation_compare_elements_in_tree_order);++ let vm = cx.vm();+ let animations = MarkedVec::new(vm);+ for animation in &relevant_animations {+ animations.push(animation_object(vm, animation));+ }+ animations+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rsnew file mode 100644index 00000000000..1f13e4b9b12--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation.rs@@ -0,0 +1,972 @@+/*+ * Copyright (c) 2023-2024, Matthew Olsson <[email protected]>.+ * Copyright (c) 2025, Jelle Raaijmakers <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Animation, https://www.w3.org/TR/web-animations-1/#the-animation-interface++use core::cell::Cell;+use core::ffi::c_void;+use core::ops::Deref;+use core::ptr::NonNull;++use ak::Utf16String;+use libcompositing_rust::animation_timing::{OptionalTimeValue, TimeValue, TimeValueType};+use libjs_rust::api::{Gc, Realm, ThrowCompletionOr, Trace, Value, Visitor, Vm};+use libweb_rust::AnimationRecordRef;+use libweb_rust::web_animations::{+ AnimationException, AnimationInterfaceKind, AnimationProcedure, AttachmentRangeEdgeValue, CssAnimationFlag,+ EffectRecordRef, HostEffect, HostEffectKind, PROPERTY_ID_ANIMATION_RANGE_END, PROPERTY_ID_ANIMATION_RANGE_START,+ StyleValue, attachment_range_edge_from_computed_value, numeric_type_matches_time, parse_property_value,+ style_value_as_host_ptr, style_value_from_host,+};++use super::animation_effect::{AnyAnimationEffect, effect_object};+use super::animation_playback_event::time_value_as_css_numberish;+use super::animation_timeline::{AnyAnimationTimeline, timeline_object};+use super::document_timeline::document_of_realm;+use crate::bindings::conversions::ToJs;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{+ Inherits, Ref, Wrappable, allocate, cell_from_abi, cell_into_abi, with_temporary_execution_context,+};+use crate::bindings::promise::{+ WebIdlPromise, create_promise, create_resolved_promise, mark_promise_as_handled, reject_promise_with_exception,+ resolve_promise,+};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::css::css_animation::CSSAnimation;+use crate::css::css_keyword_value::CSSKeywordValue;+use crate::css::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};+use crate::css::css_transition::CSSTransition;+use crate::css::typed_om::reify_a_numeric_value;++unsafe extern "C" {+ fn web_animation_perform_host_effect(effect: *const c_void);+ fn web_animation_update_style_of_owning_element(animation: *const c_void);+ fn web_animation_update_style_of_owning_element_document(animation: *const c_void);+ fn web_animation_realm_of_element(element: *mut c_void) -> *mut c_void;+ fn web_animation_document_timeline_of_document(document: *mut c_void) -> *mut c_void;+ fn web_animation_timeline_current_time_for_observation(timeline: *mut c_void) -> OptionalTimeValue;+ fn web_animation_absolutize_style_value(document: *mut c_void, value: *const c_void) -> *const c_void;+ fn web_animation_visit_named_cells(animation: *const c_void, visitor: *mut c_void);+ fn web_animation_commit_styles(animation: *const c_void) -> CommitStylesResult;+}++/// What committing the computed styles of an animation to the style attribute of its target answers.+#[repr(u8)]+#[allow(dead_code, reason = "The host constructs the outcomes")]+enum CommitStylesResult {+ Committed,+ TargetCannotHaveInlineStyle,+ TargetIsNotBeingRendered,+}++// https://drafts.csswg.org/web-animations-1/#the-animationplaystate-enumeration+#[derive(Clone, Copy)]+pub(crate) enum AnimationPlayState {+ Idle,+ Running,+ Paused,+ Finished,+}++// https://drafts.csswg.org/web-animations-1/#the-animationreplacestate-enumeration+#[derive(Clone, Copy)]+pub(crate) enum AnimationReplaceState {+ Active,+ Removed,+ Persisted,+}++// https://drafts.csswg.org/web-animations-2/#dictdef-timelinerangeoffset+pub(crate) struct TimelineRangeOffset {+ pub(crate) range_name: Option<Option<Utf16String>>,+ pub(crate) offset: Option<AnyCSSNumericValue>,+}++/// The union (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) of an attachment range edge.+pub(crate) enum TimelineRangeValue {+ TimelineRangeOffset(TimelineRangeOffset),+ CSSNumericValue(AnyCSSNumericValue),+ CSSKeywordValue(Ref<CSSKeywordValue>),+ DOMString(Utf16String),+}++/// Has the host perform what a procedure asked for.+pub(crate) extern "C" fn perform_host_effect(effect: &HostEffect) {+ // SAFETY: The host performs the effects of the procedures of its animations.+ unsafe { web_animation_perform_host_effect(core::ptr::from_ref(effect).cast()) };+}++fn exception_of(exception: AnimationException) -> Exception {+ match exception {+ AnimationException::InvalidState(message) => {+ Exception::Dom("InvalidStateError", Utf16String::from_utf8(message))+ }+ AnimationException::TypeError(message) => Exception::type_error(message),+ }+}++fn run(animation: &AnimationRecordRef, procedure: AnimationProcedure) -> WebIdlResult<()> {+ animation.run(procedure, perform_host_effect).map_err(exception_of)+}++/// Has the owning element of a CSS animation or transition compute its style, where the style changed.+pub(crate) fn update_style_if_needed(animation: &AnimationRecordRef) {+ // SAFETY: The animation is live.+ unsafe { web_animation_update_style_of_owning_element(animation.as_host_ptr()) };+}++/// The current time of the timeline of the animation as script observes it, which is unresolved where it has none.+fn timeline_time_for_observation(animation: &AnimationRecordRef) -> Option<TimeValue> {+ let timeline = animation.timeline()?;+ let cell = timeline.facade()?;+ // SAFETY: The cell is the live object of the timeline of the animation.+ unsafe { web_animation_timeline_current_time_for_observation(cell.as_ptr()) }.get()+}++/// https://www.w3.org/TR/web-animations-1/#animation-current-time+/// As script observes it.+pub(crate) fn current_time_for_observation(animation: &AnimationRecordRef) -> Option<TimeValue> {+ animation.current_time_at(timeline_time_for_observation(animation))+}++/// AD-HOC: What an update of the timing of the associated effect tells the animation.+pub(crate) fn effect_timing_changed(animation: &AnimationRecordRef) {+ animation.update_finished_state(true, None, perform_host_effect);+}++/// The realm of the host's `DOM::Element`'s node document's relevant global object.+pub(crate) fn realm_of_element(element: NonNull<c_void>) -> Gc<Realm> {+ // SAFETY: The element is live, and the host returns the live realm of its document.+ unsafe {+ Gc::from_non_null(+ NonNull::new(web_animation_realm_of_element(element.as_ptr()).cast::<Realm>())+ .expect("an element's document has a relevant realm"),+ )+ }+}++/// https://drafts.csswg.org/web-animations-1/#default-document-timeline+/// Of the host's `DOM::Document`.+pub(crate) fn default_document_timeline(document: NonNull<c_void>) -> libweb_rust::web_animations::TimelineRecordRef {+ // SAFETY: The document is live, and the host returns the live cell of its timeline.+ let cell = unsafe { web_animation_document_timeline_of_document(document.as_ptr()) };+ // SAFETY: The cell is the live cell of a timeline.+ unsafe { timeline_object(cell) }.record().clone()+}++/// https://html.spec.whatwg.org/multipage/webappapis.html#concept-relevant-realm+/// That of the object of the animation, or for a CSS animation or transition without one, of the document of its+/// owning element, and for the animation of an SVG animation element, of the document of that element.+pub(crate) fn animation_relevant_realm(animation: &AnimationRecordRef) -> Option<Gc<Realm>> {+ if let Some(object) = existing_animation_object(animation) {+ return Some(object.realm);+ }+ let element = animation+ .owning_element()+ .map(|(element, _)| element)+ .or_else(|| animation.smil_animation_element())?;+ Some(realm_of_element(element))+}++// https://www.w3.org/TR/web-animations-1/#the-animation-interface+pub(crate) struct Animation {+ event_target: CppEventTarget,+ realm: Gc<Realm>,+ // NB: The animation's state, which lives as long as the animation.+ record: AnimationRecordRef,++ // https://www.w3.org/TR/web-animations-1/#current-ready-promise+ // NB: Created as script first asks for it. Until then, it is pending while the animation has a pending play or+ // pause task, and resolved otherwise.+ current_ready_promise: Cell<Option<WebIdlPromise>>,++ // https://www.w3.org/TR/web-animations-1/#current-finished-promise+ // NB: Created as script first asks for it. Until then, it is resolved while the animation is finished, and pending+ // otherwise.+ current_finished_promise: Cell<Option<WebIdlPromise>>,+}++// SAFETY: Visits the event target, the realm, the promises and the cells of the host the record names.+unsafe impl Trace for Animation {+ fn trace(&self, visitor: &mut Visitor) {+ self.event_target.trace(visitor);+ visitor.visit(self.realm);+ if let Some(promise) = self.current_ready_promise.get() {+ visitor.visit(promise);+ }+ if let Some(promise) = self.current_finished_promise.get() {+ visitor.visit(promise);+ }+ // SAFETY: The animation holds a reference to the record, and the visitor is one LibGC passed in.+ unsafe { web_animation_visit_named_cells(self.record.as_host_ptr(), visitor.as_raw().cast()) };+ }+}++impl Wrappable for Animation {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ Some(self.realm)+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event_target.as_cpp_parent()+ }++ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ object.finalize_animation();+ }+}++impl GetTheParent for Animation {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++/// An object script sees of an animation, of the interface its kind picks.+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+#[allow(clippy::enum_variant_names, reason = "the variants have the interfaces’ names")]+pub(crate) enum AnyAnimation {+ Animation(Ref<Animation>),+ CSSAnimation(Ref<CSSAnimation>),+ CSSTransition(Ref<CSSTransition>),+}++impl Deref for AnyAnimation {+ type Target = Animation;++ fn deref(&self) -> &Animation {+ match self {+ Self::Animation(animation) => animation,+ Self::CSSAnimation(animation) => animation.parent(),+ Self::CSSTransition(animation) => animation.parent(),+ }+ }+}++impl ToJs for AnyAnimation {+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {+ match self {+ Self::Animation(animation) => animation.to_js(cx),+ Self::CSSAnimation(animation) => animation.to_js(cx),+ Self::CSSTransition(animation) => animation.to_js(cx),+ }+ }+}++impl AnyAnimation {+ fn cell(self) -> *mut c_void {+ match self {+ Self::Animation(animation) => cell_into_abi(animation),+ Self::CSSAnimation(animation) => cell_into_abi(animation),+ Self::CSSTransition(animation) => cell_into_abi(animation),+ }+ }++ fn event_target_owner(self) {+ match self {+ Self::Animation(animation) => animation.event_target.set_owner(animation),+ Self::CSSAnimation(animation) => animation.parent().event_target.set_owner(animation),+ Self::CSSTransition(animation) => animation.parent().event_target.set_owner(animation),+ }+ }++ fn value_in(self, vm: &Vm, realm: Gc<Realm>) -> Value {+ self.to_js(&CallContext::new(vm, realm))+ .expect("wrapping an animation does not throw")+ }+}++/// The object of the animation, if it has one.+pub(crate) fn existing_animation_object(animation: &AnimationRecordRef) -> Option<AnyAnimation> {+ let cell = animation.facade()?.as_ptr();+ // SAFETY: The facade of an animation is the live cell of its object, of the interface its kind picks.+ Some(unsafe {+ match animation.kind() {+ AnimationInterfaceKind::Script => AnyAnimation::Animation(cell_from_abi(cell)),+ AnimationInterfaceKind::CssAnimation => AnyAnimation::CSSAnimation(cell_from_abi(cell)),+ AnimationInterfaceKind::CssTransition => AnyAnimation::CSSTransition(cell_from_abi(cell)),+ AnimationInterfaceKind::Smil => unreachable!("script never sees the animation of an SVG animation element"),+ }+ })+}++/// The object script sees of the animation, a CSS animation or transition or one script created, which a CSS animation+/// or transition gets as script first asks for it.+pub(crate) fn animation_object(vm: &Vm, animation: &AnimationRecordRef) -> AnyAnimation {+ if let Some(object) = existing_animation_object(animation) {+ return object;+ }+ let (owner, _) = animation+ .owning_element()+ .expect("an animation without an object is a CSS animation or transition, which has an owning element");+ // NB: The realm is that of the document of the owning element as script first asks for the object.+ let realm = realm_of_element(owner);+ let base = Animation::new(realm, animation.clone());+ let object = match animation.kind() {+ AnimationInterfaceKind::CssAnimation => AnyAnimation::CSSAnimation(CSSAnimation::allocate(vm, base)),+ AnimationInterfaceKind::CssTransition => AnyAnimation::CSSTransition(CSSTransition::allocate(vm, base)),+ AnimationInterfaceKind::Script | AnimationInterfaceKind::Smil => {+ unreachable!("only CSS animations and transitions get their objects lazily")+ }+ };+ object.event_target_owner();+ animation.set_facade(NonNull::new(object.cell()));+ object+}++impl Animation {+ pub(crate) fn new(realm: Gc<Realm>, record: AnimationRecordRef) -> Self {+ Self {+ event_target: CppEventTarget::new(),+ realm,+ record,+ current_ready_promise: Cell::new(None),+ current_finished_promise: Cell::new(None),+ }+ }++ /// The animation's state, which lives as long as the animation.+ pub(crate) fn record(&self) -> &AnimationRecordRef {+ &self.record+ }++ pub(crate) fn finalize_animation(&self) {+ // NB: The record can outlive the animation until what holds the record is swept.+ self.record.set_facade(None);+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-animation+ pub(crate) fn construct(+ cx: &mut CallContext,+ effect: Option<AnyAnimationEffect>,+ timeline: Option<Option<AnyAnimationTimeline>>,+ ) -> WebIdlResult<Ref<Self>> {+ let vm = cx.vm();+ let realm = cx.realm();+ // NB: A missing timeline is the default document timeline of the Document associated with the Window that is+ // the current global object.+ let timeline = match timeline {+ Some(timeline) => timeline.map(|timeline| timeline.record().clone()),+ None => Some(default_document_timeline(document_of_realm(realm))),+ };++ Ok(Self::create(+ vm,+ realm,+ effect.as_ref().map(|effect| effect.record()),+ timeline.as_ref(),+ ))+ }++ /// The procedure of the Animation() constructor, in the realm.+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ effect: Option<&EffectRecordRef>,+ timeline: Option<&libweb_rust::web_animations::TimelineRecordRef>,+ ) -> Ref<Self> {+ // 1. Let animation be a new Animation object.+ let animation = allocate(vm, |_| Self::new(realm, AnimationRecordRef::new_script_animation()));+ animation.event_target.set_owner(animation);+ animation.record.set_facade(NonNull::new(cell_into_abi(animation)));++ // 2. Run the procedure to set the timeline of an animation on animation passing timeline as the new timeline.+ animation.record.set_timeline(timeline, perform_host_effect);++ // 3. Run the procedure to set the associated effect of an animation on animation passing source as the new+ // effect.+ animation.record.set_effect(effect, perform_host_effect);++ animation+ }++ /// The object of the animation in the realm of its record, with its promises settled in that realm.+ fn object(&self) -> AnyAnimation {+ existing_animation_object(&self.record).expect("an animation is the object of its record while it is alive")+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-id+ pub(crate) fn id(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.record.dom_id())+ }++ pub(crate) fn set_id(&self, _: &mut CallContext, id: Utf16String) -> WebIdlResult<()> {+ self.record.set_dom_id(&id);+ Ok(())+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-effect+ pub(crate) fn effect(&self, cx: &mut CallContext) -> WebIdlResult<Option<AnyAnimationEffect>> {+ Ok(self.record.effect().map(|effect| effect_object(cx.vm(), &effect)))+ }++ pub(crate) fn set_effect(&self, _: &mut CallContext, effect: Option<AnyAnimationEffect>) -> WebIdlResult<()> {+ // Setting this attribute updates the object’s associated effect using the procedure to set the associated+ // effect of an animation.+ // NB: The procedure runs in the record. Where new effect is the associated effect of another animation, it+ // sets that one's associated effect too, on that one's timeline. The old effect stays alive while the host+ // performs what the procedure asks, which recomputes the style of its target.+ let _old_effect: Option<EffectRecordRef> = self.record.effect();+ self.record+ .set_effect(effect.as_ref().map(|effect| effect.record()), perform_host_effect);+ Ok(())+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-timeline+ pub(crate) fn timeline(&self, _: &mut CallContext) -> WebIdlResult<Option<AnyAnimationTimeline>> {+ update_style_if_needed(&self.record);+ Ok(self.record.timeline().map(|timeline| {+ let cell = timeline+ .facade()+ .expect("the timeline of an animation script reaches is alive");+ // SAFETY: The cell is the live cell of a timeline.+ unsafe { timeline_object(cell.as_ptr()) }+ }))+ }++ // https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation+ // https://drafts.csswg.org/web-animations-2/#setting-the-timeline+ pub(crate) fn set_timeline(&self, _: &mut CallContext, timeline: Option<AnyAnimationTimeline>) -> WebIdlResult<()> {+ // AD-HOC: When the timeline of a CSS animation is modified by the author from JS we should no longer apply+ // changes to the `animation-timeline` property. See https://github.com/w3c/csswg-drafts/issues/13472+ if self.record.kind() == AnimationInterfaceKind::CssAnimation {+ self.record.set_css_animation_flag(CssAnimationFlag::ScriptSetTimeline);+ }+ // NB: The procedure runs in the record.+ self.record+ .set_timeline(timeline.as_ref().map(|timeline| timeline.record()), perform_host_effect);+ Ok(())+ }++ // https://drafts.csswg.org/web-animations-2/#validating-a-css-numberish-time+ fn validate_a_css_numberish_time(&self, time: Option<CSSNumberish>) -> WebIdlResult<Option<TimeValue>> {+ // The procedure to validate a CSSNumberish time for an input value of time is based on the first condition+ // that matches:+ let progress_based = self.record.has_progress_based_timeline();+ let numeric_type = match &time {+ Some(CSSNumberish::CSSNumericValue(value)) => Some(value.numeric_type()),+ _ => None,+ };++ // If all of the following conditions are true:+ // - The animation is associated with a progress-based timeline, and+ // - time is not a CSSNumeric value with percent units:+ if progress_based+ && !numeric_type+ .as_ref()+ .is_some_and(|numeric_type| numeric_type.matches_percentage())+ {+ // throw a TypeError.+ // return false;+ return Err(Exception::type_error(+ "CSSNumberish must be a percentage for progress-based animations",+ ));+ }++ // If all of the following conditions are true:+ // - The animation is not associated with a progress-based timeline, and+ // - time is a CSSNumericValue, and+ // - the units of time are not duration units:+ // AD-HOC: While it's not mentioned in the spec WPT also expects us to support CSSNumericValue number value, see+ // https://github.com/w3c/csswg-drafts/issues/13196+ if !progress_based+ && let Some(numeric_type) = &numeric_type+ && !numeric_type_matches_time(numeric_type)+ && !numeric_type.matches_number(None)+ {+ // throw a TypeError.+ // return false.+ return Err(Exception::type_error(+ "CSSNumericValue must be a time for non-progress based animations",+ ));+ }++ // Otherwise+ // return true.++ // AD-HOC: The spec doesn't say when we should absolutize the validated value so we do it here and return the+ // absolutized value instead of a boolean+ let Some(time) = time else {+ return Ok(None);+ };+ Ok(Some(match time {+ CSSNumberish::Double(milliseconds) => TimeValue {+ r#type: TimeValueType::Milliseconds,+ value: milliseconds,+ },+ CSSNumberish::CSSNumericValue(value) => {+ let calculation = value.create_calculation_node()?;+ libweb_rust::web_animations::time_value_of_calculation(calculation, value.numeric_type())+ .ok_or_else(|| Exception::type_error("Invalid CSSNumberish time"))?+ }+ }))+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animation-starttime+ pub(crate) fn start_time(&self, cx: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ update_style_if_needed(&self.record);+ Ok(self+ .record+ .playback()+ .start_time+ .get()+ .map(|time| time_value_as_css_numberish(cx.vm(), time)))+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-starttime+ // https://www.w3.org/TR/web-animations-1/#set-the-start-time+ pub(crate) fn set_start_time(&self, _: &mut CallContext, new_start_time: Option<CSSNumberish>) -> WebIdlResult<()> {+ // Setting this attribute updates the start time using the procedure to set the start time of this object to+ // the new value.++ // 1. Let valid start time be the result of running the validate a CSSNumberish time procedure with new start+ // time as the input.+ // 2. If valid start time is false, abort this procedure.+ // AD-HOC: The validate_a_css_numberish_time throws on validation failure which is handled by the ? operator so+ // there is no need to assign the `valid start time` variable here.+ let new_start_time = self.validate_a_css_numberish_time(new_start_time)?;++ // NB: The other steps run in the record.+ self.record.set_start_time(new_start_time, perform_host_effect);+ Ok(())+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animation-currenttime+ pub(crate) fn current_time(&self, cx: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ update_style_if_needed(&self.record);+ Ok(current_time_for_observation(&self.record).map(|time| time_value_as_css_numberish(cx.vm(), time)))+ }++ // https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time+ pub(crate) fn set_current_time(&self, _: &mut CallContext, seek_time: Option<CSSNumberish>) -> WebIdlResult<()> {+ // AD-HOC: We validate here instead of within silently_set_current_time so we have access to the `TimeValue`+ // value within this function.+ let seek_time = self.validate_a_css_numberish_time(seek_time)?;++ // NB: The procedure runs in the record.+ self.record+ .set_current_time(seek_time, perform_host_effect)+ .map_err(exception_of)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-playbackrate+ pub(crate) fn playback_rate(&self, _: &mut CallContext) -> WebIdlResult<f64> {+ Ok(self.record.playback_rate())+ }++ pub(crate) fn set_playback_rate(&self, _: &mut CallContext, playback_rate: f64) -> WebIdlResult<()> {+ // Setting this attribute follows the procedure to set the playback rate of this object to the new value.+ run(&self.record, AnimationProcedure::SetPlaybackRate(playback_rate))+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animation-rangestart+ pub(crate) fn range_start(&self, cx: &mut CallContext) -> WebIdlResult<TimelineRangeValue> {+ update_style_if_needed(&self.record);+ let [start, _] = self.record.range();+ Ok(range_edge_to_bindings(cx.vm(), start, false))+ }++ pub(crate) fn set_range_start(&self, cx: &mut CallContext, value: TimelineRangeValue) -> WebIdlResult<()> {+ self.set_range_edge(cx, value, false)+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animation-rangeend+ pub(crate) fn range_end(&self, cx: &mut CallContext) -> WebIdlResult<TimelineRangeValue> {+ update_style_if_needed(&self.record);+ let [_, end] = self.record.range();+ Ok(range_edge_to_bindings(cx.vm(), end, true))+ }++ pub(crate) fn set_range_end(&self, cx: &mut CallContext, value: TimelineRangeValue) -> WebIdlResult<()> {+ self.set_range_edge(cx, value, true)+ }++ fn set_range_edge(&self, _: &mut CallContext, value: TimelineRangeValue, is_end: bool) -> WebIdlResult<()> {+ let edge = parse_timeline_range_edge(document_of_realm(self.realm), value, is_end)?;+ self.record.set_range_edge(is_end, edge, perform_host_effect);+ // AD-HOC: Like the timeline, a range edge script sets takes precedence over the animation-range-start or+ // animation-range-end property from then on, as WPT expects+ // (scroll-animations/css/animation-range-ignored.html).+ if self.record.kind() == AnimationInterfaceKind::CssAnimation {+ self.record.set_css_animation_flag(if is_end {+ CssAnimationFlag::ScriptSetRangeEnd+ } else {+ CssAnimationFlag::ScriptSetRangeStart+ });+ }+ Ok(())+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-playstate+ pub(crate) fn play_state(&self, _: &mut CallContext) -> WebIdlResult<AnimationPlayState> {+ use libweb_rust::web_animations::AnimationPlayState as RecordPlayState;+ // NB: Script observes the play state of an animation with the style of the document of its owning element+ // computed, at the current time it observes.+ // SAFETY: The animation is live.+ unsafe { web_animation_update_style_of_owning_element_document(self.record.as_host_ptr()) };+ let current_time = current_time_for_observation(&self.record);+ Ok(match self.record.play_state_at(current_time) {+ RecordPlayState::Idle => AnimationPlayState::Idle,+ RecordPlayState::Running => AnimationPlayState::Running,+ RecordPlayState::Paused => AnimationPlayState::Paused,+ RecordPlayState::Finished => AnimationPlayState::Finished,+ })+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-replacestate+ pub(crate) fn replace_state(&self, _: &mut CallContext) -> WebIdlResult<AnimationReplaceState> {+ use libweb_rust::web_animations::AnimationReplaceState as RecordReplaceState;+ Ok(match self.record.replace_state() {+ RecordReplaceState::Active => AnimationReplaceState::Active,+ RecordReplaceState::Removed => AnimationReplaceState::Removed,+ RecordReplaceState::Persisted => AnimationReplaceState::Persisted,+ })+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-pending+ pub(crate) fn pending(&self, _: &mut CallContext) -> WebIdlResult<bool> {+ update_style_if_needed(&self.record);+ Ok(self.record.pending())+ }++ // https://www.w3.org/TR/web-animations-1/#current-ready-promise+ fn current_ready_promise(&self, vm: &Vm) -> WebIdlPromise {+ if let Some(promise) = self.current_ready_promise.get() {+ return promise;+ }+ // The current ready promise is initially a resolved Promise created using the procedure to create a new+ // resolved Promise with the animation itself as its value and created in the relevant Realm of the animation.+ // NB: A promise the procedures replaced, which script did not ask for yet, is pending while the animation has+ // a pending play or pause task.+ let promise = if self.record.pending() {+ create_promise(vm, self.realm)+ } else {+ create_resolved_promise(vm, self.realm, self.object().value_in(vm, self.realm))+ };+ self.current_ready_promise.set(Some(promise));+ promise+ }++ // https://www.w3.org/TR/web-animations-1/#current-finished-promise+ fn current_finished_promise(&self, vm: &Vm) -> WebIdlPromise {+ if let Some(promise) = self.current_finished_promise.get() {+ return promise;+ }+ // The current finished promise is initially a pending Promise object.+ // NB: A promise the procedures resolved, which script did not ask for yet, is resolved while the animation is+ // finished.+ let promise = if self.record.playback().is_finished {+ create_resolved_promise(vm, self.realm, self.object().value_in(vm, self.realm))+ } else {+ create_promise(vm, self.realm)+ };+ self.current_finished_promise.set(Some(promise));+ promise+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-ready+ pub(crate) fn ready(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ update_style_if_needed(&self.record);+ Ok(self.current_ready_promise(cx.vm()))+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-finished+ pub(crate) fn finished(&self, cx: &mut CallContext) -> WebIdlResult<WebIdlPromise> {+ update_style_if_needed(&self.record);+ // NB: An animation that script observes finished ahead of the timeline's own current time settles its finished+ // promise as it reads it, at the time it observes.+ if let Some(timeline) = self.record.timeline() {+ use libweb_rust::web_animations::AnimationPlayState as RecordPlayState;+ let observed_timeline_time = timeline_time_for_observation(&self.record);+ let observed_current_time = self.record.current_time_at(observed_timeline_time);+ let current_time = self.record.current_time_at(timeline.current_time());+ if !self.record.playback().is_finished+ && self.record.play_state_at(current_time) != RecordPlayState::Finished+ && self.record.play_state_at(observed_current_time) == RecordPlayState::Finished+ {+ let previous_override = timeline.style_sampling_override();+ timeline.set_style_sampling_override(Some(observed_timeline_time));+ self.record+ .update_finished_state(false, observed_current_time, perform_host_effect);+ timeline.set_style_sampling_override(previous_override);+ }+ }+ Ok(self.current_finished_promise(cx.vm()))+ }++ /// Settles a promise of the animation, as a procedure asked.+ fn perform_promise_effect(&self, vm: &Vm, kind: HostEffectKind) {+ let reject = |promise: &Cell<Option<WebIdlPromise>>| {+ // OPTIMIZATION: A promise that was never created is one nothing can observe. Rejecting it does nothing,+ // and the new promise the record then implies is just like it, so this only matters for a+ // created one.+ let Some(promise) = promise.take() else {+ return;+ };+ reject_promise_with_exception(+ vm,+ promise,+ Exception::Dom("AbortError", Utf16String::from_ascii(b"Animation was cancelled")),+ );+ mark_promise_as_handled(vm, promise);+ };+ let resolve = |promise: &Cell<Option<WebIdlPromise>>| {+ // NB: Resolving a promise with the animation reads its "then" property, which script can observe, so a+ // promise that was never created is created to be resolved.+ let promise = match promise.get() {+ Some(promise) => promise,+ None => {+ let created = create_promise(vm, self.realm);+ promise.set(Some(created));+ created+ }+ };+ resolve_promise(vm, promise, self.object().value_in(vm, self.realm));+ };+ match kind {+ // NB: The new promise is the pending one the record now implies, which script creates as it asks for it.+ HostEffectKind::ReplaceReadyPromise => self.current_ready_promise.set(None),+ HostEffectKind::ResolveReadyPromise => resolve(&self.current_ready_promise),+ HostEffectKind::RejectReadyPromise => reject(&self.current_ready_promise),+ HostEffectKind::ReplaceFinishedPromise => self.current_finished_promise.set(None),+ HostEffectKind::ResolveFinishedPromise => resolve(&self.current_finished_promise),+ HostEffectKind::RejectFinishedPromise => reject(&self.current_finished_promise),+ _ => unreachable!("the effect is one of the promises of the animation"),+ }+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-cancel+ pub(crate) fn cancel(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.+ if self.record.is_idle() {+ return run(&self.record, AnimationProcedure::Cancel);+ }+ with_temporary_execution_context(self.realm, || run(&self.record, AnimationProcedure::Cancel))+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-finish+ pub(crate) fn finish(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // NB: Finishing an animation can resolve its current ready promise.+ with_temporary_execution_context(self.realm, || run(&self.record, AnimationProcedure::Finish))+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-play+ pub(crate) fn play(&self, _: &mut CallContext) -> WebIdlResult<()> {+ run(&self.record, AnimationProcedure::Play)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-pause+ pub(crate) fn pause(&self, _: &mut CallContext) -> WebIdlResult<()> {+ run(&self.record, AnimationProcedure::Pause)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-updateplaybackrate+ pub(crate) fn update_playback_rate(&self, _: &mut CallContext, playback_rate: f64) -> WebIdlResult<()> {+ run(&self.record, AnimationProcedure::UpdatePlaybackRate(playback_rate))+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-reverse+ pub(crate) fn reverse(&self, _: &mut CallContext) -> WebIdlResult<()> {+ run(&self.record, AnimationProcedure::Reverse)+ }++ // https://drafts.csswg.org/web-animations-1/#dom-animation-commitstyles+ pub(crate) fn commit_styles(&self, _: &mut CallContext) -> WebIdlResult<()> {+ // SAFETY: The animation is live for the call, and the host commits its styles without retaining it.+ match unsafe { web_animation_commit_styles(self.record.as_host_ptr()) } {+ CommitStylesResult::Committed => Ok(()),+ CommitStylesResult::TargetCannotHaveInlineStyle => Err(Exception::Dom(+ "NoModificationAllowedError",+ Utf16String::from_ascii(b"The animation target cannot have an inline style"),+ )),+ CommitStylesResult::TargetIsNotBeingRendered => Err(Exception::Dom(+ "InvalidStateError",+ Utf16String::from_ascii(b"The animation target is not being rendered"),+ )),+ }+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animation-persist+ pub(crate) fn persist(&self, _: &mut CallContext) -> WebIdlResult<()> {+ run(&self.record, AnimationProcedure::Persist)+ }++ /// The bytes of the object, and those of the object of its associated effect.+ pub(crate) fn memory_size(object: AnyAnimation) -> usize {+ let object_size = match object {+ AnyAnimation::Animation(_) => size_of::<Animation>(),+ AnyAnimation::CSSAnimation(_) => size_of::<CSSAnimation>(),+ AnyAnimation::CSSTransition(_) => size_of::<CSSTransition>(),+ };+ let effect_size = object+ .record+ .effect()+ .and_then(|effect| super::animation_effect::existing_effect_object(&effect))+ .map_or(0, |effect| effect.memory_size());+ object_size + effect_size+ }+}++/// The value the attribute rangeStart, or rangeEnd where `is_end`, reads of an edge: either a TimelineRangeOffset or the+/// DOMString "normal".+fn range_edge_to_bindings(vm: &Vm, edge: AttachmentRangeEdgeValue, is_end: bool) -> TimelineRangeValue {+ use crate::css::css_unit_value::CSSUnitValue;++ if edge.is_normal(is_end) {+ return TimelineRangeValue::DOMString(Utf16String::from_ascii(b"normal"));+ }++ let px = AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, edge.px, "px"));+ let percentage = AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(vm, edge.percentage, "percent"));+ let mut offset = if edge.px == 0.0 { percentage } else { px };+ if edge.px != 0.0 && edge.percentage != 0.0 {+ let values = libjs_rust::api::MarkedVec::new(vm);+ values.push(CSSNumberish::CSSNumericValue(percentage));+ if let Ok(sum) = px.add(vm, &values) {+ offset = sum;+ }+ }+ if let Some(calculated) = &edge.calculated+ && let Some(reified) = reify_a_numeric_value(vm, calculated)+ {+ offset = reified;+ }++ let range_name = libweb_rust::web_animations::timeline_range_name_to_string(edge.name)+ .map(|name| Utf16String::from_ascii(name.as_bytes()));+ TimelineRangeValue::TimelineRangeOffset(TimelineRangeOffset {+ range_name: Some(range_name),+ offset: Some(offset),+ })+}++fn invalid_timeline_range() -> Exception {+ Exception::type_error("Invalid timeline range")+}++/// https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+/// The edge `value` gives as the start of an attachment range, or as its end where `is_end`, for the host's+/// `DOM::Document` `document`.+pub(crate) fn parse_timeline_range_edge(+ document: NonNull<c_void>,+ value: TimelineRangeValue,+ is_end: bool,+) -> WebIdlResult<AttachmentRangeEdgeValue> {+ let property = if is_end {+ PROPERTY_ID_ANIMATION_RANGE_END+ } else {+ PROPERTY_ID_ANIMATION_RANGE_START+ };+ // A DOMString value is parsed as an 'animation-range-start' (or 'animation-range-end') value to yield a+ // TimelineRangeOffset rangeName and offset or alternatively a CSSKeywordValue with the value of "normal"; a+ // CSSNumericValue is interpreted as a TimelineRangeOffset with that offset and a null rangeName.+ let parse = |text: &Utf16String| -> WebIdlResult<AttachmentRangeEdgeValue> {+ let parsed = parse_property_value(property, text).ok_or_else(invalid_timeline_range)?;+ // NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.+ if parsed.is_css_wide_keyword() || parsed.is_unresolved() || parsed.is_pending_substitution() {+ return Err(invalid_timeline_range());+ }+ // SAFETY: The document and the value are live, and the host hands over a reference to the absolutized value.+ let computed: StyleValue = unsafe {+ style_value_from_host(web_animation_absolutize_style_value(+ document.as_ptr(),+ style_value_as_host_ptr(&parsed),+ ))+ };+ attachment_range_edge_from_computed_value(&computed, is_end).ok_or_else(invalid_timeline_range)+ };+ let normal = || Utf16String::from_ascii(b"normal");+ match value {+ TimelineRangeValue::TimelineRangeOffset(offset) => {+ let mut text = String::new();+ if let Some(Some(range_name)) = &offset.range_name {+ text.push_str(&String::from_utf16_lossy(&range_name.to_utf16()));+ }+ if let Some(offset) = offset.offset {+ text.push(' ');+ text.push_str(&String::from_utf16_lossy(&offset.to_css_string().to_utf16()));+ }+ // NB: A TimelineRangeOffset that gives neither a range name nor an offset is the default edge.+ if text.is_empty() {+ return parse(&normal());+ }+ parse(&Utf16String::from_utf8(&text))+ }+ TimelineRangeValue::CSSNumericValue(offset) => parse(&offset.to_css_string()),+ // Passing a CSSKeywordValue with a value other than "normal" as the rangeStart or rangeEnd value to any API+ // defined to accept KeyframeAnimationOptions throws a TypeError.+ TimelineRangeValue::CSSKeywordValue(keyword) => {+ if !String::from_utf16_lossy(&keyword.raw_value().to_utf16()).eq_ignore_ascii_case("normal") {+ return Err(invalid_timeline_range());+ }+ parse(&normal())+ }+ TimelineRangeValue::DOMString(text) => parse(&text),+ }+}++/// The realm of the object of the animation, or null where it has none.+///+/// # Safety+///+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_object_realm(animation: *const c_void) -> *mut c_void {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationRecordRef::retained_from_host(animation) };+ existing_animation_object(&animation).map_or(core::ptr::null_mut(), |object| object.realm.as_ptr().cast())+}++/// The host's `DOM::EventTarget` of the object of the animation, which a playback event of it is dispatched at.+///+/// # Safety+///+/// `animation` must be an animation the host holds a reference to, which has an object.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_object_event_target(animation: *const c_void) -> *mut c_void {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationRecordRef::retained_from_host(animation) };+ existing_animation_object(&animation)+ .expect("an animation that hears its playback events has an object")+ .event_target+ .as_ptr()+}++/// The bytes of the object of the animation and of the object of its associated effect, or zero where the animation has+/// no object.+///+/// # Safety+///+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_object_memory_size(animation: *const c_void) -> usize {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationRecordRef::retained_from_host(animation) };+ existing_animation_object(&animation).map_or(0, Animation::memory_size)+}++/// Settles a promise of the object of the animation `effect` names, as a procedure asked.+///+/// # Safety+///+/// `vm` must be the live VM, and `effect` an effect the host performs.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_perform_promise_effect(vm: *mut c_void, effect: &HostEffect) {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ // SAFETY: The effect names an animation the host holds a reference to.+ let animation = unsafe { AnimationRecordRef::retained_from_host(effect.animation.as_ptr().cast()) };+ // NB: Only an animation with an object has promises script can observe.+ if let Some(object) = existing_animation_object(&animation) {+ object.perform_promise_effect(vm, effect.kind);+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rsnew file mode 100644index 00000000000..f56a3d5e638--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_effect.rs@@ -0,0 +1,422 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! AnimationEffect, https://www.w3.org/TR/web-animations-1/#the-animationeffect-interface++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+pub(crate) use libcompositing_rust::animation_timing::{FillMode, PlaybackDirection};+use libcompositing_rust::animation_timing::{SpecifiedIterationDuration, TimeValue};+use libjs_rust::api::{Gc, Realm, Trace, Visitor};+use libweb_rust::AnimationRecordRef;+use libweb_rust::web_animations::{EffectRecordRef, ParsedEasing, parse_easing_function};++use super::animation::{+ animation_relevant_realm, current_time_for_observation, effect_timing_changed, update_style_if_needed,+};+use super::animation_playback_event::time_value_as_css_numberish;+use super::keyframe_effect::KeyframeEffect;+use crate::bindings::conversions::ToJs;+use crate::bindings::interface::Wrappable;+use crate::bindings::interface::{Inherits, Ref, cell_from_abi, cell_into_abi};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::css::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};+use core::ops::Deref;+use libjs_rust::api::{ThrowCompletionOr, Value, Vm};++unsafe extern "C" {+ fn web_animation_effect_visit_host_cells(effect: *const c_void, visitor: *mut c_void);+}++/// The union (unrestricted double or CSSNumericValue or DOMString) of the duration member of EffectTiming.+pub(crate) enum UnrestrictedDoubleOrCSSNumericValueOrDOMString {+ UnrestrictedDouble(f64),+ CSSNumericValue(AnyCSSNumericValue),+ DOMString(Utf16String),+}++/// The union (unrestricted double or DOMString) of the duration member of OptionalEffectTiming.+pub(crate) enum UnrestrictedDoubleOrDOMString {+ UnrestrictedDouble(f64),+ DOMString(Utf16String),+}++// https://www.w3.org/TR/web-animations-1/#dictdef-effecttiming+pub(crate) struct EffectTiming {+ pub(crate) delay: f64,+ pub(crate) direction: PlaybackDirection,+ pub(crate) duration: UnrestrictedDoubleOrCSSNumericValueOrDOMString,+ pub(crate) easing: Utf16String,+ pub(crate) end_delay: f64,+ pub(crate) fill: FillMode,+ pub(crate) iteration_start: f64,+ pub(crate) iterations: f64,+}++// https://www.w3.org/TR/web-animations-1/#dictdef-computedeffecttiming+pub(crate) struct ComputedEffectTiming {+ pub(crate) parent: EffectTiming,+ pub(crate) active_duration: Option<CSSNumberish>,+ pub(crate) current_iteration: Option<Option<f64>>,+ pub(crate) end_time: Option<CSSNumberish>,+ pub(crate) local_time: Option<Option<CSSNumberish>>,+ pub(crate) progress: Option<Option<f64>>,+}++// https://www.w3.org/TR/web-animations-1/#dictdef-optionaleffecttiming+#[derive(Default)]+pub(crate) struct OptionalEffectTiming {+ pub(crate) delay: Option<f64>,+ pub(crate) direction: Option<PlaybackDirection>,+ pub(crate) duration: Option<UnrestrictedDoubleOrDOMString>,+ pub(crate) easing: Option<Utf16String>,+ pub(crate) end_delay: Option<f64>,+ pub(crate) fill: Option<FillMode>,+ pub(crate) iteration_start: Option<f64>,+ pub(crate) iterations: Option<f64>,+}++/// Whether the string is the ASCII text.+pub(crate) fn utf16_string_equals(string: &Utf16String, text: &str) -> bool {+ string.to_utf16().iter().copied().eq(text.encode_utf16())+}++// https://www.w3.org/TR/web-animations-1/#the-animationeffect-interface+pub(crate) struct AnimationEffect {+ record: EffectRecordRef,+}++// SAFETY: Visits the cells of the host that keep the record's associated animation and target element alive, as the+// host visits them.+unsafe impl Trace for AnimationEffect {+ fn trace(&self, visitor: &mut Visitor) {+ // SAFETY: The effect holds a reference to the record, and the visitor is one LibGC passed in.+ unsafe { web_animation_effect_visit_host_cells(self.record.as_host_ptr(), visitor.as_raw().cast()) };+ }+}++impl Wrappable for AnimationEffect {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ self.relevant_realm()+ }+}++impl AnimationEffect {+ /// The part as an AnimationEffect of the object of the effect whose state `record` holds.+ pub(crate) fn from_record(record: EffectRecordRef) -> Self {+ Self { record }+ }++ /// The effect's state, which lives as long as the effect.+ pub(crate) fn record(&self) -> &EffectRecordRef {+ &self.record+ }++ /// The realm of the relevant global object of the associated animation, if there is one.+ pub(crate) fn relevant_realm(&self) -> Option<Gc<Realm>> {+ animation_relevant_realm(&self.record.associated_animation()?)+ }++ pub(crate) fn update_style_if_needed(&self) {+ if let Some(animation) = self.record.associated_animation() {+ update_style_if_needed(&animation);+ }+ }++ fn associated_animation(&self) -> Option<AnimationRecordRef> {+ self.record.associated_animation()+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animationeffect-gettiming+ pub(crate) fn get_timing(&self, _cx: &mut CallContext) -> WebIdlResult<EffectTiming> {+ self.update_style_if_needed();++ // 1. Returns the specified timing properties for this animation effect.+ let specified = self.record.specified_timing();+ let timing = self.record.timing();+ Ok(EffectTiming {+ delay: specified.start_delay,+ direction: timing.playback_direction,+ duration: if specified.iteration_duration.is_auto {+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::DOMString(Utf16String::from_ascii(b"auto"))+ } else {+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::UnrestrictedDouble(+ specified.iteration_duration.milliseconds,+ )+ },+ easing: self.record.timing_function_serialization(),+ end_delay: specified.end_delay,+ fill: timing.fill_mode,+ iteration_start: specified.iteration_start,+ iterations: specified.iteration_count,+ })+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animationeffect-getcomputedtiming+ // https://drafts.csswg.org/web-animations-2/#dom-animationeffect-getcomputedtiming+ pub(crate) fn get_computed_timing(&self, cx: &mut CallContext) -> WebIdlResult<ComputedEffectTiming> {+ let vm = cx.vm();+ self.update_style_if_needed();++ // NB: The local time is the current time of the associated animation as script observes it.+ let local_time = self+ .associated_animation()+ .and_then(|animation| current_time_for_observation(&animation));++ // 1. Returns the calculated timing properties for this animation effect.++ // Note: Although some of the attributes of the object returned by getTiming() and getComputedTiming() are+ // common, their values may differ in the following ways:++ // - duration: while getTiming() may return the string auto, getComputedTiming() must return a number+ // corresponding to the calculated value of the iteration duration as defined in the description of the+ // duration member of the EffectTiming interface.+ //+ // If duration is the string auto, this attribute will return the current calculated value of the+ // intrinsic iteration duration, which may be a expressed as a double representing the duration in+ // milliseconds or a percentage when the effect is associated with a progress-based timeline.+ let timing_properties = self.record.timing();+ let duration = match time_value_as_css_numberish(vm, timing_properties.iteration_duration) {+ CSSNumberish::Double(value) => UnrestrictedDoubleOrCSSNumericValueOrDOMString::UnrestrictedDouble(value),+ CSSNumberish::CSSNumericValue(value) => {+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::CSSNumericValue(value)+ }+ };++ // - fill: likewise, while getTiming() may return the string auto, getComputedTiming() must return the+ // specific FillMode used for timing calculations as defined in the description of the fill member of the+ // EffectTiming interface.+ //+ // In this level of the specification, that simply means that an auto value is replaced by the none+ // FillMode.+ let specified_fill_mode = timing_properties.fill_mode;+ let fill = if specified_fill_mode == FillMode::Auto {+ FillMode::None+ } else {+ specified_fill_mode+ };++ let specified = self.record.specified_timing();+ let timing = self.record.resolve_timing(local_time, specified_fill_mode, true);+ let as_css_numberish = |time: TimeValue| time_value_as_css_numberish(vm, time);+ Ok(ComputedEffectTiming {+ parent: EffectTiming {+ delay: specified.start_delay,+ direction: timing_properties.playback_direction,+ duration,+ easing: self.record.timing_function_serialization(),+ end_delay: specified.end_delay,+ fill,+ iteration_start: timing_properties.iteration_start,+ iterations: timing_properties.iteration_count,+ },+ active_duration: Some(as_css_numberish(timing.active_duration)),+ current_iteration: Some(timing.current_iteration.get()),+ end_time: Some(as_css_numberish(timing.end_time)),+ local_time: Some(local_time.map(as_css_numberish)),+ progress: Some(timing.transformed_progress.get()),+ })+ }++ // https://www.w3.org/TR/web-animations-1/#dom-animationeffect-updatetiming+ pub(crate) fn update_timing(&self, _cx: &mut CallContext, timing: OptionalEffectTiming) -> WebIdlResult<()> {+ self.update_the_timing_properties(timing)+ }++ // https://www.w3.org/TR/web-animations-1/#update-the-timing-properties-of-an-animation-effect+ // https://drafts.csswg.org/web-animations-2/#updating-animationeffect-timing+ pub(crate) fn update_the_timing_properties(&self, timing: OptionalEffectTiming) -> WebIdlResult<()> {+ // 1. If the iterationStart member of input exists and is less than zero, throw a TypeError and abort this+ // procedure.+ if timing+ .iteration_start+ .is_some_and(|iteration_start| iteration_start < 0.0)+ {+ return Err(Exception::type_error("Invalid iteration start value"));+ }++ // 2. If the iterations member of input exists, and is less than zero or is the value NaN, throw a TypeError+ // and abort this procedure.+ if timing+ .iterations+ .is_some_and(|iterations| iterations < 0.0 || iterations.is_nan())+ {+ return Err(Exception::type_error("Invalid iteration count value"));+ }++ // 3. If the duration member of input exists, and is less than zero or is the value NaN, throw a TypeError and+ // abort this procedure.+ // Note: "auto", the only valid string value, is treated as 0.+ let has_valid_duration_value = match &timing.duration {+ None => true,+ Some(UnrestrictedDoubleOrDOMString::UnrestrictedDouble(duration)) => {+ !(*duration < 0.0 || duration.is_nan())+ }+ Some(UnrestrictedDoubleOrDOMString::DOMString(duration)) => utf16_string_equals(duration, "auto"),+ };+ if !has_valid_duration_value {+ return Err(Exception::type_error("Invalid duration value"));+ }++ // 4. If the easing member of input exists but cannot be parsed using the <easing-function> production+ // [CSS-EASING-1], throw a TypeError and abort this procedure.+ let easing_value: Option<ParsedEasing> = match &timing.easing {+ Some(easing) => {+ Some(parse_easing_function(easing).ok_or_else(|| Exception::type_error("Invalid easing function"))?)+ }+ None => None,+ };++ // 5. Assign each member that exists in input to the corresponding timing property of effect as follows:+ let mut specified = self.record.specified_timing();++ // - delay → specified start delay+ if let Some(delay) = timing.delay {+ specified.start_delay = delay;+ }++ // - endDelay → specified end delay+ if let Some(end_delay) = timing.end_delay {+ specified.end_delay = end_delay;+ }++ // - fill → fill mode+ if let Some(fill) = timing.fill {+ specified.fill_mode = fill;+ }++ // - iterationStart → iteration start+ if let Some(iteration_start) = timing.iteration_start {+ specified.iteration_start = iteration_start;+ }++ // - iterations → iteration count+ if let Some(iterations) = timing.iterations {+ specified.iteration_count = iterations;+ }++ // - duration → specified iteration duration+ // NB: "auto" is the only string an iteration duration can be.+ match timing.duration {+ Some(UnrestrictedDoubleOrDOMString::UnrestrictedDouble(duration)) => {+ specified.iteration_duration = SpecifiedIterationDuration::milliseconds(duration);+ }+ Some(UnrestrictedDoubleOrDOMString::DOMString(_)) => {+ specified.iteration_duration = SpecifiedIterationDuration::AUTO;+ }+ None => {}+ }++ // - direction → playback direction+ if let Some(direction) = timing.direction {+ specified.playback_direction = direction;+ }+ self.record.set_specified_timing(specified);++ // - easing → timing function+ if let Some(easing_value) = &easing_value {+ self.record.set_timing_function(easing_value);+ }++ // 6. Follow the procedure to normalize specified timing.+ self.record.normalize_specified_timing();++ // AD-HOC: Notify the associated animation that the effect timing has changed.+ if let Some(animation) = self.associated_animation() {+ effect_timing_changed(&animation);+ }++ Ok(())+ }+}++/// An EffectTiming as the OptionalEffectTiming with each of its members, which the procedure to update the timing+/// properties of an animation effect takes; none of its durations is a CSSNumericValue.+pub(crate) fn to_optional_effect_timing(effect_timing: EffectTiming) -> OptionalEffectTiming {+ OptionalEffectTiming {+ delay: Some(effect_timing.delay),+ direction: Some(effect_timing.direction),+ duration: Some(match effect_timing.duration {+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::UnrestrictedDouble(value) => {+ UnrestrictedDoubleOrDOMString::UnrestrictedDouble(value)+ }+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::DOMString(value) => {+ UnrestrictedDoubleOrDOMString::DOMString(value)+ }+ // NB: We check that this isn't the case in the caller+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::CSSNumericValue(_) => {+ unreachable!("the caller rejects a CSSNumericValue duration")+ }+ }),+ easing: Some(effect_timing.easing),+ end_delay: Some(effect_timing.end_delay),+ fill: Some(effect_timing.fill),+ iteration_start: Some(effect_timing.iteration_start),+ iterations: Some(effect_timing.iterations),+ }+}++/// An object script sees of an effect, of the interface that inherits from AnimationEffect it is of.+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+#[allow(clippy::enum_variant_names, reason = "the variants have the interfaces’ names")]+pub(crate) enum AnyAnimationEffect {+ AnimationEffect(Ref<AnimationEffect>),+ KeyframeEffect(Ref<KeyframeEffect>),+}++impl Deref for AnyAnimationEffect {+ type Target = AnimationEffect;++ fn deref(&self) -> &AnimationEffect {+ match self {+ Self::AnimationEffect(effect) => effect,+ Self::KeyframeEffect(effect) => effect.parent(),+ }+ }+}++impl ToJs for AnyAnimationEffect {+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {+ match self {+ Self::AnimationEffect(effect) => effect.to_js(cx),+ Self::KeyframeEffect(effect) => effect.to_js(cx),+ }+ }+}++impl AnyAnimationEffect {+ /// The bytes the object of the effect holds.+ pub(crate) fn memory_size(&self) -> usize {+ match self {+ Self::AnimationEffect(_) => size_of::<AnimationEffect>(),+ Self::KeyframeEffect(effect) => effect.memory_size(),+ }+ }+}++/// The object of the effect, if it has one.+pub(crate) fn existing_effect_object(effect: &EffectRecordRef) -> Option<AnyAnimationEffect> {+ let cell = effect.facade()?;+ // SAFETY: The facade of an effect is the live cell of its object, a KeyframeEffect, the only AnimationEffect there+ // is.+ Some(AnyAnimationEffect::KeyframeEffect(unsafe {+ cell_from_abi(cell.as_ptr())+ }))+}++/// The object script sees of the effect, a KeyframeEffect, which the effect of a CSS animation or transition gets as+/// script first asks for it.+pub(crate) fn effect_object(vm: &Vm, effect: &EffectRecordRef) -> AnyAnimationEffect {+ if let Some(object) = existing_effect_object(effect) {+ return object;+ }+ let object = KeyframeEffect::create_for_record(vm, effect.clone());+ effect.set_facade(NonNull::new(cell_into_abi(object)));+ AnyAnimationEffect::KeyframeEffect(object)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_playback_event.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_playback_event.rsnew file mode 100644index 00000000000..4827b8b445d--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_playback_event.rs@@ -0,0 +1,100 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! AnimationPlaybackEvent, https://drafts.csswg.org/web-animations-2/#animationplaybackevent++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libcompositing_rust::animation_timing::{TimeValue, TimeValueType};+use libjs_rust::api::{Gc, Realm, Trace, Vm};++use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::{Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};+use crate::css::css_numeric_value::{AnyCSSNumericValue, CSSNumberish};+use crate::css::css_unit_value::CSSUnitValue;+use crate::dom::event::EventInit;++/// The dictionary AnimationPlaybackEventInit of Animations/AnimationPlaybackEvent.idl.+pub(crate) struct AnimationPlaybackEventInit {+ pub(crate) parent: EventInit,+ pub(crate) current_time: Option<CSSNumberish>,+ pub(crate) timeline_time: Option<CSSNumberish>,+}++// https://drafts.csswg.org/web-animations-2/#animationplaybackevent+#[derive(Trace)]+#[gc(crate = libjs_rust)]+pub(crate) struct AnimationPlaybackEvent {+ event: CppEvent,+ // https://drafts.csswg.org/web-animations-2/#dom-animationplaybackevent-currenttime+ current_time: Option<CSSNumberish>,+ // https://drafts.csswg.org/web-animations-2/#dom-animationplaybackevent-timelinetime+ timeline_time: Option<CSSNumberish>,+}++impl Wrappable for AnimationPlaybackEvent {+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.event.as_cpp_parent()+ }+}++/// A time value as the CSSNumberish that the attributes of the event expose: a double for milliseconds and a+/// CSSUnitValue for a percentage.+pub(crate) fn time_value_as_css_numberish(vm: &Vm, time: TimeValue) -> CSSNumberish {+ match time.r#type {+ TimeValueType::Milliseconds => CSSNumberish::Double(time.value),+ TimeValueType::Percentage => CSSNumberish::CSSNumericValue(AnyCSSNumericValue::CSSUnitValue(+ CSSUnitValue::create(vm, time.value, "percent"),+ )),+ }+}++impl AnimationPlaybackEvent {+ pub(crate) fn create(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: AnimationPlaybackEventInit,+ ) -> Ref<AnimationPlaybackEvent> {+ let event = CppEvent::create_for_owner(+ realm,+ event_name,+ event_init.parent.bubbles,+ event_init.parent.cancelable,+ event_init.parent.composed,+ );+ let object = allocate(vm, |_| AnimationPlaybackEvent {+ event,+ current_time: event_init.current_time,+ timeline_time: event_init.timeline_time,+ });+ object.event.set_owner(object);+ object+ }++ pub(crate) fn construct(+ cx: &mut CallContext,+ r#type: Utf16String,+ event_init_dict: AnimationPlaybackEventInit,+ ) -> WebIdlResult<Ref<AnimationPlaybackEvent>> {+ Ok(Self::create(cx.vm(), cx.realm(), &r#type, event_init_dict))+ }++ pub(crate) fn event(&self) -> &CppEvent {+ &self.event+ }++ pub(crate) fn current_time(&self, _: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ Ok(self.current_time)+ }++ pub(crate) fn timeline_time(&self, _: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ Ok(self.timeline_time)+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rsnew file mode 100644index 00000000000..4a643d7ef81--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/animation_timeline.rs@@ -0,0 +1,272 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! AnimationTimeline, https://drafts.csswg.org/web-animations-2/#the-animationtimeline-interface++use core::ffi::c_void;+use core::ptr::NonNull;++use libcompositing_rust::animation_timing::OptionalTimeValue;+use libjs_rust::api::{Gc, Object, Trace, Visitor, Vm};+use libweb_rust::web_animations::{TimelineInterfaceKind, TimelineRecordRef};++use super::animation_playback_event::time_value_as_css_numberish;+use super::document_timeline::DocumentTimeline;+use super::scroll_timeline::ScrollTimeline;+use super::view_timeline::ViewTimeline;+use crate::bindings::conversions::CppInterface;+use core::ops::Deref;++use libjs_rust::api::{ThrowCompletionOr, Value};++use crate::bindings::conversions::ToJs;+use crate::bindings::interface::{+ Inherits, Interface, Ref, Wrappable, allocate, cell_from_abi, cell_if_abi, cell_into_abi,+};+use crate::bindings::{CallContext, WebIdlResult};+use crate::css::css_numeric_value::CSSNumberish;+use crate::internals::internal_animation_timeline::InternalAnimationTimeline;++unsafe extern "C" {+ fn web_animation_timeline_did_create(timeline: *mut c_void);+ fn web_animation_timeline_current_time_for_observation(timeline: *mut c_void) -> OptionalTimeValue;+ fn web_animation_wrap_element(realm: *mut c_void, element: *mut c_void) -> *mut c_void;+ fn web_animation_element_of_wrapper(wrapper: *mut c_void) -> *mut c_void;+}++// https://drafts.csswg.org/web-animations-2/#the-animationtimeline-interface+pub(crate) struct AnimationTimeline {+ record: TimelineRecordRef,+}++// SAFETY: Visits the cells of the host that the record names: the document the timeline is associated with, and the+// element a scroll timeline finds its scroller from.+unsafe impl Trace for AnimationTimeline {+ fn trace(&self, visitor: &mut Visitor) {+ self.record.for_each_host_cell(|cell| {+ // SAFETY: The record names live cells of the host, which this keeps alive.+ visitor.visit(unsafe { Gc::from_non_null(cell) });+ });+ }+}++impl Wrappable for AnimationTimeline {}++impl AnimationTimeline {+ /// The timeline's state, which lives as long as the timeline.+ pub(crate) fn record(&self) -> &TimelineRecordRef {+ &self.record+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animationtimeline-currenttime+ pub(crate) fn current_time(&self, cx: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ // Returns the current time for this timeline or null if this timeline is inactive. The value is expressed as a+ // percentage for a progress-based timeline, or as a double in milliseconds otherwise.+ // NB: Script observes the current time as the host samples it for observation.+ // SAFETY: The record names the live cell of this timeline.+ let current_time = unsafe { web_animation_timeline_current_time_for_observation(self.cell()) };+ Ok(current_time+ .get()+ .map(|time| time_value_as_css_numberish(cx.vm(), time)))+ }++ // https://drafts.csswg.org/web-animations-2/#dom-animationtimeline-duration+ pub(crate) fn duration(&self, cx: &mut CallContext) -> WebIdlResult<Option<CSSNumberish>> {+ // Returns the duration for this timeline.+ Ok(self+ .record+ .duration()+ .map(|time| time_value_as_css_numberish(cx.vm(), time)))+ }++ /// The cell of the object of this timeline, as the host names it.+ pub(crate) fn cell(&self) -> *mut c_void {+ self.record+ .facade()+ .expect("a timeline script reaches is alive")+ .as_ptr()+ }+}++/// Finalizes a timeline: the record can outlive the timeline until what holds the record is swept.+pub(crate) fn finalize_timeline(timeline: &AnimationTimeline) {+ timeline.record.set_facade(None);+}++impl AnimationTimeline {+ pub(crate) fn new(record: TimelineRecordRef) -> Self {+ Self { record }+ }+}++/// Has the host note a new timeline, whose cell it then reaches the timeline through.+pub(crate) fn did_create_timeline(cell: *mut c_void) {+ // SAFETY: The cell is that of a new timeline.+ let timeline = unsafe { timeline_of_cell(cell) }.expect("the cell is that of a timeline");+ timeline.record.set_facade(NonNull::new(cell));+ // SAFETY: The cell is that of a new timeline.+ unsafe { web_animation_timeline_did_create(cell) };+}++/// A new timeline of the record the host describes, which picks its interface by the kind of the record.+fn create_timeline_from_record(vm: &Vm, record: TimelineRecordRef) -> *mut c_void {+ let timeline = AnimationTimeline::new(record);+ let cell = match timeline.record.kind() {+ TimelineInterfaceKind::Document => cell_into_abi(allocate(vm, |_| DocumentTimeline::from_timeline(timeline))),+ TimelineInterfaceKind::Scroll => cell_into_abi(allocate(vm, |_| ScrollTimeline::from_timeline(timeline))),+ TimelineInterfaceKind::View => cell_into_abi(allocate(vm, |_| ViewTimeline::from_timeline(timeline))),+ TimelineInterfaceKind::Internal => {+ cell_into_abi(allocate(vm, |_| InternalAnimationTimeline::from_timeline(timeline)))+ }+ };+ did_create_timeline(cell);+ cell+}++/// The part as an AnimationTimeline of the timeline whose cell the host names.+///+/// # Safety+///+/// `cell` must be a live cell.+pub(crate) unsafe fn timeline_of_cell<'a>(cell: *mut c_void) -> Option<&'a AnimationTimeline> {+ // NB: The cells live while the host names them, which outlives the reference the caller uses.+ fn extend<'a, T: Interface>(object: Ref<T>, timeline: impl Fn(&T) -> &AnimationTimeline) -> &'a AnimationTimeline {+ let timeline: *const AnimationTimeline = timeline(&object);+ // SAFETY: The cell lives while the host names it.+ unsafe { &*timeline }+ }+ // SAFETY: Guaranteed by the caller.+ unsafe {+ if let Some(object) = cell_if_abi::<DocumentTimeline>(cell) {+ return Some(extend(object, |object| object.timeline()));+ }+ if let Some(object) = cell_if_abi::<ScrollTimeline>(cell) {+ return Some(extend(object, |object| object.timeline()));+ }+ if let Some(object) = cell_if_abi::<ViewTimeline>(cell) {+ return Some(extend(object, |object| object.scroll_timeline().timeline()));+ }+ if let Some(object) = cell_if_abi::<InternalAnimationTimeline>(cell) {+ return Some(extend(object, |object| object.timeline()));+ }+ if let Some(object) = cell_if_abi::<AnimationTimeline>(cell) {+ return Some(extend(object, |object| object));+ }+ }+ None+}++/// The wrapper of the host's `DOM::Element` in the realm of the call.+pub(crate) fn element_wrapper(cx: &CallContext, element: NonNull<c_void>) -> CppInterface {+ // SAFETY: The realm is live, and the element is a live element.+ let wrapper = unsafe { web_animation_wrap_element(cx.realm().as_ptr().cast(), element.as_ptr()) };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the element");+ // SAFETY: LibWeb returns a live wrapper of an Element.+ unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }+}++/// The host's `DOM::Element` of a wrapper of an Element.+pub(crate) fn element_of_wrapper(element: CppInterface) -> NonNull<c_void> {+ // SAFETY: The wrapper is that of a live Element.+ NonNull::new(unsafe { web_animation_element_of_wrapper(element.wrapper().as_ptr().cast()) })+ .expect("a wrapper of an Element wraps an element")+}++/// The record of the timeline whose cell the host names, which lives as long as the timeline.+///+/// # Safety+///+/// `timeline` must be a live cell of an AnimationTimeline.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_timeline_record(timeline: *mut c_void) -> *const c_void {+ // SAFETY: Guaranteed by the caller.+ unsafe { timeline_of_cell(timeline) }+ .expect("the host names the cell of a timeline")+ .record+ .as_host_ptr()+}++/// A new timeline associated with the host's `DOM::Document` `document`, as `description`, the host's+/// `FfiTimelineDescription`, describes it.+///+/// # Safety+///+/// `vm` must be the live VM, `document` a live document and `description` a live description.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_timeline_create(+ vm: *mut c_void,+ document: *mut c_void,+ description: *const c_void,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM.+ let vm = unsafe { &*vm.cast::<Vm>() };+ let document = NonNull::new(document).expect("a timeline is associated with a document");+ // SAFETY: Guaranteed by the caller.+ let record = unsafe { TimelineRecordRef::from_host_description(document, description) };+ create_timeline_from_record(vm, record)+}++/// An object script sees of a timeline, of the interface that inherits from AnimationTimeline it is of.+#[derive(Clone, Copy, PartialEq, Trace)]+#[gc(crate = libjs_rust)]+#[allow(clippy::enum_variant_names, reason = "the variants have the interfaces’ names")]+pub(crate) enum AnyAnimationTimeline {+ AnimationTimeline(Ref<AnimationTimeline>),+ DocumentTimeline(Ref<DocumentTimeline>),+ ScrollTimeline(Ref<ScrollTimeline>),+ ViewTimeline(Ref<ViewTimeline>),+ InternalAnimationTimeline(Ref<InternalAnimationTimeline>),+}++impl Deref for AnyAnimationTimeline {+ type Target = AnimationTimeline;++ fn deref(&self) -> &AnimationTimeline {+ match self {+ Self::AnimationTimeline(timeline) => timeline,+ Self::DocumentTimeline(timeline) => timeline.parent(),+ Self::ScrollTimeline(timeline) => timeline.parent(),+ Self::ViewTimeline(timeline) => timeline.parent().parent(),+ Self::InternalAnimationTimeline(timeline) => timeline.parent(),+ }+ }+}++impl ToJs for AnyAnimationTimeline {+ fn to_js(self, cx: &CallContext) -> ThrowCompletionOr<Value> {+ match self {+ Self::AnimationTimeline(timeline) => timeline.to_js(cx),+ Self::DocumentTimeline(timeline) => timeline.to_js(cx),+ Self::ScrollTimeline(timeline) => timeline.to_js(cx),+ Self::ViewTimeline(timeline) => timeline.to_js(cx),+ Self::InternalAnimationTimeline(timeline) => timeline.to_js(cx),+ }+ }+}++/// The object of the timeline whose cell the host names.+///+/// # Safety+///+/// `cell` must be the live cell of a timeline.+pub(crate) unsafe fn timeline_object(cell: *mut c_void) -> AnyAnimationTimeline {+ // SAFETY: Guaranteed by the caller.+ unsafe {+ if let Some(object) = cell_if_abi::<DocumentTimeline>(cell) {+ return AnyAnimationTimeline::DocumentTimeline(object);+ }+ if let Some(object) = cell_if_abi::<ViewTimeline>(cell) {+ return AnyAnimationTimeline::ViewTimeline(object);+ }+ if let Some(object) = cell_if_abi::<ScrollTimeline>(cell) {+ return AnyAnimationTimeline::ScrollTimeline(object);+ }+ if let Some(object) = cell_if_abi::<InternalAnimationTimeline>(cell) {+ return AnyAnimationTimeline::InternalAnimationTimeline(object);+ }+ AnyAnimationTimeline::AnimationTimeline(cell_from_abi::<AnimationTimeline>(cell))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/document_or_shadow_root.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/document_or_shadow_root.rsnew file mode 100644index 00000000000..9d1dcc68e82--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/document_or_shadow_root.rs@@ -0,0 +1,33 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! https://drafts.csswg.org/web-animations-1/#extensions-to-the-documentorshadowroot-interface-mixin++use libjs_rust::api::MarkedVec;++use super::animatable::sorted_relevant_animations;+use crate::bindings::conversions::CppInterface;+use crate::bindings::{CallContext, WebIdlResult};++/// https://drafts.csswg.org/web-animations-1/#dom-documentorshadowroot-getanimations+pub(crate) fn get_animations<'vm>(+ this: &CppInterface,+ cx: &mut CallContext<'vm>,+) -> WebIdlResult<MarkedVec<'vm, super::animation::AnyAnimation>> {+ // Returns the set of relevant animations for a subtree for the document or shadow root on which this method is+ // called.+ // NB: LibWeb updates the style of the document before it collects the animations.+ // The returned list is sorted using the composite order described for the associated animations of effects in+ // § 5.4.2 The effect stack.+ let animations = sorted_relevant_animations(this, true, cx);++ // Calling this method triggers a style change event for the document. As a result, the returned list reflects+ // the state after applying any pending style changes to animation such as changes to animation-related style+ // properties that have yet to be processed.+ // FIXME: Implement this.++ Ok(animations)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rsnew file mode 100644index 00000000000..db754b099f7--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/document_timeline.rs@@ -0,0 +1,85 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! DocumentTimeline, https://drafts.csswg.org/web-animations-1/#the-documenttimeline-interface++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{Gc, Realm, Trace, Visitor, Vm};+use libweb_rust::web_animations::{TimelineDescription, TimelineRecordRef};++use super::animation_timeline::{AnimationTimeline, did_create_timeline, finalize_timeline};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ fn web_css_realm_document(realm: *mut c_void) -> *mut c_void;+}++/// The dictionary DocumentTimelineOptions of Animations/DocumentTimeline.idl.+pub(crate) struct DocumentTimelineOptions {+ pub(crate) origin_time: f64,+}++/// The host's `DOM::Document` associated with the Window that is the global object of the realm.+pub(crate) fn document_of_realm(realm: Gc<Realm>) -> NonNull<c_void> {+ // SAFETY: The realm is live.+ NonNull::new(unsafe { web_css_realm_document(realm.as_ptr().cast()) })+ .expect("the realm of a Window has an associated document")+}++// https://drafts.csswg.org/web-animations-1/#the-documenttimeline-interface+pub(crate) struct DocumentTimeline {+ timeline: AnimationTimeline,+}++// SAFETY: The timeline visits what it reaches.+unsafe impl Trace for DocumentTimeline {+ fn trace(&self, visitor: &mut Visitor) {+ self.timeline.trace(visitor);+ }+}++impl Inherits<AnimationTimeline> for DocumentTimeline {+ fn parent(&self) -> &AnimationTimeline {+ &self.timeline+ }+}++impl Wrappable for DocumentTimeline {+ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ finalize_timeline(&object.timeline);+ }+}++impl DocumentTimeline {+ pub(crate) fn from_timeline(timeline: AnimationTimeline) -> Self {+ Self { timeline }+ }++ pub(crate) fn timeline(&self) -> &AnimationTimeline {+ &self.timeline+ }++ /// A new document timeline associated with the host's `DOM::Document` `document`, with the origin time.+ pub(crate) fn create(vm: &Vm, document: NonNull<c_void>, origin_time: f64) -> Ref<Self> {+ let record = TimelineRecordRef::new(document, TimelineDescription::Document { origin_time });+ let object = allocate(vm, |_| Self::from_timeline(AnimationTimeline::new(record)));+ did_create_timeline(cell_into_abi(object));+ object+ }++ // https://drafts.csswg.org/web-animations-1/#dom-documenttimeline-documenttimeline+ pub(crate) fn construct(cx: &mut CallContext, options: DocumentTimelineOptions) -> WebIdlResult<Ref<Self>> {+ // Creates a new DocumentTimeline. The Document with which the timeline is associated is the Document associated+ // with the Window that is the current global object.+ let document = document_of_realm(cx.realm());+ Ok(Self::create(cx.vm(), document, options.origin_time))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rsnew file mode 100644index 00000000000..2a83e216689--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/exports.rs@@ -0,0 +1,50 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the C++ code of LibWeb asks of the interfaces of Web Animations, declared in+//! Libraries/LibWeb/Animations/RecordHandles.cpp.++use core::ffi::c_void;++use ak::Utf16String;+use libcompositing_rust::animation_timing::OptionalTimeValue;++use super::animation_playback_event::{+ AnimationPlaybackEvent, AnimationPlaybackEventInit, time_value_as_css_numberish,+};+use crate::bindings::interface::realm_arguments;+use crate::dom::event::EventInit;++/// A new AnimationPlaybackEvent that neither bubbles nor can be canceled, as the Event that C++ dispatches.+///+/// # Safety+///+/// `vm` must be the live VM, `realm` a live realm, and `event_name` a raw string that C++ hands over.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn web_animation_playback_event_create(+ vm: *mut c_void,+ realm: *mut c_void,+ event_name: usize,+ current_time: OptionalTimeValue,+ timeline_time: OptionalTimeValue,+) -> *mut c_void {+ // SAFETY: The caller passes the live VM and a live realm.+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };+ // SAFETY: The caller hands over the string.+ let event_name = unsafe { Utf16String::from_raw_owned(event_name) };+ let event_init = AnimationPlaybackEventInit {+ parent: EventInit {+ bubbles: false,+ cancelable: false,+ composed: false,+ },+ current_time: current_time.get().map(|time| time_value_as_css_numberish(vm, time)),+ timeline_time: timeline_time.get().map(|time| time_value_as_css_numberish(vm, time)),+ };+ AnimationPlaybackEvent::create(vm, realm, &event_name, event_init)+ .event()+ .as_ptr()+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rsnew file mode 100644index 00000000000..1a22cc6d214--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/keyframe_effect.rs@@ -0,0 +1,1318 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! KeyframeEffect, https://www.w3.org/TR/web-animations-1/#the-keyframeeffect-interface++use core::cell::RefCell;+use core::ffi::c_void;+use core::ptr::{NonNull, null_mut};++use ak::Utf16String;+use libjs_rust::api::{+ ErrorKind, ErrorType, Gc, MarkedVec, Object, PrimitiveString, PropertyKey, PropertyKind, Realm, Trace, Value,+ Visitor, Vm, get_iterator_from_method_impl, iterator_step_value,+};+pub(crate) use libweb_rust::web_animations::CompositeOperation;+use libweb_rust::web_animations::{+ CompositeOperationOrAuto, CssKeyframeValues, EffectRecordRef, KeyframePropertyName, KeyframeSetInput,+ KeyframeSetRef, PROPERTY_ID_CUSTOM, PROPERTY_ID_FLOAT, PROPERTY_ID_OFFSET, ParsedEasing, ParsedPseudoElement,+ StyleValue, camel_case_property_name, clone_property_value, is_animatable_property, parse_easing_function,+ parse_property_value, parse_pseudo_element_selector, property_id_from_camel_case, serialize_property_value,+};++use super::animation_effect::{+ AnimationEffect, EffectTiming, UnrestrictedDoubleOrCSSNumericValueOrDOMString, to_optional_effect_timing,+ utf16_string_equals,+};+use crate::bindings::conversions::{CppInterface, iterator_method};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::{CallContext, Exception, WebIdlResult};++unsafe extern "C" {+ fn web_animation_effect_set_target(effect: *const c_void, element: *mut c_void, update: bool);+ fn web_animation_effect_invalidate(effect: *const c_void);+ fn web_animation_effect_set_composite(effect: *const c_void, composite: CompositeOperation);+ fn web_animation_effect_set_keyframe_set(effect: *const c_void, keyframe_set: *const c_void);+ fn web_animation_element_of_wrapper(wrapper: *mut c_void) -> *mut c_void;+ fn web_animation_wrap_element(realm: *mut c_void, element: *mut c_void) -> *mut c_void;+}++// https://www.w3.org/TR/web-animations-1/#dictdef-keyframeeffectoptions+pub(crate) struct KeyframeEffectOptions {+ pub(crate) parent: EffectTiming,+ pub(crate) composite: CompositeOperation,+ pub(crate) pseudo_element: Option<Utf16String>,+}++/// The union (unrestricted double or KeyframeEffectOptions) of the options of the KeyframeEffect constructor.+pub(crate) enum UnrestrictedDoubleOrKeyframeEffectOptions {+ UnrestrictedDouble(f64),+ KeyframeEffectOptions(KeyframeEffectOptions),+}++/// A value of a member of a property-indexed keyframe, which may be a list.+enum MaybeList<T> {+ Single(T),+ List(Vec<T>),+}++impl<T> MaybeList<T> {+ fn into_list(self) -> Vec<T> {+ match self {+ Self::Single(value) => vec![value],+ Self::List(values) => values,+ }+ }+}++// https://www.w3.org/TR/web-animations-1/#dictdef-basepropertyindexedkeyframe+// Note: This is an intermediate structure used only when parsing Keyframes provided by the caller in a slightly+// different format. It is converted to BaseKeyframe, which is why it doesn't need to store the parsed properties+struct BasePropertyIndexedKeyframe {+ offset: MaybeList<Option<f64>>,+ easing: MaybeList<Utf16String>,+ composite: MaybeList<CompositeOperationOrAuto>,+ properties: Vec<(Utf16String, Vec<Utf16String>)>,+}++impl Default for BasePropertyIndexedKeyframe {+ fn default() -> Self {+ Self {+ offset: MaybeList::List(Vec::new()),+ easing: MaybeList::List(Vec::new()),+ composite: MaybeList::List(Vec::new()),+ properties: Vec::new(),+ }+ }+}++// https://www.w3.org/TR/web-animations-1/#dictdef-basekeyframe+// NB: A keyframe before its property values and its easing are parsed.+struct BaseKeyframe {+ offset: Option<f64>,+ easing: Utf16String,+ composite: CompositeOperationOrAuto,+ computed_offset: Option<f64>,+ properties: Vec<(Utf16String, Utf16String)>,+}++impl Default for BaseKeyframe {+ fn default() -> Self {+ Self {+ offset: None,+ easing: Utf16String::from_ascii(b"linear"),+ composite: CompositeOperationOrAuto::Auto,+ computed_offset: None,+ properties: Vec::new(),+ }+ }+}++/// A keyframe of a KeyframeEffect, https://www.w3.org/TR/web-animations-1/#keyframe, with its property values and its+/// easing parsed.+pub(crate) struct ProcessedKeyframe {+ offset: Option<f64>,+ computed_offset: Option<f64>,+ easing: ParsedEasing,+ composite: CompositeOperationOrAuto,+ properties: Vec<(KeyframePropertyName, StyleValue)>,+}++impl From<CssKeyframeValues> for ProcessedKeyframe {+ fn from(keyframe: CssKeyframeValues) -> Self {+ Self {+ offset: Some(keyframe.offset),+ computed_offset: Some(keyframe.offset),+ easing: keyframe.easing,+ composite: keyframe.composite,+ properties: keyframe.properties,+ }+ }+}++impl Clone for ProcessedKeyframe {+ fn clone(&self) -> Self {+ Self {+ offset: self.offset,+ computed_offset: self.computed_offset,+ easing: self.easing.clone(),+ composite: self.composite,+ properties: self+ .properties+ .iter()+ .map(|(property, value)| (property.clone(), clone_property_value(value)))+ .collect(),+ }+ }+}++/// What compute_missing_keyframe_offsets() reads and writes of a keyframe.+trait KeyframeOffsets {+ fn offset(&self) -> Option<f64>;+ fn computed_offset(&self) -> Option<f64>;+ fn set_computed_offset(&mut self, computed_offset: Option<f64>);+}++impl KeyframeOffsets for BaseKeyframe {+ fn offset(&self) -> Option<f64> {+ self.offset+ }++ fn computed_offset(&self) -> Option<f64> {+ self.computed_offset+ }++ fn set_computed_offset(&mut self, computed_offset: Option<f64>) {+ self.computed_offset = computed_offset;+ }+}++impl KeyframeOffsets for ProcessedKeyframe {+ fn offset(&self) -> Option<f64> {+ self.offset+ }++ fn computed_offset(&self) -> Option<f64> {+ self.computed_offset+ }++ fn set_computed_offset(&mut self, computed_offset: Option<f64>) {+ self.computed_offset = computed_offset;+ }+}++fn type_error(message: String) -> Exception {+ Exception::TypeError(Utf16String::from_utf8(&message))+}++fn display(string: &Utf16String) -> String {+ String::from_utf16_lossy(&string.to_utf16())+}++fn throw<T>(vm: &Vm, error_type: ErrorType, value: Value) -> WebIdlResult<T> {+ Err(vm+ .throw_completion::<T>(ErrorKind::TypeError, error_type, &[&value])+ .err()+ .expect("throwing throws")+ .into())+}++fn convert_value_to_maybe_list<T>(+ vm: &Vm,+ value: Value,+ undefined_element: impl Fn() -> T,+ value_converter: impl Fn(Value) -> WebIdlResult<T>,+) -> WebIdlResult<MaybeList<T>> {+ // NB: As the union conversion rules of Web IDL have it, an object with an @@iterator method converts to the+ // sequence, each element as the iterator yields it.+ if value.is_object()+ && let Some(method) = iterator_method(vm, value)?+ {+ let mut elements = Vec::new();+ let iterator = get_iterator_from_method_impl(vm, value, method)?;+ while let Some(element) = iterator_step_value(vm, &iterator)? {+ if element.is_undefined() {+ elements.push(undefined_element());+ } else {+ elements.push(value_converter(element)?);+ }+ }++ return Ok(MaybeList::List(elements));+ }++ Ok(MaybeList::Single(value_converter(value)?))+}++fn to_offset(vm: &Vm, value: Value) -> WebIdlResult<Option<f64>> {+ if value.is_nullish() {+ return Ok(None);+ }+ let double_value = value.to_double(vm)?;+ if double_value.is_nan() || double_value.is_infinite() {+ return Err(type_error(format!(+ "Invalid offset value: {}",+ display(&value.to_utf16_string(vm)?)+ )));+ }+ Ok(Some(double_value))+}++fn to_string(vm: &Vm, value: Value) -> WebIdlResult<Utf16String> {+ Ok(value.to_utf16_string(vm)?)+}++fn to_composite_operation(vm: &Vm, value: Value) -> WebIdlResult<CompositeOperationOrAuto> {+ if value.is_undefined() {+ return Ok(CompositeOperationOrAuto::Auto);+ }++ let string_value = value.to_utf16_string(vm)?;+ if utf16_string_equals(&string_value, "replace") {+ return Ok(CompositeOperationOrAuto::Replace);+ }+ if utf16_string_equals(&string_value, "add") {+ return Ok(CompositeOperationOrAuto::Add);+ }+ if utf16_string_equals(&string_value, "accumulate") {+ return Ok(CompositeOperationOrAuto::Accumulate);+ }+ if utf16_string_equals(&string_value, "auto") {+ return Ok(CompositeOperationOrAuto::Auto);+ }++ Err(Exception::type_error("Invalid composite value"))+}++fn is_a_custom_property_name_string(name: &[u16]) -> bool {+ // A custom property is any property whose name starts with two dashes (U+002D HYPHEN-MINUS), like --foo.+ // The <custom-property-name> production corresponds to this: it’s defined as any <dashed-ident> (a valid+ // identifier that starts with two dashes), except -- itself, which is reserved for future use by CSS.+ name.len() > 2 && name[0] == u16::from(b'-') && name[1] == u16::from(b'-')+}++fn units_equal(units: &[u16], text: &str) -> bool {+ units.iter().copied().eq(text.encode_utf16())+}++/// What steps 2 to 5 of the procedure to process a keyframe-like object make of the names of the properties of the+/// keyframe input: its animation properties, sorted.+fn animation_properties(vm: &Vm, keyframe_object: Gc<Object>) -> WebIdlResult<Vec<Utf16String>> {+ // 2. Build up a list of animatable properties as follows:+ //+ // 1. Let animatable properties be a list of property names (including shorthand properties that have longhand+ // sub-properties that are animatable) that can be animated by the implementation.+ // 2. Convert each property name in animatable properties to the equivalent IDL attribute by applying the+ // animation property name to IDL attribute name algorithm.++ // 3. Let input properties be the result of calling the EnumerableOwnNames operation with keyframe input as the+ // object.++ // 4. Make up a new list animation properties that consists of all of the properties that are in both input+ // properties and animatable properties, or which are in input properties and conform to the+ // <custom-property-name> production.+ let input_properties = keyframe_object.enumerable_own_property_names(vm, PropertyKind::Key)?;++ let mut animation_properties: Vec<Utf16String> = Vec::new();++ for index in 0..input_properties.len() {+ let input_property = input_properties.get(index).expect("the index is in the list");+ if !input_property.is_string() {+ continue;+ }++ let name = input_property.as_string().utf16_string();+ let units = name.to_utf16();++ // Handle the two special cases+ if units_equal(&units, "cssFloat") || units_equal(&units, "cssOffset") {+ animation_properties.push(name.clone());+ } else if units_equal(&units, "float") || units_equal(&units, "offset") {+ // Ignore these property names+ } else if is_a_custom_property_name_string(&units) {+ animation_properties.push(name.clone());+ } else if let Some(property) = property_id_from_camel_case(&name)+ && is_animatable_property(property)+ {+ animation_properties.push(name.clone());+ }+ }++ // 5. Sort animation properties in ascending order by the Unicode codepoints that define each property name.+ animation_properties.sort_by(|a, b| a.to_utf16().cmp(&b.to_utf16()));++ Ok(animation_properties)+}++/// The value of the member `name` of the keyframe input, or the string `default`, where there is one and the member is+/// undefined.+/// NB: The dictionary conversion gets each member and converts it before it gets the next, in the order composite,+/// easing, offset.+fn keyframe_member(vm: &Vm, keyframe_object: Gc<Object>, name: &str, default: Option<&[u8]>) -> WebIdlResult<Value> {+ let value = keyframe_object.get(vm, &PropertyKey::from_utf8(name))?;+ Ok(match default {+ Some(default) if value.is_undefined() => {+ Value::from_string(PrimitiveString::create(vm, Utf16String::from_ascii(default)))+ }+ _ => value,+ })+}++// https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object+// NB: With the allow lists flag set to true.+fn process_a_keyframe_like_object_allowing_lists(+ vm: &Vm,+ keyframe_input: Value,+) -> WebIdlResult<BasePropertyIndexedKeyframe> {+ // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript+ // value, and the dictionary type depending on the value of the allow lists flag as follows:+ //+ // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.+ // -> Otherwise, use the following dictionary type: <BaseKeyframe>.+ //+ // Store the result of this procedure as keyframe output.+ let mut keyframe_output = BasePropertyIndexedKeyframe::default();+ if keyframe_input.is_nullish() {+ return Ok(keyframe_output);+ }++ let keyframe_object = keyframe_input.as_object();++ // NB: An undefined element of a list converts to the default value of its type.+ let composite = keyframe_member(vm, keyframe_object, "composite", Some(b"auto"))?;+ keyframe_output.composite = convert_value_to_maybe_list(+ vm,+ composite,+ || CompositeOperationOrAuto::Replace,+ |value| to_composite_operation(vm, value),+ )?;+ let easing = keyframe_member(vm, keyframe_object, "easing", Some(b"linear"))?;+ keyframe_output.easing =+ convert_value_to_maybe_list(vm, easing, Utf16String::default, |value| to_string(vm, value))?;+ let offset = keyframe_member(vm, keyframe_object, "offset", None)?;+ keyframe_output.offset = convert_value_to_maybe_list(vm, offset, || None, |value| to_offset(vm, value))?;++ // 2. through 5.+ let animation_properties = animation_properties(vm, keyframe_object)?;++ // 6. For each property name in animation properties,+ for property_name in animation_properties {+ // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name+ // as the property key and keyframe input as the receiver.+ // 2. Check the completion record of raw value.+ let raw_value = keyframe_object.get(vm, &PropertyKey::from_utf16_string(&property_name))?;++ // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:++ // -> If allow lists is true,+ // Let property values be the result of converting raw value to IDL type (DOMString or sequence<DOMString>)+ // using the procedures defined for converting an ECMAScript value to an IDL value [WEBIDL].+ //+ // If property values is a single DOMString, replace property values with a sequence of DOMStrings with the+ // original value of property values as the only element.+ let property_values =+ convert_value_to_maybe_list(vm, raw_value, Utf16String::default, |value| to_string(vm, value))?.into_list();++ // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation+ // property name algorithm to property name.+ // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL+ // attribute name) in the steps above.++ // 5. Add a property to keyframe output with normalized property name as the property name, and property values+ // as the property value.+ keyframe_output.properties.push((property_name, property_values));+ }++ Ok(keyframe_output)+}++// https://www.w3.org/TR/web-animations-1/#process-a-keyframe-like-object+// NB: With the allow lists flag set to false.+fn process_a_keyframe_like_object(vm: &Vm, keyframe_input: Value) -> WebIdlResult<BaseKeyframe> {+ // 1. Run the procedure to convert an ECMAScript value to a dictionary type with keyframe input as the ECMAScript+ // value, and the dictionary type depending on the value of the allow lists flag as follows:+ //+ // -> If allow lists is true, use the following dictionary type: <BasePropertyIndexedKeyframe>.+ // -> Otherwise, use the following dictionary type: <BaseKeyframe>.+ //+ // Store the result of this procedure as keyframe output.+ let mut keyframe_output = BaseKeyframe::default();+ if keyframe_input.is_nullish() {+ return Ok(keyframe_output);+ }++ let keyframe_object = keyframe_input.as_object();+ let composite = keyframe_member(vm, keyframe_object, "composite", Some(b"auto"))?;+ keyframe_output.composite = to_composite_operation(vm, composite)?;+ let easing = keyframe_member(vm, keyframe_object, "easing", Some(b"linear"))?;+ keyframe_output.easing = to_string(vm, easing)?;+ let offset = keyframe_member(vm, keyframe_object, "offset", None)?;+ keyframe_output.offset = to_offset(vm, offset)?;++ // 2. through 5.+ let animation_properties = animation_properties(vm, keyframe_object)?;++ // 6. For each property name in animation properties,+ for property_name in animation_properties {+ // 1. Let raw value be the result of calling the [[Get]] internal method on keyframe input, with property name+ // as the property key and keyframe input as the receiver.+ // 2. Check the completion record of raw value.+ let raw_value = keyframe_object.get(vm, &PropertyKey::from_utf16_string(&property_name))?;++ // 3. Convert raw value to a DOMString or sequence of DOMStrings property values as follows:++ // -> Otherwise,+ // Let property values be the result of converting raw value to a DOMString using the procedure for+ // converting an ECMAScript value to a DOMString [WEBIDL].+ let property_values = raw_value.to_utf16_string(vm)?;++ // 4. Calculate the normalized property name as the result of applying the IDL attribute name to animation+ // property name algorithm to property name.+ // Note: We do not need to do this, since we did not need to do the reverse step (animation property name to IDL+ // attribute name) in the steps above.++ // 5. Add a property to keyframe output with normalized property name as the property name, and property values+ // as the property value.+ keyframe_output.properties.push((property_name, property_values));+ }++ Ok(keyframe_output)+}++// https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets+fn compute_missing_keyframe_offsets<K: KeyframeOffsets>(keyframes: &mut [K]) {+ // 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe+ // offset value.+ for keyframe in keyframes.iter_mut() {+ keyframe.set_computed_offset(keyframe.offset());+ }++ // 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in+ // keyframes is null, set the computed keyframe offset of the first keyframe to 0.+ if keyframes.len() > 1 && keyframes[0].computed_offset().is_none() {+ keyframes[0].set_computed_offset(Some(0.0));+ }++ // 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset+ // to 1.+ if let Some(last) = keyframes.last_mut()+ && last.computed_offset().is_none()+ {+ last.set_computed_offset(Some(1.0));+ }++ // 4. For each pair of keyframes A and B where:+ // - A appears before B in keyframes, and+ // - A and B have a computed keyframe offset that is not null, and+ // - all keyframes between A and B have a null computed keyframe offset,+ let find_next_index_of_keyframe_with_computed_offset = |keyframes: &[K], starting_index: usize| {+ (starting_index..keyframes.len()).find(|&index| keyframes[index].computed_offset().is_some())+ };++ let Some(mut index_a) = find_next_index_of_keyframe_with_computed_offset(keyframes, 0) else {+ return;+ };+ let mut maybe_index_b = find_next_index_of_keyframe_with_computed_offset(keyframes, index_a + 1);++ while let Some(index_b) = maybe_index_b {+ // calculate the computed keyframe offset of each keyframe between A and B as follows:+ for keyframe_index in index_a + 1..index_b {+ // 1. Let offsetk be the computed keyframe offset of a keyframe k.+ let offset_a = keyframes[index_a]+ .computed_offset()+ .expect("A has a computed keyframe offset");+ let offset_b = keyframes[index_b]+ .computed_offset()+ .expect("B has a computed keyframe offset");++ // 2. Let n be the number of keyframes between and including A and B minus 1.+ #[expect(clippy::cast_precision_loss)]+ let n = (index_b - index_a) as f64;++ // 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the+ // first keyframe after A has an index of 1.+ #[expect(clippy::cast_precision_loss)]+ let index = (keyframe_index - index_a) as f64;++ // 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.+ keyframes[keyframe_index].set_computed_offset(Some(offset_a + (offset_b - offset_a) * index / n));+ }++ index_a = index_b;+ maybe_index_b = find_next_index_of_keyframe_with_computed_offset(keyframes, index_b + 1);+ }+}++// https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset+fn is_loosely_sorted_by_offset(keyframes: &[BaseKeyframe]) -> bool {+ // The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe+ // in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the+ // previous keyframe in the list with a keyframe offset that is not null, if any.++ let mut last_offset: Option<f64> = None;+ for keyframe in keyframes {+ let Some(offset) = keyframe.offset else {+ continue;+ };++ if last_offset.is_some_and(|last_offset| offset < last_offset) {+ return false;+ }++ last_offset = Some(offset);+ }++ true+}++/// The property a property name of a keyframe names, or none for a name the keyframe ignores.+fn keyframe_property_of_name(name: &Utf16String) -> Option<(KeyframePropertyName, u16)> {+ let units = name.to_utf16();+ // Handle some special cases+ if units_equal(&units, "cssFloat") {+ return Some((KeyframePropertyName::Id(PROPERTY_ID_FLOAT), PROPERTY_ID_FLOAT));+ }+ if units_equal(&units, "cssOffset") {+ return Some((KeyframePropertyName::Id(PROPERTY_ID_OFFSET), PROPERTY_ID_OFFSET));+ }+ if units_equal(&units, "float") || units_equal(&units, "offset") {+ // Ignore these properties+ return None;+ }+ if is_a_custom_property_name_string(&units) {+ return Some((KeyframePropertyName::Custom(name.clone()), PROPERTY_ID_CUSTOM));+ }+ property_id_from_camel_case(name).map(|property_id| (KeyframePropertyName::Id(property_id), property_id))+}++fn invalid_easing(easing: &Utf16String) -> Exception {+ type_error(format!("Invalid animation easing value: \"{}\"", display(easing)))+}++// https://www.w3.org/TR/web-animations-1/#process-a-keyframes-argument+pub(crate) fn process_a_keyframes_argument(+ vm: &Vm,+ object: Option<Gc<Object>>,+) -> WebIdlResult<Vec<ProcessedKeyframe>> {+ // 1. If object is null, return an empty sequence of keyframes.+ let Some(object) = object else {+ return Ok(Vec::new());+ };+ let object_value = Value::from_object(object);++ // 2. Let processed keyframes be an empty sequence of keyframes.+ let mut processed_keyframes: Vec<BaseKeyframe> = Vec::new();+ let mut unused_easings: Vec<Utf16String> = Vec::new();++ // 3. Let method be the result of GetMethod(object, @@iterator).+ // 4. Check the completion record of method.+ let method = iterator_method(vm, object_value)?;++ // 5. Perform the steps corresponding to the first matching condition from below,++ // -> If method is not undefined,+ if let Some(method) = method {+ // 1. Let iter be GetIterator(object, method).+ // 2. Check the completion record of iter.+ let iter = get_iterator_from_method_impl(vm, object_value, method)?;++ // 3. Repeat:+ // 1. Let next be IteratorStep(iter).+ // 2. Check the completion record of next.+ // 3. If next is false abort this loop.+ // 4. Let nextItem be IteratorValue(next).+ // 5. Check the completion record of nextItem.+ // FIXME: The spec should be updated to use IteratorStepValue instead.+ while let Some(next_item) = iterator_step_value(vm, &iter)? {+ // 6. If Type(nextItem) is not Undefined, Null or Object, then throw a TypeError and abort these steps.+ if !next_item.is_nullish() && !next_item.is_object() {+ return throw(vm, ErrorType::NotAnObjectOrNull, next_item);+ }++ // 7. Append to processed keyframes the result of running the procedure to process a keyframe-like object+ // passing nextItem as the keyframe input and with the allow lists flag set to false.+ processed_keyframes.push(process_a_keyframe_like_object(vm, next_item)?);+ }+ }+ // -> Otherwise,+ else {+ // 1. Let property-indexed keyframe be the result of running the procedure to process a keyframe-like object+ // passing object as the keyframe input and with the allow lists flag set to true.+ let property_indexed_keyframe = process_a_keyframe_like_object_allowing_lists(vm, object_value)?;++ // 2. For each member, m, in property-indexed keyframe, perform the following steps:+ for (property_name, property_values) in &property_indexed_keyframe.properties {+ // 1. Let property name be the key for m.++ // 2. If property name is "composite", or "easing", or "offset", skip the remaining steps in this loop and+ // continue from the next member in property-indexed keyframe after m.+ // Note: This will never happen, since these fields have dedicated members on BasePropertyIndexedKeyframe++ // 3. Let property values be the value for m.++ // 4. Let property keyframes be an empty sequence of keyframes.+ let mut property_keyframes: Vec<BaseKeyframe> = Vec::new();++ // 5. For each value, v, in property values perform the following steps:+ for value in property_values {+ // 1. Let k be a new keyframe with a null keyframe offset.+ let mut keyframe = BaseKeyframe::default();++ // 2. Add the property-value pair, property name → v, to k.+ keyframe.properties.push((property_name.clone(), value.clone()));++ // 3. Append k to property keyframes.+ property_keyframes.push(keyframe);+ }++ // 6. Apply the procedure to compute missing keyframe offsets to property keyframes.+ compute_missing_keyframe_offsets(&mut property_keyframes);++ // 7. Add keyframes in property keyframes to processed keyframes.+ processed_keyframes.extend(property_keyframes);+ }++ // 3. Sort processed keyframes by the computed keyframe offset of each keyframe in increasing order.+ processed_keyframes.sort_by(|a, b| {+ let a = a+ .computed_offset+ .expect("a property keyframe has a computed keyframe offset");+ let b = b+ .computed_offset+ .expect("a property keyframe has a computed keyframe offset");+ a.partial_cmp(&b).unwrap_or(core::cmp::Ordering::Equal)+ });++ // 4. Merge adjacent keyframes in processed keyframes when they have equal computed keyframe offsets.+ // Note: The spec doesn't specify how to merge them, but WebKit seems to just override the properties of the+ // earlier keyframe with the properties of the later keyframe.+ let mut i = 0;+ while i + 1 < processed_keyframes.len() {+ if processed_keyframes[i].computed_offset == processed_keyframes[i + 1].computed_offset {+ let keyframe_b = processed_keyframes.remove(i + 1);+ let keyframe_a = &mut processed_keyframes[i];+ keyframe_a.easing = keyframe_b.easing;+ keyframe_a.composite = keyframe_b.composite;+ for (name, value) in keyframe_b.properties {+ match keyframe_a+ .properties+ .iter_mut()+ .find(|(existing, _)| existing.to_utf16() == name.to_utf16())+ {+ Some((_, existing_value)) => *existing_value = value,+ None => keyframe_a.properties.push((name, value)),+ }+ }+ } else {+ i += 1;+ }+ }++ // 5. Let offsets be a sequence of nullable double values assigned based on the type of the "offset" member+ // of the property-indexed keyframe as follows:+ //+ // -> sequence<double?>,+ // The value of "offset" as-is.+ // -> double?,+ // A sequence of length one with the value of "offset" as its single item, i.e. « offset »,+ let offsets = property_indexed_keyframe.offset.into_list();++ // 6. Assign each value in offsets to the keyframe offset of the keyframe with corresponding position in+ // processed keyframes until the end of either sequence is reached.+ for (keyframe, offset) in processed_keyframes.iter_mut().zip(offsets) {+ keyframe.offset = offset;+ }++ // 7. Let easings be a sequence of DOMString values assigned based on the type of the "easing" member of the+ // property-indexed keyframe as follows:+ //+ // -> sequence<DOMString>,+ // The value of "easing" as-is.+ // -> DOMString,+ // A sequence of length one with the value of "easing" as its single item, i.e. « easing »,+ let mut easings = property_indexed_keyframe.easing.into_list();++ // 8. If easings is an empty sequence, let it be a sequence of length one containing the single value "linear",+ // i.e. « "linear" ».+ if easings.is_empty() {+ easings.push(Utf16String::from_ascii(b"linear"));+ }++ // 9. If easings has fewer items than processed keyframes, repeat the elements in easings successively starting+ // from the beginning of the list until easings has as many items as processed keyframes.+ //+ // For example, if processed keyframes has five items, and easings is the sequence « "ease-in", "ease-out" »,+ // easings would be repeated to become « "ease-in", "ease-out", "ease-in", "ease-out", "ease-in" ».+ let num_easings = easings.len();+ let mut index = 0;+ while easings.len() < processed_keyframes.len() {+ easings.push(easings[index % num_easings].clone());+ index += 1;+ }++ // 10. If easings has more items than processed keyframes, store the excess items as unused easings.+ while easings.len() > processed_keyframes.len() {+ unused_easings.push(easings.pop().expect("easings has more items than processed keyframes"));+ }++ // 11. Assign each value in easings to a property named "easing" on the keyframe with the corresponding position+ // in processed keyframes until the end of processed keyframes is reached.+ for (keyframe, easing) in processed_keyframes.iter_mut().zip(easings) {+ keyframe.easing = easing;+ }++ // 12. If the "composite" member of the property-indexed keyframe is not an empty sequence:+ let composite_value = property_indexed_keyframe.composite;+ if !matches!(&composite_value, MaybeList::List(values) if values.is_empty()) {+ // 1. Let composite modes be a sequence of CompositeOperationOrAuto values assigned from the "composite"+ // member of property-indexed keyframe. If that member is a single CompositeOperationOrAuto value+ // operation, let composite modes be a sequence of length one, with the value of the "composite" as its+ // single item.+ let mut composite_modes = composite_value.into_list();++ // 2. As with easings, if composite modes has fewer items than processed keyframes, repeat the elements in+ // composite modes successively starting from the beginning of the list until composite modes has as+ // many items as processed keyframes.+ let num_composite_modes = composite_modes.len();+ index = 0;+ while composite_modes.len() < processed_keyframes.len() {+ composite_modes.push(composite_modes[index % num_composite_modes]);+ index += 1;+ }++ // 3. Assign each value in composite modes that is not auto to the keyframe-specific composite operation on+ // the keyframe with the corresponding position in processed keyframes until the end of processed+ // keyframes is reached.+ for (keyframe, composite_mode) in processed_keyframes.iter_mut().zip(composite_modes) {+ if composite_mode != CompositeOperationOrAuto::Auto {+ keyframe.composite = composite_mode;+ }+ }+ }+ }++ // 6. If processed keyframes is not loosely sorted by offset, throw a TypeError and abort these steps.+ if !is_loosely_sorted_by_offset(&processed_keyframes) {+ return Err(Exception::type_error(+ "Keyframes are not in ascending order based on offset",+ ));+ }++ // 7. If there exist any keyframe in processed keyframes whose keyframe offset is non-null and less than zero or+ // greater than one, throw a TypeError and abort these steps.+ for (i, keyframe) in processed_keyframes.iter().enumerate() {+ let Some(offset) = keyframe.offset else {+ continue;+ };++ if !(0.0..=1.0).contains(&offset) {+ return Err(type_error(format!("Keyframe {i} has invalid offset value {offset}")));+ }+ }++ // 8. For each frame in processed keyframes, perform the following steps:+ let mut keyframes = Vec::with_capacity(processed_keyframes.len());+ for keyframe in processed_keyframes {+ // 1. For each property-value pair in frame, parse the property value using the syntax specified for that+ // property.+ //+ // If the property value is invalid according to the syntax for the property, discard the property-value pair.+ // User agents that provide support for diagnosing errors in content SHOULD produce an appropriate warning+ // highlight+ let mut parsed_properties: Vec<(KeyframePropertyName, StyleValue)> = Vec::new();+ for (property_string, value_string) in &keyframe.properties {+ let Some((property, property_id)) = keyframe_property_of_name(property_string) else {+ continue;+ };++ if let Some(style_value) = parse_property_value(property_id, value_string) {+ parsed_properties.push((property, style_value));+ }+ }++ // 2. Let the timing function of frame be the result of parsing the "easing" property on frame using the CSS+ // syntax defined for the easing member of the EffectTiming dictionary.+ //+ // If parsing the "easing" property fails, throw a TypeError and abort this procedure.+ let easing = parse_easing_function(&keyframe.easing).ok_or_else(|| invalid_easing(&keyframe.easing))?;++ keyframes.push(ProcessedKeyframe {+ offset: keyframe.offset,+ computed_offset: keyframe.computed_offset,+ easing,+ composite: keyframe.composite,+ properties: parsed_properties,+ });+ }++ // 9. Parse each of the values in unused easings using the CSS syntax defined for easing member of the EffectTiming+ // interface, and if any of the values fail to parse, throw a TypeError and abort this procedure.+ for unused_easing in &unused_easings {+ if parse_easing_function(unused_easing).is_none() {+ return Err(invalid_easing(unused_easing));+ }+ }++ Ok(keyframes)+}++/// The keyframes of the effect as they are reflected to script, read before any script runs.+struct ReflectedKeyframe {+ offset: Option<f64>,+ computed_offset: f64,+ easing: Utf16String,+ composite: &'static str,+ properties: Vec<(Utf16String, Utf16String)>,+}++/// The result of pseudo-element parsing on the value.+// https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudoelement+pub(super) fn pseudo_element_parsing(value: Option<&Utf16String>) -> WebIdlResult<Option<ParsedPseudoElement>> {+ let Some(value) = value else {+ return Ok(None);+ };+ match parse_pseudo_element_selector(value) {+ Some(pseudo_element) => Ok(Some(pseudo_element)),+ None => Err(Exception::syntax_error(Utf16String::from_utf8(&format!(+ "Invalid pseudo-element selector: \"{}\"",+ display(value)+ )))),+ }+}++/// The keyframes argument of the KeyframeEffect(target, keyframes, options) constructor, or the keyframes+/// Animatable.animate() processed from it before it constructs its effect.+pub(crate) enum KeyframesArgument {+ Unprocessed(Option<Gc<Object>>),+ Processed(Vec<ProcessedKeyframe>),+}++// https://www.w3.org/TR/web-animations-1/#the-keyframeeffect-interface+pub(crate) struct KeyframeEffect {+ effect: AnimationEffect,+ // https://www.w3.org/TR/web-animations-1/#keyframe+ keyframes: RefCell<Vec<ProcessedKeyframe>>,+}++// SAFETY: The keyframes reach no cell; the effect visits what it reaches.+unsafe impl Trace for KeyframeEffect {+ fn trace(&self, visitor: &mut Visitor) {+ self.effect.trace(visitor);+ }+}++impl Inherits<AnimationEffect> for KeyframeEffect {+ fn parent(&self) -> &AnimationEffect {+ &self.effect+ }+}++impl Wrappable for KeyframeEffect {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ self.effect.relevant_realm()+ }++ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ // NB: The record can outlive the effect until what holds the record is swept.+ object.effect.record().set_facade(None);+ }+}++impl KeyframeEffect {+ /// A new effect with the default timing, no keyframes and no target.+ pub(crate) fn create(vm: &Vm) -> Ref<Self> {+ let object = Self::create_for_record(vm, EffectRecordRef::new());+ object.effect.record().set_facade(NonNull::new(cell_into_abi(object)));+ object+ }++ /// The object of the effect whose state `record` holds, which notes no keyframes of its own.+ pub(crate) fn create_for_record(vm: &Vm, record: EffectRecordRef) -> Ref<Self> {+ allocate(vm, |_| Self {+ effect: AnimationEffect::from_record(record),+ keyframes: RefCell::new(Vec::new()),+ })+ }++ pub(crate) fn effect(&self) -> &AnimationEffect {+ &self.effect+ }++ fn record_ptr(&self) -> *const c_void {+ self.effect.record().as_host_ptr()+ }++ fn invalidate(&self) {+ // SAFETY: The effect holds a reference to the record.+ unsafe { web_animation_effect_invalidate(self.record_ptr()) };+ }++ /// Sets the target element of the effect to the host's `DOM::Element`, or to none, invalidating what that changes+ /// where `update`.+ pub(crate) fn set_target_element(&self, element: *mut c_void, update: bool) {+ // SAFETY: The effect holds a reference to the record, and the element is null or a live element.+ unsafe { web_animation_effect_set_target(self.record_ptr(), element, update) };+ }++ fn set_target_pseudo_element(&self, pseudo_element: Option<&ParsedPseudoElement>) {+ self.effect.record().set_pseudo_element(pseudo_element);+ self.invalidate();+ // FIXME: We don't remove the animated style from the old target element as part of normal animated style update and+ // it will remain "stuck" until it's style is fully invalidated for some other reason.+ }++ fn set_composite_operation(&self, composite: CompositeOperation) {+ // SAFETY: The effect holds a reference to the record.+ unsafe { web_animation_effect_set_composite(self.record_ptr(), composite) };+ }++ /// Sets the keyframes of the effect to the processed keyframes, whose missing offsets this computes.+ pub(crate) fn set_processed_keyframes(&self, keyframes: Vec<ProcessedKeyframe>) {+ self.set_processed_keyframes_copied_from(keyframes, None);+ }++ /// Sets the keyframes of the effect to the processed keyframes, whose missing offsets this computes, which resolve+ /// what they reference against the style sheet of those of `source` where they are a copy of its keyframes.+ fn set_processed_keyframes_copied_from(+ &self,+ mut keyframes: Vec<ProcessedKeyframe>,+ source: Option<&EffectRecordRef>,+ ) {+ // FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed+ // keyframes using the procedure outlined in the second half of+ // https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the+ // missing keyframe offsets+ compute_missing_keyframe_offsets(&mut keyframes);++ let inputs = keyframes+ .iter()+ .map(|keyframe| KeyframeSetInput {+ computed_offset: keyframe+ .computed_offset+ .expect("a keyframe has a computed keyframe offset"),+ composite: keyframe.composite,+ easing: &keyframe.easing,+ properties: &keyframe.properties,+ })+ .collect::<Vec<_>>();+ let keyframe_set = match source {+ Some(source) => KeyframeSetRef::from_keyframes_of_copy(&inputs, source),+ None => KeyframeSetRef::from_keyframes(&inputs),+ };+ drop(inputs);+ // NB: Keyframes script sets replace those of CSS for good.+ self.effect.record().note_keyframes_set_by_script();+ *self.keyframes.borrow_mut() = keyframes;+ // SAFETY: The effect holds a reference to the record, and hands over the reference to the keyframe set.+ unsafe { web_animation_effect_set_keyframe_set(self.record_ptr(), keyframe_set.into_host_ptr()) };+ }++ /// The bytes the effect holds, as Animation's memory report counts them.+ pub(crate) fn memory_size(&self) -> usize {+ size_of::<Self>() + self.keyframes.borrow().capacity() * size_of::<ProcessedKeyframe>()+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect+ pub(crate) fn construct(+ cx: &mut CallContext,+ target: Option<CppInterface>,+ keyframes: Option<Gc<Object>>,+ options: UnrestrictedDoubleOrKeyframeEffectOptions,+ ) -> WebIdlResult<Ref<Self>> {+ let target = target.map_or(null_mut(), |target| {+ // SAFETY: The wrapper is that of a live Element.+ unsafe { web_animation_element_of_wrapper(target.wrapper().as_ptr().cast()) }+ });+ Self::construct_for_target(cx, target, KeyframesArgument::Unprocessed(keyframes), options)+ }++ /// The procedure of the KeyframeEffect(target, keyframes, options) constructor, of the host's `DOM::Element`+ /// `target`, or of none where it is null.+ pub(crate) fn construct_for_target(+ cx: &mut CallContext,+ target: *mut c_void,+ keyframes: KeyframesArgument,+ options: UnrestrictedDoubleOrKeyframeEffectOptions,+ ) -> WebIdlResult<Ref<Self>> {+ let vm = cx.vm();++ // 1. Create a new KeyframeEffect object, effect.+ let effect = Self::create(vm);++ // 2. Set the target element of effect to target.+ effect.set_target_element(target, true);++ // 3. Set the target pseudo-selector to the result corresponding to the first matching condition from below.++ // If options is a KeyframeEffectOptions object with a pseudoElement property,+ if let UnrestrictedDoubleOrKeyframeEffectOptions::KeyframeEffectOptions(options) = &options {+ // Set the target pseudo-selector to the value of the pseudoElement property.+ //+ // When assigning this property, the error-handling defined for the pseudoElement setter on the interface+ // is applied. If the setter requires an exception to be thrown, this procedure must throw the same+ // exception and abort all further steps.+ effect.set_pseudo_element(cx, options.pseudo_element.clone())?;+ }+ // Otherwise,+ // Set the target pseudo-selector to null.+ // Note: This is the default when constructed++ // 4. Let timing input be the result corresponding to the first matching condition from below.+ let (timing_input, composite) = match options {+ // If options is a KeyframeEffectOptions object,+ // Let timing input be options.+ UnrestrictedDoubleOrKeyframeEffectOptions::KeyframeEffectOptions(options) => {+ (options.parent, Some(options.composite))+ }+ // Otherwise (if options is a double),+ // Let timing input be a new EffectTiming object with all members set to their default values and+ // duration set to options.+ UnrestrictedDoubleOrKeyframeEffectOptions::UnrestrictedDouble(duration) => (+ EffectTiming {+ delay: 0.0,+ direction: super::animation_effect::PlaybackDirection::Normal,+ duration: UnrestrictedDoubleOrCSSNumericValueOrDOMString::UnrestrictedDouble(duration),+ easing: Utf16String::from_ascii(b"linear"),+ end_delay: 0.0,+ fill: super::animation_effect::FillMode::Auto,+ iteration_start: 0.0,+ iterations: 1.0,+ },+ None,+ ),+ };++ // https://drafts.csswg.org/web-animations-2/#the-effecttiming-dictionaries+ // Note: In this version of the spec, duration is not settable as a CSSNumericValue; however, duration may be+ // returned as a CSSNumericValue when resolving the duration in getComputedTiming(). Future versions of+ // the spec may enable setting the duration as a CSSNumeric value, where the unit is a valid time unit or+ // percent.+ if matches!(+ timing_input.duration,+ UnrestrictedDoubleOrCSSNumericValueOrDOMString::CSSNumericValue(_)+ ) {+ return Err(Exception::type_error(+ "Setting duration as a CSSNumericValue is not supported",+ ));+ }++ // 5. Call the procedure to update the timing properties of an animation effect of effect from timing input.+ // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.+ effect+ .effect+ .update_the_timing_properties(to_optional_effect_timing(timing_input))?;++ // 6. If options is a KeyframeEffectOptions object, assign the composite property of effect to the corresponding+ // value from options.+ //+ // When assigning this property, the error-handling defined for the corresponding setter on the KeyframeEffect+ // interface is applied. If the setter requires an exception to be thrown for the value specified by options,+ // this procedure must throw the same exception and abort all further steps.+ if let Some(composite) = composite {+ effect.set_composite_operation(composite);+ }++ // 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes() passing keyframes as+ // the input.+ match keyframes {+ KeyframesArgument::Unprocessed(keyframes) => effect.set_keyframes(cx, keyframes)?,+ KeyframesArgument::Processed(keyframes) => effect.set_processed_keyframes(keyframes),+ }++ Ok(effect)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect-source+ pub(crate) fn construct_from_source(cx: &mut CallContext, source: Ref<Self>) -> WebIdlResult<Ref<Self>> {+ // 1. Create a new KeyframeEffect object, effect.+ let effect = Self::create(cx.vm());++ // 2. Set the following properties of effect using the corresponding values of source:++ // - effect target,+ let target = source+ .effect+ .record()+ .target_element()+ .map_or(null_mut(), NonNull::as_ptr);+ effect.set_target_element(target, false);+ effect.effect.record().copy_pseudo_element_from(source.effect.record());++ // - keyframes,+ // NB: The keyframes are those the effect runs as well, which for keyframes of CSS are those its style sheet+ // declares.+ if source.effect.record().keyframes_from_css() {+ let keyframes = source+ .effect+ .record()+ .css_keyframes_of_copy()+ .into_iter()+ .map(ProcessedKeyframe::from)+ .collect();+ effect.set_processed_keyframes_copied_from(keyframes, Some(source.effect.record()));+ } else {+ effect.set_processed_keyframes(source.keyframes.borrow().clone());+ }++ // - composite operation, and+ effect.set_composite_operation(source.effect.record().composite());++ // - all specified timing properties:++ // AD-HOC: This is defined in the web-animations level 1 spec so doesn't explicitly mention the level 2 properties+ // (specified start delay, specified end delay, specified iteration duration) but it is required that we+ // copy these and then normalize them as opposed to copying the already normalized values which may be+ // invalid in this context i.e. if the existing effect was associated with a progress-based timeline++ // - specified start delay,+ // - specified end delay,+ // - fill mode,+ // - iteration start,+ // - iteration count,+ // - specified iteration duration,+ // - playback direction, and+ // - timing function.+ effect+ .effect+ .record()+ .copy_specified_timing_and_timing_function_from(source.effect.record());++ effect.effect.record().normalize_specified_timing();++ Ok(effect)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-target+ pub(crate) fn target(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ let Some(element) = self.effect.record().target_element() else {+ return Ok(None);+ };+ // SAFETY: The realm is live, and the element is the live target of the effect.+ let wrapper = unsafe { web_animation_wrap_element(cx.realm().as_ptr().cast(), element.as_ptr()) };+ let wrapper = NonNull::new(wrapper.cast::<Object>()).expect("LibWeb returns the wrapper of the element");+ // SAFETY: LibWeb returns a live wrapper of an Element.+ Ok(Some(unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) }))+ }++ pub(crate) fn set_target(&self, _cx: &mut CallContext, value: Option<CppInterface>) -> WebIdlResult<()> {+ let element = value.map_or(null_mut(), |target| {+ // SAFETY: The wrapper is that of a live Element.+ unsafe { web_animation_element_of_wrapper(target.wrapper().as_ptr().cast()) }+ });+ self.set_target_element(element, true);+ Ok(())+ }++ // https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudoelement+ pub(crate) fn pseudo_element(&self, _cx: &mut CallContext) -> WebIdlResult<Option<Utf16String>> {+ Ok(self.effect.record().pseudo_element_serialization())+ }++ pub(crate) fn set_pseudo_element(&self, _cx: &mut CallContext, value: Option<Utf16String>) -> WebIdlResult<()> {+ // On setting, sets the target pseudo-selector of the animation effect to the result of+ // pseudo-element parsing on the provided value, defined as the following:+ // NOTE: The actual definition is in pseudo_element_parsing().+ let pseudo_element = pseudo_element_parsing(value.as_ref())?;+ self.set_target_pseudo_element(pseudo_element.as_ref());+ Ok(())+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-composite+ pub(crate) fn composite(&self, _cx: &mut CallContext) -> WebIdlResult<CompositeOperation> {+ self.effect.update_style_if_needed();+ Ok(self.effect.record().composite())+ }++ pub(crate) fn set_composite(&self, _cx: &mut CallContext, value: CompositeOperation) -> WebIdlResult<()> {+ self.set_composite_operation(value);+ Ok(())+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-getkeyframes+ pub(crate) fn get_keyframes<'vm>(&self, cx: &mut CallContext<'vm>) -> WebIdlResult<MarkedVec<'vm, Gc<Object>>> {+ let vm = cx.vm();+ let realm = cx.realm();++ self.effect.update_style_if_needed();++ // NB: The keyframes of a CSS animation or transition are those its style sheet or style change declares, as+ // they compute over the style of the target.+ let css_keyframes: Vec<ProcessedKeyframe> = if self.effect.record().keyframes_from_css() {+ self.effect+ .record()+ .computed_css_keyframes()+ .into_iter()+ .map(ProcessedKeyframe::from)+ .collect()+ } else {+ Vec::new()+ };++ // NB: The keyframes are read before any script runs, as setting a property of a new object can call a setter+ // on its prototype that changes them.+ let script_keyframes = self.keyframes.borrow();+ let keyframes_to_reflect: &[ProcessedKeyframe] = if self.effect.record().keyframes_from_css() {+ &css_keyframes+ } else {+ &script_keyframes+ };+ let reflected_keyframes: Vec<ReflectedKeyframe> = keyframes_to_reflect+ .iter()+ .map(|keyframe| ReflectedKeyframe {+ offset: keyframe.offset,+ computed_offset: keyframe+ .computed_offset+ .expect("a keyframe has a computed keyframe offset"),+ easing: keyframe.easing.serialization().clone(),+ composite: match keyframe.composite {+ CompositeOperationOrAuto::Replace => "replace",+ CompositeOperationOrAuto::Add => "add",+ CompositeOperationOrAuto::Accumulate => "accumulate",+ CompositeOperationOrAuto::Auto => "auto",+ },+ properties: keyframe+ .properties+ .iter()+ .map(|(property, value)| {+ // https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name+ // 1. If property follows the <custom-property-name> production, return property.+ // 2. If property refers to the CSS float property, return the string "cssFloat".+ // 3. If property refers to the CSS offset property, return the string "cssOffset".+ // 4. Otherwise, return the result of applying the CSS property to IDL attribute algorithm+ // [CSSOM] to property.+ let key = match property {+ KeyframePropertyName::Custom(name) => name.clone(),+ KeyframePropertyName::Id(PROPERTY_ID_FLOAT) => Utf16String::from_ascii(b"cssFloat"),+ KeyframePropertyName::Id(PROPERTY_ID_OFFSET) => Utf16String::from_ascii(b"cssOffset"),+ KeyframePropertyName::Id(property_id) => {+ Utf16String::from_utf8(camel_case_property_name(*property_id))+ }+ };+ (key, serialize_property_value(value))+ })+ .collect(),+ })+ .collect();+ drop(script_keyframes);++ // The getKeyframes() algorithm returns a fresh sequence of fresh objects on every invocation.+ let keyframes = MarkedVec::new(vm);+ let string = |string: Utf16String| Value::from_string(PrimitiveString::create(vm, string));+ for keyframe in reflected_keyframes {+ let object = Object::create(vm, realm, Some(realm.intrinsics().object_prototype(vm)));+ keyframes.push(object);+ // NB: The members of the keyframe and its animation properties are its own data properties, whatever the+ // prototype of the object defines.+ let set = |key: &PropertyKey, value: Value| object.create_data_property_or_throw(vm, key, value);+ set(+ &PropertyKey::from_utf8("offset"),+ keyframe.offset.map_or(Value::NULL, Value::from_f64),+ )?;+ set(+ &PropertyKey::from_utf8("computedOffset"),+ Value::from_f64(keyframe.computed_offset),+ )?;+ set(&PropertyKey::from_utf8("easing"), string(keyframe.easing))?;+ set(+ &PropertyKey::from_utf8("composite"),+ string(Utf16String::from_ascii(keyframe.composite.as_bytes())),+ )?;+ for (key, value) in keyframe.properties {+ set(&PropertyKey::from_utf16_string(&key), string(value))?;+ }+ }+ Ok(keyframes)+ }++ // https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes+ pub(crate) fn set_keyframes(&self, cx: &mut CallContext, keyframes: Option<Gc<Object>>) -> WebIdlResult<()> {+ let keyframes = process_a_keyframes_argument(cx.vm(), keyframes)?;+ self.set_processed_keyframes(keyframes);+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rsnew file mode 100644index 00000000000..42688650b36--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/mod.rs@@ -0,0 +1,19 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Web Animations, https://drafts.csswg.org/web-animations-1/++pub(crate) mod animatable;+pub(crate) mod animation;+pub(crate) mod animation_effect;+pub(crate) mod animation_playback_event;+pub(crate) mod animation_timeline;+pub(crate) mod document_or_shadow_root;+pub(crate) mod document_timeline;+pub(crate) mod exports;+pub(crate) mod keyframe_effect;+pub(crate) mod scroll_timeline;+pub(crate) mod view_timeline;diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rsnew file mode 100644index 00000000000..6af954f9210--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/scroll_timeline.rs@@ -0,0 +1,138 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ScrollTimeline, https://drafts.csswg.org/scroll-animations-1/#scrolltimeline++use core::ffi::c_void;+use core::ptr::NonNull;++use libjs_rust::api::{Trace, Visitor, Vm};+use libweb_rust::web_animations::{TimelineDescription, TimelineRecordRef};++use super::animation_timeline::{+ AnimationTimeline, did_create_timeline, element_of_wrapper, element_wrapper, finalize_timeline,+};+use super::document_timeline::document_of_realm;+use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ fn web_scroll_timeline_source(timeline: *mut c_void) -> *mut c_void;+ fn web_animation_document_scrolling_element(document: *mut c_void) -> *mut c_void;+}++// https://drafts.csswg.org/scroll-animations-1/#enumdef-scrollaxis+// NB: The numeric values are those of the host's ScrollAxis.+#[derive(Clone, Copy, PartialEq, Eq)]+#[repr(u8)]+pub(crate) enum ScrollAxis {+ Block,+ Inline,+ X,+ Y,+}++impl ScrollAxis {+ fn from_host(axis: u8) -> Self {+ match axis {+ 0 => Self::Block,+ 1 => Self::Inline,+ 2 => Self::X,+ 3 => Self::Y,+ _ => unreachable!("a scroll axis is one of four"),+ }+ }+}++/// The dictionary ScrollTimelineOptions of Animations/ScrollTimeline.idl.+pub(crate) struct ScrollTimelineOptions {+ pub(crate) source: Option<Option<CppInterface>>,+ pub(crate) axis: ScrollAxis,+}++// https://drafts.csswg.org/scroll-animations-1/#scrolltimeline+pub(crate) struct ScrollTimeline {+ timeline: AnimationTimeline,+}++// SAFETY: The timeline visits what it reaches.+unsafe impl Trace for ScrollTimeline {+ fn trace(&self, visitor: &mut Visitor) {+ self.timeline.trace(visitor);+ }+}++impl Inherits<AnimationTimeline> for ScrollTimeline {+ fn parent(&self) -> &AnimationTimeline {+ &self.timeline+ }+}++impl Wrappable for ScrollTimeline {+ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ finalize_timeline(&object.timeline);+ }+}++impl ScrollTimeline {+ pub(crate) fn from_timeline(timeline: AnimationTimeline) -> Self {+ Self { timeline }+ }++ pub(crate) fn timeline(&self) -> &AnimationTimeline {+ &self.timeline+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-scrolltimeline+ pub(crate) fn construct(cx: &mut CallContext, options: ScrollTimelineOptions) -> WebIdlResult<Ref<Self>> {+ let document = document_of_realm(cx.realm());++ // 1. Let timeline be the new ScrollTimeline object.+ // 2. Set the source of timeline to:+ let source = match options.source {+ // If the source member of options is present,+ // The source member of options.+ Some(source) => source.map(element_of_wrapper),+ // Otherwise,+ // The scrollingElement of the Document associated with the Window that is the current global object.+ // SAFETY: The document is live.+ None => NonNull::new(unsafe { web_animation_document_scrolling_element(document.as_ptr()) }),+ };++ // 3. Set the axis property of timeline to the corresponding value from options.+ let record = TimelineRecordRef::new(+ document,+ TimelineDescription::Scroll {+ source,+ axis: options.axis as u8,+ },+ );+ Ok(Self::create(cx.vm(), record))+ }++ fn create(vm: &Vm, record: TimelineRecordRef) -> Ref<Self> {+ let object = allocate(vm, |_| Self::from_timeline(AnimationTimeline::new(record)));+ did_create_timeline(cell_into_abi(object));+ object+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source+ pub(crate) fn source(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {+ // NB: The host finds the scroll container element an anonymous source names from its target, and the source of a+ // view timeline from its subject.+ // SAFETY: The cell is that of this live timeline.+ let source = NonNull::new(unsafe { web_scroll_timeline_source(self.timeline.cell()) });+ Ok(source.map(|source| element_wrapper(cx, source)))+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-axis+ pub(crate) fn axis(&self, _: &mut CallContext) -> WebIdlResult<ScrollAxis> {+ Ok(ScrollAxis::from_host(self.timeline.record().axis()))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rsnew file mode 100644index 00000000000..ac97df5f892--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/animations/view_timeline.rs@@ -0,0 +1,238 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! ViewTimeline, https://drafts.csswg.org/scroll-animations-1/#viewtimeline++use core::ffi::c_void;++use ak::Utf16String;+use libjs_rust::api::{MarkedVec, Trace, Visitor};+use libweb_rust::web_animations::{+ PROPERTY_ID_VIEW_TIMELINE_INSET, StyleValue, TimelineDescription, TimelineRecordRef, ViewTimelineInsetEdgeValue,+ ViewTimelineInsetValue, parse_property_value, style_value_as_host_ptr, style_value_from_host,+ view_timeline_inset_has_relative_length,+};++use super::animation_timeline::{+ AnimationTimeline, did_create_timeline, element_of_wrapper, element_wrapper, finalize_timeline,+};+use super::document_timeline::document_of_realm;+use super::scroll_timeline::{ScrollAxis, ScrollTimeline};+use crate::bindings::conversions::CppInterface;+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate, cell_into_abi};+use crate::bindings::{CallContext, Exception, WebIdlResult};+use crate::css::css_keyword_value::CSSKeywordValue;+use crate::css::css_numeric_value::AnyCSSNumericValue;+use crate::css::css_unit_value::CSSUnitValue;++unsafe extern "C" {+ fn web_animation_absolutize_style_value(document: *mut c_void, value: *const c_void) -> *const c_void;+}++/// The union (CSSNumericValue or CSSKeywordValue or DOMString) of the members of a sequence inset.+#[derive(Clone)]+pub(crate) enum CSSNumericValueOrCSSKeywordValueOrDOMString {+ CSSNumericValue(AnyCSSNumericValue),+ CSSKeywordValue(Ref<CSSKeywordValue>),+ DOMString(Utf16String),+}++// SAFETY: Visits the cells of the variant.+unsafe impl Trace for CSSNumericValueOrCSSKeywordValueOrDOMString {+ fn trace(&self, visitor: &mut Visitor) {+ match self {+ Self::CSSNumericValue(value) => value.trace(visitor),+ Self::CSSKeywordValue(value) => visitor.visit(*value),+ Self::DOMString(_) => {}+ }+ }+}++/// The union (DOMString or sequence<(CSSNumericValue or CSSKeywordValue or DOMString)>) of ViewTimelineOptions.inset.+pub(crate) enum DOMStringOrCSSNumericValueOrCSSKeywordValueOrDOMStringSequence<'vm> {+ DOMString(Utf16String),+ Sequence(MarkedVec<'vm, CSSNumericValueOrCSSKeywordValueOrDOMString>),+}++/// The dictionary ViewTimelineOptions of Animations/ViewTimeline.idl.+pub(crate) struct ViewTimelineOptions<'vm> {+ pub(crate) subject: CppInterface,+ pub(crate) axis: ScrollAxis,+ pub(crate) inset: DOMStringOrCSSNumericValueOrCSSKeywordValueOrDOMStringSequence<'vm>,+}++// https://drafts.csswg.org/scroll-animations-1/#viewtimeline+pub(crate) struct ViewTimeline {+ scroll_timeline: ScrollTimeline,+}++// SAFETY: The timeline visits what it reaches.+unsafe impl Trace for ViewTimeline {+ fn trace(&self, visitor: &mut Visitor) {+ self.scroll_timeline.trace(visitor);+ }+}++impl Inherits<ScrollTimeline> for ViewTimeline {+ fn parent(&self) -> &ScrollTimeline {+ &self.scroll_timeline+ }+}++impl Wrappable for ViewTimeline {+ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ finalize_timeline(object.scroll_timeline.timeline());+ }+}++fn invalid_inset() -> Exception {+ Exception::type_error("Invalid view timeline inset")+}++/// The inset the text parses as for the document, as a <'view-timeline-inset'> value.+fn parse_inset(document: *mut c_void, text: &Utf16String) -> WebIdlResult<ViewTimelineInsetValue> {+ let value = parse_property_value(PROPERTY_ID_VIEW_TIMELINE_INSET, text).ok_or_else(invalid_inset)?;+ // NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.+ // AD-HOC: Relative lengths are not allowed, see https://github.com/w3c/csswg-drafts/issues/13852+ if value.is_css_wide_keyword()+ || value.is_unresolved()+ || value.is_pending_substitution()+ || view_timeline_inset_has_relative_length(&value)+ {+ return Err(invalid_inset());+ }+ // SAFETY: The document and the value are live, and the host hands over a reference to the absolutized value.+ let computed: StyleValue = unsafe {+ style_value_from_host(web_animation_absolutize_style_value(+ document,+ style_value_as_host_ptr(&value),+ ))+ };+ Ok(ViewTimelineInsetValue::from_computed_value(&computed))+}++fn parse_auto(keyword: &Utf16String) -> WebIdlResult<ViewTimelineInsetEdgeValue> {+ let is_auto = keyword+ .to_utf16()+ .iter()+ .map(|&code_unit| {+ if (u16::from(b'A')..=u16::from(b'Z')).contains(&code_unit) {+ code_unit + 0x20+ } else {+ code_unit+ }+ })+ .eq("auto".encode_utf16());+ if !is_auto {+ return Err(Exception::type_error("A view timeline inset keyword must be auto"));+ }+ Ok(ViewTimelineInsetEdgeValue::auto())+}++impl ViewTimeline {+ pub(crate) fn from_timeline(timeline: AnimationTimeline) -> Self {+ Self {+ scroll_timeline: ScrollTimeline::from_timeline(timeline),+ }+ }++ pub(crate) fn scroll_timeline(&self) -> &ScrollTimeline {+ &self.scroll_timeline+ }++ fn record(&self) -> &TimelineRecordRef {+ self.scroll_timeline.timeline().record()+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-viewtimeline+ pub(crate) fn construct(cx: &mut CallContext, options: ViewTimelineOptions<'_>) -> WebIdlResult<Ref<Self>> {+ let document = document_of_realm(cx.realm());++ // 1. Let timeline be the new ViewTimeline object.+ // 2. Set the subject and axis properties of timeline to the corresponding values from options.+ let subject = element_of_wrapper(options.subject);++ // 3. Set the source of timeline to the subject’s nearest ancestor scroll container element that's scrollable+ // in the specified axis.+ // NB: The source is found from the subject whenever it is asked for.++ // 4. If a DOMString value is provided as an inset, parse it as a <'view-timeline-inset'> value; if a sequence+ // is provided, the first value represents the start inset and the second value represents the end inset. If+ // the sequence has only one value, it is duplicated. If it has zero values or more than two values, or if it+ // contains a CSSKeywordValue whose value is not "auto", throw a TypeError.+ let inset = match options.inset {+ DOMStringOrCSSNumericValueOrCSSKeywordValueOrDOMStringSequence::DOMString(string) => {+ parse_inset(document.as_ptr(), &string)?+ }+ DOMStringOrCSSNumericValueOrCSSKeywordValueOrDOMStringSequence::Sequence(values) => {+ if values.is_empty() || values.len() > 2 {+ return Err(Exception::type_error("A view timeline inset takes one or two values"));+ }+ let mut edges = Vec::with_capacity(2);+ for value in values.values().iter() {+ edges.push(match value {+ CSSNumericValueOrCSSKeywordValueOrDOMString::CSSNumericValue(numeric) => {+ parse_inset(document.as_ptr(), &numeric.to_css_string())?.into_start()+ }+ CSSNumericValueOrCSSKeywordValueOrDOMString::CSSKeywordValue(keyword) => {+ parse_auto(&keyword.raw_value())?+ }+ // INTEROP: Blink takes "auto" as a string in the sequence too.+ CSSNumericValueOrCSSKeywordValueOrDOMString::DOMString(keyword) => parse_auto(keyword)?,+ });+ }+ let start = edges.remove(0);+ let end = edges.pop().unwrap_or_else(|| start.clone());+ ViewTimelineInsetValue::from_edges(start, end)+ }+ };++ // These insets define the ViewTimeline’s view progress visibility range.+ let record = TimelineRecordRef::new(+ document,+ TimelineDescription::View {+ subject,+ axis: options.axis as u8,+ inset,+ },+ );+ let object = allocate(cx.vm(), |_| Self::from_timeline(AnimationTimeline::new(record)));+ did_create_timeline(cell_into_abi(object));+ Ok(object)+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-subject+ pub(crate) fn subject(&self, cx: &mut CallContext) -> WebIdlResult<CppInterface> {+ let subject = self.record().subject().expect("a view timeline has a subject");+ Ok(element_wrapper(cx, subject))+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-startoffset+ pub(crate) fn start_offset(&self, cx: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {+ // Represents the starting (0% progress) scroll position of the view progress timeline as a length offset (in+ // px) from the scroll origin.+ let start = self.record().cover_range().map_or(0.0, |(start, _)| start);+ Ok(AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(+ cx.vm(),+ start,+ "px",+ )))+ }++ // https://drafts.csswg.org/scroll-animations-1/#dom-viewtimeline-endoffset+ pub(crate) fn end_offset(&self, cx: &mut CallContext) -> WebIdlResult<AnyCSSNumericValue> {+ // Represents the ending (100% progress) scroll position of the view progress timeline as a length offset (in+ // px) from the scroll origin.+ let end = self.record().cover_range().map_or(0.0, |(_, end)| end);+ Ok(AnyCSSNumericValue::CSSUnitValue(CSSUnitValue::create(+ cx.vm(),+ end,+ "px",+ )))+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rsindex 5051ac43818..c3dfb4fe76e 100644--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/interface.rs@@ -29,6 +29,7 @@ use libjs_rust::api::{};use crate::bindings::CallContext;+use crate::bindings::conversions::implements_cpp_interface;use crate::bindings::realm_data::wrapper_world_of;use crate::bindings::services::{web_bindings_define_unforgeable_attributes, web_bindings_ensure_web_constructor, web_bindings_ensure_web_prototype,@@ -271,6 +272,33 @@ pub(crate) fn this_object(vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&interface_name])}+/// The object an attribute or an operation of an interface implemented in C++ runs on, if it is a wrapper of an object+/// that implements the interface, which the value of its Web::Bindings::InterfaceName names, with the object's realm.+/// A nullish this value stands for the global object of the current realm.+/// https://webidl.spec.whatwg.org/#implementation-check-an-object+pub(crate) fn this_cpp_object(+ vm: &Vm,+ interface_name: u16,+ name: &str,+ identifier: &str,+ check_type: SecurityCheckType,+) -> ThrowCompletionOr<(Gc<Object>, Gc<Realm>)> {+ let mut this_value = vm.this_value();+ if this_value.is_nullish() {+ let current_realm = vm.current_realm().expect("a native function runs in a realm");+ this_value = Value::from_object(current_realm.global_object());+ }+ if this_value.is_object() {+ let object = this_value.as_object();+ if implements_cpp_interface(object, interface_name) {+ return Ok((object, object.shape().realm()));+ }+ }+ // NB: This runs after the check above, which no Window or Location object passes.+ perform_a_security_check(vm, this_value, identifier, check_type)?;+ vm.throw_completion(ErrorKind::TypeError, ErrorType::NotAnObjectOfType, &[&name])+}+/// The object that a wrapper of exactly the interface wraps.pub(crate) fn implementation_of<T: Interface>(wrapper: Gc<Object>) -> Ref<T> {implementation_if(wrapper).expect("a wrapper holds the cell of its object")diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rsindex 378d8ab1b9f..9ad46130d05 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/animation_event.rs@@ -10,30 +10,57 @@ use core::ffi::c_void;use core::ptr::NonNull;use ak::Utf16String;-use libjs_rust::api::{Gc, Realm, Trace, Vm};+use libjs_rust::api::{Gc, Realm, Trace, Visitor, Vm};+use libweb_rust::AnimationRecordRef;-use super::css_rule::wrap_cpp_cell;-use crate::bindings::conversions::CppInterface;-use crate::bindings::cpp_cell::CppCell;+use super::css_animation::CSSAnimation;+use crate::animations::animation::{Animation, AnyAnimation, animation_object};use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::Inherits;use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::{CallContext, WebIdlResult};use crate::dom::event::EventInit;+/// The animation an event names, as its record. The event visits what keeps the record's object, or the elements the+/// record names, alive.+pub(crate) struct EventAnimation(AnimationRecordRef);+unsafe extern "C" {- fn web_css_animation_of_wrapper(wrapper: *mut c_void) -> *mut c_void;+ fn web_animation_visit_host_cells(animation: *const c_void, visitor: *mut c_void);+}++impl EventAnimation {+ /// # Safety+ ///+ /// `animation` must be an animation the host holds a reference to.+ pub(crate) unsafe fn retained_from_host(animation: *const c_void) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { AnimationRecordRef::retained_from_host(animation) })+ }++ /// The animation of an object of it.+ pub(crate) fn of_object(animation: &Animation) -> Self {+ Self(animation.record().clone())+ }++ /// The object of the animation, which a CSS animation or transition gets as script first asks for it.+ pub(crate) fn wrap(&self, cx: &CallContext) -> AnyAnimation {+ animation_object(cx.vm(), &self.0)+ }}-/// The Animation behind a wrapper of it, which an event holds to wrap it again for the world of each caller.-pub(crate) fn animation_of_wrapper(animation: CppInterface) -> CppCell {- // SAFETY: The caller passes a wrapper of an Animation, whose cell is live.- unsafe { CppCell::from_raw(web_css_animation_of_wrapper(animation.wrapper().as_ptr().cast())) }+// SAFETY: Visits the cells of the host that keep the record's object, or the elements the record names, alive.+unsafe impl Trace for EventAnimation {+ fn trace(&self, visitor: &mut Visitor) {+ // SAFETY: The event holds a reference to the record, and the visitor is one LibGC passed in.+ unsafe { web_animation_visit_host_cells(self.0.as_host_ptr(), visitor.as_raw().cast()) };+ }}/// The dictionary AnimationEventInit of CSS/AnimationEvent.idl.pub(crate) struct AnimationEventInit {pub(crate) parent: EventInit,- pub(crate) animation: Option<CppInterface>,+ pub(crate) animation: Option<Ref<CSSAnimation>>,pub(crate) animation_name: Utf16String,pub(crate) elapsed_time: f64,pub(crate) pseudo_element: Utf16String,@@ -49,7 +76,7 @@ pub(crate) struct AnimationEvent {elapsed_time: f64,#[gc(untraced)]pseudo_element: Utf16String,- animation: Option<CppCell>,+ animation: Option<EventAnimation>,}impl Wrappable for AnimationEvent {@@ -64,6 +91,21 @@ impl AnimationEvent {realm: Gc<Realm>,event_name: &Utf16String,event_init: AnimationEventInit,+ ) -> Ref<AnimationEvent> {+ let animation = event_init+ .animation+ .as_ref()+ .map(|animation| EventAnimation::of_object(animation.parent()));+ Self::create_for_animation(vm, realm, event_name, event_init, animation)+ }++ /// A new event that names `animation` in place of the animation of `event_init`.+ pub(crate) fn create_for_animation(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: AnimationEventInit,+ animation: Option<EventAnimation>,) -> Ref<AnimationEvent> {let event = CppEvent::create_for_owner(realm,@@ -77,7 +119,7 @@ impl AnimationEvent {animation_name: event_init.animation_name,elapsed_time: event_init.elapsed_time,pseudo_element: event_init.pseudo_element,- animation: event_init.animation.map(animation_of_wrapper),+ animation,});object.event.set_owner(object);object@@ -107,7 +149,7 @@ impl AnimationEvent {Ok(self.pseudo_element.clone())}- pub(crate) fn animation(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {- Ok(self.animation.as_ref().map(|animation| wrap_cpp_cell(cx, animation)))+ pub(crate) fn animation(&self, cx: &mut CallContext) -> WebIdlResult<Option<AnyAnimation>> {+ Ok(self.animation.as_ref().map(|animation| animation.wrap(cx)))}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rsnew file mode 100644index 00000000000..0c437245b82--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_animation.rs@@ -0,0 +1,71 @@+/*+ * Copyright (c) 2024, Matthew Olsson <[email protected]>.+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CSSAnimation, https://drafts.csswg.org/css-animations-2/#cssanimation++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Visitor, Vm};++use crate::animations::animation::Animation;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++// https://drafts.csswg.org/css-animations-2/#cssanimation+pub(crate) struct CSSAnimation {+ animation: Animation,+}++// SAFETY: The animation visits what it reaches.+unsafe impl Trace for CSSAnimation {+ fn trace(&self, visitor: &mut Visitor) {+ self.animation.trace(visitor);+ }+}++impl Inherits<Animation> for CSSAnimation {+ fn parent(&self) -> &Animation {+ &self.animation+ }+}++impl Wrappable for CSSAnimation {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ self.animation.relevant_realm()+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.animation.cpp_parent()+ }++ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ object.animation.finalize_animation();+ }+}++impl GetTheParent for CSSAnimation {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl CSSAnimation {+ /// The object of a CSS animation, whose state `animation` holds.+ pub(crate) fn allocate(vm: &Vm, animation: Animation) -> Ref<Self> {+ allocate(vm, |_| Self { animation })+ }++ // https://drafts.csswg.org/css-animations-2/#dom-cssanimation-animationname+ pub(crate) fn animation_name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.animation.record().css_animation_name())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rsindex e9c56932223..04a0fbbe5ea 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_numeric_value.rs@@ -349,7 +349,7 @@ impl AnyCSSNumericValue {values}- fn add(&self, vm: &Vm, initial_values: &MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Self> {+ pub(crate) fn add(&self, vm: &Vm, initial_values: &MarkedVec<'_, CSSNumberish>) -> WebIdlResult<Self> {let own_values = match self {Self::CSSMathSum(math_sum) => Some(math_sum.numeric_array()),_ => None,diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs b/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rsnew file mode 100644index 00000000000..6b03bb9c4bb--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/css/css_transition.rs@@ -0,0 +1,72 @@+/*+ * Copyright (c) 2024, Matthew Olsson <[email protected]>+ * Copyright (c) 2024, Sam Atkins <[email protected]>+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CSSTransition, https://drafts.csswg.org/css-transitions-2/#the-CSSTransition-interface++use core::ffi::c_void;+use core::ptr::NonNull;++use ak::Utf16String;+use libjs_rust::api::{Gc, Realm, Trace, Visitor, Vm};++use crate::animations::animation::Animation;+use crate::bindings::event_target::{CppEventTarget, GetTheParent};+use crate::bindings::interface::{Inherits, Ref, Wrappable, allocate};+use crate::bindings::{CallContext, WebIdlResult};++// https://drafts.csswg.org/css-transitions-2/#the-CSSTransition-interface+pub(crate) struct CSSTransition {+ animation: Animation,+}++// SAFETY: The animation visits what it reaches.+unsafe impl Trace for CSSTransition {+ fn trace(&self, visitor: &mut Visitor) {+ self.animation.trace(visitor);+ }+}++impl Inherits<Animation> for CSSTransition {+ fn parent(&self) -> &Animation {+ &self.animation+ }+}++impl Wrappable for CSSTransition {+ fn relevant_realm(&self) -> Option<Gc<Realm>> {+ self.animation.relevant_realm()+ }++ fn cpp_parent(&self) -> Option<NonNull<c_void>> {+ self.animation.cpp_parent()+ }++ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ object.animation.finalize_animation();+ }+}++impl GetTheParent for CSSTransition {+ fn get_the_parent(&self) -> Option<CppEventTarget> {+ None+ }+}++impl CSSTransition {+ /// The object of a CSS transition, whose state `animation` holds.+ pub(crate) fn allocate(vm: &Vm, animation: Animation) -> Ref<Self> {+ allocate(vm, |_| Self { animation })+ }++ // https://drafts.csswg.org/css-transitions-2/#dom-csstransition-transitionproperty+ pub(crate) fn transition_property(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {+ Ok(self.animation.record().css_transition_property())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rsindex b909b58c2f5..cb17d6d9649 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/exports.rs@@ -8,17 +8,17 @@//! Libraries/LibWeb/CSS/TypedOM.cpp.use core::ffi::c_void;-use core::ptr::{NonNull, null_mut};+use core::ptr::null_mut;use std::rc::Rc;use std::sync::Arc;use ak::Utf16String;use libcompositing_rust::css_pixels::{CssPixelRect, FfiCssPixelPoint, FfiCssPixelRect};-use libjs_rust::api::{Gc, MarkedVec, Vm};+use libjs_rust::api::{MarkedVec, Vm};use libweb_rust::typed_om::{FfiNumericType, RetainedStyleValue};use libweb_rust::{NativeMediaList, NativeRule, NativeRuleList};-use super::animation_event::{AnimationEvent, AnimationEventInit};+use super::animation_event::{AnimationEvent, AnimationEventInit, EventAnimation};use super::css_container_rule::CSSContainerRule;use super::css_counter_style_rule::CSSCounterStyleRule;use super::css_font_face_rule::CSSFontFaceRule;@@ -68,7 +68,6 @@ use super::style_sheet_list::StyleSheetList;use super::transition_event::{TransitionEvent, TransitionEventInit};use super::typed_om;use super::visual_viewport::VisualViewport;-use crate::bindings::conversions::CppInterface;use crate::bindings::cpp_cell::CppCell;use crate::bindings::interface::{Ref, allocate, cell_from_abi, cell_if_abi, cell_into_abi, realm_arguments};use crate::dom::event::EventInit;@@ -676,23 +675,12 @@ pub unsafe extern "C" fn web_screen_create(vm: *mut c_void, realm: *mut c_void,cell_into_abi(Screen::create(vm, realm, window))}-/// The object of a wrapper that C++ passes, if it passes one.-///-/// # Safety-///-/// `wrapper` must be null or a live wrapper of an object of an interface that LibWeb implements in C++.-unsafe fn cpp_interface_from_abi(wrapper: *mut c_void) -> Option<CppInterface> {- let wrapper = NonNull::new(wrapper.cast())?;- // SAFETY: The caller passes a live wrapper.- Some(unsafe { CppInterface::from_wrapper(Gc::from_non_null(wrapper)) })-}-/// A new AnimationEvent that bubbles, as the Event that C++ dispatches.////// # Safety////// `vm` must be the live VM, `realm` a live realm, `event_name`, `animation_name` and `pseudo_element` raw strings that-/// C++ hands over, and `animation` a live wrapper of a CSSAnimation.+/// C++ hands over, and `animation` a CSS animation C++ holds a reference to.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_animation_event_create(vm: *mut c_void,@@ -701,27 +689,27 @@ pub unsafe extern "C" fn web_animation_event_create(animation_name: usize,elapsed_time: f64,pseudo_element: usize,- animation: *mut c_void,+ animation: *const c_void,) -> *mut c_void {// SAFETY: The caller passes the live VM and a live realm.let (vm, realm) = unsafe { realm_arguments(vm, realm) };- // SAFETY: The caller hands over the strings and passes a live wrapper.+ // SAFETY: The caller hands over the strings and passes an animation it holds a reference to.let (event_name, animation_name, pseudo_element, animation) = unsafe {(Utf16String::from_raw_owned(event_name),Utf16String::from_raw_owned(animation_name),Utf16String::from_raw_owned(pseudo_element),- cpp_interface_from_abi(animation),+ EventAnimation::retained_from_host(animation),)};let event_init = AnimationEventInit {parent: bubbling_event_init(),- animation,+ animation: None,animation_name,elapsed_time,pseudo_element,};- let event = AnimationEvent::create(vm, realm, &event_name, event_init);+ let event = AnimationEvent::create_for_animation(vm, realm, &event_name, event_init, Some(animation));event.event().set_is_trusted(true);event.event().as_ptr()}@@ -731,7 +719,7 @@ pub unsafe extern "C" fn web_animation_event_create(/// # Safety////// `vm` must be the live VM, `realm` a live realm, `event_name`, `property_name` and `pseudo_element` raw strings that-/// C++ hands over, and `animation` a live wrapper of a CSSTransition.+/// C++ hands over, and `animation` a CSS transition C++ holds a reference to.#[unsafe(no_mangle)]pub unsafe extern "C" fn web_transition_event_create(vm: *mut c_void,@@ -740,27 +728,27 @@ pub unsafe extern "C" fn web_transition_event_create(property_name: usize,elapsed_time: f64,pseudo_element: usize,- animation: *mut c_void,+ animation: *const c_void,) -> *mut c_void {// SAFETY: The caller passes the live VM and a live realm.let (vm, realm) = unsafe { realm_arguments(vm, realm) };- // SAFETY: The caller hands over the strings and passes a live wrapper.+ // SAFETY: The caller hands over the strings and passes an animation it holds a reference to.let (event_name, property_name, pseudo_element, animation) = unsafe {(Utf16String::from_raw_owned(event_name),Utf16String::from_raw_owned(property_name),Utf16String::from_raw_owned(pseudo_element),- cpp_interface_from_abi(animation),+ EventAnimation::retained_from_host(animation),)};let event_init = TransitionEventInit {parent: bubbling_event_init(),- animation,+ animation: None,elapsed_time,property_name,pseudo_element,};- let event = TransitionEvent::create(vm, realm, &event_name, event_init);+ let event = TransitionEvent::create_for_animation(vm, realm, &event_name, event_init, Some(animation));event.event().set_is_trusted(true);event.event().as_ptr()}diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rsindex 5901de22302..4f91fe10ada 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/mod.rs@@ -9,6 +9,7 @@pub(crate) mod animation_event;#[allow(clippy::module_inception)]pub(crate) mod css;+pub(crate) mod css_animation;pub(crate) mod css_condition_rule;pub(crate) mod css_container_rule;pub(crate) mod css_counter_style_rule;@@ -65,6 +66,7 @@ pub(crate) mod css_style_value;pub(crate) mod css_supports_rule;pub(crate) mod css_transform_component;pub(crate) mod css_transform_value;+pub(crate) mod css_transition;pub(crate) mod css_translate;pub(crate) mod css_unit_value;pub(crate) mod css_unparsed_value;diff --git a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rsindex d073d6be0db..0d3062c2ec9 100644--- a/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/css/transition_event.rs@@ -12,11 +12,11 @@ use core::ptr::NonNull;use ak::Utf16String;use libjs_rust::api::{Gc, Realm, Trace, Vm};-use super::animation_event::animation_of_wrapper;-use super::css_rule::wrap_cpp_cell;-use crate::bindings::conversions::CppInterface;-use crate::bindings::cpp_cell::CppCell;+use super::animation_event::EventAnimation;+use super::css_transition::CSSTransition;+use crate::animations::animation::AnyAnimation;use crate::bindings::event_target::CppEvent;+use crate::bindings::interface::Inherits;use crate::bindings::interface::{Ref, Wrappable, allocate};use crate::bindings::{CallContext, WebIdlResult};use crate::dom::event::EventInit;@@ -24,7 +24,7 @@ use crate::dom::event::EventInit;/// The dictionary TransitionEventInit of CSS/TransitionEvent.idl.pub(crate) struct TransitionEventInit {pub(crate) parent: EventInit,- pub(crate) animation: Option<CppInterface>,+ pub(crate) animation: Option<Ref<CSSTransition>>,pub(crate) elapsed_time: f64,pub(crate) property_name: Utf16String,pub(crate) pseudo_element: Utf16String,@@ -40,7 +40,7 @@ pub(crate) struct TransitionEvent {elapsed_time: f64,#[gc(untraced)]pseudo_element: Utf16String,- animation: Option<CppCell>,+ animation: Option<EventAnimation>,}impl Wrappable for TransitionEvent {@@ -55,6 +55,21 @@ impl TransitionEvent {realm: Gc<Realm>,event_name: &Utf16String,event_init: TransitionEventInit,+ ) -> Ref<TransitionEvent> {+ let animation = event_init+ .animation+ .as_ref()+ .map(|animation| EventAnimation::of_object(animation.parent()));+ Self::create_for_animation(vm, realm, event_name, event_init, animation)+ }++ /// A new event that names `animation` in place of the animation of `event_init`.+ pub(crate) fn create_for_animation(+ vm: &Vm,+ realm: Gc<Realm>,+ event_name: &Utf16String,+ event_init: TransitionEventInit,+ animation: Option<EventAnimation>,) -> Ref<TransitionEvent> {let event = CppEvent::create_for_owner(realm,@@ -68,7 +83,7 @@ impl TransitionEvent {property_name: event_init.property_name,elapsed_time: event_init.elapsed_time,pseudo_element: event_init.pseudo_element,- animation: event_init.animation.map(animation_of_wrapper),+ animation,});object.event.set_owner(object);object@@ -98,7 +113,7 @@ impl TransitionEvent {Ok(self.pseudo_element.clone())}- pub(crate) fn animation(&self, cx: &mut CallContext) -> WebIdlResult<Option<CppInterface>> {- Ok(self.animation.as_ref().map(|animation| wrap_cpp_cell(cx, animation)))+ pub(crate) fn animation(&self, cx: &mut CallContext) -> WebIdlResult<Option<AnyAnimation>> {+ Ok(self.animation.as_ref().map(|animation| animation.wrap(cx)))}}diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rsindex 8c0f47c983c..6821ffb43f6 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/document.rs@@ -4,21 +4,29 @@* SPDX-License-Identifier: BSD-2-Clause*/+//! The members of Document that are implemented in Rust, https://dom.spec.whatwg.org/#interface-document+use core::ffi::c_void;use ak::Utf16String;-use libjs_rust::api::{Trace, Vm};+use libjs_rust::api::{MarkedVec, Trace, Vm};use liburl_rust::origin::{Host, Origin};use liburl_rust::{FfiOrigin, FfiUrlHost, Url};+use crate::animations::animation::AnyAnimation;+use crate::animations::document_or_shadow_root;+use crate::animations::document_timeline::DocumentTimeline;+use crate::bindings::conversions::CppInterface;use crate::bindings::cpp_cell::{CppCell, WeakCppCell};use crate::bindings::interface::{Ref, cell_from_abi, cell_into_abi};+use crate::bindings::{CallContext, WebIdlResult};use crate::html::navigable::CppNavigable;use crate::html::visibility_state::VisibilityState;use crate::navigation_timing::performance_navigation_timing::PerformanceNavigationTiming;use crate::permissions_policy::permissions_policy::PolicyControlledFeature;unsafe extern "C" {+ fn web_animation_document_timeline(document_wrapper: *mut c_void) -> *mut c_void;fn web_bindings_is_a_registrable_domain_suffix_of_or_is_equal_to(host_suffix_string: usize,original_host: *const FfiUrlHost,@@ -203,3 +211,20 @@ pub(crate) fn is_a_registrable_domain_suffix_of_or_is_equal_to()}}++/// https://drafts.csswg.org/web-animations-1/#dom-document-timeline+pub(crate) fn timeline(this: &CppInterface, _: &mut CallContext) -> WebIdlResult<Ref<DocumentTimeline>> {+ // The DocumentTimeline object representing the default document timeline.+ // SAFETY: The wrapper is live, and LibWeb returns the cell of the document's default document timeline.+ let cell = unsafe { web_animation_document_timeline(this.wrapper().as_ptr().cast()) };+ // SAFETY: LibWeb returns the live cell of a DocumentTimeline.+ Ok(unsafe { cell_from_abi::<DocumentTimeline>(cell) })+}++/// https://drafts.csswg.org/web-animations-1/#dom-documentorshadowroot-getanimations+pub(crate) fn get_animations<'vm>(+ this: &CppInterface,+ cx: &mut CallContext<'vm>,+) -> WebIdlResult<MarkedVec<'vm, AnyAnimation>> {+ document_or_shadow_root::get_animations(this, cx)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rsindex 64a511e25c5..ea85cc8b5ed 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/element.rs@@ -4,12 +4,18 @@* SPDX-License-Identifier: BSD-2-Clause*/+//! The members of Element that are implemented in Rust, https://dom.spec.whatwg.org/#interface-element+use core::ffi::c_void;use ak::Utf16String;-use libjs_rust::api::Trace;+use libjs_rust::api::{Gc, MarkedVec, Object, Trace};+use crate::animations::animatable::{self, GetAnimationsOptions, UnrestrictedDoubleOrKeyframeAnimationOptions};+use crate::animations::animation::AnyAnimation;+use crate::bindings::conversions::CppInterface;use crate::bindings::cpp_cell::CppCell;+use crate::bindings::{CallContext, WebIdlResult};unsafe extern "C" {fn web_dom_is_valid_attribute_local_name(name: usize) -> bool;@@ -61,3 +67,22 @@ pub(crate) fn is_valid_attribute_local_name(name: &Utf16String) -> bool {// SAFETY: The name is live for the call.unsafe { web_dom_is_valid_attribute_local_name(name.raw_identity()) }}++/// https://drafts.csswg.org/web-animations-1/#dom-animatable-getanimations+pub(crate) fn get_animations<'vm>(+ this: &CppInterface,+ cx: &mut CallContext<'vm>,+ options: GetAnimationsOptions,+) -> WebIdlResult<MarkedVec<'vm, AnyAnimation>> {+ animatable::get_animations(this, cx, options)+}++/// https://drafts.csswg.org/web-animations-1/#dom-animatable-animate+pub(crate) fn animate(+ this: &CppInterface,+ cx: &mut CallContext,+ keyframes: Option<Gc<Object>>,+ options: UnrestrictedDoubleOrKeyframeAnimationOptions,+) -> WebIdlResult<AnyAnimation> {+ animatable::animate(this, cx, keyframes, options)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rsindex c9d8bc7db86..578a96d199f 100644--- a/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/mod.rs@@ -15,3 +15,5 @@ pub(crate) mod document;#[cfg(not(test))]pub(crate) mod element;pub(crate) mod event;+#[cfg(not(test))]+pub(crate) mod shadow_root;diff --git a/Libraries/LibWeb/Bindings/Rust/src/dom/shadow_root.rs b/Libraries/LibWeb/Bindings/Rust/src/dom/shadow_root.rsnew file mode 100644index 00000000000..697c6007562--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/dom/shadow_root.rs@@ -0,0 +1,22 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The members of ShadowRoot that are implemented in Rust, https://dom.spec.whatwg.org/#interface-shadowroot++use libjs_rust::api::MarkedVec;++use crate::animations::animation::AnyAnimation;+use crate::animations::document_or_shadow_root;+use crate::bindings::conversions::CppInterface;+use crate::bindings::{CallContext, WebIdlResult};++/// https://drafts.csswg.org/web-animations-1/#dom-documentorshadowroot-getanimations+pub(crate) fn get_animations<'vm>(+ this: &CppInterface,+ cx: &mut CallContext<'vm>,+) -> WebIdlResult<MarkedVec<'vm, AnyAnimation>> {+ document_or_shadow_root::get_animations(this, cx)+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rsnew file mode 100644index 00000000000..96a0435dd79--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/internals/internal_animation_timeline.rs@@ -0,0 +1,67 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! InternalAnimationTimeline, the timeline whose time tests set.++use core::ffi::c_void;++use libcompositing_rust::animation_timing::OptionalNumber;+use libjs_rust::api::{Trace, Visitor};++use crate::animations::animation_timeline::{AnimationTimeline, finalize_timeline};+use crate::bindings::interface::{Inherits, Ref, Wrappable};+use crate::bindings::{CallContext, WebIdlResult};++unsafe extern "C" {+ fn web_internal_animation_timeline_set_time(timeline: *mut c_void, time: OptionalNumber, for_observation: bool);+}++pub(crate) struct InternalAnimationTimeline {+ timeline: AnimationTimeline,+}++// SAFETY: The timeline visits what it reaches.+unsafe impl Trace for InternalAnimationTimeline {+ fn trace(&self, visitor: &mut Visitor) {+ self.timeline.trace(visitor);+ }+}++impl Inherits<AnimationTimeline> for InternalAnimationTimeline {+ fn parent(&self) -> &AnimationTimeline {+ &self.timeline+ }+}++impl Wrappable for InternalAnimationTimeline {+ const FINALIZES: bool = true;++ fn finalize(object: Ref<Self>) {+ finalize_timeline(&object.timeline);+ }+}++impl InternalAnimationTimeline {+ pub(crate) fn from_timeline(timeline: AnimationTimeline) -> Self {+ Self { timeline }+ }++ pub(crate) fn timeline(&self) -> &AnimationTimeline {+ &self.timeline+ }++ pub(crate) fn set_time(&self, _: &mut CallContext, time: Option<f64>) -> WebIdlResult<()> {+ // SAFETY: The cell is that of this live timeline.+ unsafe { web_internal_animation_timeline_set_time(self.timeline.cell(), time.into(), false) };+ Ok(())+ }++ pub(crate) fn set_time_for_observation(&self, _: &mut CallContext, time: f64) -> WebIdlResult<()> {+ // SAFETY: The cell is that of this live timeline.+ unsafe { web_internal_animation_timeline_set_time(self.timeline.cell(), Some(time).into(), true) };+ Ok(())+ }+}diff --git a/Libraries/LibWeb/Bindings/Rust/src/internals/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/internals/mod.rsnew file mode 100644index 00000000000..a8b98981045--- /dev/null+++ b/Libraries/LibWeb/Bindings/Rust/src/internals/mod.rs@@ -0,0 +1,9 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The interfaces that tests reach through window.internals.++pub(crate) mod internal_animation_timeline;diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rsindex d01162466b2..e329dd6a6f1 100644--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs@@ -27,6 +27,16 @@ mod rust_demangle;mod rust_panic;pub(crate) mod ak_format;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]+pub(crate) mod animations;#[cfg(test)]mod ffi_test_stubs;@@ -99,7 +109,10 @@ pub(crate) mod crypto;pub(crate) mod css;#[cfg_attr(not(web_idl_bindings),- allow(dead_code, reason = "only the generated bindings use the dictionaries")+ allow(+ dead_code,+ reason = "only the generated bindings use the dictionaries and the members"+ ))]#[allow(clippy::unnecessary_wraps,@@ -198,6 +211,16 @@ pub(crate) mod indexed_db;clippy::unnecessary_wraps,reason = "the bindings call every attribute and operation as one that can throw")]+pub(crate) mod internals;+#[cfg(not(test))]+#[cfg_attr(+ not(web_idl_bindings),+ allow(dead_code, reason = "only the generated bindings use the interfaces")+)]+#[allow(+ clippy::unnecessary_wraps,+ reason = "the bindings call every attribute and operation as one that can throw"+)]pub(crate) mod largest_contentful_paint;#[cfg(not(test))]#[cfg_attr(diff --git a/Libraries/LibWeb/CMakeLists.txt b/Libraries/LibWeb/CMakeLists.txtindex 476b7d5674e..ded34a4a873 100644--- a/Libraries/LibWeb/CMakeLists.txt+++ b/Libraries/LibWeb/CMakeLists.txt@@ -2,18 +2,11 @@ include(libweb_generators)set(SOURCESAnimations/Animatable.cpp- Animations/Animation.cppAnimations/AnimationEffect.cpp- Animations/AnimationPlaybackEvent.cppAnimations/AnimationTimeline.cppAnimations/TimeValue.cpp- Animations/DocumentTimeline.cpp- Animations/KeyframeEffect.cppAnimations/NamedTimelines.cpp- Animations/PseudoElementParsing.cpp- Animations/ScrollTimeline.cpp- Animations/TimelineRange.cpp- Animations/ViewTimeline.cpp+ Animations/RecordHandles.cppARIA/AriaData.cppARIA/ARIAMixin.cppARIA/AttributeNames.cpp@@ -642,7 +635,6 @@ set(SOURCESIndexedDB/RustIntegration.cppInfra/ByteSequences.cppInfra/JSON.cpp- Internals/InternalAnimationTimeline.cppInternals/InternalGamepad.cppInternals/Internals.cppInternals/InternalsBase.cpp@@ -762,7 +754,6 @@ set(SOURCESSVG/AttributeNames.cppSVG/AttributeParsing.cppSVG/Path.cpp- SVG/SMILAnimation.cppSVG/SMILTimeContainer.cppSVG/SVGAElement.cppSVG/SVGAngle.cppdiff --git a/Libraries/LibWeb/CSS/CSSAnimation.cpp b/Libraries/LibWeb/CSS/CSSAnimation.cppindex 467ac74f59e..02fdfba2671 100644--- a/Libraries/LibWeb/CSS/CSSAnimation.cpp+++ b/Libraries/LibWeb/CSS/CSSAnimation.cpp@@ -6,15 +6,15 @@#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/AnimationEffect.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/Animations/NamedTimelines.h>-#include <LibWeb/Animations/ScrollTimeline.h>-#include <LibWeb/Animations/ViewTimeline.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/CSS/CSSAnimation.h>#include <LibWeb/CSS/PropertyID.h>#include <LibWeb/CSS/PseudoElement.h>+#include <LibWeb/CSS/StyleValues/StyleValue.h>+#include <LibWeb/ComputedValuesRustFFI.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>#include <LibWeb/DOM/Event.h>@@ -25,429 +25,189 @@ namespace Web::CSS {extern "C" {-// Declared in Bindings/Rust/src/css/animation_event.rs.-void* web_css_animation_of_wrapper(void* wrapper);-// Defined in Bindings/Rust/src/css/exports.rs.-void* web_animation_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, void* animation);-}--void* web_css_animation_of_wrapper(void* wrapper)-{- auto* animation = Bindings::impl_from<Animations::Animation>(static_cast<JS::Object*>(wrapper));- VERIFY(animation);- return static_cast<GC::Cell*>(animation);+void* web_animation_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, Animations::RustFFI::AnimationCell const* animation);}-GC::Ref<DOM::Event> CSSAnimation::create_event(DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element)+GC::Ref<DOM::Event> CSSAnimation::create_event(Animations::AnimationRef const& animation, DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element){auto& realm = HTML::relevant_realm(document);- auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref<CSSAnimation> { *this });- auto* event = web_animation_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), animation_name().to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), JS::HostABI::object_to_abi(wrapper.ptr()));+ auto* event = web_animation_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), animation_name(animation).to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), &animation.record());return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };}-GC_DEFINE_ALLOCATOR(CSSAnimation);--GC::Ref<CSSAnimation> CSSAnimation::create(HTML::EnvironmentSettingsObject& environment)+Animations::AnimationRef CSSAnimation::create(DOM::AbstractElement owner, ComputedValuesFFI::FfiComputedAnimation const& definition, Animations::KeyframeSetHandle keyframe_set, size_t name_index){- return GC::Heap::the().allocate<CSSAnimation>(environment);-}+ // An animation applies to an element if its name appears as one of the identifiers in the computed value of the+ // animation-name property and the animation uses a valid @keyframes rule+ // FIXME:+ // CSS Animations generated using the markup defined in this specification are not added to the global animation+ // list when they are created. Instead, these animations are appended to the global animation list at the first+ // moment when they transition out of the idle play state after being disassociated from their owning element. CSS+ // Animations that have been disassociated from their owning element but are still idle do not have a defined+ // composite order.+ // NB: Script gets the object of the animation, a CSSAnimation, as it first asks for it.+ auto animation = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_css_animation_create());+ Animations::RustFFI::animations_css_animation_set_name(&animation.record(), css_string_from_rust(definition.name).raw_identity());+ Animations::set_owning_element(animation, owner);-// https://www.w3.org/TR/css-animations-2/#animation-composite-order-int CSSAnimation::class_specific_composite_order(GC::Ref<Animations::Animation> other_animation) const-{- auto other = GC::Ref { as<CSSAnimation>(*other_animation) };+ auto effect = Animations::EffectRef::create_keyframe_effect();+ Animations::RustFFI::animations_animation_set_effect(&animation.record(), &effect.record(), true, Animations::perform_host_effect);- // The existence of an owning element determines the animation class, so both animations should have their owning- // element in the same state- VERIFY(owning_element().has_value() == other->owning_element().has_value());+ apply_css_properties(animation, definition, owner);+ set_animation_name_index(animation, name_index);- // Within the set of CSS Animations with an owning element, two animations A and B are sorted in composite order- // (first to last) as follows:- if (owning_element().has_value()) {- // 1. If the owning element of A and B differs, sort A and B by tree order of their corresponding owning elements.- // With regard to pseudo-elements, the sort order is as follows:- // - element- // - ::marker- // - ::before- // - any other pseudo-elements not mentioned specifically in this list, sorted in ascending order by the Unicode- // codepoints that make up each selector- // - ::after- // - element children- if (owning_element() != other->owning_element()) {- auto& element = owning_element()->element();- auto& other_element = other->owning_element()->element();- if (&element != &other_element) {- // NB: An element's pseudo-elements sort with it, so before its children.- return element.document().compare_elements_in_tree_order_for_composite_order(element, other_element);- }- auto rank = [](Optional<PseudoElement> pseudo_element) {- if (!pseudo_element.has_value())- return 0;- switch (*pseudo_element) {- case PseudoElement::Marker:- return 1;- case PseudoElement::Before:- return 2;- case PseudoElement::After:- return 4;- default:- return 3;- }- };- auto pseudo_element = owning_element()->pseudo_element();- auto other_pseudo_element = other->owning_element()->pseudo_element();- if (auto order = rank(pseudo_element) - rank(other_pseudo_element); order != 0)- return order;- return pseudo_element_name(*pseudo_element) < pseudo_element_name(*other_pseudo_element) ? -1 : 1;- }+ effect.set_keyframe_set(move(keyframe_set));- // 2. Otherwise, sort A and B based on their position in the computed value of the animation-name property of the- // (common) owning element.- return m_animation_name_index - other->m_animation_name_index;- }+ effect.set_target(owner);+ return animation;+}- // The composite order of CSS Animations without an owning element is based on their position in the global animation list.- return global_animation_list_order() - other->global_animation_list_order();+Utf16FlyString CSSAnimation::animation_name(Animations::AnimationRef const& animation)+{+ auto raw = Animations::RustFFI::animations_css_animation_state(&animation.record()).name;+ return raw ? Utf16FlyString::from_raw(raw) : Utf16FlyString {};}-void CSSAnimation::set_animation_name_index(size_t index)+void CSSAnimation::set_animation_name_index(Animations::AnimationRef const& animation, size_t index){- if (m_animation_name_index == index)+ if (!Animations::RustFFI::animations_css_animation_set_name_index(&animation.record(), static_cast<u32>(index)))return;- m_animation_name_index = index;- if (auto effect = this->effect(); effect && is<Animations::KeyframeEffect>(*effect)) {- if (auto target = static_cast<Animations::KeyframeEffect&>(*effect).target())+ if (auto effect = animation.effect(); effect.has_value()) {+ if (auto* target = effect->target())target->invalidate_associated_animation_composite_order();}}-Animations::AnimationClass CSSAnimation::animation_class() const+using TimelineKind = ComputedValuesFFI::FfiAnimationTimelineKind;++static Animations::ScrollAxis requested_axis(ComputedValuesFFI::FfiComputedAnimation const& definition){- if (owning_element().has_value())- return Animations::AnimationClass::CSSAnimationWithOwningElement;- return Animations::AnimationClass::CSSAnimationWithoutOwningElement;+ return Animations::scroll_axis_from_css_axis(static_cast<Axis>(definition.scroll_axis));}-static Animations::ScrollTimeline::AnonymousSource anonymous_scroll_source(AnimationTimelineSource const& requested, DOM::AbstractElement target)+static Animations::AnimationTimeline::AnonymousScrollSource anonymous_scroll_source(ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target){- return Animations::ScrollTimeline::AnonymousSource {- .scroller = requested.scroller,+ return Animations::AnimationTimeline::AnonymousScrollSource {+ .scroller = static_cast<Scroller>(definition.scroll_scroller),.target = target,};}+static Utf16FlyString timeline_name(ComputedValuesFFI::FfiComputedAnimation const& definition)+{+ return definition.timeline_name ? css_string_from_rust(definition.timeline_name) : Utf16FlyString {};+}+// NB: Unrelated style changes shouldn't cause us to recreate anonymous timelines, to achieve this we drop updates// between two equivalent anonymous timelines. The comparison is made against the description of the requested// timeline, so that the timeline a definition names is only ever created when it will replace the one the// animation already has.-static bool should_update_timeline(GC::Ptr<Animations::AnimationTimeline> old_timeline, AnimationTimelineSource const& requested, DOM::AbstractElement target)+static bool should_update_timeline(GC::Ptr<Animations::AnimationTimeline> old_timeline, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target){- switch (requested.kind) {- case AnimationTimelineSource::Kind::None:+ switch (definition.timeline_kind) {+ case TimelineKind::None:return old_timeline != nullptr;- case AnimationTimelineSource::Kind::Document: {+ case TimelineKind::Document: {GC::Ptr<Animations::AnimationTimeline> const document_timeline = target.document().timeline();return old_timeline != document_timeline;}- case AnimationTimelineSource::Kind::Named:- return old_timeline != target.document().named_timelines().target_timeline(target, requested.name);- case AnimationTimelineSource::Kind::View: {- auto const* old_view_timeline = as_if<Animations::ViewTimeline>(old_timeline.ptr());- return !old_view_timeline- || old_view_timeline->subject_internal() != target- || old_view_timeline->axis() != Animations::scroll_axis_from_css_axis(requested.axis)- || old_view_timeline->inset() != requested.view_inset;+ case TimelineKind::Named:+ return old_timeline != target.document().named_timelines().target_timeline(target, timeline_name(definition));+ case TimelineKind::View: {+ return !old_timeline+ || !old_timeline->is_view_timeline()+ || old_timeline->view_subject() != target+ || old_timeline->axis() != requested_axis(definition)+ || old_timeline->view_inset() != Animations::view_timeline_inset_from_ffi(definition.view_inset);}- case AnimationTimelineSource::Kind::Scroll:+ case TimelineKind::Scroll:break;}- auto const* old_scroll_timeline = as_if<Animations::ScrollTimeline>(old_timeline.ptr());- if (!old_scroll_timeline || is<Animations::ViewTimeline>(*old_scroll_timeline))+ if (!old_timeline || !old_timeline->is_scroll_timeline() || old_timeline->is_view_timeline())return true;- if (old_scroll_timeline->axis() != Animations::scroll_axis_from_css_axis(requested.axis))+ if (old_timeline->axis() != requested_axis(definition))return true;- auto old_source = old_scroll_timeline->source_internal();- if (!old_source.has<Animations::ScrollTimeline::AnonymousSource>())+ auto old_source = old_timeline->scroll_source();+ if (!old_source.has<Animations::AnimationTimeline::AnonymousScrollSource>())return true;- return old_source.get<Animations::ScrollTimeline::AnonymousSource>() != anonymous_scroll_source(requested, target);+ return old_source.get<Animations::AnimationTimeline::AnonymousScrollSource>() != anonymous_scroll_source(definition, target);}-static GC::Ptr<Animations::AnimationTimeline> materialize_timeline(AnimationTimelineSource const& requested, DOM::AbstractElement target)+static GC::Ptr<Animations::AnimationTimeline> materialize_timeline(ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement target){- switch (requested.kind) {- case AnimationTimelineSource::Kind::Document:+ switch (definition.timeline_kind) {+ case TimelineKind::Document:return target.document().timeline();- case AnimationTimelineSource::Kind::None:+ case TimelineKind::None:return {};- case AnimationTimelineSource::Kind::Scroll:- return Animations::ScrollTimeline::create(- target.document(),- anonymous_scroll_source(requested, target),- Animations::scroll_axis_from_css_axis(requested.axis));- case AnimationTimelineSource::Kind::View:- return Animations::ViewTimeline::create(target.document(), target, Animations::scroll_axis_from_css_axis(requested.axis), requested.view_inset);- case AnimationTimelineSource::Kind::Named:- return target.document().named_timelines().target_timeline(target, requested.name);+ case TimelineKind::Scroll:+ return Animations::AnimationTimeline::create_scroll_timeline(target.document(), anonymous_scroll_source(definition, target), requested_axis(definition));+ case TimelineKind::View:+ return Animations::AnimationTimeline::create_view_timeline(target.document(), target, requested_axis(definition), Animations::view_timeline_inset_from_ffi(definition.view_inset));+ case TimelineKind::Named:+ return target.document().named_timelines().target_timeline(target, timeline_name(definition));}VERIFY_NOT_REACHED();}-void CSSAnimation::apply_css_properties(AnimationProperties const& animation_properties, Animations::KeyframeEffect::KeyFrameSet const* keyframe_set, DOM::AbstractElement timeline_target)+void CSSAnimation::apply_css_properties(Animations::AnimationRef const& animation, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement timeline_target){// FIXME: Don't apply overridden properties as defined here: https://drafts.csswg.org/css-animations-2/#animations- VERIFY(effect());-- auto& effect = as<Animations::KeyframeEffect>(*this->effect());+ VERIFY(animation.effect().has_value());// NB: Recorded before the early return below, so that the definition always says what the style// computation last computed.- m_applied_keyframe_set = keyframe_set;- m_applied_timing_function_value = animation_properties.timing_function_value;- m_applied_definition_range = animation_properties.range;- m_applied_definition = {- .values = {- .duration = animation_properties.duration.visit(- [](double duration) { return duration; },- [](Utf16String const&) { return 0.0; }),- .iteration_count = animation_properties.iteration_count,- .delay = animation_properties.delay,- .range_start_px = animation_properties.range.start.offset_px,- .range_start_percentage = animation_properties.range.start.offset_percentage,- .range_end_px = animation_properties.range.end.offset_px,- .range_end_percentage = animation_properties.range.end.offset_percentage,- .duration_is_auto = animation_properties.duration.has<Utf16String>(),- .direction = to_underlying(animation_properties.direction),- .play_state = to_underlying(animation_properties.play_state),- .fill_mode = to_underlying(animation_properties.fill_mode),- .composition = to_underlying(animation_properties.composition),- .timeline_kind = to_underlying(animation_properties.timeline.kind),- .scroll_scroller = to_underlying(animation_properties.timeline.scroller),- .scroll_axis = to_underlying(animation_properties.timeline.axis),- .range_start_name = to_underlying(animation_properties.range.start.name),- .range_end_name = to_underlying(animation_properties.range.end.name),- },- .keyframe_set = m_applied_keyframe_set.ptr(),- .timing_function = m_applied_timing_function_value.data(),- .range_start_calculated = m_applied_definition_range.start.calculated_offset.data(),- .range_end_calculated = m_applied_definition_range.end.calculated_offset.data(),- };+ // NB: An animation that names its timeline looks it up again from its owning element as the timelines its+ // document declares change, also while the name finds no timeline. The record notes the name it follows.+ auto const follows_named_timeline = definition.timeline_kind == TimelineKind::Named;+ auto const applies_the_same_properties = Animations::RustFFI::animations_css_animation_apply_definition(&animation.record(), &definition, follows_named_timeline ? timeline_name(definition).raw_identity() : 0);- auto const update_timeline = !m_ignored_css_properties.contains(PropertyID::AnimationTimeline)- && should_update_timeline(timeline(), animation_properties.timeline, timeline_target);- AppliedCSSProperties applied_properties {- .duration = animation_properties.duration,- .timing_function = animation_properties.timing_function,- .iteration_count = animation_properties.iteration_count,- .direction = animation_properties.direction,- .play_state = animation_properties.play_state,- .delay = animation_properties.delay,- .fill_mode = animation_properties.fill_mode,- .composition = animation_properties.composition,- .range = animation_properties.range,- };- // NB: An animation that names its timeline looks it up again as the timelines its document declares change, also- // while the name finds no timeline.- if (animation_properties.timeline.kind == AnimationTimelineSource::Kind::Named) {- m_named_timeline_source = NamedTimelineSource { animation_properties.timeline.name, timeline_target };- timeline_target.document().named_timelines().track_animation(*this);- } else {- m_named_timeline_source.clear();- }+ GC::Ptr<Animations::AnimationTimeline> timeline = static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&animation.record()));+ auto const update_timeline = !has_flag(animation, Flag::ScriptSetTimeline)+ && should_update_timeline(timeline, definition, timeline_target);+ if (follows_named_timeline)+ timeline_target.document().named_timelines().track_animation(animation);// NB: Style feedback can recompute an animation's owning element. Reapplying unchanged// properties would invalidate the effect and turn that feedback into an endless cycle.- if (!update_timeline && m_applied_css_properties == applied_properties)+ if (!update_timeline && applies_the_same_properties)return;- m_applied_css_properties = applied_properties;+ HTML::TemporaryExecutionContext context(HTML::relevant_realm(Animations::relevant_global_object_of(animation)));if (update_timeline) {- HTML::TemporaryExecutionContext context(relevant_settings_object());- set_timeline(materialize_timeline(animation_properties.timeline, timeline_target));- }- // NB: An edge of the range that script set is no longer the style's to change.- auto range = animation_properties.range;- if (m_ignored_css_properties.contains(PropertyID::AnimationRangeStart))- range.start = this->range().start;- if (m_ignored_css_properties.contains(PropertyID::AnimationRangeEnd))- range.end = this->range().end;- set_range(range);-- effect.set_specified_iteration_duration(animation_properties.duration);- effect.set_specified_start_delay(animation_properties.delay);- effect.set_iteration_count(animation_properties.iteration_count);- // https://drafts.csswg.org/web-animations-2/#updating-animationeffect-timing- // Timing properties may also be updated due to a style change. Any change to a CSS animation property that affects- // timing requires rerunning the procedure to normalize specified timing.- effect.normalize_specified_timing();- // NB: animation-timing-function is applied per-keyframe, not as the effect-level timing function.- // The effect-level timing function remains linear. The effect's description for the style engine- // gives it to every keyframe that declares no easing of its own, so a new one describes it again.- if (m_default_easing != animation_properties.timing_function) {- m_default_easing = animation_properties.timing_function;- effect.invalidate_animation_preparation();- }- effect.set_fill_mode(Animations::css_fill_mode_to_bindings_fill_mode(animation_properties.fill_mode));- effect.set_playback_direction(Animations::css_animation_direction_to_bindings_playback_direction(animation_properties.direction));- effect.set_composite(Animations::css_animation_composition_to_composite_operation(animation_properties.composition));- {- HTML::TemporaryExecutionContext context(relevant_settings_object());- effect_timing_changed_by_style();+ auto new_timeline = materialize_timeline(definition, timeline_target);+ Animations::RustFFI::animations_animation_set_timeline(&animation.record(), new_timeline ? &new_timeline->record() : nullptr, Animations::perform_host_effect);}-- if (animation_properties.play_state != last_css_animation_play_state()) {- if (!m_script_overrode_play_state) {- if (animation_properties.play_state == CSS::AnimationPlayState::Running && play_state() != Animations::AnimationPlayState::Running) {- HTML::TemporaryExecutionContext context(relevant_settings_object());- play_from_css();- } else if (animation_properties.play_state == CSS::AnimationPlayState::Paused && play_state() != Animations::AnimationPlayState::Paused) {- HTML::TemporaryExecutionContext context(relevant_settings_object());- pause_from_css();- }- }-- set_last_css_animation_play_state(animation_properties.play_state);- }-}--void CSSAnimation::mark_script_play_state_override()-{- if (!m_applying_css_play_state)- m_script_overrode_play_state = true;-}--void CSSAnimation::play_from_css()-{- m_applying_css_play_state = true;- Animations::Animation::play().release_value_but_fixme_should_propagate_errors();- m_applying_css_play_state = false;-}--void CSSAnimation::pause_from_css()-{- m_applying_css_play_state = true;- Animations::Animation::pause().release_value_but_fixme_should_propagate_errors();- m_applying_css_play_state = false;-}--WebIDL::ExceptionOr<void> CSSAnimation::set_start_time_for_bindings(Animations::NullableCSSNumberish const& value)-{- auto previous_play_state = play_state();- auto result = Animations::Animation::set_start_time_for_bindings(value);- if (!result.is_error() && previous_play_state != play_state())- mark_script_play_state_override();- return result;+ Animations::RustFFI::animations_css_animation_apply_properties(&animation.record(), &definition, Animations::perform_host_effect);}-WebIDL::ExceptionOr<void> CSSAnimation::set_current_time_for_bindings(Animations::NullableCSSNumberish const& value)+bool CSSAnimation::has_flag(Animations::AnimationRef const& animation, Flag flag){- auto previous_play_state = play_state();- auto result = Animations::Animation::set_current_time_for_bindings(value);- if (!result.is_error() && previous_play_state != play_state())- mark_script_play_state_override();- return result;+ return Animations::RustFFI::animations_css_animation_has_flag(&animation.record(), flag);}-WebIDL::ExceptionOr<void> CSSAnimation::set_playback_rate(double value)+bool CSSAnimation::update_named_timeline(Animations::AnimationRef const& animation){- return Animations::Animation::set_playback_rate(value);-}--void CSSAnimation::cancel(Animations::Animation::ShouldInvalidate should_invalidate)-{- mark_script_play_state_override();- Animations::Animation::cancel(should_invalidate);-}--WebIDL::ExceptionOr<void> CSSAnimation::play(Animations::Animation::ShouldInvalidate should_invalidate)-{- auto previous_play_state = play_state();- auto result = Animations::Animation::play(should_invalidate);- if (!result.is_error() && previous_play_state != play_state())- mark_script_play_state_override();- return result;-}--WebIDL::ExceptionOr<void> CSSAnimation::pause()-{- auto result = Animations::Animation::pause();- if (!result.is_error())- mark_script_play_state_override();- return result;-}--WebIDL::ExceptionOr<void> CSSAnimation::update_playback_rate(double value)-{- return Animations::Animation::update_playback_rate(value);-}--WebIDL::ExceptionOr<void> CSSAnimation::reverse()-{- auto previous_play_state = play_state();- auto result = Animations::Animation::reverse();- if (!result.is_error() && previous_play_state != play_state())- mark_script_play_state_override();- return result;-}--// AD-HOC: Like the timeline, a range edge script sets takes precedence over the animation-range-start or-// animation-range-end property from then on, as WPT expects (scroll-animations/css/animation-range-ignored.html).-WebIDL::ExceptionOr<void> CSSAnimation::set_range_start_for_bindings(Animations::TimelineRangeBindingValue const& value)-{- TRY(Animations::Animation::set_range_start_for_bindings(value));- m_ignored_css_properties.set(PropertyID::AnimationRangeStart);- return {};-}--WebIDL::ExceptionOr<void> CSSAnimation::set_range_end_for_bindings(Animations::TimelineRangeBindingValue const& value)-{- TRY(Animations::Animation::set_range_end_for_bindings(value));- m_ignored_css_properties.set(PropertyID::AnimationRangeEnd);- return {};-}--void CSSAnimation::update_named_timeline()-{- if (!m_named_timeline_source.has_value() || m_ignored_css_properties.contains(PropertyID::AnimationTimeline))- return;- auto const& [name, target] = *m_named_timeline_source;- GC::Ptr<Animations::AnimationTimeline> timeline = target.document().named_timelines().target_timeline(target, name);- if (timeline == this->timeline())- return;- HTML::TemporaryExecutionContext context(relevant_settings_object());- set_timeline(timeline);-}--void CSSAnimation::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- if (m_named_timeline_source.has_value())- m_named_timeline_source->target.visit(visitor);-}--void CSSAnimation::set_timeline_for_bindings(GC::Ptr<Animations::AnimationTimeline> timeline)-{- // AD-HOC: When the timeline of a CSS animation is modified by the author from JS we should no longer apply changes- // to the `animation-timeline` property. See https://github.com/w3c/csswg-drafts/issues/13472- m_ignored_css_properties.set(PropertyID::AnimationTimeline);- set_timeline(timeline);-}--CSSAnimation::CSSAnimation(HTML::EnvironmentSettingsObject& environment)- : Animations::Animation(environment)-{- // FIXME:- // CSS Animations generated using the markup defined in this specification are not added to the global animation- // list when they are created. Instead, these animations are appended to the global animation list at the first- // moment when they transition out of the idle play state after being disassociated from their owning element. CSS- // Animations that have been disassociated from their owning element but are still idle do not have a defined- // composite order.+ auto state = Animations::RustFFI::animations_css_animation_state(&animation.record());+ if (!state.named_timeline || has_flag(animation, Flag::ScriptSetTimeline))+ return false;+ // NB: The owning element of a CSS animation is the element whose style names the timeline, which the animation+ // keeps alive.+ auto owner = Animations::RustFFI::animations_animation_owning_element(&animation.record());+ VERIFY(owner.element);+ DOM::AbstractElement target { *static_cast<DOM::Element*>(owner.element), owner.has_pseudo_element ? static_cast<PseudoElement>(owner.pseudo_element) : Optional<PseudoElement> {} };+ GC::Ptr<Animations::AnimationTimeline> timeline = target.document().named_timelines().target_timeline(target, Utf16FlyString::from_raw(state.named_timeline));+ if (timeline.ptr() == static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&animation.record())))+ return false;+ HTML::TemporaryExecutionContext context { HTML::relevant_realm(Animations::relevant_global_object_of(animation)) };+ Animations::RustFFI::animations_animation_set_timeline(&animation.record(), timeline ? &timeline->record() : nullptr, Animations::perform_host_effect);+ return true;}}diff --git a/Libraries/LibWeb/CSS/CSSAnimation.h b/Libraries/LibWeb/CSS/CSSAnimation.hindex c1be707adce..40d49045016 100644--- a/Libraries/LibWeb/CSS/CSSAnimation.h+++ b/Libraries/LibWeb/CSS/CSSAnimation.h@@ -6,118 +6,44 @@#pragma once-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/CSS/CSSAnimationProperties.h>-#include <LibWeb/CSS/EasingFunction.h>-#include <LibWeb/CSS/StyleValues/StyleValue.h>+#include <LibWeb/Animations/AnimationEffect.h>+#include <LibWeb/Animations/RecordHandles.h>-namespace Web::CSS {--// https://www.w3.org/TR/css-animations-2/#cssanimation-class CSSAnimation : public Animations::Animation {- WEB_WRAPPABLE(CSSAnimation, Animations::Animation);- GC_DECLARE_ALLOCATOR(CSSAnimation);--public:- static GC::Ref<CSSAnimation> create(HTML::EnvironmentSettingsObject&);-- // A new AnimationEvent for this animation that bubbles, which is implemented in Rust.- GC::Ref<DOM::Event> create_event(DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);-- Utf16FlyString const& animation_name() const { return m_animation_name; }- void set_animation_name(Utf16FlyString const& animation_name) { m_animation_name = animation_name; }+namespace Web::CSS::ComputedValuesFFI {- virtual Animations::AnimationClass animation_class() const override;- virtual int class_specific_composite_order(GC::Ref<Animations::Animation> other) const override;+struct FfiComputedAnimation;- // Applies a plan's definition, whose keyframes the caller gives the animation's effect.- void apply_css_properties(AnimationProperties const&, Animations::KeyframeEffect::KeyFrameSet const* keyframe_set, DOM::AbstractElement timeline_target);-- void set_animation_name_index(size_t index);+}- EasingFunction const& default_easing() const { return m_default_easing; }+namespace Web::CSS {- virtual void set_timeline_for_bindings(GC::Ptr<Animations::AnimationTimeline> timeline) override;- virtual WebIDL::ExceptionOr<void> set_range_start_for_bindings(Animations::TimelineRangeBindingValue const&) override;- virtual WebIDL::ExceptionOr<void> set_range_end_for_bindings(Animations::TimelineRangeBindingValue const&) override;+// https://www.w3.org/TR/css-animations-2/#cssanimation+// What the style engine does with the records of CSS animations, whose objects Bindings/Rust/src/css implements.+class CSSAnimation {+public:+ // A new AnimationEvent for `animation`, a CSS animation, that bubbles, which is implemented in Rust.+ static GC::Ref<DOM::Event> create_event(Animations::AnimationRef const& animation, DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);- // Looks the named timeline the animation follows up again.- void update_named_timeline();- // A removed animation no longer follows its named timeline.- void stop_following_named_timeline() { m_named_timeline_source.clear(); }+ // https://drafts.csswg.org/css-animations-1/#animations+ // Creates the CSS animation `owner` runs for the definition a style computation computed, `definition`, at+ // position `name_index` of its animation-name, running `keyframe_set`.+ static Animations::AnimationRef create(DOM::AbstractElement owner, ComputedValuesFFI::FfiComputedAnimation const& definition, Animations::KeyframeSetHandle keyframe_set, size_t name_index);- virtual WebIDL::ExceptionOr<void> set_start_time_for_bindings(Animations::NullableCSSNumberish const&) override;- virtual WebIDL::ExceptionOr<void> set_current_time_for_bindings(Animations::NullableCSSNumberish const&) override;- virtual WebIDL::ExceptionOr<void> set_playback_rate(double) override;- virtual void cancel(Animations::Animation::ShouldInvalidate = Animations::Animation::ShouldInvalidate::Yes) override;- virtual WebIDL::ExceptionOr<void> play(Animations::Animation::ShouldInvalidate = Animations::Animation::ShouldInvalidate::Yes) override;- virtual WebIDL::ExceptionOr<void> pause() override;- virtual WebIDL::ExceptionOr<void> update_playback_rate(double) override;- virtual WebIDL::ExceptionOr<void> reverse() override;+ static Utf16FlyString animation_name(Animations::AnimationRef const&);- void play_from_css();- void pause_from_css();+ // Applies the definition a style computation computed, `definition`, to the CSS animation `animation`, whose+ // keyframes the caller gives its effect.+ static void apply_css_properties(Animations::AnimationRef const& animation, ComputedValuesFFI::FfiComputedAnimation const& definition, DOM::AbstractElement timeline_target);- Optional<CSS::AnimationPlayState> last_css_animation_play_state() const { return m_last_css_animation_play_state; }- void set_last_css_animation_play_state(CSS::AnimationPlayState state) { m_last_css_animation_play_state = state; }+ static void set_animation_name_index(Animations::AnimationRef const&, size_t index);- // The definition the last plan applied, which the style engine compares the next plan's against.- StyleEngineFFI::FfiAppliedAnimationDefinition const& applied_definition() const { return m_applied_definition; }+ // Looks the named timeline the CSS animation follows up again from its owning element, answering whether that+ // changed its timeline.+ static bool update_named_timeline(Animations::AnimationRef const&);private:- struct AppliedCSSProperties {- Variant<double, Utf16String> duration;- EasingFunction timing_function;- double iteration_count;- AnimationDirection direction;- AnimationPlayState play_state;- double delay;- AnimationFillMode fill_mode;- AnimationComposition composition;- Animations::AnimationAttachmentRange range;-- bool operator==(AppliedCSSProperties const&) const = default;- };-- explicit CSSAnimation(HTML::EnvironmentSettingsObject&);-- virtual bool is_css_animation() const override { return true; }-- // https://drafts.csswg.org/css-animations-2/#dom-cssanimation-animationname- Utf16FlyString m_animation_name;-- // https://drafts.csswg.org/css-animations-1/#animation-timing-function- // The default per-keyframe easing, from the animation-timing-function property on the element.- EasingFunction m_default_easing { EasingFunction::ease() };-- HashTable<CSS::PropertyID> m_ignored_css_properties;-- Optional<CSS::AnimationPlayState> m_last_css_animation_play_state;- Optional<AppliedCSSProperties> m_applied_css_properties;-- // What the style computation last computed for this animation, as computed values rather than- // the easings and enums `m_applied_css_properties` holds, with the keyframe set and the timing- // function and range calculations it names, which the animation retains for as long as it names them.- StyleEngineFFI::FfiAppliedAnimationDefinition m_applied_definition {};- RefPtr<Animations::KeyframeEffect::KeyFrameSet const> m_applied_keyframe_set;- Animations::AnimationAttachmentRange m_applied_definition_range;- RustStyleValueHandle m_applied_timing_function_value;-- bool m_script_overrode_play_state { false };- bool m_applying_css_play_state { false };-- size_t m_animation_name_index { 0 };-- void mark_script_play_state_override();-- virtual void visit_edges(Cell::Visitor&) override;-- struct NamedTimelineSource {- Utf16FlyString name;- DOM::AbstractElement target;- };- Optional<NamedTimelineSource> m_named_timeline_source;+ using Flag = Animations::RustFFI::CssAnimationFlag;+ static bool has_flag(Animations::AnimationRef const&, Flag);};}diff --git a/Libraries/LibWeb/CSS/CSSAnimation.idl b/Libraries/LibWeb/CSS/CSSAnimation.idlindex a07e883b652..67a12a60e14 100644--- a/Libraries/LibWeb/CSS/CSSAnimation.idl+++ b/Libraries/LibWeb/CSS/CSSAnimation.idl@@ -1,5 +1,5 @@// https://drafts.csswg.org/css-animations-2/#cssanimation-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface CSSAnimation : Animation {readonly attribute CSSOMString animationName;};diff --git a/Libraries/LibWeb/CSS/CSSAnimationProperties.h b/Libraries/LibWeb/CSS/CSSAnimationProperties.hdeleted file mode 100644index 2274b35f22a..00000000000--- a/Libraries/LibWeb/CSS/CSSAnimationProperties.h+++ /dev/null@@ -1,60 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <AK/Utf16FlyString.h>-#include <AK/Utf16String.h>-#include <AK/Variant.h>-#include <LibGC/Ptr.h>-#include <LibWeb/Animations/TimelineRange.h>-#include <LibWeb/CSS/ComputedValues.h>-#include <LibWeb/CSS/EasingFunction.h>-#include <LibWeb/CSS/StyleValues/RustStyleValueHandle.h>-#include <LibWeb/Forward.h>--namespace Web::CSS {--// The timeline an animation definition asks for. A scroll timeline is a GC object, and a definition-// is built for every animation on every style recomputation while the timeline it names almost-// never changes, so the definition carries the description and the object is materialized only-// where one is actually needed.-struct AnimationTimelineSource {- enum class Kind : u8 {- Document,- None,- Scroll,- View,- Named,- };-- Kind kind { Kind::Document };- Scroller scroller {};- Axis axis {};- Animations::ViewTimelineInset view_inset {};- Utf16FlyString name {};-- bool operator==(AnimationTimelineSource const&) const = default;-};--struct AnimationProperties {- Variant<double, Utf16String> duration;- EasingFunction timing_function;- double iteration_count;- AnimationDirection direction;- AnimationPlayState play_state;- double delay;- AnimationFillMode fill_mode;- AnimationComposition composition;- Utf16FlyString name;- AnimationTimelineSource timeline;- Animations::AnimationAttachmentRange range;- // The computed `animation-timing-function` the easing was parsed out of, which the style engine- // compares the next computation's against.- RustStyleValueHandle timing_function_value;-};--}diff --git a/Libraries/LibWeb/CSS/CSSTransition.cpp b/Libraries/LibWeb/CSS/CSSTransition.cppindex 6b83049217a..1ac9508e3f2 100644--- a/Libraries/LibWeb/CSS/CSSTransition.cpp+++ b/Libraries/LibWeb/CSS/CSSTransition.cpp@@ -7,8 +7,7 @@#include <LibGC/Heap.h>#include <LibJS/HostClassBuilder.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Bindings/WrapperWorld.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/CSS/CSSStyleDeclaration.h>#include <LibWeb/CSS/CSSTransition.h>#include <LibWeb/CSS/PropertyID.h>@@ -27,20 +26,17 @@ namespace Web::CSS {extern "C" {// Defined in Bindings/Rust/src/css/exports.rs.-void* web_transition_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, void* animation);+void* web_transition_event_create(JSVM*, void* realm, FlatPtr event_name, FlatPtr name, double elapsed_time, FlatPtr pseudo_element, Animations::RustFFI::AnimationCell const* animation);}-GC::Ref<DOM::Event> CSSTransition::create_event(DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element)+GC::Ref<DOM::Event> CSSTransition::create_event(Animations::AnimationRef const& transition, DOM::Document const& document, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element){auto& realm = HTML::relevant_realm(document);- auto wrapper = Bindings::wrap(Bindings::host_defined_wrapper_world(realm), realm, GC::Ref<CSSTransition> { *this });- auto* event = web_transition_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), transition_property().to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), JS::HostABI::object_to_abi(wrapper.ptr()));+ auto* event = web_transition_event_create(JS::HostABI::vm_to_abi(realm.vm()), &realm, type.to_utf16_string().into_raw(), transition_property_name_and_id(transition).name().to_utf16_string().into_raw(), elapsed_time, move(pseudo_element).into_raw(), &transition.record());return GC::Ref { *static_cast<DOM::Event*>(static_cast<GC::Cell*>(event)) };}-GC_DEFINE_ALLOCATOR(CSSTransition);--GC::Ref<CSSTransition> CSSTransition::start_a_provisional_transition(+Animations::AnimationRef CSSTransition::start_a_provisional_transition(DOM::AbstractElement abstract_element,PropertyNameAndID property,size_t transition_generation,@@ -53,86 +49,20 @@ GC::Ref<CSSTransition> CSSTransition::start_a_provisional_transition(double reversing_shortening_factor,EasingFunction timing_function){- auto& environment = abstract_element.document().relevant_settings_object();- return GC::Heap::the().allocate<CSSTransition>(environment, abstract_element, move(property), transition_generation, delay, start_time, end_time, start_value, end_value, reversing_adjusted_start_value, reversing_shortening_factor, move(timing_function));-}--Utf16FlyString const& CSSTransition::transition_property() const-{- return m_transition_property.name();-}--Animations::AnimationClass CSSTransition::animation_class() const-{- return Animations::AnimationClass::CSSTransition;-}--int CSSTransition::class_specific_composite_order(GC::Ref<Animations::Animation> other_animation) const-{- auto other = GC::Ref { as<CSSTransition>(*other_animation) };-- // Within the set of CSS Transitions, two animations A and B are sorted in composite order (first to last) as- // follows:-- // 1. If neither A nor B has an owning element, sort based on their relative position in the global animation list.- if (!owning_element().has_value() && !other->owning_element().has_value())- return global_animation_list_order() - other->global_animation_list_order();-- // 2. Otherwise, if only one of A or B has an owning element, let the animation with an owning element sort first.- if (owning_element().has_value() && !other->owning_element().has_value())- return -1;- if (!owning_element().has_value() && other->owning_element().has_value())- return 1;-- // 3. Otherwise, if the owning element of A and B differs, sort A and B by tree order of their corresponding owning- // elements. With regard to pseudo-elements, the sort order is as follows:- // - element- // - ::marker- // - ::before- // - any other pseudo-elements not mentioned specifically in this list, sorted in ascending order by the Unicode- // codepoints that make up each selector- // - ::after- // - element children- if (owning_element() != other->owning_element()) {- // FIXME: Actually sort by tree order- return 0;- }-- // 4. Otherwise, if A and B have different transition generation values, sort by their corresponding transition- // generation in ascending order.- if (m_transition_generation != other->m_transition_generation)- return m_transition_generation - other->m_transition_generation;-- // 5. Otherwise, sort A and B in ascending order by the Unicode codepoints that make up the expanded transition- // property name of each transition (i.e. without attempting case conversion and such that ‘-moz-column-width’- // sorts before ‘column-width’).- return transition_property() <=> other->transition_property();-}+ Animations::RustFFI::FfiCssTransition description {+ .generation = transition_generation,+ .start_time = start_time + delay,+ .end_time = end_time + delay,+ .reversing_shortening_factor = reversing_shortening_factor,+ .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,+ .start_value = start_value->rust_style_value_data(),+ .end_value = end_value->rust_style_value_data(),+ .reversing_adjusted_start_value = reversing_adjusted_start_value->rust_style_value_data(),+ .property_id = to_underlying(property.id()),+ };+ // NB: Script gets the object of the transition, a CSSTransition, as it first asks for it.+ auto transition = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_css_transition_create(&description));-CSSTransition::CSSTransition(- HTML::EnvironmentSettingsObject& environment,- DOM::AbstractElement abstract_element,- PropertyNameAndID property,- size_t transition_generation,- double delay,- double start_time,- double end_time,- NonnullRefPtr<StyleValue const> start_value,- NonnullRefPtr<StyleValue const> end_value,- NonnullRefPtr<StyleValue const> reversing_adjusted_start_value,- double reversing_shortening_factor,- EasingFunction timing_function)- : Animations::Animation(environment)- , m_transition_property(move(property))- , m_transition_generation(transition_generation)- , m_start_time(start_time + delay)- , m_end_time(end_time + delay)- , m_start_value(move(start_value))- , m_end_value(move(end_value))- , m_reversing_adjusted_start_value(move(reversing_adjusted_start_value))- , m_reversing_shortening_factor(reversing_shortening_factor)- , m_keyframe_effect(Animations::KeyframeEffect::create())-{// FIXME:// Transitions generated using the markup defined in this specification are not added to the global animation list// when they are created. Instead, these animations are appended to the global animation list at the first moment@@ -141,67 +71,68 @@ CSSTransition::CSSTransition(// Construct a KeyframesEffect for our animation// NB: The current style computation collects this effect before publishing its result, so scheduling a second- // animated style update here would evaluate the same transition twice.- m_keyframe_effect->set_target(abstract_element, Animations::KeyframeEffect::InvalidateEffect::No);- m_keyframe_effect->set_specified_start_delay(delay);- m_keyframe_effect->set_specified_iteration_duration(end_time - start_time);- // AD-HOC: CSS Transitions require the start value to apply during transition-delay. A default KeyframeEffect does- // not fill in the before phase, so use backwards fill to keep the transition value in the cascade until- // the active interval starts.- m_keyframe_effect->set_fill_mode(Animations::FillMode::Backwards);- // https://drafts.csswg.org/web-animations-2/#updating-animationeffect-timing- // Timing properties may also be updated due to a style change. Any change to a CSS animation property that affects- // timing requires rerunning the procedure to normalize specified timing.- m_keyframe_effect->normalize_specified_timing();- m_keyframe_effect->set_timing_function(move(timing_function));-- auto key_frame_set = adopt_ref(*new Animations::KeyframeEffect::KeyFrameSet);- key_frame_set->computed_value_zoom = abstract_element.computed_style()->effective_zoom();- Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame initial_keyframe;- initial_keyframe.properties.set(m_transition_property, RustStyleValueHandle::retained(m_start_value->rust_style_value_data()));-- Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame final_keyframe;- final_keyframe.properties.set(m_transition_property, RustStyleValueHandle::retained(m_end_value->rust_style_value_data()));-- key_frame_set->keyframes_by_key.insert(0, initial_keyframe);- key_frame_set->keyframes_by_key.insert(100 * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor, final_keyframe);-- m_keyframe_effect->set_key_frame_set(key_frame_set);- set_timeline(abstract_element.document().timeline());- set_owning_element(abstract_element);- set_provisional_effect(m_keyframe_effect);-- HTML::TemporaryExecutionContext context(environment);- play(Animations::Animation::ShouldInvalidate::No).release_value_but_fixme_should_propagate_errors();+ // animated style update here would evaluate the same transition twice. The record keeps the effect the+ // transition is started with.+ auto keyframe_effect_record = Animations::EffectRef::create_keyframe_effect();+ keyframe_effect_record.set_target(abstract_element, Animations::EffectRef::InvalidateEffect::No);+ keyframe_effect_record.set_keyframe_set(Animations::KeyframeSetHandle::adopt(Animations::RustFFI::animations_keyframe_set_for_transition(+ to_underlying(property.id()),+ property.is_custom_property() ? property.name().raw_identity() : 0,+ start_value->rust_style_value_data(),+ end_value->rust_style_value_data(),+ static_cast<float>(abstract_element.computed_style()->effective_zoom()))));+ Animations::set_owning_element(transition, abstract_element);+ auto* timeline = abstract_element.document().timeline().ptr();+ Animations::RustFFI::animations_animation_set_timeline(&transition.record(), timeline ? &timeline->record() : nullptr, Animations::perform_host_effect);++ // NB: The record sets the timing of the effect, sets it as the transition's associated effect and plays the+ // transition, which creates its ready promise.+ Utf16FlyString timing_function_serialization { timing_function.to_utf16_string() };+ Animations::RustFFI::FfiProvisionalTransitionTiming timing {+ .delay = delay,+ .duration = end_time - start_time,+ .timing_function = timing_function.descriptor(),+ .timing_function_serialization = timing_function_serialization.raw_identity(),+ };+ HTML::TemporaryExecutionContext context(abstract_element.document().relevant_settings_object());+ Animations::RustFFI::animations_css_transition_start_provisionally(&transition.record(), &keyframe_effect_record.record(), &timing, Animations::perform_host_effect);+ return transition;}-void CSSTransition::commit_provisional_transition()+PropertyNameAndID CSSTransition::transition_property_name_and_id(Animations::AnimationRef const& transition){- VERIFY(m_is_provisional);- auto target = m_keyframe_effect->target();- VERIFY(target);- auto owner = owning_element();- VERIFY(owner.has_value());- target->associate_with_animation(*this);- target->set_transition(owner->pseudo_element(), m_transition_property, *this);- m_is_provisional = false;+ auto state = Animations::RustFFI::animations_css_transition(&transition.record());+ if (state.custom_name)+ return PropertyNameAndID::from_name(Utf16FlyString::from_raw(state.custom_name)).release_value();+ return PropertyNameAndID::from_id(static_cast<PropertyID>(state.property_id));}-void CSSTransition::discard_provisional_transition()+NonnullRefPtr<StyleValue const> CSSTransition::transition_start_value(Animations::AnimationRef const& transition){- VERIFY(m_is_provisional);- set_timeline({});- discard_provisional_effect();- m_is_provisional = false;+ auto state = Animations::RustFFI::animations_css_transition(&transition.record());+ return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(state.start_value)));}-// The identity the style engine describes the effect of `transition` by, or 0.-static u64 effect_identity(CSSTransition const& transition)+void CSSTransition::commit_provisional_transition(Animations::AnimationRef const& transition, Animations::RustFFI::TransitionOrigin origin){+ // NB: The associated effect of a provisional transition is the effect it was started with.auto effect = transition.effect();- if (!effect || !effect->is_keyframe_effect())- return 0;- return static_cast<Animations::KeyframeEffect const&>(*effect).animation_preparation_identity();+ VERIFY(effect.has_value());+ auto* target = effect->target();+ VERIFY(target);+ auto owner = Animations::RustFFI::animations_animation_owning_element(&transition.record());+ VERIFY(owner.element);+ Optional<PseudoElement> pseudo_element;+ if (owner.has_pseudo_element)+ pseudo_element = static_cast<PseudoElement>(owner.pseudo_element);+ target->commit_provisional_transition(pseudo_element, transition, origin);+}++void CSSTransition::discard_provisional_transition(Animations::AnimationRef const& transition)+{+ Animations::RustFFI::animations_animation_set_timeline(&transition.record(), nullptr, Animations::perform_host_effect);+ // NB: The record lets the transition have no associated effect.+ Animations::RustFFI::animations_css_transition_discard_provisional(&transition.record());}void CSSTransition::adopt_lane_transitions(DOM::Document& document)@@ -218,49 +149,48 @@ void CSSTransition::adopt_lane_transitions(DOM::Document& document)if (!element || !element->is_connected())return;// A transition the lane started that the host took in already runs from when the lane started it.- auto runs_as_lane_does = [&](CSSTransition const& transition, PropertyNameAndID const& property) {- return any_of(lane_transitions, [&](auto const& lane_transition) {- if (lane_transition.property_id != to_underlying(property.id()))- return false;- if (lane_transition.host_identity != 0)- return lane_transition.host_identity == effect_identity(transition);- return transition.m_adopted_from_lane && transition.transition_start_time() == lane_transition.start_time + lane_transition.delay;- });+ auto runs_as_lane_does = [&](Animations::AnimationRef const& transition) {+ return Animations::RustFFI::animations_css_transition_runs_as_lane_does(&transition.record(), lane_transitions);};- // The transitions of the host's the lane's steps ended as they ran end as they did, and so does one the lane- // started that the host took in and the lane no longer runs. One the steps saw end by itself ends as it does,- // with its events. One the host started since the lane forked is its own: the lane decided nothing over it, and- // the host decides what becomes of it, and of its property, in its turn. So does one script finished meanwhile.- GC::RootVector<GC::Ref<CSSTransition>> ended;+ // NB: The record of each running transition decides what becomes of it (see LaneAdoption). One the steps saw+ // end by itself ends as it does, with its events, and so does one script finished meanwhile.+ GC::RootVector<Animations::AnimationRef> ended;Vector<PropertyNameAndID> host_decides;- if (auto const* existing = element->existing_transitions({})) {- for (auto const& [property, transition] : *existing) {- if (transition->is_idle() || transition->is_finished() || runs_as_lane_does(transition, property))- continue;- auto identity = effect_identity(transition);- if (cancelled.contains_slow(identity)) {- ended.append(transition);- } else if (seen.contains_slow(identity)) {- continue;- } else if (transition->m_adopted_from_lane) {- ended.append(transition);- } else {- host_decides.append(property);- }+ for (auto const& transition : element->existing_transitions({})) {+ auto timing = transition.timing_state();+ if (timing.play_state == Animations::RustFFI::AnimationPlayState::Idle || timing.playback.is_finished)+ continue;+ switch (Animations::RustFFI::animations_css_transition_lane_adoption(&transition.record(), lane_transitions, cancelled, seen)) {+ case Animations::RustFFI::LaneAdoption::Stands:+ break;+ case Animations::RustFFI::LaneAdoption::Ends:+ ended.append(transition);+ break;+ case Animations::RustFFI::LaneAdoption::HostDecides:+ host_decides.append(transition_property_name_and_id(transition));+ break;}}- for (auto& transition : ended) {- transition->cancel();- element->remove_transition({}, transition->m_transition_property);+ for (auto const& transition : ended) {+ transition.cancel();+ element->remove_transition({}, transition_property_name_and_id(transition));}+ // NB: The start time of a transition is a time of the document timeline, which validating it as script sets+ // it would only read as milliseconds.+ auto set_start_time = [](Animations::AnimationRef const& transition, double start_time) {+ Animations::RustFFI::animations_animation_set_start_time(&transition.record(), Animations::to_ffi(Optional<Animations::TimeValue> { Animations::TimeValue { Animations::TimeValue::Type::Milliseconds, start_time } }), Animations::perform_host_effect);+ };// A transition of the host's whose play is still pending runs from when the lane took it to start.for (auto const& lane_transition : lane_transitions) {if (lane_transition.host_identity == 0)continue;auto transition = element->property_transition({}, PropertyNameAndID::from_id(static_cast<PropertyID>(lane_transition.property_id)));- if (transition && effect_identity(*transition) == lane_transition.host_identity && !transition->start_time().has_value()- && transition->pending() && transition->play_state() != Bindings::AnimationPlayState::Paused)- (void)transition->set_start_time_for_bindings(Animations::NullableCSSNumberish { lane_transition.start_time });+ if (!transition.has_value() || !Animations::RustFFI::animations_css_transition_is_host_transition_of(&transition->record(), &lane_transition))+ continue;+ auto timing = transition->timing_state();+ if (!timing.playback.start_time.has_value && (timing.playback.has_pending_play_task || timing.playback.has_pending_pause_task)+ && timing.play_state != Animations::RustFFI::AnimationPlayState::Paused)+ set_start_time(*transition, lane_transition.start_time);}for (auto const& lane_transition : lane_transitions) {if (lane_transition.host_identity != 0)@@ -268,22 +198,22 @@ void CSSTransition::adopt_lane_transitions(DOM::Document& document)auto property = PropertyNameAndID::from_id(static_cast<PropertyID>(lane_transition.property_id));if (host_decides.contains_slow(property))continue;- if (auto current = element->property_transition({}, property)) {- if (runs_as_lane_does(*current, property))+ if (auto current = element->property_transition({}, property); current.has_value()) {+ if (runs_as_lane_does(*current))continue;// A completed transition of the property gives way to the one the lane started. One the lane saw end,// which the host's timeline has yet to reach, ends now.- if (!current->is_idle() && !current->is_finished())- (void)current->finish();+ auto timing = current->timing_state();+ if (timing.play_state != Animations::RustFFI::AnimationPlayState::Idle && !timing.playback.is_finished)+ (void)Animations::RustFFI::animations_animation_finish(¤t->record(), Animations::perform_host_effect);element->remove_transition({}, property);}auto transition = start_a_provisional_transition(*element, property, document.transition_generation(),lane_transition.delay, lane_transition.start_time, lane_transition.start_time + lane_transition.duration,adopt_value(lane_transition.start_value), adopt_value(lane_transition.end_value), adopt_value(lane_transition.reversing_adjusted_start_value),lane_transition.reversing_shortening_factor, EasingFunction::from_style_value(adopt_value(lane_transition.timing_function)));- transition->commit_provisional_transition();- transition->m_adopted_from_lane = true;- (void)transition->set_start_time_for_bindings(Animations::NullableCSSNumberish { lane_transition.start_time });+ commit_provisional_transition(transition, Animations::RustFFI::TransitionOrigin::Lane);+ set_start_time(transition, lane_transition.start_time);}};// Starting and cancelling transitions settles their promises in the document's realm. The rendering update runs@@ -296,29 +226,4 @@ void CSSTransition::adopt_lane_transitions(DOM::Document& document)});}-void CSSTransition::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_cached_declaration);- visitor.visit(m_keyframe_effect);-}--double CSSTransition::style_change_event_time() const-{- return m_start_time - m_keyframe_effect->start_delay().value;-}--double CSSTransition::timing_function_output_at_time(double t) const-{- // AD-HOC: If the transition has an empty duration then we get NaN here,- // setting progress to 1 because an instant transition may be considered "finished".- double progress = 1;- if (transition_start_time() < transition_end_time())- progress = (t - transition_start_time()) / (transition_end_time() - transition_start_time());-- // FIXME: Is this before_flag value correct?- bool before_flag = t < transition_start_time();- return m_keyframe_effect->timing_function().evaluate_at(progress, before_flag);-}-}diff --git a/Libraries/LibWeb/CSS/CSSTransition.h b/Libraries/LibWeb/CSS/CSSTransition.hindex ffb717cf18c..c5b198bf639 100644--- a/Libraries/LibWeb/CSS/CSSTransition.h+++ b/Libraries/LibWeb/CSS/CSSTransition.h@@ -7,23 +7,21 @@#pragma once-#include <LibWeb/Animations/Animation.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/CSS/EasingFunction.h>#include <LibWeb/CSS/PropertyNameAndID.h>#include <LibWeb/CSS/StyleValues/StyleValue.h>namespace Web::CSS {-class CSSTransition : public Animations::Animation {- WEB_WRAPPABLE(CSSTransition, Animations::Animation);- GC_DECLARE_ALLOCATOR(CSSTransition);-+// What the style engine does with the records of CSS transitions, whose objects Bindings/Rust/src/css implements.+class CSSTransition {public:- // A new TransitionEvent for this transition that bubbles, which is implemented in Rust.- GC::Ref<DOM::Event> create_event(DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);+ // A new TransitionEvent for `transition`, a CSS transition, that bubbles, which is implemented in Rust.+ static GC::Ref<DOM::Event> create_event(Animations::AnimationRef const& transition, DOM::Document const&, Utf16FlyString const& type, double elapsed_time, Utf16String pseudo_element);// A transition is started provisionally, and associated with its target only once committed.- static GC::Ref<CSSTransition> start_a_provisional_transition(+ static Animations::AnimationRef start_a_provisional_transition(DOM::AbstractElement,PropertyNameAndID,size_t transition_generation,@@ -36,91 +34,16 @@ public:double reversing_shortening_factor,EasingFunction timing_function);- void commit_provisional_transition();- void discard_provisional_transition();+ static void commit_provisional_transition(Animations::AnimationRef const&, Animations::RustFFI::TransitionOrigin = Animations::RustFFI::TransitionOrigin::StyleChange);+ static void discard_provisional_transition(Animations::AnimationRef const&);// AD-HOC: Runs the transitions the hover of the document's clock lane left elements running beside a task, which// the screen showed, in place of those its steps ended, as the rendering update that takes them in begins.static void adopt_lane_transitions(DOM::Document&);- Utf16FlyString const& transition_property() const;-- virtual Animations::AnimationClass animation_class() const override;- virtual int class_specific_composite_order(GC::Ref<Animations::Animation> other) const override;-- double style_change_event_time() const;- double transition_start_time() const { return m_start_time; }- double transition_end_time() const { return m_end_time; }- NonnullRefPtr<StyleValue const> transition_start_value() const { return m_start_value; }- NonnullRefPtr<StyleValue const> transition_end_value() const { return m_end_value; }- NonnullRefPtr<StyleValue const> reversing_adjusted_start_value() const { return m_reversing_adjusted_start_value; }- double reversing_shortening_factor() const { return m_reversing_shortening_factor; }-- double timing_function_output_at_time(double t) const;-- // This is designed to be created from AnimationEffect::Phase.- enum class Phase : u8 {- Before,- Active,- After,- Idle,- Pending,- };- Phase previous_phase() const { return m_previous_phase; }- void set_previous_phase(Phase phase) { m_previous_phase = phase; }--private:- CSSTransition(- HTML::EnvironmentSettingsObject&,- DOM::AbstractElement,- PropertyNameAndID,- size_t transition_generation,- double delay,- double start_time,- double end_time,- NonnullRefPtr<StyleValue const> start_value,- NonnullRefPtr<StyleValue const> end_value,- NonnullRefPtr<StyleValue const> reversing_adjusted_start_value,- double reversing_shortening_factor,- EasingFunction timing_function);-- virtual void visit_edges(Cell::Visitor&) override;-- virtual bool is_css_transition() const override { return true; }-- PropertyNameAndID m_transition_property;-- // https://drafts.csswg.org/css-transitions-2/#transition-generation- size_t m_transition_generation;-- // https://drafts.csswg.org/css-transitions/#transition-start-time- double m_start_time;-- // https://drafts.csswg.org/css-transitions/#transition-end-time- double m_end_time;-- // https://drafts.csswg.org/css-transitions/#transition-start-value- NonnullRefPtr<CSS::StyleValue const> m_start_value;-- // https://drafts.csswg.org/css-transitions/#transition-end-value- NonnullRefPtr<CSS::StyleValue const> m_end_value;-- // https://drafts.csswg.org/css-transitions/#transition-reversing-adjusted-start-value- NonnullRefPtr<CSS::StyleValue const> m_reversing_adjusted_start_value;-- // https://drafts.csswg.org/css-transitions/#transition-reversing-shortening-factor- double m_reversing_shortening_factor;-- GC::Ref<Animations::KeyframeEffect> m_keyframe_effect;-- GC::Ptr<CSS::CSSStyleDeclaration const> m_cached_declaration;-- bool m_is_provisional { true };-- // Whether the transition is one the hover of a clock lane started, which the host took in.- bool m_adopted_from_lane { false };+ static PropertyNameAndID transition_property_name_and_id(Animations::AnimationRef const&);- Phase m_previous_phase { Phase::Idle };+ static NonnullRefPtr<StyleValue const> transition_start_value(Animations::AnimationRef const&);};}diff --git a/Libraries/LibWeb/CSS/CSSTransition.idl b/Libraries/LibWeb/CSS/CSSTransition.idlindex 3a554cbe772..7b6f2610c5a 100644--- a/Libraries/LibWeb/CSS/CSSTransition.idl+++ b/Libraries/LibWeb/CSS/CSSTransition.idl@@ -1,5 +1,5 @@// https://drafts.csswg.org/css-transitions-2/#the-CSSTransition-interface-[Exposed=Window]+[Exposed=Window, ImplementedIn=Rust]interface CSSTransition : Animation {readonly attribute CSSOMString transitionProperty;};diff --git a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cppindex 0973555e1f6..f7b7afb0048 100644--- a/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp+++ b/Libraries/LibWeb/CSS/DevToolsAppliedStyleRules.cpp@@ -24,9 +24,7 @@#include <LibGC/Heap.h>#include <LibGfx/Font/FontDatabase.h>#include <LibWeb/Animations/AnimationEffect.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/ScrollTimeline.h>-#include <LibWeb/Animations/ViewTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>#include <LibWeb/CSS/CSSAnimation.h>#include <LibWeb/CSS/CSSImportRule.h>diff --git a/Libraries/LibWeb/CSS/EasingFunction.cpp b/Libraries/LibWeb/CSS/EasingFunction.cppindex 3d41b844d70..b3f5fd1691c 100644--- a/Libraries/LibWeb/CSS/EasingFunction.cpp+++ b/Libraries/LibWeb/CSS/EasingFunction.cpp@@ -6,6 +6,9 @@#include <LibWeb/CSS/EasingFunction.h>#include <LibWeb/CSS/Enums.h>+#include <LibWeb/CSS/Parser/Parser.h>+#include <LibWeb/CSS/PropertyID.h>+#include <LibWeb/CSS/StyleValues/StyleValueList.h>namespace Web::CSS {@@ -20,20 +23,6 @@ EasingFunction EasingFunction::linear()return easing;}-// https://drafts.csswg.org/css-easing-2/#valdef-cubic-bezier-easing-function-ease-EasingFunction EasingFunction::ease()-{- // Equivalent to cubic-bezier(0.25, 0.1, 0.25, 1).- EasingFunction easing;- easing.m_descriptor.kind = Compositing::RustFFI::FfiEasingKind::CubicBezier;- easing.m_descriptor.x1 = 0.25;- easing.m_descriptor.y1 = 0.1;- easing.m_descriptor.x2 = 0.25;- easing.m_descriptor.y2 = 1;- easing.m_text = "ease"_utf16;- return easing;-}-EasingFunction EasingFunction::from_style_value(StyleValue const& style_value){EasingFunction easing;@@ -48,10 +37,22 @@ EasingFunction EasingFunction::from_style_value(StyleValue const& style_value)return easing;}-double EasingFunction::evaluate_at(double input_progress, bool before_flag) const+Optional<EasingFunction> EasingFunction::parse(Utf16View value){- auto descriptor = this->descriptor();- return StyleValueFFI::rust_evaluate_easing(&descriptor, input_progress, before_flag);+ if (auto style_value = parse_css_value(Parser::ParsingParams(), value, PropertyID::AnimationTimingFunction)) {+ if (style_value->is_unresolved() || style_value->is_css_wide_keyword())+ return {};++ auto easing_values = style_value->as_value_list().values();++ if (easing_values.size() != 1)+ return {};++ // FIXME: We should absolutize the style value to resolve relative lengths within calcs+ return from_style_value(easing_values[0]);+ }++ return {};}}diff --git a/Libraries/LibWeb/CSS/EasingFunction.h b/Libraries/LibWeb/CSS/EasingFunction.hindex c0f3fcb9509..1f089ed2eaf 100644--- a/Libraries/LibWeb/CSS/EasingFunction.h+++ b/Libraries/LibWeb/CSS/EasingFunction.h@@ -17,9 +17,11 @@ public:using LinearPoint = Compositing::RustFFI::FfiLinearEasingPoint;static EasingFunction linear();- static EasingFunction ease();static EasingFunction from_style_value(StyleValue const&);+ // The easing function the text parses as with the <easing-function> production, as the easing member of+ // EffectTiming parses it.+ static Optional<EasingFunction> parse(Utf16View);// The descriptor borrows this function's control points.Descriptor descriptor() const@@ -40,7 +42,6 @@ public:return descriptor;}- double evaluate_at(double input_progress, bool before_flag) const;Utf16String const& to_utf16_string() const { return m_text; }// NB: The serialization is of the value the function was made from, so it tells functions apart.diff --git a/Libraries/LibWeb/CSS/RustRule.h b/Libraries/LibWeb/CSS/RustRule.hindex 3cd2ca1100b..4f6c595962d 100644--- a/Libraries/LibWeb/CSS/RustRule.h+++ b/Libraries/LibWeb/CSS/RustRule.h@@ -112,13 +112,7 @@ public:});return name;}- void for_each_keyframe(Function<void(ReadonlySpan<double>, RustDeclarationBlockSnapshot const&)> const& callback) const- {- Parser::ValueParserFFI::rust_rule_view_keyframes(&m_view, &callback, [](void const* context, double const* keys, size_t count, Parser::ValueParserFFI::DeclarationBlockHeader const* declarations) {- RustDeclarationBlockSnapshot snapshot { Parser::ValueParserFFI::rust_declaration_data_retain(declarations) };- (*static_cast<Function<void(ReadonlySpan<double>, RustDeclarationBlockSnapshot const&)> const*>(context))({ keys, count }, snapshot);- });- }+ Parser::ValueParserFFI::NativeRuleView const& native_view() const { return m_view; }private:Parser::ValueParserFFI::NativeRuleView const& m_view;diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cppindex ae162de8c7d..8dc81121d0b 100644--- a/Libraries/LibWeb/CSS/StyleComputer.cpp+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp@@ -27,9 +27,7 @@#include <LibGC/Heap.h>#include <LibGfx/Font/FontDatabase.h>#include <LibWeb/Animations/AnimationEffect.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/ScrollTimeline.h>-#include <LibWeb/Animations/ViewTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/Bindings/PrincipalHostDefined.h>#include <LibWeb/CSS/CSSAnimation.h>#include <LibWeb/CSS/CSSImportRule.h>@@ -76,6 +74,7 @@#include <LibWeb/CSS/StyleValues/TimeStyleValue.h>#include <LibWeb/CSS/StyleValues/TransformationStyleValue.h>#include <LibWeb/CSS/StyleValues/UnresolvedStyleValue.h>+#include <LibWeb/CSS/Zoom.h>#include <LibWeb/DOM/Attr.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Element.h>@@ -108,7 +107,8 @@ namespace Web::CSS {void StyleComputer::AnimationRefreshRequest::visit_edges(GC::Cell::Visitor& visitor) const{abstract_element.visit_edges(visitor);- visitor.visit(effects);+ for (auto const& effect : effects)+ effect.visit_edges(visitor);}void StyleComputer::SampledAnimationOverlay::visit_edges(GC::Cell::Visitor& visitor) const@@ -348,8 +348,11 @@ void StyleComputer::visit_edges(Visitor& visitor)for (auto const& state : m_provisional_transition_states) {visitor.visit(state.element);- visitor.visit(state.committed_transition);- visitor.visit(state.proposed_transition);+ // NB: An AnimationRef visits the Animation of its record, which keeps the elements the record names alive.+ if (state.committed_transition.has_value())+ state.committed_transition->visit_edges(visitor);+ if (state.proposed_transition.has_value())+ state.proposed_transition->visit_edges(visitor);}}@@ -384,15 +387,15 @@ void StyleComputer::record_transition_baseline_for_later_passes(DOM::AbstractEle// started it, but it is not associated with its target until the stabilization epoch commits. An// animated style update running before that commit has to collect it anyway, or it rebuilds the// target's style without the transition's value and clobbers it.-void StyleComputer::for_each_provisional_transition_effect(DOM::AbstractElement const& abstract_element, Function<void(Animations::KeyframeEffect&)> const& callback) const+void StyleComputer::for_each_provisional_transition_effect(DOM::AbstractElement const& abstract_element, Function<void(Animations::EffectRef const&)> const& callback) const{for (auto const& state : m_provisional_transition_states) {if (state.element.ptr() != &abstract_element.element() || state.pseudo_element != abstract_element.pseudo_element())continue;- if (!state.proposed_transition)+ if (!state.proposed_transition.has_value())continue;- if (auto effect = state.proposed_transition->effect(); effect && effect->is_keyframe_effect())- callback(static_cast<Animations::KeyframeEffect&>(*effect));+ if (auto effect = state.proposed_transition->effect(); effect.has_value())+ callback(*effect);}}@@ -406,13 +409,13 @@ void StyleComputer::commit_transition_stabilization_epoch()element.remove_transition(state.pseudo_element, state.property);};auto cancel_and_remove_committed_transition = [&] {- VERIFY(state.committed_transition);+ VERIFY(state.committed_transition.has_value());state.committed_transition->cancel();remove_committed_transition();};auto commit_proposed_transition = [&] {- VERIFY(state.proposed_transition);- state.proposed_transition->commit_provisional_transition();+ VERIFY(state.proposed_transition.has_value());+ CSSTransition::commit_provisional_transition(*state.proposed_transition);HTML::note_rendering_trace_event("transition started"sv);};@@ -424,7 +427,7 @@ void StyleComputer::commit_transition_stabilization_epoch()remove_committed_transition();break;case Cancel:- VERIFY(state.committed_transition);+ VERIFY(state.committed_transition.has_value());state.committed_transition->cancel();break;case Start:@@ -495,8 +498,7 @@ struct StyleComputer::AnimationSample {ComputedStyleWorkingSet& computed_properties;} context;AnimationSamplePurpose purpose { AnimationSamplePurpose::Rendering };- Vector<ComputedValuesFFI::FfiSampledAnimationEffect, 1> sampled_effects;- Vector<Vector<Compositing::RustFFI::FfiLinearEasingPoint>, 1> easing_points;+ Vector<Animations::RustFFI::FfiSampledEffect, 1> sampled_effects;Vector<u8> document_supported_color_scheme_codes;// The custom-property environments whose stores the input names.RefPtr<CustomPropertyData const> custom_property_data;@@ -506,7 +508,7 @@ struct StyleComputer::AnimationSample {ComputedValuesFFI::FfiHostAnimationSample input {};};-void StyleComputer::collect_animations_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const+void StyleComputer::collect_animations_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<Animations::EffectRef> effects, ComputedStyleWorkingSet& computed_properties) const{// A refresh samples over the record the element holds, which the working set was reconstructed from.collect_animation_effects_into(read, abstract_element, effects, computed_properties);@@ -543,50 +545,34 @@ void StyleComputer::finish_animation_refresh(Layout::BegunRead const& read, DOM:finalize_animated_box_type(read, computed_properties, abstract_element);}-void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const+void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<Animations::EffectRef> effects, ComputedStyleWorkingSet& computed_properties) const{auto sample = begin_animation_sample(read, abstract_element, effects, computed_properties);auto result = ComputedValuesFFI::rust_sample_animation_effects(&sample->input, &read);finish_animation_sample(*sample, result);}-NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::compute_style_for_animation_commit(Layout::BegunRead const& read, DOM::AbstractElement element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects) const+NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::compute_style_for_animation_commit(Layout::BegunRead const& read, DOM::AbstractElement element, ReadonlySpan<Animations::EffectRef> effects) const{auto style = reconstruct_computed_properties_for_animation(element.installed_style());auto sample = begin_animation_sample(read, element, effects, *style, AnimationSamplePurpose::CommitStyles);- with_animation_effect_descriptions(effects, [&](auto const& descriptions) {- auto result = ComputedValuesFFI::rust_sample_animation_effects_for_commit_styles(&sample->input, &descriptions, &read);- finish_animation_sample(*sample, result);- });+ auto result = ComputedValuesFFI::rust_sample_animation_effects_for_commit_styles(&sample->input, &read);+ finish_animation_sample(*sample, result);return style;}-NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties, AnimationSamplePurpose purpose) const+NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<Animations::EffectRef> effects, ComputedStyleWorkingSet& computed_properties, AnimationSamplePurpose purpose) const{auto sample = make<AnimationSample>(*this, abstract_element, computed_properties);sample->purpose = purpose;- // The style engine samples each effect from the description it holds of it, kept current here, right before- // the element is sampled.- auto const animation_slot = abstract_element.pseudo_element().map([](auto pseudo_element) { return static_cast<u8>(to_underlying(pseudo_element) + 1); }).value_or(0);- if (purpose == AnimationSamplePurpose::Rendering)- 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 style engine samples each effect from the description its record keeps, which the sample publishes to the+ // engine where the engine does not have it yet, with its animation's timing and timeline as they stand.auto& sampled_effects = sample->sampled_effects;- auto& easing_points = sample->easing_points;sampled_effects.ensure_capacity(effects.size());- easing_points.ensure_capacity(effects.size());- for (auto effect : effects) {- auto animation = effect->associated_animation();- if (!animation)- continue;- easing_points.unchecked_append({});+ for (auto const& effect : effects) {sampled_effects.unchecked_append({- .identity = effect->animation_preparation_identity(),- .generation = effect->animation_preparation_generation(),- .timing = effect->timing_snapshot(),- .easing = effect->timing_function().descriptor_with_points_in(easing_points.last()),+ .effect = &effect.record(),+ .animation = Animations::RustFFI::animations_effect_associated_animation(&effect.record()),});}@@ -646,6 +632,7 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sam.pseudo_kind = abstract_element.pseudo_element().map([](auto pseudo_element) { return static_cast<u8>(to_underlying(pseudo_element)); }).value_or(NumericLimits<u8>::max()),.effects = sampled_effects.data(),.effect_count = sampled_effects.size(),+ .animations = &abstract_element.element().ensure_animations(),.record = computed_properties.record(),.animated_overlay = computed_properties.animated_overlay(Badge<StyleComputer> {}),.style_record = abstract_element.installed_style().record_pointer(),@@ -681,32 +668,12 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_samreturn sample;}-Animations::BaseKeyframe::ParsedProperties StyleComputer::compute_css_keyframe_values(DOM::AbstractElement element, Vector<Animations::BaseKeyframe>& frames, Optional<Animations::KeyframeEffect::KeyFrameSet::StyleSheetResourceContext> const& resource_context) const+void StyleComputer::compute_css_keyframe_values(DOM::AbstractElement element, ReadonlySpan<ComputedValuesFFI::FfiReflectedKeyframeProperty> properties, size_t keyframe_count, ComputedValuesFFI::FfiStyleSheetResourceContext const& resource_context, void* context, CSSKeyframeValueCallback emit) const{Layout::ForcedReadScope read { element.element().document() };- auto properties = reconstruct_computed_properties_for_animation(element.installed_style());- auto sample = begin_animation_sample(read, element, {}, *properties, AnimationSamplePurpose::KeyframeReflection);- Vector<ComputedValuesFFI::FfiReflectedKeyframeProperty> declarations;- for (size_t i = 0; i < frames.size(); ++i) {- for (auto const& [property, value] : frames[i].parsed_properties()) {- declarations.append({ i, to_underlying(property.id()), value.data() });- }- }- ComputedValuesFFI::FfiStyleSheetResourceContext context {};- if (resource_context.has_value()) {- auto bytes = resource_context->base_url.bytes();- context = { bytes.data(), bytes.size(), true, resource_context->origin_clean };- }- Vector<Animations::BaseKeyframe::ParsedProperties> computed;- computed.resize(frames.size() + 1);- ComputedValuesFFI::rust_compute_css_keyframe_values(&sample->input, read, declarations.data(), declarations.size(), frames.size(), &context, &computed,- [](void* context, size_t index, u16 property, auto* value) {- auto& computed = *static_cast<Vector<Animations::BaseKeyframe::ParsedProperties>*>(context);- computed[index].set(PropertyNameAndID::from_id(static_cast<PropertyID>(property)), RustStyleValueHandle::retained(value));- });- for (size_t i = 0; i < frames.size(); ++i)- frames[i].properties = move(computed[i]);- return move(computed.last());+ auto computed_properties = reconstruct_computed_properties_for_animation(element.installed_style());+ auto sample = begin_animation_sample(read, element, {}, *computed_properties, AnimationSamplePurpose::KeyframeReflection);+ ComputedValuesFFI::rust_compute_css_keyframe_values(&sample->input, read, properties.data(), properties.size(), keyframe_count, &resource_context, context, emit);}void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedValuesFFI::FfiHostAnimationSampleResult const& result) const@@ -841,52 +808,10 @@ void StyleComputer::invalidate_animated_custom_property_readers(DOM::AbstractEle// itself, as the engine learns of the element's new environment.}-// The host's form of one animation definition a style computation decided.-static AnimationProperties animation_properties_from_ffi(ComputedValuesFFI::FfiComputedAnimation const& animation)-{- Variant<double, Utf16String> duration { animation.duration };- if (animation.duration_is_auto)- duration = "auto"_utf16;- auto timing_function_value = RustStyleValueHandle::retained(static_cast<StyleValueFFI::StyleValueData const*>(animation.timing_function));- auto timing_function = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(timing_function_value.data()));- static_assert(to_underlying(AnimationTimelineSource::Kind::Document) == to_underlying(ComputedValuesFFI::FfiAnimationTimelineKind::Document));- static_assert(to_underlying(AnimationTimelineSource::Kind::None) == to_underlying(ComputedValuesFFI::FfiAnimationTimelineKind::None));- static_assert(to_underlying(AnimationTimelineSource::Kind::Scroll) == to_underlying(ComputedValuesFFI::FfiAnimationTimelineKind::Scroll));- static_assert(to_underlying(AnimationTimelineSource::Kind::View) == to_underlying(ComputedValuesFFI::FfiAnimationTimelineKind::View));- static_assert(to_underlying(AnimationTimelineSource::Kind::Named) == to_underlying(ComputedValuesFFI::FfiAnimationTimelineKind::Named));- return {- .duration = move(duration),- .timing_function = EasingFunction::from_style_value(timing_function),- .iteration_count = animation.iteration_count,- .direction = static_cast<AnimationDirection>(animation.direction),- .play_state = static_cast<AnimationPlayState>(animation.play_state),- .delay = animation.delay,- .fill_mode = static_cast<AnimationFillMode>(animation.fill_mode),- .composition = static_cast<AnimationComposition>(animation.composition),- .name = css_string_from_rust(animation.name),- .timeline = {- .kind = static_cast<AnimationTimelineSource::Kind>(animation.timeline_kind),- .scroller = static_cast<Scroller>(animation.scroll_scroller),- .axis = static_cast<Axis>(animation.scroll_axis),- .view_inset = Animations::view_timeline_inset_from_ffi(animation.view_inset),- .name = animation.timeline_name ? css_string_from_rust(animation.timeline_name) : Utf16FlyString {},- },- .range = {- .start = { static_cast<Animations::TimelineRangeName>(animation.range_start_name), animation.range_start_px, animation.range_start_percentage, Animations::retain_calculated_offset(animation.range_start_calculated) },- .end = { static_cast<Animations::TimelineRangeName>(animation.range_end_name), animation.range_end_px, animation.range_end_percentage, Animations::retain_calculated_offset(animation.range_end_calculated) },- },- .timing_function_value = move(timing_function_value),- };-}-void StyleComputer::apply_animation_definitions(DOM::AbstractElement& abstract_element, ReadonlySpan<ComputedValuesFFI::FfiComputedAnimation> animation_definitions, bool in_display_none_subtree) const{- auto& document = abstract_element.document();-- auto const* element_animations = abstract_element.css_defined_animations();-- // If we have a nullptr for element_animations it means that the pseudo element was invalid and thus we shouldn't apply animations- if (!element_animations)+ // Only the element and its known pseudo-elements have CSS animations to apply.+ if (!Animations::Animatable::can_own_css_animations_and_transitions(abstract_element.pseudo_element()))return;// https://drafts.csswg.org/css-animations-1/#animations@@ -904,30 +829,29 @@ void StyleComputer::apply_animation_definitions(DOM::AbstractElement& abstract_e// the animations this element holds, which it publishes. See match_existing_animations(). So are the// keyframes each definition runs, from the `@keyframes` every style scope publishes.- GC::RootVector<GC::Ref<CSSAnimation>> existing_animations { element_animations->span() };+ auto existing_animations = abstract_element.element().css_defined_animations(abstract_element.pseudo_element());Vector<bool> existing_animation_was_claimed;existing_animation_was_claimed.resize(existing_animations.size());- GC::RootVector<GC::Ref<CSSAnimation>> new_animations;+ GC::RootVector<Animations::AnimationRef> new_animations;for (size_t i = animation_definitions.size(); i-- > 0;) {auto const& definition = animation_definitions[i];- auto animation_properties = animation_properties_from_ffi(definition);- auto const* keyframe_set = static_cast<Animations::KeyframeEffect::KeyFrameSet const*>(definition.keyframe_set);+ auto keyframe_set = Animations::KeyframeSetHandle::retained(static_cast<Animations::RustFFI::KeyframeSet const*>(definition.keyframe_set));auto matched_index = definition.matched_existing_index;VERIFY(matched_index < static_cast<i32>(existing_animations.size()));if (matched_index >= 0) {- auto existing_animation = existing_animations[matched_index];- VERIFY(existing_animation->animation_name() == animation_properties.name);+ auto const& existing_animation = existing_animations[matched_index];+ VERIFY(CSSAnimation::animation_name(existing_animation) == css_string_from_rust(definition.name));VERIFY(!existing_animation_was_claimed[matched_index]);existing_animation_was_claimed[matched_index] = true;- if (auto effect = existing_animation->effect()) {- as<Animations::KeyframeEffect>(*effect).set_key_frame_set(keyframe_set);- existing_animation->apply_css_properties(animation_properties, keyframe_set, abstract_element);+ if (auto effect = existing_animation.effect(); effect.has_value()) {+ effect->set_keyframe_set(keyframe_set);+ CSSAnimation::apply_css_properties(existing_animation, definition, abstract_element);}- existing_animation->set_animation_name_index(i);+ CSSAnimation::set_animation_name_index(existing_animation, i);new_animations.append(existing_animation);continue;}@@ -935,37 +859,21 @@ void StyleComputer::apply_animation_definitions(DOM::AbstractElement& abstract_eif (in_display_none_subtree)continue;- // An animation applies to an element if its name appears as one of the identifiers in the computed value of the- // animation-name property and the animation uses a valid @keyframes rule- auto animation = CSSAnimation::create(document.relevant_settings_object());- animation->set_animation_name(animation_properties.name);- animation->set_owning_element(abstract_element);-- auto effect = Animations::KeyframeEffect::create();- animation->set_effect(effect);-- animation->apply_css_properties(animation_properties, keyframe_set, abstract_element);- animation->set_animation_name_index(i);-- effect->set_key_frame_set(keyframe_set);-- effect->set_target(abstract_element);- new_animations.append(animation);+ new_animations.append(CSSAnimation::create(abstract_element, definition, keyframe_set, i));}// Once an animation has started it continues until it ends or the animation-name is removed// NB: An animation no definition claimed is one whose animation-name entry has gone.for (size_t i = 0; i < existing_animations.size(); ++i) {if (!existing_animation_was_claimed[i]) {- existing_animations[i]->cancel(Animations::Animation::ShouldInvalidate::No);- existing_animations[i]->stop_following_named_timeline();+ existing_animations[i].cancel(false);}}// NB: We create animations in reverse definition order so flip it back.new_animations.reverse();- abstract_element.set_css_defined_animations(move(new_animations));+ abstract_element.element().set_css_defined_animations(abstract_element.pseudo_element(), new_animations);}void StyleComputer::apply_settled_animation_plan(Layout::BegunRead const& read, DOM::AbstractElement& abstract_element) const@@ -974,8 +882,7 @@ void StyleComputer::apply_settled_animation_plan(Layout::BegunRead const& read,GC::Ref<StyleComputer const> style_computer;DOM::AbstractElement& abstract_element;} context { *this, abstract_element };- auto const* animations = abstract_element.css_defined_animations();- bool has_animations = animations && !animations->is_empty();+ bool has_animations = abstract_element.element().has_css_defined_animations(abstract_element.pseudo_element());ComputedValuesFFI::rust_settled_animation_plan(m_style_engine.host(), &read, abstract_element.element().style_node_id().value(), pseudo_element_to_ffi(abstract_element.pseudo_element()), abstract_element.installed_style().record_pointer(), has_animations, &context, [](void* context_pointer, ComputedValuesFFI::FfiComputedAnimation const* definitions, size_t count, bool in_display_none_subtree) {auto& context = *static_cast<Context*>(context_pointer);context.style_computer->apply_animation_definitions(context.abstract_element, { definitions, count }, in_display_none_subtree);@@ -1146,29 +1053,22 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::Vector<NonnullRefPtr<StyleValue const>> custom_current_values;// A running transition of a custom property holds it at what the overlay of the target's environment answers. One// not sampled yet holds it at its start value.- auto custom_current_value = [&](PropertyNameAndID const& property, CSSTransition const& transition) -> StyleValueFFI::StyleValueData const* {- auto value = transition.transition_start_value();+ auto custom_current_value = [&](Utf16FlyString const& name, Animations::AnimationRef const& transition) -> StyleValueFFI::StyleValueData const* {+ auto value = CSSTransition::transition_start_value(transition);if (auto data = abstract_element.custom_property_data(); data && abstract_element.custom_property_data_is_animation_overlay()) {- if (auto animated = data->get(property.name()); animated.has_value())+ if (auto animated = data->get(name); animated.has_value())value = *animated->value;}custom_current_values.append(value);return value->rust_style_value_data();};- if (auto const* transitions = element.existing_transitions(pseudo_element)) {- for (auto const& [property, transition] : *transitions) {- bool running = !transition->is_finished() && !transition->is_idle();- existing_transitions.append({- .property_id = to_underlying(property.id()),- .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,- .custom_current_value = property.is_custom_property() && running ? custom_current_value(property, transition) : nullptr,- .running = running,- .end_value = transition->transition_end_value()->rust_style_value_data(),- .reversing_adjusted_start_value = transition->reversing_adjusted_start_value()->rust_style_value_data(),- .timing_function_output = running ? transition->timing_function_output_at_time(style_change_event_time) : 0,- .reversing_shortening_factor = transition->reversing_shortening_factor(),- });- }+ // NB: The element holds each transition, which lends what is read of it for as long as the element holds it.+ for (auto const& transition : element.existing_transitions(pseudo_element)) {+ StyleValueFFI::FfiExistingTransition existing;+ Animations::RustFFI::animations_css_transition_existing(&transition.record(), style_change_event_time, &existing);+ if (existing.custom_name && existing.running)+ existing.custom_current_value = custom_current_value(Utf16FlyString::from_raw(existing.custom_name), transition);+ existing_transitions.append(existing);}// A transition action is provisional until the stabilization epoch commits; a later pass of the epoch decides@@ -1178,9 +1078,9 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::if (state.has_decision)HTML::note_rendering_trace_event("provisional transition decision superseded"sv);state.has_decision = true;- if (state.proposed_transition)- state.proposed_transition->discard_provisional_transition();- state.proposed_transition = nullptr;+ if (state.proposed_transition.has_value())+ CSSTransition::discard_provisional_transition(*state.proposed_transition);+ state.proposed_transition = {};state.action = action;};auto ensure_state = [&](PropertyNameAndID const& property) -> ProvisionalTransitionState& {@@ -1192,7 +1092,7 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::.pseudo_element = pseudo_element,.property = property,.committed_transition = element.property_transition(pseudo_element, property),- .proposed_transition = nullptr,+ .proposed_transition = {},.action = StyleValueFFI::FfiTransitionActionKind::None,.has_decision = false,});@@ -1218,17 +1118,19 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::return StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(value));};- GC::RootVector<GC::Ref<Animations::KeyframeEffect>> newly_started_transition_effects;- GC::RootHashTable<Animations::KeyframeEffect*> replaced_transition_effects;+ // NB: The traced provisional transition states hold each transition started here until it is committed or+ // discarded, and the root vector holds its effect for the update past that.+ GC::RootVector<Animations::EffectRef> newly_started_transition_effects;+ HashTable<Animations::RustFFI::AnimationEffectId> replaced_transition_effects;auto on_actions = [&](ReadonlySpan<StyleValueFFI::FfiTransitionAction> actions) {for (auto const& action : actions) {auto property = property_of_action(action);auto& state = ensure_state(property);decide(state, action.kind);if (action.kind != StyleValueFFI::FfiTransitionActionKind::None && action.kind != StyleValueFFI::FfiTransitionActionKind::Start) {- VERIFY(state.committed_transition);- if (auto effect = state.committed_transition->effect(); effect && effect->is_keyframe_effect())- replaced_transition_effects.set(static_cast<Animations::KeyframeEffect*>(effect.ptr()));+ VERIFY(state.committed_transition.has_value());+ if (auto effect = state.committed_transition->effect(); effect.has_value())+ replaced_transition_effects.set(effect->id());}if (!action.start_value)continue;@@ -1236,8 +1138,9 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::action.delay, style_change_event_time, style_change_event_time + action.active_duration,adopt(action.start_value), adopt(action.end_value), adopt(action.reversing_adjusted_start_value),action.reversing_shortening_factor, EasingFunction::from_style_value(adopt(action.timing_function)));- state.proposed_transition = transition;- newly_started_transition_effects.append(as<Animations::KeyframeEffect>(*transition->effect()));+ // NB: The associated effect of a provisional transition is the effect it was started with.+ newly_started_transition_effects.append(*transition.effect());+ state.proposed_transition = move(transition);}// A property an earlier pass of the epoch decided over that this one does not leaves its transitions as they are.auto indices = m_provisional_transition_state_indices_by_target.get(target_key);@@ -1266,31 +1169,25 @@ RefPtr<ComputedStyleWorkingSet> StyleComputer::start_needed_transitions(Layout::// changes to the effect stack require rebuilding the overlay.auto new_style = reconstruct_computed_properties_for_animation(abstract_element.installed_style());new_style->clear_animated_properties(Badge<StyleComputer> {});- auto animations = abstract_element.element().get_animations_internal(- Animations::Animatable::GetAnimationsSorted::Yes,- Animations::Animatable::GetAnimationsOptions { .subtree = false, .pseudo_element = {} });- if (animations.is_exception()) {- dbgln("Error getting animations for element {}", abstract_element.debug_description());- } else {- GC::RootVector<GC::Ref<Animations::KeyframeEffect>> remaining_effects;- for (auto& animation : animations.value()) {- auto effect = animation->effect();- if (!effect || !effect->is_keyframe_effect())- continue;- auto& keyframe_effect = static_cast<Animations::KeyframeEffect&>(*effect);- if (keyframe_effect.pseudo_element_type() != abstract_element.pseudo_element())- continue;- if (replaced_transition_effects.contains(&keyframe_effect))- continue;- remaining_effects.append(keyframe_effect);- }- remaining_effects.extend(newly_started_transition_effects);- quick_sort(remaining_effects, [](auto const& a, auto const& b) {- return Animations::KeyframeEffect::composite_order(a, b) < 0;- });- if (!remaining_effects.is_empty())- collect_animations_into(read, abstract_element, remaining_effects.span(), *new_style);+ // NB: The effects of the relevant animations of the element that target the same element or pseudo-element as+ // this style, beside those of the SVG animation elements, which script does not see.+ GC::RootVector<Animations::EffectRef> remaining_effects;+ for (auto const& animation : abstract_element.element().associated_animations_unordered()) {+ if (animation.timing_state().kind == Animations::RustFFI::FfiAnimationKind::Smil || !animation.is_relevant())+ continue;+ auto effect = animation.effect();+ if (!effect.has_value() || effect->pseudo_element_type() != abstract_element.pseudo_element())+ continue;+ if (replaced_transition_effects.contains(effect->id()))+ continue;+ remaining_effects.append(effect.release_value());}+ remaining_effects.extend(newly_started_transition_effects);+ quick_sort(remaining_effects, [](auto const& a, auto const& b) {+ return Animations::AnimationRef::composite_order(*a.associated_animation(), *b.associated_animation()) < 0;+ });+ if (!remaining_effects.is_empty())+ collect_animations_into(read, abstract_element, remaining_effects, *new_style);if (!newly_started_transition_effects.is_empty()) {// NB: Construction does not invalidate animated style because the effects were just evaluated. Request thediff --git a/Libraries/LibWeb/CSS/StyleComputer.h b/Libraries/LibWeb/CSS/StyleComputer.hindex 0666db42873..b7561fb2b20 100644--- a/Libraries/LibWeb/CSS/StyleComputer.h+++ b/Libraries/LibWeb/CSS/StyleComputer.h@@ -15,8 +15,7 @@#include <AK/Utf16View.h>#include <AK/WeakPtr.h>#include <LibGC/Weak.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/CSS/CSSAnimationProperties.h>+#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/CSS/CSSFontFaceRule.h>#include <LibWeb/CSS/CSSKeyframesRule.h>#include <LibWeb/CSS/CascadeOrigin.h>@@ -71,7 +70,11 @@ public:void register_style_engine_sheet_source(StyleSheetState const&);[[nodiscard]] Optional<StyleEngineRuleTarget> style_engine_rule_target(Layout::BegunRead const& read, StyleEngineRuleID rule_id) const;- Animations::BaseKeyframe::ParsedProperties compute_css_keyframe_values(DOM::AbstractElement, Vector<Animations::BaseKeyframe>&, Optional<Animations::KeyframeEffect::KeyFrameSet::StyleSheetResourceContext> const&) const;+ // Computes, for script reading the keyframes of a CSS animation, what the declarations `properties` of+ // `keyframe_count` keyframes from a style sheet with `resource_context` compute to over the style of the element,+ // emitting each computed value with the index of its keyframe, and each value of the element with `keyframe_count`.+ using CSSKeyframeValueCallback = void (*)(void*, size_t, u16, StyleValueFFI::StyleValueData const*);+ void compute_css_keyframe_values(DOM::AbstractElement, ReadonlySpan<ComputedValuesFFI::FfiReflectedKeyframeProperty>, size_t keyframe_count, ComputedValuesFFI::FfiStyleSheetResourceContext const& resource_context, void* context, CSSKeyframeValueCallback) const;static CSSPixels default_user_font_size();@@ -136,11 +139,11 @@ public:// environment the engine resolved them over. Nothing where `identity` is not an environment the engine resolved.[[nodiscard]] RefPtr<CustomPropertyData const> engine_custom_property_declarations_over(Layout::BegunRead const& read, u64 identity, RefPtr<CustomPropertyData const> const& inherited) const;- void collect_animations_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&) const;+ void collect_animations_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<Animations::EffectRef>, ComputedStyleWorkingSet&) const;// One element's animations, refreshed over the record it holds as `collect_animations_into()` refreshes them.struct AnimationRefreshRequest {DOM::AbstractElement abstract_element;- ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects;+ ReadonlySpan<Animations::EffectRef> effects;ComputedStyleWorkingSet& computed_properties;void visit_edges(GC::Cell::Visitor&) const;@@ -167,7 +170,7 @@ public:void apply_animated_properties_to_reconstruction(ComputedStyleWorkingSet&, ComputedValues const&) const;[[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> reconstruct_computed_properties_for_animation(InstalledStyle const&) const;- [[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> compute_style_for_animation_commit(Layout::BegunRead const&, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>) const;+ [[nodiscard]] NonnullRefPtr<ComputedStyleWorkingSet> compute_style_for_animation_commit(Layout::BegunRead const&, DOM::AbstractElement, ReadonlySpan<Animations::EffectRef>) const;void begin_transition_stabilization_epoch();// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style@@ -181,7 +184,7 @@ public:// of the style change.[[nodiscard]] RequiredInvalidationAfterStyleChange run_transition_step_for_installed_record(Layout::BegunRead const& read, DOM::AbstractElement, InstalledStyle const& before_change_style) const;void commit_transition_stabilization_epoch();- void for_each_provisional_transition_effect(DOM::AbstractElement const&, Function<void(Animations::KeyframeEffect&)> const&) const;+ void for_each_provisional_transition_effect(DOM::AbstractElement const&, Function<void(Animations::EffectRef const&)> const&) const;// The media features of the current style update, which the style engine copies with each transaction.[[nodiscard]] Parser::ValueParserFFI::FfiMediaEnvironment const* ensure_media_environment_for_style_update() const;@@ -193,14 +196,14 @@ private:private:// Samples over the record the element holds, which the working set was reconstructed from.- void collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&) const;+ void collect_animation_effects_into(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<Animations::EffectRef>, ComputedStyleWorkingSet&) const;enum class AnimationSamplePurpose {Rendering,CommitStyles,KeyframeReflection,};struct AnimationSample;- [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&, AnimationSamplePurpose = AnimationSamplePurpose::Rendering) const;+ [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<Animations::EffectRef>, ComputedStyleWorkingSet&, AnimationSamplePurpose = AnimationSamplePurpose::Rendering) const;void finish_animation_sample(AnimationSample&, ComputedValuesFFI::FfiHostAnimationSampleResult const&) const;void finish_animation_refresh(Layout::BegunRead const& read, DOM::AbstractElement, ComputedStyleWorkingSet&) const;void publish_animated_custom_properties(ComputedStyleWorkingSet&, DOM::AbstractElement) const;@@ -309,8 +312,8 @@ private:GC::Ptr<DOM::Element> element;Optional<PseudoElement> pseudo_element;PropertyNameAndID property;- GC::Ptr<CSSTransition> committed_transition;- GC::Ptr<CSSTransition> proposed_transition;+ Optional<Animations::AnimationRef> committed_transition;+ Optional<Animations::AnimationRef> proposed_transition;StyleValueFFI::FfiTransitionActionKind action {};bool has_decision { false };};diff --git a/Libraries/LibWeb/CSS/StyleEngineBridge.h b/Libraries/LibWeb/CSS/StyleEngineBridge.hindex 1bd9a7507c8..f7fb7ce4e3f 100644--- a/Libraries/LibWeb/CSS/StyleEngineBridge.h+++ b/Libraries/LibWeb/CSS/StyleEngineBridge.h@@ -94,7 +94,6 @@ void style_engine_set_element_backing_pseudo_kind(DocumentHost const*, StyleNodevoid style_engine_set_counter_style_environment_identity(DocumentHost const*, TreeScopeID tree_scope, u64 identity);void style_engine_set_held_style_record(DocumentHost const*, StyleNodeID node, void const* record);void style_engine_set_held_pseudo_style_record(DocumentHost const*, StyleNodeID node, u8 pseudo_kind, StyleAtomID highlight_name, u64 style_record, void const* released);-void style_engine_set_element_css_defined_animations(DocumentHost const*, StyleNodeID node, u8 slot, ReadonlySpan<FlatPtr> names, ReadonlySpan<FfiAppliedAnimationDefinition> definitions);void style_engine_set_tree_scope_root(DocumentHost const*, TreeScopeID tree_scope, StyleNodeID root);void style_engine_set_sheet_conditions_hold(DocumentHost const*, SheetID sheet, bool conditions_hold);u32 style_engine_connected_element_count(DocumentHost const*, BegunRead const*);diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cppindex f78f119cd23..0a73fd6457c 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp@@ -9,7 +9,7 @@#include <AK/SetUnion.h>#include <LibGC/RootHashTable.h>#include <LibGC/RootVector.h>-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/CSS/CSSAnimation.h>#include <LibWeb/CSS/CSSStyleRule.h>#include <LibWeb/CSS/CSSTransition.h>@@ -2307,89 +2307,18 @@ static void record_element_disconnecting(DOM::Element& element, TreeScopeID treeelement.set_style_node_id(no_style_node);}-// The names of the CSS animations the element owns, in one of its per-pseudo-element lists, and the-// definition each one last had applied.-//-// This one is an input: the computation of an element's animation definitions matches them-// against the animations the element already has, and this is what it matches them against.-void record_element_css_defined_animations(DOM::Element& element, u8 slot, ReadonlySpan<Utf16FlyString> names, ReadonlySpan<StyleEngineFFI::FfiAppliedAnimationDefinition> definitions)+Layout::RustFFI::DocumentHost const* style_engine_host_for_identified(DOM::Element& element){auto* style_engine = style_engine_for_identified(element);- if (!style_engine)- return;+ return style_engine ? style_engine->host() : nullptr;+}- // The names cross as the fly strings they are, which the engine copies. A list is almost always a single name.- Vector<FlatPtr, 1> raw_names;- raw_names.ensure_capacity(names.size());- for (auto const& name : names)- raw_names.unchecked_append(name.raw_identity());- StyleEngineFFI::style_engine_set_element_css_defined_animations(style_engine->host(), element.style_node_id(), slot, raw_names, definitions);-}--// A keyframe's composite operation as a published keyframe spells it: the keyframe's own, or its effect's where the-// keyframe's is auto.-static StyleValueFFI::FfiCompositeOperation published_composite_operation(Bindings::CompositeOperationOrAuto keyframe, Bindings::CompositeOperation effect)-{- switch (keyframe) {- case Bindings::CompositeOperationOrAuto::Replace:- return StyleValueFFI::FfiCompositeOperation::Replace;- case Bindings::CompositeOperationOrAuto::Add:- return StyleValueFFI::FfiCompositeOperation::Add;- case Bindings::CompositeOperationOrAuto::Accumulate:- return StyleValueFFI::FfiCompositeOperation::Accumulate;- case Bindings::CompositeOperationOrAuto::Auto:- break;- }- switch (effect) {- case Bindings::CompositeOperation::Replace:- return StyleValueFFI::FfiCompositeOperation::Replace;- case Bindings::CompositeOperation::Add:- return StyleValueFFI::FfiCompositeOperation::Add;- case Bindings::CompositeOperation::Accumulate:- return StyleValueFFI::FfiCompositeOperation::Accumulate;- }- VERIFY_NOT_REACHED();-}--// One keyframe's easing, spelled out for publication. A `linear()` keeps its control points in the-// shared buffer the keyframe names by range.-static void describe_easing(EasingFunction const& easing, StyleEngineFFI::FfiPublishedAnimationKeyframe& keyframe, Vector<StyleEngineFFI::FfiPublishedLinearEasingPoint>& points)-{- static_assert(to_underlying(StyleEngineFFI::FfiPublishedEasingKind::Steps) == to_underlying(Compositing::RustFFI::FfiEasingKind::Steps));- auto descriptor = easing.descriptor();- keyframe.easing_kind = static_cast<StyleEngineFFI::FfiPublishedEasingKind>(to_underlying(descriptor.kind));- keyframe.x1 = descriptor.x1;- keyframe.y1 = descriptor.y1;- keyframe.x2 = descriptor.x2;- keyframe.y2 = descriptor.y2;- keyframe.interval_count = descriptor.interval_count;- keyframe.step_position = descriptor.step_position;- keyframe.first_linear_point = static_cast<u32>(points.size());- for (size_t index = 0; index < descriptor.linear_point_count; ++index)- points.append({ .input = descriptor.linear_points[index].input, .output = descriptor.linear_points[index].output });- keyframe.linear_point_count = static_cast<u32>(points.size()) - keyframe.first_linear_point;-}--// The effects one of an element's animation lists holds, in composite order, described for the style-// engine to sample them from, unless it already describes exactly these versions of them: every change-// that moves what a description says moves its effect's generation.-//-// Everything a keyframe declares that does not depend on the element being sampled is settled here. What-// does, a value or an easing still to be substituted against the element, travels as written.-void record_attr_names_read_by_keyframes(DOM::Element& element, Animations::KeyframeEffect const& effect)+void record_attr_names_read_by_keyframes(DOM::Element& element, Animations::KeyframeSetView const& keyframe_set){auto* style_engine = style_engine_for(element);- if (!style_engine || !effect.key_frame_set())+ if (!style_engine || !keyframe_set)return;- bool reads_more_attributes = false;- for (auto const& keyframe : effect.key_frame_set()->keyframes_by_key) {- for (auto const& [property, value] : keyframe.properties) {- if (auto const* handle = value.get_pointer<RustStyleValueHandle>())- reads_more_attributes |= StyleEngineFFI::style_engine_note_attr_names_read_by_value(style_engine->host(), handle->data());- }- if (auto const* easing = keyframe.easing.get_pointer<RustStyleValueHandle>())- reads_more_attributes |= StyleEngineFFI::style_engine_note_attr_names_read_by_value(style_engine->host(), easing->data());- }+ bool reads_more_attributes = Animations::RustFFI::animations_note_attr_names_read_by_keyframe_set(style_engine->host(), keyframe_set.ptr());// NB: An effect is sampled against what the engine holds as a read begins, so the attributes go over// now. Only a script's keyframes get here with a new name, between reads: the keyframes of a CSS// animation were noted as their rule was published.@@ -2397,124 +2326,6 @@ void record_attr_names_read_by_keyframes(DOM::Element& element, Animations::Keyfstyle_engine->flush();}-void record_element_animation_effect_descriptions(DOM::Element& element, u8 slot, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects)-{- auto* style_engine = style_engine_for_identified(element);- if (!style_engine)- return;-- Vector<StyleEngineFFI::FfiAnimationEffectVersion, 4> versions;- versions.ensure_capacity(effects.size());- for (auto const& effect : effects)- versions.unchecked_append({ .identity = effect->animation_preparation_identity(), .generation = effect->animation_preparation_generation() });- if (StyleEngineFFI::style_engine_describes_animation_effects(style_engine->host(), element.style_node_id().value(), slot, versions.span()))- return;-- with_animation_effect_descriptions(effects, [&](auto const& descriptions) {- StyleEngineFFI::style_engine_set_element_animation_effect_descriptions(style_engine->host(), element.style_node_id().value(), slot, &descriptions);- });-}--void with_animation_effect_descriptions(ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, Function<void(StyleEngineFFI::FfiAnimationEffectDescriptions const&)> const& callback)-{- Vector<StyleEngineFFI::FfiPublishedAnimationEffect> ffi_effects;- Vector<StyleEngineFFI::FfiPublishedAnimationKeyframe> ffi_keyframes;- Vector<StyleEngineFFI::FfiPublishedAnimationDeclaration> ffi_declarations;- Vector<StyleEngineFFI::FfiPublishedAnimationCustomDeclaration> ffi_custom_declarations;- Vector<StyleEngineFFI::FfiPublishedLinearEasingPoint> ffi_points;- Vector<u8> base_url_bytes;- ffi_effects.ensure_capacity(effects.size());- for (auto const& effect : effects) {- auto animation = effect->associated_animation();- StyleEngineFFI::FfiPublishedAnimationEffect row {};- row.identity = effect->animation_preparation_identity();- row.generation = effect->animation_preparation_generation();- row.first_keyframe = static_cast<u32>(ffi_keyframes.size());- row.base_url_offset = static_cast<u32>(base_url_bytes.size());- row.is_transition = animation && animation->is_css_transition();- row.reversing_shortening_factor = 1;- if (row.is_transition) {- auto const& transition = static_cast<CSSTransition const&>(*animation);- row.reversing_adjusted_start_value = transition.reversing_adjusted_start_value()->rust_style_value_data();- row.reversing_shortening_factor = transition.reversing_shortening_factor();- }- // An effect with no animation, or whose animation runs no keyframes, is described with none, which is- // all there is to sample of it.- auto const* key_frame_set = animation ? effect->key_frame_set() : nullptr;- if (!key_frame_set) {- ffi_effects.unchecked_append(row);- continue;- }- if (auto const& resource_context = key_frame_set->style_sheet_resource_context; resource_context.has_value()) {- row.has_resource_context = true;- row.resource_context_is_origin_clean = resource_context->origin_clean;- auto bytes = resource_context->base_url.bytes();- base_url_bytes.append(bytes.data(), bytes.size());- row.base_url_length = static_cast<u32>(bytes.size());- }- // A keyframe that declares no easing of its own runs the animation's.- auto default_easing = animation->is_css_animation()- ? static_cast<CSSAnimation const&>(*animation).default_easing()- : EasingFunction::linear();- for (auto it = key_frame_set->keyframes_by_key.begin(); it != key_frame_set->keyframes_by_key.end(); ++it) {- StyleEngineFFI::FfiPublishedAnimationKeyframe keyframe {};- keyframe.key = static_cast<i64>(it.key());- auto easing = it->easing.visit(- [&](Empty) { return default_easing; },- [](EasingFunction const& easing) { return easing; },- [&](RustStyleValueHandle const& value) {- // The value can need substitution against the element, which the engine does when- // it samples it; the animation's easing is what the keyframe runs if it resolves to- // none.- keyframe.easing_value = value.data();- return default_easing;- });- describe_easing(easing, keyframe, ffi_points);- keyframe.composite = published_composite_operation(it->composite, effect->composite());- keyframe.first_declaration = static_cast<u32>(ffi_declarations.size());- keyframe.first_custom_declaration = static_cast<u32>(ffi_custom_declarations.size());- for (auto const& [property, value] : it->properties) {- // A keyframe the host synthesized holds the element's own value, which is not known- // until the element is sampled, and travels as no value. A shorthand's stands for its- // longhands', which have keyframes of their own.- bool const use_initial = value.has<Animations::KeyframeEffect::KeyFrameSet::UseInitial>();- if (use_initial && !property.is_custom_property() && property_is_shorthand(property.id()))- continue;- StyleValueFFI::StyleValueData const* data = use_initial ? nullptr : value.get<RustStyleValueHandle>().data();- // A value that is invalid at computed-value time animates nothing. A longhand pending the- // substitution of its shorthand's value is substituted with it when the engine samples it.- // https://drafts.csswg.org/css-values-5/#invalid-at-computed-value-time- if (!use_initial && data->tag == StyleValueFFI::StyleValueData::Tag::GuaranteedInvalid && !property.is_custom_property())- continue;- if (property.is_custom_property())- ffi_custom_declarations.append({ .name = property.name().raw_identity(), .value = data });- else- ffi_declarations.append({ .property_id = to_underlying(property.id()), .value = data });- }- keyframe.declaration_count = static_cast<u32>(ffi_declarations.size()) - keyframe.first_declaration;- keyframe.custom_declaration_count = static_cast<u32>(ffi_custom_declarations.size()) - keyframe.first_custom_declaration;- ffi_keyframes.append(keyframe);- }- row.keyframe_count = static_cast<u32>(ffi_keyframes.size()) - row.first_keyframe;- ffi_effects.unchecked_append(row);- }-- callback({- .effects = ffi_effects.data(),- .effect_count = ffi_effects.size(),- .keyframes = ffi_keyframes.data(),- .keyframe_count = ffi_keyframes.size(),- .declarations = ffi_declarations.data(),- .declaration_count = ffi_declarations.size(),- .custom_declarations = ffi_custom_declarations.data(),- .custom_declaration_count = ffi_custom_declarations.size(),- .linear_points = ffi_points.data(),- .linear_point_count = ffi_points.size(),- .base_url_bytes = base_url_bytes.data(),- .base_url_byte_count = base_url_bytes.size(),- });-}-// An element's heading level, which `:heading()` tests. It follows from what the element is plus// the heading offset its ancestors declare, so it moves when the element does and when one of those// attributes changes - not with anything the element itself publishes.diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.h b/Libraries/LibWeb/CSS/StyleEngineInput.hindex 75c40080bea..e10ef2e0536 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.h+++ b/Libraries/LibWeb/CSS/StyleEngineInput.h@@ -13,10 +13,14 @@#include <LibWeb/Export.h>#include <LibWeb/Forward.h>+namespace Web::Layout::RustFFI {++struct DocumentHost;++}+namespace Web::CSS::StyleEngineFFI {-struct FfiAppliedAnimationDefinition;-struct FfiAnimationEffectDescriptions;enum class FfiElementDeclarationKind : u8;}@@ -145,6 +149,9 @@ WEB_API u32 element_box_type_adjustment_facts(DOM::Element const&);WEB_API void record_element_adjustment_facts(DOM::Element&);// The element's animations changed: an element with animations has its style composed by the host.void record_element_animations_changed(DOM::Element&);+// The host of the style engine an element's facts are recorded into, once the element has taken its style node+// identity, or null.+Layout::RustFFI::DocumentHost const* style_engine_host_for_identified(DOM::Element&);WEB_API void record_element_construction_facts(DOM::Element&);// Called where which box an element asks for may have moved without its type or an attribute's presence moving.WEB_API void record_element_box_kind(DOM::Element&);@@ -153,12 +160,9 @@ WEB_API void record_element_replaced_content_input(DOM::Element&);WEB_API bool record_element_presentational_hint_properties(DOM::Element&, ReadonlySpan<StyleProperty>);// Publish the element's hints again, after something they are mapped from beside its own attributes moved.WEB_API void republish_presentational_hints(DOM::Element&);-WEB_API void record_element_css_defined_animations(DOM::Element&, u8 slot, ReadonlySpan<Utf16FlyString> names, ReadonlySpan<StyleEngineFFI::FfiAppliedAnimationDefinition> definitions);// Called where an effect takes keyframes or a target: ahead of the read that samples it, as an attr() in the keyframes// needs the attributes it names handed over before then.-WEB_API void record_attr_names_read_by_keyframes(DOM::Element&, Animations::KeyframeEffect const&);-WEB_API void with_animation_effect_descriptions(ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, Function<void(StyleEngineFFI::FfiAnimationEffectDescriptions const&)> const&);-WEB_API void record_element_animation_effect_descriptions(DOM::Element&, u8 slot, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>);+WEB_API void record_attr_names_read_by_keyframes(DOM::Element&, Animations::KeyframeSetView const&);// Report that a child of an element arrived, left, or changed in a way that can move whether the// element is empty. `counted_before` and `counts_after` say whether that child is one `:empty` counts:diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cppindex d8da8ed7069..39449ac5cd1 100644--- a/Libraries/LibWeb/CSS/StyleScope.cpp+++ b/Libraries/LibWeb/CSS/StyleScope.cpp@@ -465,111 +465,11 @@ void StyleRuleCache::add_rules_from_sheet(StyleSheetState& sheet, CascadeOriginif (rule.type() != RustRule::Type::Keyframes)return;- // Loosely based on https://drafts.csswg.org/css-animations-2/#keyframe-processing- auto name = rule.name();- auto keyframe_set = adopt_ref(*new Animations::KeyframeEffect::KeyFrameSet);- keyframe_set->css_keyframes.emplace();auto base_url = sheet.style_resource_base_url();- keyframe_set->style_sheet_resource_context = {- .base_url = base_url.has_value() ? base_url->to_string() : String {},- .origin_clean = sheet.is_origin_clean(),- };- HashTable<PropertyNameAndID> animated_properties;-- // Forwards pass, resolve all the user-specified keyframe properties.- Function<void(ReadonlySpan<double>, RustDeclarationBlockSnapshot const&)> append_keyframe = [&](ReadonlySpan<double> keys, RustDeclarationBlockSnapshot const& keyframe_style) {- Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame resolved_keyframe;-- auto append_property = [&](Parser::ValueParserFFI::FfiDeclaredProperty const& declaration) {- auto* value = static_cast<StyleValueFFI::StyleValueData const*>(declaration.value);- if (declaration.name.length != 0) {- auto name = Utf16FlyString::from_utf16({ reinterpret_cast<char16_t const*>(declaration.name.utf16), declaration.name.length });- auto property = PropertyNameAndID::from_name(name);- if (!property.has_value())- return;- animated_properties.set(*property);- resolved_keyframe.properties.set(*property, RustStyleValueHandle::retained(value));- return;- }- auto property_id = static_cast<PropertyID>(declaration.property_id);- if (property_id == PropertyID::AnimationTimingFunction) {- // animation-timing-function is a list property, but inside @keyframes only- // a single value is meaningful.- if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList) {- auto const& list = value->value_list.values;- if (list.length() == 0)- return;- value = static_cast<StyleValueFFI::StyleValueData const*>(list.pointer[0].pointer);- }- if (value->tag == StyleValueFFI::StyleValueData::Tag::Keyword && is_css_wide_keyword(static_cast<Keyword>(value->keyword.keyword)))- return;- if (value->tag == StyleValueFFI::StyleValueData::Tag::Easing || value->tag == StyleValueFFI::StyleValueData::Tag::Keyword) {- auto easing_value = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(value));- resolved_keyframe.easing = EasingFunction::from_style_value(*easing_value);- } else {- resolved_keyframe.easing = RustStyleValueHandle::retained(value);- }- return;- }- if (property_id == PropertyID::AnimationComposition) {- AnimationComposition composition = AnimationComposition::Replace;- if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList && value->value_list.values.length() == 1)- value = static_cast<StyleValueFFI::StyleValueData const*>(value->value_list.values.pointer[0].pointer);- if (value->tag == StyleValueFFI::StyleValueData::Tag::Keyword) {- if (static_cast<Keyword>(value->keyword.keyword) == Keyword::Add)- composition = AnimationComposition::Add;- else if (static_cast<Keyword>(value->keyword.keyword) == Keyword::Accumulate)- composition = AnimationComposition::Accumulate;- }- resolved_keyframe.composite = Animations::css_animation_composition_to_composite_operation_or_auto(composition);- return;- }- if (!is_animatable_property(property_id))- return;-- // Unresolved properties will be resolved in collect_animation_into()- auto expansion = ComputedValuesFFI::rust_expand_property_shorthands(- to_underlying(property_id), value);- for (size_t i = 0; i < expansion.count; ++i) {- auto const& property = expansion.properties[i];- auto longhand_property = PropertyNameAndID::from_id(static_cast<PropertyID>(property.property_id));- animated_properties.set(longhand_property);- resolved_keyframe.properties.set(longhand_property,- RustStyleValueHandle::retained(static_cast<StyleValueFFI::StyleValueData const*>(property.data)));- }- ComputedValuesFFI::rust_shorthand_expansion_destroy(expansion.storage);- };- Parser::ValueParserFFI::rust_declaration_data_visit(keyframe_style.data(), &append_property, [](void* context, Parser::ValueParserFFI::FfiDeclaredProperty const* property) {- (*static_cast<decltype(append_property)*>(context))(*property);- });-- for (auto key : keys) {- auto resolved_key = static_cast<u64>(key * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor);-- keyframe_set->css_keyframes->append({ resolved_key, resolved_keyframe });- if (auto* existing_keyframe = keyframe_set->keyframes_by_key.find(resolved_key)) {- for (auto& [property, value] : resolved_keyframe.properties)- existing_keyframe->properties.set(property, value);- if (resolved_keyframe.composite != Bindings::CompositeOperationOrAuto::Auto)- existing_keyframe->composite = resolved_keyframe.composite;- if (!resolved_keyframe.easing.has<Empty>())- existing_keyframe->easing = resolved_keyframe.easing;- } else {- keyframe_set->keyframes_by_key.insert(resolved_key, resolved_keyframe);- }- }- };- rule.for_each_keyframe(append_keyframe);-- Animations::KeyframeEffect::generate_initial_and_final_frames(keyframe_set, animated_properties);-- if constexpr (LIBWEB_CSS_DEBUG) {- dbgln("Resolved keyframe set '{}' into {} keyframes:", name, keyframe_set->keyframes_by_key.size());- for (auto it = keyframe_set->keyframes_by_key.begin(); it != keyframe_set->keyframes_by_key.end(); ++it)- dbgln(" - keyframe {}: {} properties", it.key(), it->properties.size());- }-- rules_by_animation_keyframes.set(Utf16FlyString { name }, move(keyframe_set));+ auto base_url_string = base_url.has_value() ? base_url->to_string() : String {};+ auto keyframe_set = Animations::KeyframeSetHandle::adopt(Animations::RustFFI::animations_keyframe_set_from_keyframes_rule(+ &rule.native_view(), true, base_url_string.bytes(), sheet.is_origin_clean()));+ rules_by_animation_keyframes.set(Utf16FlyString { rule.name() }, move(keyframe_set));});}@@ -605,25 +505,22 @@ void StyleScope::publish_animation_keyframes()Vector<u32> name_lengths;Vector<u16> name_units;Vector<size_t> keyframe_sets;- Vector<NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet const>> published;name_lengths.ensure_capacity(keyframes.size());keyframe_sets.ensure_capacity(keyframes.size());- published.ensure_capacity(keyframes.size());for (auto const& [name, keyframe_set] : keyframes) {name_lengths.unchecked_append(name.length_in_code_units());for (size_t index = 0; index < name.length_in_code_units(); ++index)name_units.append(name.code_unit_at(index));keyframe_sets.unchecked_append(bit_cast<size_t>(keyframe_set.ptr()));- published.unchecked_append(*keyframe_set);}// A scope that defined nothing before and defines nothing now has no row to replace.- if (published.is_empty() && m_published_keyframe_sets.is_empty())+ if (keyframe_sets.is_empty() && !m_has_published_animation_keyframes)return;StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(document().style_computer().style_engine().host(), style_engine_tree_scope().value(),name_lengths.span(), name_units.span(),keyframe_sets.span());- m_published_keyframe_sets = move(published);+ m_has_published_animation_keyframes = !keyframe_sets.is_empty();}// The @position-try rules this scope defines, as the rule cache just built resolved them. The position options of an@@ -669,11 +566,12 @@ Optional<StyleScope::DepartedAnimationKeyframes> StyleScope::take_published_animm_published_position_try_names.clear();m_published_position_try_declarations.clear();auto* shadow_root = as_if<DOM::ShadowRoot>(*m_node);- if (!shadow_root || (m_published_keyframe_sets.is_empty() && !has_position_try_rules))+ bool const has_animation_keyframes = exchange(m_has_published_animation_keyframes, false);+ if (!shadow_root || (!has_animation_keyframes && !has_position_try_rules))return {};return DepartedAnimationKeyframes {.tree_scope = shadow_root->style_engine_tree_scope(),- .keyframe_sets = move(m_published_keyframe_sets),+ .has_animation_keyframes = has_animation_keyframes,.has_position_try_rules = has_position_try_rules,};}diff --git a/Libraries/LibWeb/CSS/StyleScope.h b/Libraries/LibWeb/CSS/StyleScope.hindex 53d172c3f6b..c2cbf53145d 100644--- a/Libraries/LibWeb/CSS/StyleScope.h+++ b/Libraries/LibWeb/CSS/StyleScope.h@@ -15,7 +15,7 @@#include <AK/Utf16FlyString.h>#include <AK/Vector.h>#include <LibGC/Ptr.h>-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/KeyframeSetHandle.h>#include <LibWeb/CSS/CascadeOrigin.h>#include <LibWeb/CSS/ContainerQuery.h>#include <LibWeb/CSS/RustDeclarationBlock.h>@@ -67,7 +67,7 @@ struct StyleRuleCache {// Take in what another cache collected, as if from a later sheet.void add_rules_from_cache(StyleRuleCache const&);- HashMap<Utf16FlyString, NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet>> rules_by_animation_keyframes;+ HashMap<Utf16FlyString, Animations::KeyframeSetHandle> rules_by_animation_keyframes;// https://drafts.csswg.org/css-anchor-position-1/#fallback-rule// If multiple @position-try rules are declared with the same name, they cascade (overriding each other) the same// as @keyframes rules do.@@ -116,11 +116,12 @@ public:void publish_position_try_rules();void invalidate_user_style_sheet();- // The `@keyframes` row a shadow root's scope published to the style engine, taken from the scope as the root- // leaves its document, with the keyframe sets the row names: they stay alive until the row is given up.+ // The rows a shadow root's scope published to the style engine, taken from the scope as the root leaves its+ // document, to be given up before the next style update.struct DepartedAnimationKeyframes {TreeScopeID tree_scope;- Vector<NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet const>> keyframe_sets;+ // NB: Whether the scope published a `@keyframes` row.+ bool has_animation_keyframes { false };// NB: Whether the scope published a `@position-try` row too, which is given up along with this one.bool has_position_try_rules { false };};@@ -155,9 +156,8 @@ public:void visit_edges(GC::Cell::Visitor&);- // The keyframe sets this scope last published. The style engine names them by pointer, so they stay alive after- // the rule cache they came from is invalidated, until the scope publishes again or gives its row up.- Vector<NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet const>> m_published_keyframe_sets;+ // Whether the style engine holds a `@keyframes` row this scope published.+ bool m_has_published_animation_keyframes { false };// The names and declarations of the @position-try rules this scope last published.Vector<Utf16FlyString> m_published_position_try_names;diff --git a/Libraries/LibWeb/CSS/UpdateStyle.cpp b/Libraries/LibWeb/CSS/UpdateStyle.cppindex 47a3fe66c03..fb9a17edad8 100644--- a/Libraries/LibWeb/CSS/UpdateStyle.cpp+++ b/Libraries/LibWeb/CSS/UpdateStyle.cpp@@ -898,12 +898,11 @@ void Document::drain_style_update_that_flew(Layout::BegunRead const& read){// The animations dirtied beside the transaction are the next style update's, as are the writes made beside it: the// drain samples those its own reactions create.- auto effects_beside = exchange(m_effects_needing_animated_style_update, {});+ set_aside_effects_needing_animated_style_update();bool needed_beside = exchange(m_needs_animated_style_update, false);bool forced_beside = exchange(m_force_throttled_animation_style_update, false);CSS::update_style(read, *this, CSS::FlownStyleUpdate { m_flown_style_update_inputs.release_value() });- for (auto& effect : effects_beside)- m_effects_needing_animated_style_update.set(effect);+ restore_effects_needing_animated_style_update();m_needs_animated_style_update |= needed_beside;m_force_throttled_animation_style_update |= forced_beside;}diff --git a/Libraries/LibWeb/DOM/AbstractElement.cpp b/Libraries/LibWeb/DOM/AbstractElement.cppindex a825a0c0479..9a81631d172 100644--- a/Libraries/LibWeb/DOM/AbstractElement.cpp+++ b/Libraries/LibWeb/DOM/AbstractElement.cpp@@ -219,14 +219,4 @@ CSS::StyleScope const& AbstractElement::style_scope() constreturn m_element->style_scope();}-Vector<GC::Ref<CSS::CSSAnimation>> const* AbstractElement::css_defined_animations() const-{- return m_element->css_defined_animations(m_pseudo_element);-}--void AbstractElement::set_css_defined_animations(Vector<GC::Ref<CSS::CSSAnimation>>&& animations)-{- m_element->set_css_defined_animations(m_pseudo_element, move(animations));-}-}diff --git a/Libraries/LibWeb/DOM/AbstractElement.h b/Libraries/LibWeb/DOM/AbstractElement.hindex 55deae3891d..3024a13c6b7 100644--- a/Libraries/LibWeb/DOM/AbstractElement.h+++ b/Libraries/LibWeb/DOM/AbstractElement.h@@ -79,9 +79,6 @@ public:[[nodiscard]] bool custom_property_data_is_animation_overlay() const;RefPtr<CSS::StyleValue const> get_custom_property(Utf16FlyString const& name) const;- Vector<GC::Ref<CSS::CSSAnimation>> const* css_defined_animations() const;- void set_css_defined_animations(Vector<GC::Ref<CSS::CSSAnimation>>&&);-void visit(GC::Cell::Visitor& visitor) const;Utf16String debug_description() const;diff --git a/Libraries/LibWeb/DOM/Document.cpp b/Libraries/LibWeb/DOM/Document.cppindex 75ff3e8a3a5..09d26cdc1ee 100644--- a/Libraries/LibWeb/DOM/Document.cpp+++ b/Libraries/LibWeb/DOM/Document.cpp@@ -38,11 +38,9 @@#include <LibURL/Parser.h>#include <LibUnicode/Segmenter.h>#include <LibWeb/ARIA/AttributeNames.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/AnimationPlaybackEvent.h>#include <LibWeb/Animations/AnimationTimeline.h>-#include <LibWeb/Animations/DocumentTimeline.h>#include <LibWeb/Animations/NamedTimelines.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/Animations/TimeValue.h>#include <LibWeb/Bindings/CSS.h>#include <LibWeb/Bindings/Document.h>@@ -254,9 +252,9 @@#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/ResizeObserver/ResizeObserver.h>#include <LibWeb/ResizeObserver/ResizeObserverEntry.h>-#include <LibWeb/SVG/SMILAnimation.h>#include <LibWeb/SVG/SMILTimeContainer.h>#include <LibWeb/SVG/SVGAnimateMotionElement.h>+#include <LibWeb/SVG/SVGAnimationElement.h>#include <LibWeb/SVG/SVGClipPathElement.h>#include <LibWeb/SVG/SVGDecodedImageData.h>#include <LibWeb/SVG/SVGElement.h>@@ -311,13 +309,6 @@ void Document::PendingScrollEvent::visit_edges(GC::Cell::Visitor& visitor) constvisitor.visit(event_target);}-void Document::PendingAnimationEvent::visit_edges(GC::Cell::Visitor& visitor) const-{- visitor.visit(event);- visitor.visit(animation);- visitor.visit(target);-}-struct Document::AccessibilityRecordCache {AK_ALLOC_WITH_KMALLOC;struct Record {@@ -801,6 +792,62 @@ GC::Ref<Document> Document::create_for_fragment_parsing(Page& page, GC::Ref<Evenreturn document;}+// The animations associated with the elements of the document, which it keeps none of alive.+static Animations::WeakAnimationSetView associated_animations(Animations::RustFFI::DocumentAnimations* animations)+{+ return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(animations, Animations::RustFFI::DocumentAnimationSetKind::Associated) };+}++// The animations associated with the document during the current style stabilization epoch.+static Animations::WeakAnimationSetView animations_created_in_stabilization_epoch(Animations::RustFFI::DocumentAnimations* animations)+{+ return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(animations, Animations::RustFFI::DocumentAnimationSetKind::CreatedInStabilizationEpoch) };+}++// A set of the effects the document knows of, which keeps none of them alive.+class DocumentEffectSet {+public:+ DocumentEffectSet(Animations::RustFFI::DocumentAnimations* animations, Animations::RustFFI::DocumentEffectSetKind kind)+ : m_animations(animations)+ , m_kind(kind)+ {+ }++ bool set(Animations::EffectRef const& effect) { return Animations::RustFFI::animations_document_effect_set_insert(m_animations, m_kind, &effect.record()); }+ bool remove(Animations::RustFFI::AnimationEffectCell const& effect) { return Animations::RustFFI::animations_document_effect_set_remove(m_animations, m_kind, &effect); }+ bool contains(Animations::RustFFI::AnimationEffectCell const& effect) const { return Animations::RustFFI::animations_document_effect_set_contains(m_animations, m_kind, &effect); }++ // Empties the set, calling `callback` with each effect alive to it.+ template<typename Callback>+ void take_each(Callback callback)+ {+ Animations::RustFFI::animations_document_effect_set_take_each(m_animations, m_kind, &callback, [](void* context, Animations::RustFFI::AnimationEffectCell const* effect) {+ (*static_cast<Callback*>(context))(Animations::EffectRef { *effect });+ });+ }++ void clear()+ {+ take_each([](Animations::EffectRef const&) { });+ }++private:+ Animations::RustFFI::DocumentAnimations* m_animations { nullptr };+ Animations::RustFFI::DocumentEffectSetKind m_kind;+};++// The effects whose animated style the next animated style update samples.+static DocumentEffectSet effects_needing_animated_style_update(Animations::RustFFI::DocumentAnimations* animations)+{+ return { animations, Animations::RustFFI::DocumentEffectSetKind::NeedingAnimatedStyleUpdate };+}++// The effects to ask for an observation sample as the current animated style update finishes.+static DocumentEffectSet effects_needing_animated_style_update_after_current_update(Animations::RustFFI::DocumentAnimations* animations)+{+ return { animations, Animations::RustFFI::DocumentEffectSetKind::NeedingAnimatedStyleUpdateAfterCurrentUpdate };+}+Document::Document(Page& page, GC::Ref<EventTarget> relevant_global_event_target, URL::URL const& url, TemporaryDocumentForFragmentParsing temporary_document_for_fragment_parsing): ParentNode(*this, NodeType::DOCUMENT_NODE), m_page(page)@@ -816,13 +863,17 @@ Document::Document(Page& page, GC::Ref<EventTarget> relevant_global_event_target, m_style_scope(*this){m_rust_custom_property_registry = CSS::ComputedValuesFFI::rust_custom_property_registry_create();+ m_animations = Animations::RustFFI::animations_document_animations_create();m_is_decoded_svg = m_page->client().is_svg_page_client();HTML::main_thread_event_loop().register_document({}, *this);}-Document::~Document() = default;+Document::~Document()+{+ Animations::RustFFI::animations_document_animations_destroy(m_animations);+}void Document::create_style_computer(){@@ -1101,16 +1152,7 @@ void Document::visit_edges(Cell::Visitor& visitor)if (m_writing_suggestion_controller)m_writing_suggestion_controller->visit_edges(visitor);- for (auto& event : m_pending_animation_event_queue) {- visitor.visit(event.event);- visitor.visit(event.animation);- visitor.visit(event.target);- }- for (auto& event : m_provisional_animation_event_queue) {- visitor.visit(event.event);- visitor.visit(event.animation);- visitor.visit(event.target);- }+ Animations::RustFFI::animations_document_animations_visit_pending_events(m_animations, &visitor, Animations::visit_host_cell);for (auto& event : m_pending_fullscreen_events) {visitor.visit(event.element);@@ -2376,8 +2418,7 @@ void Document::begin_style_stabilization_epoch()return;HTML::main_thread_event_loop().defer_microtask_checkpoints();- VERIFY(m_provisional_animation_event_queue.is_empty());- VERIFY(m_animations_created_in_stabilization_epoch.is_empty());+ Animations::RustFFI::animations_document_animations_begin_style_stabilization_epoch(m_animations);style_computer().begin_transition_stabilization_epoch();m_style_stabilization_pass_count = 0;m_style_stabilization_has_style_reactions = false;@@ -2440,16 +2481,8 @@ void Document::end_style_stabilization_epoch()style_computer().commit_transition_stabilization_epoch();--m_style_stabilization_epoch_depth;- for (auto const& event : m_provisional_animation_event_queue) {- // An animation created and cancelled inside this epoch was never part of an externally- // committed style. Its cancellation is provisional too, so no observer may receive it.- if (m_animations_created_in_stabilization_epoch.contains(event.animation) && event.animation->is_idle())- continue;- m_pending_animation_event_queue.append(event);+ for (auto committed = Animations::RustFFI::animations_document_animations_commit_provisional_events(m_animations); committed > 0; --committed)HTML::note_rendering_trace_event("animation events committed"sv);- }- m_provisional_animation_event_queue.clear();- m_animations_created_in_stabilization_epoch.clear();HTML::main_thread_event_loop().resume_microtask_checkpoints();}@@ -2858,38 +2891,38 @@ void Document::sample_animation_effects_needing_style_update()finish_animated_style_update();};- GC::RootVector<GC::Ref<Animations::Animation>> animations;+ // NB: The effects stay alive for as long as the update holds them.+ GC::RootVector<Animations::EffectRef> effects;if (m_force_throttled_animation_style_update) {- for (auto& animation : m_associated_animations) {- if (!animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ for (auto const& animation : associated_animations(m_animations)) {+ auto effect = animation.effect();+ if (!effect.has_value())continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());// NB: Dirty idle effects still need to remove their last sampled values after cancellation.- if (animation.is_idle() && !m_effects_needing_animated_style_update.contains(effect))+ if (animation.timing_state().play_state == Animations::RustFFI::AnimationPlayState::Idle && !effects_needing_animated_style_update(m_animations).contains(effect->record()))continue;- animations.append(animation);+ effects.append(effect.release_value());}+ effects_needing_animated_style_update(m_animations).clear();} else {- for (auto& effect : m_effects_needing_animated_style_update) {- auto animation = effect.associated_animation();+ effects_needing_animated_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {// NB: A canceled animation still needs to remove its last sampled values.- if (!animation)- continue;- animations.append(*animation);- }+ if (!effect.associated_animation().has_value())+ return;+ effects.append(effect);+ });}- m_effects_needing_animated_style_update.clear();m_needs_animated_style_update = false;- if (animations.is_empty()) {+ if (effects.is_empty()) {m_force_throttled_animation_style_update = false;// A compositor-driven effect can remain throttled when every dirty effect was cancelled before this sample.// Preserve the flag so a later style or geometry read can still request a current main-thread sample.return;}- bool has_requested_observation_sample = any_of(animations, [](auto const& animation) {- return static_cast<Animations::KeyframeEffect&>(*animation->effect()).observation_sample_requested();+ bool has_requested_observation_sample = any_of(effects, [](auto const& effect) {+ return effect.has_flag(Animations::RustFFI::EffectFlag::NeedsObservationSample);});// A timeline script observed ahead of its current time in this task is sampled at that time too, so that a style@@ -2909,22 +2942,19 @@ void Document::sample_animation_effects_needing_style_update()Animations::AnimationUpdateContext context;- quick_sort(animations, [](GC::Ref<Animations::Animation>& a, GC::Ref<Animations::Animation>& b) {- auto& a_effect = as<Animations::KeyframeEffect>(*a->effect());- auto& b_effect = as<Animations::KeyframeEffect>(*b->effect());- return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;+ quick_sort(effects, [](Animations::EffectRef const& a, Animations::EffectRef const& b) {+ return Animations::AnimationRef::composite_order(*a.associated_animation(), *b.associated_animation()) < 0;});bool has_throttled_animation_style_update = m_force_throttled_animation_style_update ? false : m_has_throttled_animation_style_update;- for (auto& animation : animations) {- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation->effect());- bool observation_sample_requested = effect.consume_observation_sample_request();+ for (auto const& effect : effects) {+ bool observation_sample_requested = effect.set_flag(Animations::RustFFI::EffectFlag::NeedsObservationSample, false);if (effect.can_skip_per_frame_style_update()) {has_throttled_animation_style_update = true;if (!m_force_throttled_animation_style_update && !observation_sample_requested)continue;}- animation->effect()->update_computed_properties(context);+ effect.update_computed_properties(context);}m_has_throttled_animation_style_update = has_throttled_animation_style_update;@@ -2938,9 +2968,9 @@ void Document::note_animations_that_can_skip_per_frame_style_updates()if (!m_needs_throttled_animation_style_update_check || m_has_throttled_animation_style_update || !layout_is_up_to_date())return;m_needs_throttled_animation_style_update_check = false;- for (auto& animation : m_associated_animations) {- auto* effect = as_if<Animations::KeyframeEffect>(animation.effect().ptr());- if (effect && effect->can_skip_per_frame_style_update()) {+ for (auto const& animation : associated_animations(m_animations)) {+ auto effect = animation.effect();+ if (effect.has_value() && effect->can_skip_per_frame_style_update()) {note_throttled_animation_style_update();return;}@@ -2979,20 +3009,21 @@ void Document::flush_throttled_animation_style_update_for_node(Node const& node)if (!element)return;for (auto const& animation : element->associated_animations_unordered()) {- if (!animation->effect() || !is<Animations::KeyframeEffect>(*animation->effect()))+ auto associated_effect = animation.effect();+ if (!associated_effect.has_value())continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation->effect());+ auto const& effect = *associated_effect;// NB: An effect that changed since it was last sampled, such as one script seeked after an earlier read in// this task, is sampled for the read whether or not it can skip per-frame style updates now: the sample// decides that again, from a layout that may have moved since.- if (!m_is_updating_animated_style && m_effects_needing_animated_style_update.contains(effect)) {+ if (!m_is_updating_animated_style && effects_needing_animated_style_update(m_animations).contains(effect.record())) {effect.request_observation_sample();continue;}if (!effect.can_skip_per_frame_style_update())continue;if (m_is_updating_animated_style) {- m_effects_needing_animated_style_update_after_current_update.set(effect);+ effects_needing_animated_style_update_after_current_update(m_animations).set(effect);} else {effect.request_element_scoped_observation_sample(task_generation);}@@ -3032,7 +3063,7 @@ bool Document::run_empty_animation_style_update_for_testing(Badge<Internals::Int{VERIFY(!m_is_updating_animated_style);m_needs_animated_style_update = true;- m_effects_needing_animated_style_update.clear();+ effects_needing_animated_style_update(m_animations).clear();sample_animation_effects_needing_style_update();return m_has_throttled_animation_style_update;}@@ -3076,9 +3107,36 @@ void Document::throttled_animation_visibility_changed()page().client().request_frame_for(*this);}-void Document::set_needs_animated_style_update(Animations::KeyframeEffect& effect)+// The effects dirtied beside the transaction of a style update that flew, which the next style update samples.+static DocumentEffectSet effects_needing_animated_style_update_beside_flown_style_update(Animations::RustFFI::DocumentAnimations* animations){- m_effects_needing_animated_style_update.set(effect);+ return { animations, Animations::RustFFI::DocumentEffectSetKind::SetAsideWhileFlownStyleUpdateDrains };+}++void Document::set_aside_effects_needing_animated_style_update()+{+ effects_needing_animated_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {+ effects_needing_animated_style_update_beside_flown_style_update(m_animations).set(effect);+ });+}++void Document::restore_effects_needing_animated_style_update()+{+ effects_needing_animated_style_update_beside_flown_style_update(m_animations).take_each([&](Animations::EffectRef const& effect) {+ effects_needing_animated_style_update(m_animations).set(effect);+ });+}++void Document::clear_needs_animated_style_update()+{+ m_needs_animated_style_update = false;+ effects_needing_animated_style_update(m_animations).clear();+ effects_needing_animated_style_update_after_current_update(m_animations).clear();+}++void Document::set_needs_animated_style_update(Animations::EffectRef const& effect)+{+ effects_needing_animated_style_update(m_animations).set(effect);if (m_needs_animated_style_update)return;@@ -3097,13 +3155,13 @@ void Document::finish_animated_style_update()VERIFY(m_is_updating_animated_style);m_is_updating_animated_style = false;- GC::RootVector<GC::Ref<Animations::KeyframeEffect>> effects;- for (auto& effect : m_effects_needing_animated_style_update_after_current_update)+ GC::RootVector<Animations::EffectRef> effects;+ effects_needing_animated_style_update_after_current_update(m_animations).take_each([&](Animations::EffectRef const& effect) {effects.append(effect);- m_effects_needing_animated_style_update_after_current_update.clear();+ });- for (auto& effect : effects)- effect->request_observation_sample();+ for (auto const& effect : effects)+ effect.request_observation_sample();}// What preparing the paint and hit testing properties, which the render state does as they are read, asks of the@@ -4691,276 +4749,72 @@ Element* Document::find_a_potential_indicated_element(Utf16View fragment) const}// https://drafts.csswg.org/css-transitions-2/#event-dispatch-void Document::dispatch_events_for_transition(GC::Ref<CSS::CSSTransition> transition)-{- auto previous_phase = transition->previous_phase();-- using Phase = CSS::CSSTransition::Phase;- // The transition phase of a transition is initially ‘idle’ and is updated on each- // animation frame according to the first matching condition from below:- auto transition_phase = Phase::Idle;-- if (!transition->effect()) {- // If the transition has no associated effect,- if (!transition->current_time().has_value()) {- // If the transition has an unresolved current time,- // The transition phase is ‘idle’.- } else if (transition->current_time()->value < 0) {- // If the transition has a current time < 0,- // The transition phase is ‘before’.- transition_phase = Phase::Before;- } else {- // Otherwise,- // The transition phase is ‘after’.- transition_phase = Phase::After;- }- } else if (transition->pending() && (previous_phase == Phase::Idle || previous_phase == Phase::Pending)) {- // If the transition has a pending play task or a pending pause task- // and its phase was previously ‘idle’ or ‘pending’,- // The transition phase is ‘pending’.- transition_phase = Phase::Pending;- } else {- // Otherwise,- // The transition phase is the phase of its associated effect.- transition_phase = Phase(to_underlying(transition->effect()->phase()));+// https://www.w3.org/TR/css-animations-2/#event-dispatch+void Document::dispatch_events_for_animation_if_necessary(Animations::AnimationRef const& animation)+{+ // NB: The core queues the events the animation frame established for a CSS animation or transition. Each takes the+ // time stamp of when it is queued.+ auto queued = Animations::RustFFI::animations_document_animations_queue_css_events(+ m_animations, &animation.record(), m_style_stabilization_epoch_depth > 0, [](void* element) {+ return HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*static_cast<DOM::Element*>(element)));+ });+ if (queued.kind == Animations::RustFFI::FfiAnimationKind::Smil) {+ static_cast<SVG::SVGAnimationElement*>(Animations::RustFFI::animations_smil_animation_element(&animation.record()))->queue_time_events_if_necessary();+ return;}-- enum class Interval : u8 {- Start,- End,- ActiveTime,- };-- auto dispatch_event = [&](Utf16FlyString const& type, Interval interval) {- // The target for a transition event is the transition’s owning element. If there is no owning element,- // no transition events are dispatched.- if (!transition->effect() || !transition->owning_element().has_value())- return;-- auto effect = transition->effect();-- Animations::TimeValue elapsed_time = [&]() {- if (interval == Interval::Start)- return max(min(-effect->start_delay(), effect->active_duration()), Animations::TimeValue::create_zero(transition->timeline()));- if (interval == Interval::End)- return max(min(transition->associated_effect_end() - effect->start_delay(), effect->active_duration()), Animations::TimeValue::create_zero(transition->timeline()));- if (interval == Interval::ActiveTime) {- // The active time of the animation at the moment it was canceled calculated using a fill mode of both.- // FIXME: Compute this properly.- return Animations::TimeValue::create_zero(transition->timeline());+ auto provisional = m_style_stabilization_epoch_depth > 0;+ for (auto count = queued.count; count > 0; --count)+ HTML::note_rendering_trace_event(provisional ? "provisional animation events"sv : "animation events committed"sv);+}++// Creates the event the pending animation event queue of `document` holds of `animation`, and dispatches it at its+// target.+static void dispatch_pending_animation_event(Document& document, Animations::AnimationRef const& animation, Animations::RustFFI::FfiPendingAnimationEvent const& pending_event)+{+ switch (pending_event.kind) {+ case Animations::RustFFI::PendingAnimationEventKind::Css: {+ auto owner = Animations::RustFFI::animations_animation_owning_element(&animation.record());+ auto& owning_element = *static_cast<DOM::Element*>(owner.element);+ auto pseudo_element = owner.has_pseudo_element+ ? Utf16String::formatted("::{}", CSS::pseudo_element_name(static_cast<CSS::PseudoElement>(owner.pseudo_element)))+ : Utf16String {};+ auto const& type = [&] -> Utf16FlyString const& {+ switch (pending_event.css_event_type) {+ case Animations::RustFFI::FfiCssEventType::AnimationStart:+ return HTML::EventNames::animationstart;+ case Animations::RustFFI::FfiCssEventType::AnimationEnd:+ return HTML::EventNames::animationend;+ case Animations::RustFFI::FfiCssEventType::AnimationIteration:+ return HTML::EventNames::animationiteration;+ case Animations::RustFFI::FfiCssEventType::AnimationCancel:+ return HTML::EventNames::animationcancel;+ case Animations::RustFFI::FfiCssEventType::TransitionRun:+ return HTML::EventNames::transitionrun;+ case Animations::RustFFI::FfiCssEventType::TransitionStart:+ return HTML::EventNames::transitionstart;+ case Animations::RustFFI::FfiCssEventType::TransitionEnd:+ return HTML::EventNames::transitionend;+ case Animations::RustFFI::FfiCssEventType::TransitionCancel:+ return HTML::EventNames::transitioncancel;}VERIFY_NOT_REACHED();}();-- double elapsed_time_output;-- switch (elapsed_time.type) {- case Animations::TimeValue::Type::Milliseconds:- elapsed_time_output = elapsed_time.value / 1000;- break;- case Animations::TimeValue::Type::Percentage:- // FIXME: The spec doesn't specify how to handle this case- elapsed_time_output = 0;- break;- }-- auto timeline = transition->timeline();-- auto owning_element = transition->owning_element().value();- auto& global = HTML::relevant_global_object(owning_element.element().document());- auto pseudo_element = owning_element.pseudo_element().map([](auto it) {- return Utf16String::formatted("::{}", CSS::pseudo_element_name(it));- })- .value_or({});- auto event = transition->create_event(owning_element.element().document(), type, elapsed_time_output, move(pseudo_element));- event->set_time_stamp(HighResolutionTime::current_high_resolution_time(global));+ auto event = animation.timing_state().kind == Animations::RustFFI::FfiAnimationKind::CssTransition+ ? CSS::CSSTransition::create_event(animation, owning_element.document(), type, pending_event.elapsed_time, pseudo_element)+ : CSS::CSSAnimation::create_event(animation, owning_element.document(), type, pending_event.elapsed_time, pseudo_element);+ event->set_time_stamp(pending_event.time_stamp);event->set_is_trusted(true);-- append_pending_animation_event({- .event = event,- .animation = transition,- .target = transition->owning_element()->element(),- .scheduled_event_time = timeline && timeline->can_convert_a_timeline_time_to_an_origin_relative_time()- ? timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline->current_time())- : Optional<double> {},- });- };-- if (previous_phase == Phase::Idle) {- if (transition_phase == Phase::Pending || transition_phase == Phase::Before)- dispatch_event(HTML::EventNames::transitionrun, Interval::Start);-- if (transition_phase == Phase::Active) {- dispatch_event(HTML::EventNames::transitionrun, Interval::Start);- dispatch_event(HTML::EventNames::transitionstart, Interval::Start);- }-- if (transition_phase == Phase::After) {- dispatch_event(HTML::EventNames::transitionrun, Interval::Start);- dispatch_event(HTML::EventNames::transitionstart, Interval::Start);- dispatch_event(HTML::EventNames::transitionend, Interval::End);- }- } else if (previous_phase == Phase::Pending || previous_phase == Phase::Before) {- if (transition_phase == Phase::Active)- dispatch_event(HTML::EventNames::transitionstart, Interval::Start);-- if (transition_phase == Phase::After) {- dispatch_event(HTML::EventNames::transitionstart, Interval::Start);- dispatch_event(HTML::EventNames::transitionend, Interval::End);- }- } else if (previous_phase == Phase::Active) {- if (transition_phase == Phase::After)- dispatch_event(HTML::EventNames::transitionend, Interval::End);-- if (transition_phase == Phase::Before)- dispatch_event(HTML::EventNames::transitionend, Interval::Start);- } else if (previous_phase == Phase::After) {- if (transition_phase == Phase::Active)- dispatch_event(HTML::EventNames::transitionstart, Interval::End);-- if (transition_phase == Phase::Before) {- dispatch_event(HTML::EventNames::transitionstart, Interval::End);- dispatch_event(HTML::EventNames::transitionend, Interval::Start);- }- }-- if (transition_phase == Phase::Idle) {- if (previous_phase != Phase::Idle && previous_phase != Phase::After)- dispatch_event(HTML::EventNames::transitioncancel, Interval::ActiveTime);- }-- transition->set_previous_phase(transition_phase);-}--// https://www.w3.org/TR/css-animations-2/#event-dispatch-void Document::dispatch_events_for_animation_if_necessary(GC::Ref<Animations::Animation> animation)-{- if (animation->is_smil_animation()) {- as<SVG::SMILAnimation>(*animation).animation_element().queue_time_events_if_necessary();+ owning_element.dispatch_event(event);return;}-- if (animation->is_css_transition()) {- dispatch_events_for_transition(as<CSS::CSSTransition>(*animation));+ case Animations::RustFFI::PendingAnimationEventKind::Playback:+ Animations::dispatch_pending_playback_event(animation, document, pending_event);return;- }-- // Each time a new animation frame is established and the animation does not have a pending play task or pending- // pause task, the events to dispatch are determined by comparing the animation’s phase before and after- // establishing the new animation frame as follows:- auto effect = animation->effect();- if (!effect || !effect->is_keyframe_effect() || !animation->is_css_animation() || animation->pending())+ case Animations::RustFFI::PendingAnimationEventKind::Time:+ static_cast<SVG::SVGAnimationElement*>(Animations::RustFFI::animations_smil_animation_element(&animation.record()))->dispatch_pending_time_event(pending_event);return;-- auto& css_animation = as<CSS::CSSAnimation>(*animation);-- auto previous_phase = effect->previous_phase();- auto resolved_timing = effect->resolve_timing();- auto current_phase = resolved_timing.phase;- auto current_iteration = effect->current_iteration(resolved_timing).value_or(0.0);-- auto owning_element = css_animation.owning_element();-- if (!owning_element.has_value())- return;-- auto dispatch_event = [&](Utf16FlyString const& name, Animations::TimeValue elapsed_time) {- double elapsed_time_output;- switch (elapsed_time.type) {- case Animations::TimeValue::Type::Milliseconds:- elapsed_time_output = elapsed_time.value / 1000;- break;- case Animations::TimeValue::Type::Percentage:- // FIXME: The spec doesn't specify how to handle this case- elapsed_time_output = 0;- break;- }-- auto timeline = animation->timeline();-- auto pseudo_element = owning_element->pseudo_element().map([](auto it) {- return Utf16String::formatted("::{}", CSS::pseudo_element_name(it));- })- .value_or({});- auto& global = HTML::relevant_global_object(owning_element->element());- auto event = css_animation.create_event(owning_element->element().document(), name, elapsed_time_output, move(pseudo_element));- event->set_time_stamp(HighResolutionTime::current_high_resolution_time(global));- event->set_is_trusted(true);-- append_pending_animation_event({- .event = event,- .animation = css_animation,- .target = owning_element->element(),- .scheduled_event_time = timeline && timeline->can_convert_a_timeline_time_to_an_origin_relative_time()- ? timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline->current_time())- : Optional<double> {},- });- };-- // For calculating the elapsedTime of each event, the following definitions are used:-- // - interval start = max(min(-start delay, active duration), 0)- auto interval_start = [&]() {- return max(min(-effect->start_delay(), effect->active_duration()), Animations::TimeValue::create_zero(animation->timeline()));- };-- // - interval end = max(min(associated effect end - start delay, active duration), 0)- auto interval_end = [&]() {- return max(min(effect->end_time() - effect->start_delay(), effect->active_duration()), Animations::TimeValue::create_zero(animation->timeline()));- };-- switch (previous_phase) {- case Animations::AnimationEffect::Phase::Before:- [[fallthrough]];- case Animations::AnimationEffect::Phase::Idle:- if (current_phase == Animations::AnimationEffect::Phase::Active) {- dispatch_event(HTML::EventNames::animationstart, interval_start());- } else if (current_phase == Animations::AnimationEffect::Phase::After) {- dispatch_event(HTML::EventNames::animationstart, interval_start());- dispatch_event(HTML::EventNames::animationend, interval_end());- }- break;- case Animations::AnimationEffect::Phase::Active:- if (current_phase == Animations::AnimationEffect::Phase::Before) {- dispatch_event(HTML::EventNames::animationend, interval_start());- } else if (current_phase == Animations::AnimationEffect::Phase::Active) {- auto previous_current_iteration = effect->previous_current_iteration();- if (previous_current_iteration != current_iteration) {- // The elapsed time for an animationiteration event is defined as follows:-- // 1. Let previous current iteration be the current iteration from the previous animation frame.-- // 2. If previous current iteration is greater than current iteration, let iteration boundary be current iteration + 1,- // otherwise let it be current iteration.- auto iteration_boundary = previous_current_iteration > current_iteration ? current_iteration + 1 : current_iteration;-- // 3. The elapsed time is the result of evaluating (iteration boundary - iteration start) × iteration duration).- auto elapsed_time = effect->iteration_duration() * (iteration_boundary - effect->iteration_start());-- dispatch_event(HTML::EventNames::animationiteration, elapsed_time);- }- } else if (current_phase == Animations::AnimationEffect::Phase::After) {- dispatch_event(HTML::EventNames::animationend, interval_end());- }- break;- case Animations::AnimationEffect::Phase::After:- if (current_phase == Animations::AnimationEffect::Phase::Active) {- dispatch_event(HTML::EventNames::animationstart, interval_end());- } else if (current_phase == Animations::AnimationEffect::Phase::Before) {- dispatch_event(HTML::EventNames::animationstart, interval_end());- dispatch_event(HTML::EventNames::animationend, interval_start());- }- break;}-- if (current_phase == Animations::AnimationEffect::Phase::Idle && previous_phase != Animations::AnimationEffect::Phase::Idle && previous_phase != Animations::AnimationEffect::Phase::After) {- // FIXME: Calculate a non-zero time when the animation is cancelled by means other than calling cancel()- auto cancel_time = animation->release_saved_cancel_time().value_or(Animations::TimeValue::create_zero(animation->timeline()));- dispatch_event(HTML::EventNames::animationcancel, cancel_time);- }-- effect->set_previous_phase(current_phase);- effect->set_previous_current_iteration(current_iteration);+ VERIFY_NOT_REACHED();}// https://html.spec.whatwg.org/multipage/browsing-the-web.html#scroll-to-the-fragment-identifier@@ -8812,15 +8666,20 @@ void Document::prune_image_resource_caches()}// https://www.w3.org/TR/web-animations-1/#dom-document-timeline-GC::Ref<Animations::DocumentTimeline> Document::timeline()+GC::Ref<Animations::AnimationTimeline> Document::timeline(){// The DocumentTimeline object representing the default document timeline. The default document timeline has an// origin time of zero.if (!m_default_timeline)- m_default_timeline = Animations::DocumentTimeline::create(*this, 0.0);+ m_default_timeline = Animations::AnimationTimeline::create_document_timeline(*this, 0.0);return *m_default_timeline;}+Animations::WeakAnimationSetView Document::animations_following_named_timelines()+{+ return Animations::WeakAnimationSetView { *Animations::RustFFI::animations_document_animations_set(m_animations, Animations::RustFFI::DocumentAnimationSetKind::FollowingNamedTimelines) };+}+Animations::NamedTimelines& Document::named_timelines(){if (!m_named_timelines)@@ -8847,6 +8706,21 @@ int Document::compare_elements_in_tree_order_for_composite_order(Element& first,auto compare_in_tree = [&] {HTML::note_rendering_trace_event("composite order compared by tree position"sv);+ // NB: compare_document_position() orders elements of different trees by their addresses, which can disagree+ // with the order of elements within a tree. Elements of other trees than the document's, as of shadow trees+ // and removed subtrees, sort after the document's instead, by their trees, so that the order is total.+ // Elements of different documents sort by their documents, whichever document compares them.+ auto& first_root = first.root();+ auto& second_root = second.root();+ if (&first_root != &second_root) {+ if (&first.document() != &second.document())+ return &first.document() < &second.document() ? -1 : 1;+ if (&first_root == this)+ return -1;+ if (&second_root == this)+ return 1;+ return &first_root < &second_root ? -1 : 1;+ }auto position = first.compare_document_position(second);if (position & Node::DOCUMENT_POSITION_FOLLOWING)return -1;@@ -8885,21 +8759,25 @@ void Document::keep_element_tree_positions_across_attribute_change(u64 version_bm_element_tree_positions_dom_tree_version = dom_tree_version();}-void Document::associate_with_animation(GC::Ref<Animations::Animation> animation)+void Document::associate_with_animation(Animations::AnimationRef const& animation){- m_associated_animations.set(animation);+ associated_animations(m_animations).set(animation);if (m_style_stabilization_epoch_depth > 0)- m_animations_created_in_stabilization_epoch.set(animation);+ animations_created_in_stabilization_epoch(m_animations).set(animation);}-void Document::disassociate_with_animation(GC::Ref<Animations::Animation> animation)+void Document::disassociate_with_animation(Animations::AnimationRef const& animation, Optional<Animations::EffectRef> const& effect){- if (animation->effect() && is<Animations::KeyframeEffect>(*animation->effect())) {- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation->effect());- m_effects_needing_animated_style_update.remove(effect);- m_effects_needing_animated_style_update_after_current_update.remove(effect);+ if (effect.has_value()) {+ effects_needing_animated_style_update(m_animations).remove(effect->record());+ effects_needing_animated_style_update_after_current_update(m_animations).remove(effect->record());}- m_associated_animations.remove(animation);+ associated_animations(m_animations).remove(animation.record());+}++bool Document::has_associated_animations() const+{+ return !associated_animations(m_animations).is_empty();}static bool is_transform_family_property(CSS::PropertyID property_id)@@ -8911,15 +8789,23 @@ static bool is_transform_family_property(CSS::PropertyID property_id)CSS::PropertyID::Transform);}-using CompositorAnimationKeyframesByEffect = GC::RootHashMap<Animations::KeyframeEffect const*, NonnullOwnPtr<Painting::CompositorAnimationKeyframes>>;+// The keyframes the compositor animation builder reads of each effect an update pass asks about, which the pass keeps+// alive with the elements they resolve against.+struct CompositorAnimationKeyframesOfEffect {+ NonnullOwnPtr<Painting::CompositorAnimationKeyframes> keyframes;++ void visit_edges(GC::Cell::Visitor& visitor) const { keyframes->visit_edges(visitor); }+};+using CompositorAnimationKeyframesByEffect = GC::RootHashMap<Animations::RustFFI::AnimationEffectId, CompositorAnimationKeyframesOfEffect>;// The keyframes of an effect as the compositor animation builder reads them, built once for the// update pass however many animations and questions the pass takes from them.-static Painting::CompositorAnimationKeyframes const& compositor_animation_keyframes(CompositorAnimationKeyframesByEffect& keyframes_by_effect, Animations::KeyframeEffect const& effect, Animations::Animation const& animation, DOM::AbstractElement target)+static Painting::CompositorAnimationKeyframes const& compositor_animation_keyframes(CompositorAnimationKeyframesByEffect& keyframes_by_effect, Animations::EffectRef const& effect, Animations::AnimationRef const& animation, DOM::AbstractElement target){- return *keyframes_by_effect.ensure(&effect, [&] {- return make<Painting::CompositorAnimationKeyframes>(effect, animation, target);- });+ return *keyframes_by_effect.ensure(effect.id(), [&] {+ return CompositorAnimationKeyframesOfEffect { make<Painting::CompositorAnimationKeyframes>(effect, animation, target) };+ })+ .keyframes;}// Whether a box inside an SVG paints or places itself by its bounding box, which includes the transforms of the boxes@@ -8996,35 +8882,15 @@ static bool svg_transform_may_run_on_the_compositor(Element const& target, Layou// Builds the compositor animation of one target kind for an effect the compositor could drive, and// keeps it pending with the effect. The checks here are the ones that read the animation objects; the// builder in Rust lowers and validates the keyframes.-static Painting::CompositorAnimationEffectState::BuildOutcome build_compositor_animation(Layout::BegunRead const& read, Animations::KeyframeEffect& effect, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind, CompositorAnimationKeyframesByEffect& keyframes_by_effect)+static Painting::CompositorAnimationEffectState::BuildOutcome build_compositor_animation(Layout::BegunRead const& read, Animations::EffectRef const& effect, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind, CompositorAnimationKeyframesByEffect& keyframes_by_effect){auto animation = effect.associated_animation();- if (!animation || animation->play_state() != Bindings::AnimationPlayState::Running)- return {};- bool is_initial_pending_css_transition = animation->pending()- && animation->has_pending_play_task()- && animation->is_css_transition()- && as<CSS::CSSTransition>(*animation).previous_phase() == CSS::CSSTransition::Phase::Idle;- if (animation->pending() && !is_initial_pending_css_transition)- return {};- auto timeline = animation->timeline();- if (!timeline || !timeline->is_monotonically_increasing())+ if (!animation.has_value())return {};- auto phase = effect.phase();- if (phase != Animations::AnimationEffect::Phase::Before && phase != Animations::AnimationEffect::Phase::Active)- return {};- if ((!isinf(effect.iteration_count()) && effect.iteration_count() != 1) || effect.composite() != Bindings::CompositeOperation::Replace)- return {};- if (animation->playback_rate() <= 0 || !isfinite(animation->playback_rate()))- return {};- if (effect.start_delay().type != Animations::TimeValue::Type::Milliseconds- || effect.iteration_duration().type != Animations::TimeValue::Type::Milliseconds- || effect.iteration_duration().value <= 0)- return {};- if (phase == Animations::AnimationEffect::Phase::Before && effect.before_active_boundary_time() != effect.start_delay())- return {};- auto current_time = animation->current_time();- if (!current_time.has_value() || current_time->type != Animations::TimeValue::Type::Milliseconds)+ // NB: The record decides whether the compositor may run the effect as far as its timing goes, and where its+ // animation is anchored.+ auto const state = animation->timing_state();+ if (state.compositor_anchor == Animations::RustFFI::FfiCompositorAnchorKind::None)return {};if (effect.target_properties().is_empty())return {};@@ -9049,25 +8915,12 @@ static Painting::CompositorAnimationEffectState::BuildOutcome build_compositor_areturn {};}auto monotonic_time_at_anchor_ms = [&]() -> Optional<double> {- if (!is_initial_pending_css_transition) {- auto frame_timestamp = target->document().last_animation_frame_timestamp();- if (!frame_timestamp.has_value())- return {};- return *frame_timestamp + target->document().relevant_settings_object().time_origin();- }-- // OPTIMIZATION: A new CSS transition is play-pending until the next animation update. Start its compositor- // descriptor at the style change event time without resolving the Animation's pending task.- auto style_change_event_time = Animations::TimeValue {- Animations::TimeValue::Type::Milliseconds,- as<CSS::CSSTransition>(*animation).style_change_event_time(),- };- if (!timeline->can_convert_a_timeline_time_to_an_origin_relative_time())- return {};- auto origin_relative_time = timeline->convert_a_timeline_time_to_an_origin_relative_time(style_change_event_time);- if (!origin_relative_time.has_value())+ if (state.compositor_anchor == Animations::RustFFI::FfiCompositorAnchorKind::OriginRelativeTime)+ return state.compositor_anchor_origin_relative_time + target->document().relevant_settings_object().time_origin();+ auto frame_timestamp = target->document().last_animation_frame_timestamp();+ if (!frame_timestamp.has_value())return {};- return *origin_relative_time + target->document().relevant_settings_object().time_origin();+ return *frame_timestamp + target->document().relevant_settings_object().time_origin();}();if (!monotonic_time_at_anchor_ms.has_value())return {};@@ -9086,35 +8939,27 @@ static Painting::CompositorAnimationEffectState::BuildOutcome build_compositor_aif (!row.has_value())return {};- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set || key_frame_set->keyframes_by_key.size() < 2)+ auto const& keyframe_set = effect.keyframe_set();+ if (!keyframe_set || keyframe_set.keyframe_count() < 2)return {};auto const& keyframes = compositor_animation_keyframes(keyframes_by_effect, effect, *animation, *target);Painting::CompositorAnimationEffectState::TimingAnchor timing_anchor {.monotonic_time_ms = *monotonic_time_at_anchor_ms,- .local_time_ms = current_time->value,+ .local_time_ms = state.compositor_anchor_local_time,};return effect.compositor_animation_state().build(read, keyframes, *layout_node, target_kind, timing_anchor);}-static Optional<double> next_throttled_animation_iteration_event_time(Animations::Animation const& animation, Animations::KeyframeEffect const& effect)+// The local time of the next iteration event of a CSS animation whose ticks are throttled, whose timing is `state`.+static Optional<double> next_throttled_animation_iteration_event_time(Animations::RustFFI::FfiAnimationTimingState const& state, Animations::EffectRef const& effect){- if (!animation.is_css_animation() || animation.pending()- || animation.play_state() != Bindings::AnimationPlayState::Running- || animation.playback_rate() <= 0 || !isfinite(animation.playback_rate())- || !animation.timeline() || !animation.timeline()->is_monotonically_increasing()- || effect.start_delay().type != Animations::TimeValue::Type::Milliseconds- || effect.iteration_duration().type != Animations::TimeValue::Type::Milliseconds- || effect.iteration_duration().value <= 0 || !isfinite(effect.iteration_duration().value)+ // NB: The record decides this as far as the timing goes.+ if (!state.next_throttled_iteration_event_time.has_value|| !effect.can_skip_per_frame_style_update()- || effect.phase() != Animations::AnimationEffect::Phase::Active)+ || state.phase != Animations::RustFFI::AnimationEffectPhase::Active)return {};-- // NB: Observable throttled animations need a rendering update at the next iteration boundary,- // not at every display refresh. Seeking and cancellation already request their own updates.- return effect.start_delay().value- + (effect.previous_current_iteration() + 1 - effect.iteration_start()) * effect.iteration_duration().value;+ return state.next_throttled_iteration_event_time.value;}void Document::schedule_compositor_animation_wakeup(double delay_ms)@@ -9144,23 +8989,26 @@ void Document::service_compositor_animation_wakeup(double timestamp)Optional<double> next_wakeup_delay_ms;bool reached_wakeup = false;bool reached_compositor_active_start = false;- for (auto& animation : m_associated_animations) {- if (!animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ for (auto const& animation : associated_animations(m_animations)) {+ auto associated_effect = animation.effect();+ if (!associated_effect.has_value())continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());- auto timeline_time = animation.timeline() ? animation.timeline()->current_time_at_timestamp(timestamp) : Optional<Animations::TimeValue> {};- auto current_time = animation.current_time_at(timeline_time);+ auto const& effect = *associated_effect;+ auto const state = animation.timing_state_at_timestamp(timestamp);+ auto current_time = Animations::from_ffi(state.current_time_at_timestamp);if (!current_time.has_value() || current_time->type != Animations::TimeValue::Type::Milliseconds)continue;+ auto const& timing = state.effect;+ auto const playback_rate = state.playback.playback_rate;bool is_compositor_handled = effect.is_compositor_driven()|| effect.is_compositor_replaced()|| effect.has_retained_compositor_animations();- if (!animation.pending()- && animation.playback_rate() > 0- && effect.start_delay().type == Animations::TimeValue::Type::Milliseconds- && effect.phase() == Animations::AnimationEffect::Phase::Before) {- if (current_time->value < effect.start_delay().value) {- auto delay = (effect.start_delay().value - current_time->value) / animation.playback_rate();+ if (!state.playback.has_pending_play_task && !state.playback.has_pending_pause_task+ && playback_rate > 0+ && timing.start_delay.type == Animations::TimeValue::Type::Milliseconds+ && state.phase == Animations::RustFFI::AnimationEffectPhase::Before) {+ if (current_time->value < timing.start_delay.value) {+ auto delay = (timing.start_delay.value - current_time->value) / playback_rate;if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)next_wakeup_delay_ms = delay;} else {@@ -9170,10 +9018,10 @@ void Document::service_compositor_animation_wakeup(double timestamp)reached_compositor_active_start = true;}}- if (auto iteration_event_time = next_throttled_animation_iteration_event_time(animation, effect);+ if (auto iteration_event_time = next_throttled_animation_iteration_event_time(state, effect);iteration_event_time.has_value() && !effect.can_skip_per_frame_animation_tick()) {if (current_time->value < *iteration_event_time) {- auto delay = (*iteration_event_time - current_time->value) / animation.playback_rate();+ auto delay = (*iteration_event_time - current_time->value) / playback_rate;if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)next_wakeup_delay_ms = delay;} else {@@ -9181,11 +9029,11 @@ void Document::service_compositor_animation_wakeup(double timestamp)}}bool is_offscreen_handled = effect.is_offscreen_throttled() && effect.can_skip_per_frame_style_update();- if ((!is_compositor_handled && !is_offscreen_handled) || isinf(effect.iteration_count()))+ if ((!is_compositor_handled && !is_offscreen_handled) || isinf(timing.iteration_count))continue;- auto active_end = effect.start_delay().value + effect.iteration_duration().value * effect.iteration_count();+ auto active_end = timing.start_delay.value + timing.iteration_duration.value * timing.iteration_count;if (current_time->value < active_end) {- auto delay = (active_end - current_time->value) / animation.playback_rate();+ auto delay = (active_end - current_time->value) / playback_rate;if (!next_wakeup_delay_ms.has_value() || delay < *next_wakeup_delay_ms)next_wakeup_delay_ms = delay;continue;@@ -9222,11 +9070,15 @@ void Document::force_visual_context_tree_rebuild_on_next_compositor_animation_upvoid Document::update_compositor_animations(Layout::BegunRead const& read){struct CompetingPropertyEffects {- GC::Ptr<Animations::KeyframeEffect> winner;+ Optional<Animations::EffectRef> winner;bool all_effects_use_replace { true };u32 effect_count { 0 };- void visit_edges(GC::Cell::Visitor& visitor) { visitor.visit(winner); }+ void visit_edges(GC::Cell::Visitor& visitor)+ {+ if (winner.has_value())+ winner->visit_edges(visitor);+ }};struct CompetingEffects {CompetingPropertyEffects opacity;@@ -9247,15 +9099,15 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)paint_state().begin_compositor_animation_update();GC::RootHashMap<GC::Ref<Layout::Node>, bool> previous_content_retention;GC::RootHashTable<GC::Ref<Layout::Node>> retained_this_pass;- GC::RootHashTable<GC::Ref<Animations::KeyframeEffect>> previously_compositor_driven_effects;- GC::RootHashTable<GC::Ref<Animations::KeyframeEffect>> previously_compositor_replaced_effects;- GC::RootHashTable<GC::Ref<Animations::KeyframeEffect>> previously_published_effects;- GC::RootHashTable<GC::Ref<Animations::KeyframeEffect>> previously_offscreen_throttled_effects;+ HashTable<Animations::RustFFI::AnimationEffectId> previously_compositor_driven_effects;+ HashTable<Animations::RustFFI::AnimationEffectId> previously_compositor_replaced_effects;+ HashTable<Animations::RustFFI::AnimationEffectId> previously_published_effects;+ HashTable<Animations::RustFFI::AnimationEffectId> previously_offscreen_throttled_effects;GC::RootHashMap<DOM::AbstractElement, CompetingEffects> competing_effects;CompositorAnimationKeyframesByEffect keyframes_by_effect;- GC::RootHashMap<GC::Ptr<Animations::KeyframeEffect>, bool> only_translates_horizontally_cache;- GC::RootHashMap<GC::Ptr<Animations::KeyframeEffect>, bool> animated_transform_preserves_axes_cache;- HashMap<Layout::Node const*, GC::RootVector<GC::Ptr<Animations::KeyframeEffect>>> in_effect_transform_effects_by_layout_node;+ HashMap<Animations::RustFFI::AnimationEffectId, bool> only_translates_horizontally_cache;+ HashMap<Animations::RustFFI::AnimationEffectId, bool> animated_transform_preserves_axes_cache;+ HashMap<Layout::Node const*, GC::RootVector<Animations::EffectRef>> in_effect_transform_effects_by_layout_node;GC::RootHashMap<GC::Ptr<Element>, CSSPixelRect> observation_target_rect_cache;GC::RootHashTable<GC::Ref<Element>> elements_with_intersection_observation_descendants;GC::RootHashTable<GC::Ref<Element>> elements_with_visibility_observation_descendants;@@ -9301,15 +9153,15 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)&& abs(matrix[3, 0]) <= epsilon;};- auto animated_transform_preserves_axes = [&](Animations::KeyframeEffect& effect, Layout::Node const& layout_node) {- return animated_transform_preserves_axes_cache.ensure(effect, [&] {+ auto animated_transform_preserves_axes = [&](Animations::EffectRef const& effect, Layout::Node const& layout_node) {+ return animated_transform_preserves_axes_cache.ensure(effect.id(), [&] {if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Rotate)))return false;if (!effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Transform)))return true;auto animation = effect.associated_animation();auto target = effect.target_abstract_element();- if (!animation || !target.has_value() || !effect.key_frame_set())+ if (!animation.has_value() || !target.has_value() || !effect.keyframe_set())return false;return compositor_animation_keyframes(keyframes_by_effect, effect, *animation, *target).transform_preserves_axes(layout_node);});@@ -9323,8 +9175,8 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)if (ancestor->has_css_transform() && !transform_preserves_horizontal_axis(*ancestor))return true;if (auto effects = in_effect_transform_effects_by_layout_node.find(ancestor); effects != in_effect_transform_effects_by_layout_node.end()) {- for (auto effect : effects->value) {- if (!animated_transform_preserves_axes(*effect, *ancestor))+ for (auto const& effect : effects->value) {+ if (!animated_transform_preserves_axes(effect, *ancestor))return true;}}@@ -9343,7 +9195,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)animation_pass_viewport_mapping);};- auto paint_only_effect_is_offscreen = [&](Animations::KeyframeEffect const& effect, AbstractElement abstract_target) {+ auto paint_only_effect_is_offscreen = [&](Animations::EffectRef const& effect, AbstractElement abstract_target) {auto& target = abstract_target.element();bool is_svg_target = target.namespace_uri() == Namespace::SVG;if (abstract_target.pseudo_element().has_value()@@ -9458,7 +9310,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)|| ancestor->is_sticky_position() || ancestor->filter().has_filters()|| in_effect_transform_effects_by_layout_node.contains(ancestor);if (auto const* element = as_if<Element>(ancestor->dom_node())) {- if (auto effects = competing_effects.get(*element); effects.has_value() && effects->filter.winner)+ if (auto effects = competing_effects.get(*element); effects.has_value() && effects->filter.winner.has_value())can_move_or_expand_paint = true;}if (can_move_or_expand_paint) {@@ -9487,24 +9339,27 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)&& !bounds_in_viewport(*layout_node).intersects(visible_bounds);};- auto observation_has_another_transform_animation = [&](Element const& animated_target, Element const& observation_target, Animations::KeyframeEffect const& current_effect) {- for (auto& animation : m_associated_animations) {- if (animation.is_idle() || !animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ auto observation_has_another_transform_animation = [&](Element const& animated_target, Element const& observation_target, Animations::EffectRef const& current_effect) {+ for (auto const& animation : associated_animations(m_animations)) {+ auto effect = animation.effect();+ if (!effect.has_value())+ continue;+ auto const state = animation.timing_state();+ if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle)continue;- auto const& effect = static_cast<Animations::KeyframeEffect const&>(*animation.effect());- if (&effect == ¤t_effect || !effect.is_in_effect())+ if (*effect == current_effect || !state.is_in_effect)continue;- auto effect_target = effect.target();+ auto* effect_target = effect->target();if (!effect_target || !animated_target.is_shadow_including_inclusive_ancestor_of(*effect_target)|| !effect_target->is_shadow_including_inclusive_ancestor_of(observation_target))continue;- if (any_of(effect.target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); }))+ if (any_of(effect->target_properties(), [](auto const& property) { return is_transform_family_property(property.id()); }))return true;}return false;};- auto transform_affects_intersection_observation = [&](Element& animated_target, Animations::KeyframeEffect const& effect, bool only_translates_horizontally, bool& requires_main_thread_sampling) {+ auto transform_affects_intersection_observation = [&](Element& animated_target, Animations::EffectRef const& effect, bool only_translates_horizontally, bool& requires_main_thread_sampling) {if (!elements_with_intersection_observation_descendants.contains(animated_target))return false;for (auto const& observer : m_intersection_observers) {@@ -9543,29 +9398,31 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)return elements_with_visibility_observation_descendants.contains(animated_target);};- for (auto& animation : m_associated_animations) {- if (!animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ for (auto const& animation : associated_animations(m_animations)) {+ auto associated_effect = animation.effect();+ if (!associated_effect.has_value())continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());+ auto const& effect = *associated_effect;if (effect.is_compositor_driven())- previously_compositor_driven_effects.set(effect);+ previously_compositor_driven_effects.set(effect.id());if (effect.is_compositor_replaced())- previously_compositor_replaced_effects.set(effect);+ previously_compositor_replaced_effects.set(effect.id());if (effect.has_retained_compositor_animations())- previously_published_effects.set(effect);+ previously_published_effects.set(effect.id());if (effect.is_offscreen_throttled())- previously_offscreen_throttled_effects.set(effect);+ previously_offscreen_throttled_effects.set(effect.id());if (auto target = effect.target_abstract_element(); target.has_value()) {if (auto* layout_node = target->unsafe_layout_node(read)) {previous_content_retention.ensure(*layout_node, [&] { return layout_node->retains_compositor_animated_content(); });}}- effect.set_is_compositor_driven(false);- effect.set_is_compositor_replaced(false);- effect.set_is_offscreen_throttled(false);- effect.set_is_observation_relevant_compositor_animation(false);+ effect.set_flag(Animations::RustFFI::EffectFlag::CompositorDriven, false);+ effect.set_flag(Animations::RustFFI::EffectFlag::CompositorReplaced, false);+ effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, false);+ effect.set_flag(Animations::RustFFI::EffectFlag::ObservationRelevantCompositorAnimation, false);- if (animation.is_idle() || (!effect.is_in_effect() && effect.phase() != Animations::AnimationEffect::Phase::Before))+ auto const state = animation.timing_state();+ if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle || (!state.is_in_effect && state.phase != Animations::RustFFI::AnimationEffectPhase::Before))continue;auto target = effect.target_abstract_element();if (!target.has_value())@@ -9573,13 +9430,14 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)auto& effects = competing_effects.ensure(*target);auto add_competing_effect = [&](CompetingPropertyEffects& property_effects) {++property_effects.effect_count;- bool effect_produces_output = effect.is_in_effect();- if (effect_produces_output && effect.composite() != Bindings::CompositeOperation::Replace)+ bool effect_produces_output = state.is_in_effect;+ if (effect_produces_output && !effect.composite_is_replace())property_effects.all_effects_use_replace = false;- bool winner_produces_output = property_effects.winner && property_effects.winner->is_in_effect();- if (!property_effects.winner+ auto winner_animation = property_effects.winner.has_value() ? property_effects.winner->associated_animation() : Optional<Animations::AnimationRef> {};+ bool winner_produces_output = winner_animation.has_value() && winner_animation->timing_state().is_in_effect;+ if (!property_effects.winner.has_value()|| (effect_produces_output && !winner_produces_output)- || (effect_produces_output == winner_produces_output && Animations::KeyframeEffect::composite_order(*property_effects.winner, effect) < 0))+ || (effect_produces_output == winner_produces_output && Animations::AnimationRef::composite_order(*winner_animation, animation) < 0))property_effects.winner = effect;};if (effect.target_properties().contains(CSS::PropertyNameAndID::from_id(CSS::PropertyID::Opacity)))@@ -9595,35 +9453,31 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)}}- auto winner_uses_replace_keyframes = [](Animations::KeyframeEffect& effect) {- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set)- return false;- return all_of(key_frame_set->keyframes_by_key, [](auto const& entry) {- return first_is_one_of(entry.composite,- Bindings::CompositeOperationOrAuto::Auto,- Bindings::CompositeOperationOrAuto::Replace);- });+ auto winner_uses_replace_keyframes = [](Animations::EffectRef const& effect) {+ auto const& keyframe_set = effect.keyframe_set();+ return keyframe_set && !keyframe_set.facts().has_additive_keyframe;};// A keyframe that leaves a property out takes the underlying value, which is the output of the effects beneath the// winner where there are any. The compositor only knows the element's own style.- auto winner_takes_the_underlying_value = [](Animations::KeyframeEffect& effect, auto is_property) {- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set)+ auto winner_takes_the_underlying_value = [](Animations::EffectRef const& effect, auto is_property) {+ auto const& keyframe_set = effect.keyframe_set();+ if (!keyframe_set)return false;- return any_of(key_frame_set->keyframes_by_key, [&](auto const& entry) {- return any_of(entry.properties, [&](auto const& property) {- return is_property(property.key.id()) && property.value.template has<Animations::KeyframeEffect::KeyFrameSet::UseInitial>();- });- });+ for (size_t index = 0; index < keyframe_set.keyframe_count(); ++index) {+ for (auto property : effect.target_properties()) {+ if (is_property(property.id()) && keyframe_set.value(index, to_underlying(property.id())).state == Animations::RustFFI::FfiKeyframeValueState::ElementValue)+ return true;+ }+ }+ return false;};for (auto& [target, effects] : competing_effects) {(void)target;auto validate_winner = [&](CompetingPropertyEffects& property_effects, auto is_property) {if (!property_effects.all_effects_use_replace- || (property_effects.winner && !winner_uses_replace_keyframes(*property_effects.winner))- || (property_effects.winner && property_effects.effect_count > 1 && winner_takes_the_underlying_value(*property_effects.winner, is_property)))- property_effects.winner = nullptr;+ || (property_effects.winner.has_value() && !winner_uses_replace_keyframes(*property_effects.winner))+ || (property_effects.winner.has_value() && property_effects.effect_count > 1 && winner_takes_the_underlying_value(*property_effects.winner, is_property)))+ property_effects.winner.clear();};auto is = [](CSS::PropertyID property_id) {return [property_id](CSS::PropertyID id) { return id == property_id; };@@ -9636,7 +9490,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)// An opacity of 1 does not otherwise create an effects frame. Give an otherwise publishable opacity// animation a target before the normal handoff loop, and retain that target while the effect remains live.- auto can_force_opacity_effects_layer = [](Animations::KeyframeEffect const& effect) {+ auto can_force_opacity_effects_layer = [](Animations::EffectRef const& effect) {return all_of(effect.target_properties(), [](auto const& property) {return first_is_one_of(property.id(), CSS::PropertyID::Opacity, CSS::PropertyID::BackgroundColor)|| is_transform_family_property(property.id());@@ -9644,8 +9498,8 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)};bool forced_opacity_effects_layer = false;for (auto& [target, effects] : competing_effects) {- auto effect = effects.opacity.winner;- if (!effect || opacity_affects_visibility_observation(target.element()) || !can_force_opacity_effects_layer(*effect))+ auto const& effect = effects.opacity.winner;+ if (!effect.has_value() || opacity_affects_visibility_observation(target.element()) || !can_force_opacity_effects_layer(*effect))continue;bool missing_visual_context_node = build_compositor_animation(read, *effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity, keyframes_by_effect).missing_visual_context_node;@@ -9678,21 +9532,12 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)bool has_observation_relevant_compositor_animation = false;bool requested_withdrawn_effect_sample = false;- auto schedule_next_phase_wakeup = [&](Animations::KeyframeEffect const& effect, Animations::Animation const& animation) {- if (effect.start_delay().type != Animations::TimeValue::Type::Milliseconds- || effect.iteration_duration().type != Animations::TimeValue::Type::Milliseconds- || !animation.current_time().has_value()- || animation.current_time()->type != Animations::TimeValue::Type::Milliseconds- || animation.playback_rate() <= 0)+ auto schedule_next_phase_wakeup = [&](Animations::RustFFI::FfiAnimationTimingState const& state) {+ // NB: The record decides when the effect next changes phase.+ if (!state.next_phase_boundary_delay.has_value)return;- auto next_phase_boundary = effect.start_delay().value;- if (animation.current_time()->value >= next_phase_boundary) {- if (isinf(effect.iteration_count()))- return;- next_phase_boundary += effect.iteration_duration().value * effect.iteration_count();- }- auto delay = (next_phase_boundary - animation.current_time()->value) / animation.playback_rate();- if (delay > 0 && (!compositor_animation_wakeup_delay_ms.has_value() || delay < *compositor_animation_wakeup_delay_ms))+ auto delay = state.next_phase_boundary_delay.value;+ if (!compositor_animation_wakeup_delay_ms.has_value() || delay < *compositor_animation_wakeup_delay_ms)compositor_animation_wakeup_delay_ms = delay;};// Force-dark resolves colors when the display list is recorded, on the main thread. A compositor-driven@@ -9700,21 +9545,26 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)// background-color animations stay on the main thread, where every tick re-records the darkened color.auto navigable = this->navigable();bool force_dark_applies = navigable && navigable->force_dark_applies_to_active_document();- for (auto& animation : m_associated_animations) {- if (!animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ for (auto const& animation : associated_animations(m_animations)) {+ auto associated_effect = animation.effect();+ if (!associated_effect.has_value())continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());- effect.clear_pending_compositor_animations();+ auto const& effect = *associated_effect;+ auto existing_compositor_animation_state = effect.existing_compositor_animation_state();+ if (existing_compositor_animation_state.has_value())+ existing_compositor_animation_state->clear_pending();bool published_compositor_animation = false;ScopeGuard collect_effect_bookkeeping = [&] {- if (!published_compositor_animation)- effect.clear_retained_compositor_animations();- effect.clear_pending_compositor_animations();+ if (auto compositor_animation_state = effect.existing_compositor_animation_state(); compositor_animation_state.has_value()) {+ if (!published_compositor_animation)+ compositor_animation_state->clear_retained();+ compositor_animation_state->clear_pending();+ }if (effect.is_observation_relevant_compositor_animation())has_observation_relevant_compositor_animation = true;- bool was_throttled = previously_compositor_driven_effects.contains(GC::Ref { effect })- || previously_compositor_replaced_effects.contains(GC::Ref { effect })- || previously_offscreen_throttled_effects.contains(GC::Ref { effect });+ bool was_throttled = previously_compositor_driven_effects.contains(effect.id())+ || previously_compositor_replaced_effects.contains(effect.id())+ || previously_offscreen_throttled_effects.contains(effect.id());if (was_throttled && !effect.is_compositor_driven() && !effect.is_compositor_replaced() && !effect.is_offscreen_throttled()) {effect.request_observation_sample();requested_withdrawn_effect_sample = true;@@ -9725,21 +9575,15 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)auto abstract_target = effect.target_abstract_element();if (!abstract_target.has_value() || effect.target_properties().is_empty())continue;- if (animation.is_idle() || (!effect.is_in_effect() && effect.phase() != Animations::AnimationEffect::Phase::Before))+ auto const state = animation.timing_state();+ if (state.play_state == Animations::RustFFI::AnimationPlayState::Idle || (!state.is_in_effect && state.phase != Animations::RustFFI::AnimationEffectPhase::Before))continue;auto& target = abstract_target->element();- bool can_throttle_paint_only_effect = animation.play_state() == Bindings::AnimationPlayState::Running- && !animation.pending() && animation.playback_rate() > 0 && isfinite(animation.playback_rate())- && animation.timeline() && animation.timeline()->is_monotonically_increasing()- && effect.phase() == Animations::AnimationEffect::Phase::Active- && effect.start_delay().type == Animations::TimeValue::Type::Milliseconds- && effect.iteration_duration().type == Animations::TimeValue::Type::Milliseconds- && effect.iteration_duration().value > 0 && isfinite(effect.iteration_duration().value)- && effect.end_delay().value == 0;- if (can_throttle_paint_only_effect && paint_only_effect_is_offscreen(effect, *abstract_target)) {- effect.set_is_offscreen_throttled(true);- schedule_next_phase_wakeup(effect, animation);+ // NB: The record decides whether the timing of the effect lets it be throttled.+ if (state.can_throttle_offscreen_effect && paint_only_effect_is_offscreen(effect, *abstract_target)) {+ effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, true);+ schedule_next_phase_wakeup(state);continue;}@@ -9751,14 +9595,14 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)continue;auto target_effects = competing_effects.get(*abstract_target);VERIFY(target_effects.has_value());- bool opacity_has_replace_winner = !targets_opacity || target_effects->opacity.winner;- bool background_color_has_replace_winner = !targets_background_color || target_effects->background_color.winner;- bool filter_has_replace_winner = !targets_filter || target_effects->filter.winner;- bool transform_has_replace_winner = !targets_transform || target_effects->transform.winner;- bool selected_for_opacity = targets_opacity && target_effects->opacity.winner.ptr() == &effect;- bool selected_for_background_color = targets_background_color && target_effects->background_color.winner.ptr() == &effect;- bool selected_for_filter = targets_filter && target_effects->filter.winner.ptr() == &effect;- bool selected_for_transform = targets_transform && target_effects->transform.winner.ptr() == &effect;+ bool opacity_has_replace_winner = !targets_opacity || target_effects->opacity.winner.has_value();+ bool background_color_has_replace_winner = !targets_background_color || target_effects->background_color.winner.has_value();+ bool filter_has_replace_winner = !targets_filter || target_effects->filter.winner.has_value();+ bool transform_has_replace_winner = !targets_transform || target_effects->transform.winner.has_value();+ bool selected_for_opacity = targets_opacity && target_effects->opacity.winner == effect;+ bool selected_for_background_color = targets_background_color && target_effects->background_color.winner == effect;+ bool selected_for_filter = targets_filter && target_effects->filter.winner == effect;+ bool selected_for_transform = targets_transform && target_effects->transform.winner == effect;bool all_targeted_properties_have_replace_winners = opacity_has_replace_winner && background_color_has_replace_winner && filter_has_replace_winner && transform_has_replace_winner;// Background colors are display-list content, so associate their fill commands with a dedicated metadata@@ -9811,22 +9655,14 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)}if (!selected_for_opacity && !selected_for_background_color && !selected_for_filter && !selected_for_transform) {- bool can_throttle_replaced_effect = animation.play_state() == Bindings::AnimationPlayState::Running- && !animation.pending()- && animation.playback_rate() > 0- && animation.timeline() && animation.timeline()->is_monotonically_increasing()- && effect.phase() == Animations::AnimationEffect::Phase::Active- && (isinf(effect.iteration_count()) || effect.iteration_count() == 1)- && effect.start_delay().type == Animations::TimeValue::Type::Milliseconds- && effect.iteration_duration().type == Animations::TimeValue::Type::Milliseconds;- if (all_targeted_properties_have_replace_winners && can_throttle_replaced_effect) {- effect.set_is_compositor_replaced(true);- schedule_next_phase_wakeup(effect, animation);+ if (all_targeted_properties_have_replace_winners && state.can_throttle_replaced_effect) {+ effect.set_flag(Animations::RustFFI::EffectFlag::CompositorReplaced, true);+ schedule_next_phase_wakeup(state);}continue;}- auto& compositor_animation_state = effect.compositor_animation_state();+ auto compositor_animation_state = effect.compositor_animation_state();bool opacity_was_handed_off = !selected_for_opacity;if (selected_for_opacity && build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Opacity, keyframes_by_effect).built)opacity_was_handed_off = true;@@ -9857,7 +9693,7 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)auto build = build_compositor_animation(read, effect, Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform, keyframes_by_effect);transform_was_handed_off = build.built;if (build.only_translates_horizontally.has_value())- only_translates_horizontally_cache.set(effect, *build.only_translates_horizontally);+ only_translates_horizontally_cache.set(effect.id(), *build.only_translates_horizontally);}if (selected_for_opacity && opacity_affects_visibility_observation(target)) {@@ -9868,9 +9704,9 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)bool transform_affects_observation = false;bool requires_main_thread_observation_sampling = false;if (selected_for_transform) {- auto only_translates_horizontally = only_translates_horizontally_cache.ensure(effect, [&] {+ auto only_translates_horizontally = only_translates_horizontally_cache.ensure(effect.id(), [&] {auto const* layout_node = abstract_target->unsafe_layout_node(read);- if (!layout_node || !effect.key_frame_set())+ if (!layout_node || !effect.keyframe_set())return false;return compositor_animation_keyframes(keyframes_by_effect, effect, animation, *abstract_target).only_translates_horizontally(*layout_node);});@@ -9884,18 +9720,18 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)if (!compositor_animation_state.has_pending()) {auto viewport_bounds = CSSPixelRect { { 0, 0 }, viewport_rect().size() };if (selected_for_transform && !transform_affects_observation && transform_subtree_is_clipped_outside(target, viewport_bounds))- effect.set_is_offscreen_throttled(true);+ effect.set_flag(Animations::RustFFI::EffectFlag::OffscreenThrottled, true);continue;}if (all_targeted_properties_have_replace_winners && opacity_was_handed_off && background_color_was_handed_off && filter_was_handed_off && transform_was_handed_off)- effect.set_is_compositor_driven(true);- effect.set_is_observation_relevant_compositor_animation(transform_affects_observation);- schedule_next_phase_wakeup(effect, animation);+ effect.set_flag(Animations::RustFFI::EffectFlag::CompositorDriven, true);+ effect.set_flag(Animations::RustFFI::EffectFlag::ObservationRelevantCompositorAnimation, transform_affects_observation);+ schedule_next_phase_wakeup(state);// OPTIMIZATION: Ordinary rendering updates advance the WebContent timeline without changing compositor// playback. An effect published before keeps the anchors of the animations whose parameters// did not change.compositor_animation_state.publish_pending(*this,- previously_published_effects.contains(GC::Ref { effect })+ previously_published_effects.contains(effect.id())? Painting::CompositorAnimationEffectState::ReuseRetainedTimingAnchors::Yes: Painting::CompositorAnimationEffectState::ReuseRetainedTimingAnchors::No);if (auto* layout_node = abstract_target->unsafe_layout_node(read))@@ -9974,26 +9810,22 @@ void Document::update_compositor_animations(Layout::BegunRead const& read)HTML::note_rendering_trace_event("animation frame pump request"sv);}-void Document::append_pending_animation_event(Web::DOM::Document::PendingAnimationEvent const& event)+void Document::append_pending_animation_event(Animations::AnimationRef const& animation, Animations::RustFFI::FfiPendingAnimationEvent const& event){- if (m_style_stabilization_epoch_depth > 0) {- m_provisional_animation_event_queue.append(event);- HTML::note_rendering_trace_event("provisional animation events"sv);- return;- }- m_pending_animation_event_queue.append(event);- HTML::note_rendering_trace_event("animation events committed"sv);+ auto provisional = m_style_stabilization_epoch_depth > 0;+ Animations::RustFFI::animations_document_animations_append_event(m_animations, &animation.record(), &event, provisional);+ HTML::note_rendering_trace_event(provisional ? "provisional animation events"sv : "animation events committed"sv);}void Document::prepare_to_observe_css_animation_events(){- GC::RootVector<GC::Ref<Animations::KeyframeEffect>> effects_to_synchronize;- for (auto& animation : m_associated_animations) {- if (!animation.is_css_animation() || !animation.effect() || !is<Animations::KeyframeEffect>(*animation.effect()))+ GC::RootVector<Animations::EffectRef> effects_to_synchronize;+ for (auto const& animation : associated_animations(m_animations)) {+ auto effect = animation.effect();+ if (!effect.has_value() || animation.timing_state().kind != Animations::RustFFI::FfiAnimationKind::CssAnimation)continue;- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());- if (effect.per_frame_animation_tick_was_skipped())- effects_to_synchronize.append(effect);+ if (effect->per_frame_animation_tick_was_skipped())+ effects_to_synchronize.append(effect.release_value());}if (effects_to_synchronize.is_empty())return;@@ -10006,11 +9838,10 @@ void Document::prepare_to_observe_css_animation_events()// OPTIMIZATION: Events which occurred while there were no listeners were intentionally not sampled. Establish// the current phase as the baseline so a newly added listener only observes future events.- for (auto& effect : effects_to_synchronize) {- auto resolved_timing = effect->resolve_timing();- effect->set_previous_phase(resolved_timing.phase);- effect->set_previous_current_iteration(effect->current_iteration(resolved_timing).value_or(0.0));- effect->clear_per_frame_animation_tick_was_skipped();+ for (auto const& effect : effects_to_synchronize) {+ auto resolved_timing = effect.resolve_timing();+ effect.set_previous_phase_and_current_iteration(resolved_timing.phase, Animations::from_ffi(resolved_timing.current_iteration).value_or(0.0));+ effect.set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, false);}}@@ -10034,14 +9865,13 @@ void Document::update_animations_and_send_events(double timestamp)timeline->update_current_time(timestamp);// NB: We dispatch events for all animations regardless of whether they have a timeline- GC::RootVector<GC::Ref<Animations::Animation>> animations;- for (auto& animation : m_associated_animations)+ GC::RootVector<Animations::AnimationRef> animations;+ for (auto const& animation : associated_animations(m_animations))animations.append(animation);- for (auto& animation : animations) {+ for (auto const& animation : animations) {dispatch_events_for_animation_if_necessary(animation);- if (animation->disassociation_from_target_pending())- animation->disassociate_from_target_if_inert();+ animation.disassociate_from_target_if_inert();}// 2. Remove replaced animations for doc.@@ -10052,53 +9882,25 @@ void Document::update_animations_and_send_events(double timestamp)}// 4. Let events to dispatch be a copy of doc’s pending animation event queue.- GC::RootVector<PendingAnimationEvent> events_to_dispatch;- events_to_dispatch.extend(m_pending_animation_event_queue);-// 5. Clear doc’s pending animation event queue.- m_pending_animation_event_queue.clear();-// 6. Perform a stable sort of the animation events in events to dispatch as follows:- auto compare_events_by_composite_order = [](auto const& a, auto const& b) -> int {- if (!a.animation->effect() || !b.animation->effect())- return static_cast<int>(static_cast<bool>(a.animation->effect())) - static_cast<int>(static_cast<bool>(b.animation->effect()));- auto& a_effect = as<Animations::KeyframeEffect>(*a.animation->effect());- auto& b_effect = as<Animations::KeyframeEffect>(*b.animation->effect());- return Animations::KeyframeEffect::composite_order(a_effect, b_effect);- };- auto compare_events = [&](auto const& a, auto const& b) -> int {- // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort- // before events scheduled to occur later and events whose scheduled event time is unresolved sort before events- // with a resolved scheduled event time.- //- // Within events with equal scheduled event times, sort by their composite order.- if (a.scheduled_event_time.has_value() != b.scheduled_event_time.has_value())- return a.scheduled_event_time.has_value() ? 1 : -1;- if (a.scheduled_event_time != b.scheduled_event_time)- return a.scheduled_event_time.value() < b.scheduled_event_time.value() ? -1 : 1;- return compare_events_by_composite_order(a, b);- };-- // NB: The events of a frame come in the unspecified order of the document's animations, so sorting them is not- // close to a no-op. Their positions in the queue keep the sort stable.- Vector<u32> event_order;- event_order.ensure_capacity(events_to_dispatch.size());- for (u32 index = 0; index < events_to_dispatch.size(); ++index)- event_order.unchecked_append(index);- quick_sort(event_order, [&](u32 a, u32 b) {- if (auto order = compare_events(events_to_dispatch[a], events_to_dispatch[b]); order != 0)- return order < 0;- return a < b;- });- GC::RootVector<PendingAnimationEvent> sorted_events;- sorted_events.ensure_capacity(events_to_dispatch.size());- for (auto index : event_order)- sorted_events.unchecked_append(events_to_dispatch[index]);-// 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in// the previous step.- for (auto const& event : sorted_events)- event.target->dispatch_event(event.event);+ // NB: The core runs these steps over the queue it holds, and the document creates each event as it dispatches it.+ // The animation of each event stays rooted until all are dispatched.+ struct DispatchContext {+ GC::Ref<Document> document;+ GC::RootVector<Animations::AnimationRef> animations;+ } dispatch_context { *this, {} };+ Animations::RustFFI::animations_document_animations_dispatch_events(+ m_animations, Animations::compare_elements_in_tree_order_for_composite_order,+ [](void* context, Animations::RustFFI::AnimationCell const* animation) {+ Animations::keep_animation_alive_in(&static_cast<DispatchContext*>(context)->animations, animation);+ },+ [](void* context, Animations::RustFFI::AnimationCell const* animation, Animations::RustFFI::FfiPendingAnimationEvent const* event) {+ dispatch_pending_animation_event(static_cast<DispatchContext*>(context)->document, Animations::AnimationRef { *animation }, *event);+ },+ &dispatch_context);// AD-HOC: Nothing else re-requests a rendering update while time-driven animations are running, since// Document::set_needs_animated_style_update() only requests a frame when its flag flips from@@ -10106,23 +9908,22 @@ void Document::update_animations_and_send_events(double timestamp)// Without this, animations only advance when unrelated tasks happen to schedule rendering// updates. Keep the frame pump going as long as some animation attached to a monotonically// increasing timeline needs main-thread painting or observable animation events.- for (auto const& animation : m_associated_animations) {- if (animation.play_state() != Bindings::AnimationPlayState::Running)+ for (auto const& animation : associated_animations(m_animations)) {+ auto const state = animation.timing_state();+ if (state.play_state != Animations::RustFFI::AnimationPlayState::Running)continue;- auto timeline = animation.timeline();- if (!timeline || !timeline->is_monotonically_increasing())+ if (!state.has_monotonically_increasing_timeline)continue;- if (animation.effect() && is<Animations::KeyframeEffect>(*animation.effect())) {- auto& effect = static_cast<Animations::KeyframeEffect&>(*animation.effect());- if (effect.can_skip_per_frame_animation_tick()) {- effect.note_per_frame_animation_tick_was_skipped();+ if (auto effect = animation.effect(); effect.has_value()) {+ if (effect->can_skip_per_frame_animation_tick()) {+ effect->set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, true);continue;}- effect.clear_per_frame_animation_tick_was_skipped();- if (auto iteration_event_time = next_throttled_animation_iteration_event_time(animation, effect); iteration_event_time.has_value()) {- auto current_time = animation.current_time();+ effect->set_flag(Animations::RustFFI::EffectFlag::PerFrameAnimationTickWasSkipped, false);+ if (auto iteration_event_time = next_throttled_animation_iteration_event_time(state, *effect); iteration_event_time.has_value()) {+ auto current_time = Animations::from_ffi(state.current_time);if (current_time.has_value() && current_time->type == Animations::TimeValue::Type::Milliseconds) {- auto delay = (*iteration_event_time - current_time->value) / animation.playback_rate();+ auto delay = (*iteration_event_time - current_time->value) / state.playback.playback_rate;if (delay > 0) {schedule_compositor_animation_wakeup(delay);continue;@@ -10140,100 +9941,14 @@ void Document::update_animations_and_send_events(double timestamp)// https://www.w3.org/TR/web-animations-1/#remove-replaced-animationsvoid Document::remove_replaced_animations(){- // When asked to remove replaced animations for a Document, doc, then for every animation, animation, that:- // - has an associated animation effect whose effect target is a descendant of doc, and- // - is replaceable, and- // - has a replace state of active, and- // - for which there exists for each target property of every animation effect associated with animation, an- // animation effect associated with a replaceable animation with a higher composite order than animation that- // includes the same target property-- GC::RootVector<GC::Ref<Animations::Animation>> replaceable_animations;- for (auto const& timeline : m_associated_animation_timelines) {- for (auto& animation : timeline->associated_animations()) {- if (!animation.effect() || !animation.effect()->target() || &animation.effect()->target()->document() != this)- continue;-- if (!animation.is_replaceable())- continue;-- if (animation.replace_state() != Animations::AnimationReplaceState::Active)- continue;-- // Composite order is only defined for KeyframeEffects- if (!animation.effect()->is_keyframe_effect())- continue;-- replaceable_animations.append(animation);- }- }-- quick_sort(replaceable_animations, [](GC::Ref<Animations::Animation>& a, GC::Ref<Animations::Animation>& b) {- VERIFY(a->effect()->is_keyframe_effect());- VERIFY(b->effect()->is_keyframe_effect());- auto& a_effect = *static_cast<Animations::KeyframeEffect*>(a->effect().ptr());- auto& b_effect = *static_cast<Animations::KeyframeEffect*>(b->effect().ptr());- return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;- });-- // Lower value = higher priority- HashMap<CSS::PropertyNameAndID, size_t> highest_property_composite_orders;- for (int i = replaceable_animations.size() - 1; i >= 0; i--) {- auto animation = replaceable_animations[i];- bool has_any_highest_priority_property = false;-- for (auto const& property : animation->effect()->target_properties()) {- if (!highest_property_composite_orders.contains(property)) {- has_any_highest_priority_property = true;- highest_property_composite_orders.set(property, i);- }- }-- if (!has_any_highest_priority_property) {- // perform the following steps:-- // - Set animation’s replace state to removed.- animation->set_replace_state(Animations::AnimationReplaceState::Removed);-- // - Create an AnimationPlaybackEvent, removeEvent.- // - Set removeEvent’s type attribute to remove.- // - Set removeEvent’s currentTime attribute to the current time of animation.- // - Set removeEvent’s timelineTime attribute to the current time of the timeline with which animation is- // associated.- auto remove_event = Animations::AnimationPlaybackEvent::create(- HTML::EventNames::remove,- animation->current_time().has_value() ? Animations::NullableCSSNumberish { animation->current_time()->as_css_numberish() } : Animations::NullableCSSNumberish { Empty {} },- animation->timeline()->current_time().has_value() ? Animations::NullableCSSNumberish { animation->timeline()->current_time()->as_css_numberish() } : Animations::NullableCSSNumberish { Empty {} },- HighResolutionTime::current_high_resolution_time(relevant_global_object(*this)));-- // - If animation has a document for timing, then append removeEvent to its document for timing's pending- // animation event queue along with its target, animation. For the scheduled event time, use the result of- // applying the procedure to convert timeline time to origin-relative time to the current time of the- // timeline with which animation is associated.- if (auto document = animation->document_for_timing()) {- PendingAnimationEvent pending_animation_event {- .event = remove_event,- .animation = animation,- .target = animation,- .scheduled_event_time = animation->timeline()->convert_a_timeline_time_to_an_origin_relative_time(animation->timeline()->current_time()),- };- document->append_pending_animation_event(pending_animation_event);- }- // Otherwise, queue a task to dispatch removeEvent at animation. The task source for this task is the DOM- // manipulation task source.- else {- HTML::queue_global_task(HTML::Task::Source::DOMManipulation, relevant_settings_object().realm().global_object(), GC::create_function(GC::Heap::the(), GC::captures(animation, remove_event), [](auto& animation, auto& remove_event) {- animation->dispatch_event(remove_event);- }));- }- }- }-}--WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animations::Animation>>> Document::get_animations()-{- update_style();- return calculate_get_animations(*this);+ Vector<Animations::RustFFI::TimelineCell const*, 8> timelines;+ for (auto const& timeline : m_associated_animation_timelines)+ timelines.append(&timeline->record());+ // NB: What the procedure performs for an animation it removes can run the GC, which must not collect the animation.+ GC::RootVector<Animations::AnimationRef> removed_animations;+ Animations::RustFFI::animations_remove_replaced_animations(+ this, timelines.data(), timelines.size(), Animations::compare_elements_in_tree_order_for_composite_order,+ Animations::keep_animation_alive_in, &removed_animations, Animations::perform_host_effect);}// https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter@@ -11043,9 +10758,8 @@ void Document::unregister_shadow_root(Badge<DOM::ShadowRoot>, DOM::ShadowRoot& sm_shadow_roots.remove(shadow_root);m_shadow_roots_with_counter_styles_to_settle.remove(shadow_root);note_style_sheet_set_change();- // The style engine names the keyframe sets of the root's `@keyframes` by pointer. The root may be leaving from a- // garbage collection's finalizer, which must not reach into the engine, so its row is given up before the next- // style update, and the sets stay alive until then.+ // The root may be leaving from a garbage collection's finalizer, which must not reach into the engine, so the rows+ // its scope published are given up before the next style update.if (auto departed = shadow_root.style_scope().take_published_animation_keyframes(); departed.has_value())m_departed_animation_keyframes.append(departed.release_value());}@@ -11062,7 +10776,8 @@ void Document::publish_animation_keyframes_for_style_update()m_animation_keyframes_published_generation = m_style_sheet_set_generation;auto* host = style_computer().style_engine().host();for (auto const& departed : m_departed_animation_keyframes) {- CSS::StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(host, departed.tree_scope.value(), {}, {}, {});+ if (departed.has_animation_keyframes)+ CSS::StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(host, departed.tree_scope.value(), {}, {}, {});if (departed.has_position_try_rules)CSS::StyleEngineFFI::style_engine_set_tree_scope_position_try_rules(host, departed.tree_scope.value(), {}, {}, {});}diff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex 2d8a54c093a..e44b7f742ce 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -27,6 +27,7 @@#include <LibCompositing/Scrolling/AsyncScrollingState.h>#include <LibCore/Forward.h>#include <LibCore/SharedVersion.h>+#include <LibGC/Weak.h>#include <LibGC/WeakHashSet.h>#include <LibGfx/Point.h>#include <LibJS/Forward.h>@@ -92,6 +93,20 @@ struct RenderingStats;}+namespace Web::Animations {++class AnimationRef;+class EffectRef;++}++namespace Web::Animations::RustFFI {++struct DocumentAnimations;+struct FfiPendingAnimationEvent;++}+namespace Web::Compositor {struct FlightPresentation;@@ -334,7 +349,9 @@ public:[[nodiscard]] static GC::Ref<Document> create(Page&, GC::Ref<EventTarget> relevant_global_event_target, URL::URL const& url = URL::about_blank());[[nodiscard]] static GC::Ref<Document> create_for_constructor(JS::Object&);[[nodiscard]] static GC::Ref<Document> create_for_fragment_parsing(Page&, GC::Ref<EventTarget> relevant_global_event_target);- virtual ~Document() override;+ // NB: The animations of the document die when it is swept, not when it is finalized, so that the finalizer of+ // another dead cell can still reach them.+ GC_ALLOW_CELL_DESTRUCTOR virtual ~Document() override;u64 form_controls_version() const { return m_form_controls_version; }void bump_form_controls_version() { ++m_form_controls_version; }@@ -655,12 +672,7 @@ public:void sample_animation_effects_needing_style_update();void update_style_computer_viewport_rect();bool needs_animated_style_update() const { return m_needs_animated_style_update; }- void clear_needs_animated_style_update()- {- m_needs_animated_style_update = false;- m_effects_needing_animated_style_update.clear();- m_effects_needing_animated_style_update_after_current_update.clear();- }+ void clear_needs_animated_style_update();void set_cursor_may_be_stale() { m_cursor_may_be_stale = true; }[[nodiscard]] bool take_cursor_may_be_stale() { return exchange(m_cursor_may_be_stale, false); }[[nodiscard]] bool is_running_update_layout() const;@@ -1397,10 +1409,13 @@ public:void restore_the_history_object_state(NonnullRefPtr<HTML::SessionHistoryEntry> entry);- GC::Ref<Animations::DocumentTimeline> timeline();+ GC::Ref<Animations::AnimationTimeline> timeline();// The scroll progress timelines and view progress timelines the elements of the document declare by name.Animations::NamedTimelines& named_timelines();+ // The CSS animations of the elements of the document that follow a named timeline, which the document keeps none+ // of alive.+ Animations::WeakAnimationSetView animations_following_named_timelines();bool has_named_timelines() const { return m_named_timelines != nullptr; }// Moves on whenever the timelines an element declares by name, or the timeline names it scopes, may have changed.u64 timeline_declarations_generation() const { return m_timeline_declarations_generation; }@@ -1409,9 +1424,10 @@ public:void associate_with_timeline(GC::Ref<Animations::AnimationTimeline>);void disassociate_with_timeline(GC::Ref<Animations::AnimationTimeline>);- void associate_with_animation(GC::Ref<Animations::Animation>);- void disassociate_with_animation(GC::Ref<Animations::Animation>);- bool has_associated_animations() const { return !m_associated_animations.is_empty(); }+ void associate_with_animation(Animations::AnimationRef const&);+ // Disassociates the animation, whose associated effect was `effect`, from the document.+ void disassociate_with_animation(Animations::AnimationRef const&, Optional<Animations::EffectRef> const& effect);+ bool has_associated_animations() const;// Negative where `first` comes before `second` in tree order and positive where it comes after, for sorting// animations by composite order. Two distinct elements of this document take no walk of their siblings once a tree// has been asked about often enough, so that sorting many sibling elements is not quadratic in them per comparison.@@ -1420,22 +1436,16 @@ public:// version stand.void keep_element_tree_positions_across_attribute_change(u64 version_before);- struct PendingAnimationEvent {- GC::Ref<DOM::Event> event;- GC::Ref<Animations::Animation> animation;- GC::Ref<DOM::EventTarget> target;- Optional<double> scheduled_event_time;-- void visit_edges(GC::Cell::Visitor&) const;- };- void append_pending_animation_event(PendingAnimationEvent const&);+ // https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue+ // Appends an event of `animation` to the document's pending animation event queue, which holds what the event is+ // and creates it only as the document dispatches it.+ void append_pending_animation_event(Animations::AnimationRef const& animation, Animations::RustFFI::FfiPendingAnimationEvent const&);void update_animations_and_send_events(double timestamp);void prepare_to_observe_css_animation_events();void update_compositor_animations(Layout::BegunRead const& read);- void dispatch_events_for_animation_if_necessary(GC::Ref<Animations::Animation>);+ void dispatch_events_for_animation_if_necessary(Animations::AnimationRef const&);void remove_replaced_animations();- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animations::Animation>>> get_animations();HashTable<GC::Ref<Animations::AnimationTimeline>> const& associated_animation_timelines() const { return m_associated_animation_timelines; }void begin_smil_time_container_once_loaded(SVG::SMILTimeContainer&);void schedule_svg_referenced_motion_path_update(SVG::SVGAnimateMotionElement&);@@ -1473,7 +1483,7 @@ public:GC::RootVector<GC::Ref<Element>> elements_from_point(double x, double y);GC::Ptr<Element const> scrolling_element() const;- void set_needs_animated_style_update(Animations::KeyframeEffect&);+ void set_needs_animated_style_update(Animations::EffectRef const&);// What the style updates of the document measured, for the style update capture tools, and how often a style// update stopped at its pass guard.@@ -1894,6 +1904,11 @@ private:void service_compositor_animation_wakeup(double timestamp);void drain_style_update_that_flew(Layout::BegunRead const&);+ // The effects whose animated style the next animated style update samples, taken out of the document's set, and+ // put back.+ // Sets the effects whose animated style the next animated style update samples aside, and back again.+ void set_aside_effects_needing_animated_style_update();+ void restore_effects_needing_animated_style_update();GC::Ref<WebIDL::ObservableArray> adopted_style_sheets() const;@@ -1944,8 +1959,6 @@ private:Element* find_a_potential_indicated_element(Utf16View fragment) const;- void dispatch_events_for_transition(GC::Ref<CSS::CSSTransition>);-template<typename GetNotifier, typename... Args>void notify_each_document_observer(GetNotifier&& get_notifier, Args&&... args){@@ -2209,8 +2222,6 @@ private:bool m_needs_animated_style_update { false };bool m_cursor_may_be_stale { false };bool m_reads_layout_as_it_flew { false };- GC::WeakHashSet<Animations::KeyframeEffect> m_effects_needing_animated_style_update;- GC::WeakHashSet<Animations::KeyframeEffect> m_effects_needing_animated_style_update_after_current_update;bool m_is_updating_animated_style { false };bool m_has_throttled_animation_style_update { false };bool m_needs_throttled_animation_style_update_check { false };@@ -2412,9 +2423,11 @@ private:Vector<GC::Ref<SVG::SMILTimeContainer>> m_smil_time_containers_to_begin;Vector<GC::Ref<SVG::SVGAnimateMotionElement>> m_animate_motion_elements_to_update;- // NB: Weak so the document does not unnecessarily keep animations alive. Note that this also includes animations- // associated with elements in shadow trees so differs from getAnimations()- GC::WeakHashSet<Animations::Animation> m_associated_animations;+ // The animations associated with the document's elements, and those associated with it during the current style+ // stabilization epoch, none of which the document keeps alive.+ // NB: The associated animations include those associated with elements in shadow trees, so they differ from+ // getAnimations().+ Animations::RustFFI::DocumentAnimations* m_animations { nullptr };// The tree position of every element of the document by its unique ID, valid for one DOM tree version. Sorting// animations fills it once it asked the tree enough at that version.HashMap<UniqueNodeID, u32> m_element_tree_positions;@@ -2423,18 +2436,11 @@ private:u32 m_element_count_at_last_tree_positions_walk { 0 };// https://www.w3.org/TR/web-animations-1/#document-default-document-timeline- GC::Ptr<Animations::DocumentTimeline> m_default_timeline;+ GC::Ptr<Animations::AnimationTimeline> m_default_timeline;GC::Ptr<Animations::NamedTimelines> m_named_timelines;u64 m_timeline_declarations_generation { 0 };Optional<double> m_last_animation_frame_timestamp;- // https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue- Vector<PendingAnimationEvent> m_pending_animation_event_queue;- // Events produced while style and layout feedback is provisional move to the public queue only- // when the outer epoch commits.- Vector<PendingAnimationEvent> m_provisional_animation_event_queue;- GC::WeakHashSet<Animations::Animation> m_animations_created_in_stabilization_epoch;-// https://drafts.csswg.org/css-transitions-2/#current-transition-generationsize_t m_transition_generation { 0 };u64 m_style_stabilization_epoch_depth { 0 };diff --git a/Libraries/LibWeb/DOM/DocumentOrShadowRoot.h b/Libraries/LibWeb/DOM/DocumentOrShadowRoot.hindex abfc037ae2b..b2b5d9bc5cb 100644--- a/Libraries/LibWeb/DOM/DocumentOrShadowRoot.h+++ b/Libraries/LibWeb/DOM/DocumentOrShadowRoot.h@@ -8,8 +8,6 @@#pragma once#include <LibJS/Forward.h>-#include <LibWeb/Animations/Animatable.h>-#include <LibWeb/Animations/Animation.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/DOM/Utils.h>#include <LibWeb/HTML/HTMLElement.h>@@ -61,34 +59,4 @@ GC::Ptr<Element> calculate_active_element(T& self)return nullptr;}-// https://drafts.csswg.org/web-animations-1/#dom-documentorshadowroot-getanimations-template<DocumentOrShadowRoot T>-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animations::Animation>>> calculate_get_animations(T& self)-{- // Returns the set of relevant animations for a subtree for the document or shadow root on which this- // method is called.- GC::RootVector<GC::Ref<Animations::Animation>> relevant_animations;- TRY(self.template for_each_child_of_type_fallible<Element>([&](auto& child) -> WebIDL::ExceptionOr<IterationDecision> {- relevant_animations.extend(TRY(child.get_animations_internal(- Animations::Animatable::GetAnimationsSorted::No,- Animations::Animatable::GetAnimationsOptions { .subtree = true, .pseudo_element = {} })));- return IterationDecision::Continue;- }));-- // The returned list is sorted using the composite order described for the associated animations of- // effects in § 5.4.2 The effect stack.- quick_sort(relevant_animations, [](GC::Ref<Animations::Animation>& a, GC::Ref<Animations::Animation>& b) {- auto& a_effect = as<Animations::KeyframeEffect>(*a->effect());- auto& b_effect = as<Animations::KeyframeEffect>(*b->effect());- return Animations::KeyframeEffect::composite_order(a_effect, b_effect) < 0;- });-- // Calling this method triggers a style change event for the document. As a result, the returned list- // reflects the state after applying any pending style changes to animation such as changes to- // animation-related style properties that have yet to be processed.- // FIXME: Implement this.-- return relevant_animations;-}-}diff --git a/Libraries/LibWeb/DOM/Element.cpp b/Libraries/LibWeb/DOM/Element.cppindex 485b2007966..a3809218898 100644--- a/Libraries/LibWeb/DOM/Element.cpp+++ b/Libraries/LibWeb/DOM/Element.cpp@@ -389,6 +389,7 @@ void Element::finalize(){Base::finalize();CSS::Parser::ValueParserFFI::rust_declaration_block_destroy(exchange(m_inline_declarations, nullptr));+ finalize_animations();}void Element::append_to_attribute_list(QualifiedName name, Utf16String value)@@ -3029,6 +3030,7 @@ void Element::set_style_node_id(CSS::StyleNodeID style_node_id)if (m_style_node_id == style_node_id)return;m_published_presentational_hint_properties.clear();+ forget_published_effect_descriptions();auto old_style_node_id = m_style_node_id;m_style_node_id = style_node_id;Layout::Node::dom_node_style_node_changed(*this, old_style_node_id);@@ -5185,7 +5187,7 @@ CSS::InstalledStyle const& Element::installed_style(Optional<CSS::PseudoElement>return m_installed_style;}-void Element::update_animated_properties(Badge<Web::Animations::KeyframeEffect> const& badge, Optional<CSS::PseudoElement> pseudo_element_type, Web::Animations::KeyframeEffect& effect, Web::Animations::AnimationUpdateContext& context)+void Element::update_animated_properties(Badge<Web::Animations::EffectRef> const& badge, Optional<CSS::PseudoElement> pseudo_element_type, Web::Animations::EffectRef const& effect, Web::Animations::AnimationUpdateContext& context){DOM::AbstractElement abstract_element { *this, pseudo_element_type };if (pseudo_element_type.has_value()) {@@ -5197,11 +5199,11 @@ void Element::update_animated_properties(Badge<Web::Animations::KeyframeEffect>update_animated_properties_for_abstract_element(badge, abstract_element, effect, context);}-void Element::update_animated_properties_for_abstract_element(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement abstract_element, Web::Animations::KeyframeEffect& effect, Web::Animations::AnimationUpdateContext& context)+void Element::update_animated_properties_for_abstract_element(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement abstract_element, Web::Animations::EffectRef const& effect, Web::Animations::AnimationUpdateContext& context){if (!has_style())return;- effect.update_computed_properties_for_style(context, abstract_element);+ context.add_effect(abstract_element, effect);}// The animation style group of an installed style, which holds the timelines it declares by name.@@ -6918,27 +6920,7 @@ void Element::play_or_cancel_animations_after_display_property_change()return;}- auto play_or_cancel_depending_on_display = [&](Vector<GC::Ref<CSS::CSSAnimation>> const& animations) {- for (auto& animation : animations) {- // NOTE: It is safe to assume this has a value as it is set when creating a CSS defined animation- auto play_state = animation->last_css_animation_play_state().value();-- if (play_state == CSS::AnimationPlayState::Running) {- HTML::TemporaryExecutionContext context(document().relevant_settings_object());- animation->play_from_css();- } else if (play_state == CSS::AnimationPlayState::Paused) {- HTML::TemporaryExecutionContext context(document().relevant_settings_object());- animation->pause_from_css();- }- }- };-- play_or_cancel_depending_on_display(*css_defined_animations({}));-- for (auto i = 0; i < to_underlying(CSS::PseudoElement::KnownPseudoElementCount); i++) {- auto pseudo_element = static_cast<CSS::PseudoElement>(i);- play_or_cancel_depending_on_display(*css_defined_animations(pseudo_element));- }+ play_or_pause_css_animations_as_their_play_state_asks();}// https://drafts.csswg.org/selectors/#indicate-focusdiff --git a/Libraries/LibWeb/DOM/Element.h b/Libraries/LibWeb/DOM/Element.hindex 1dfe30e3db7..70d5d25a08e 100644--- a/Libraries/LibWeb/DOM/Element.h+++ b/Libraries/LibWeb/DOM/Element.h@@ -47,7 +47,6 @@namespace Web::Animations {struct AnimationUpdateContext;-class KeyframeEffect;}@@ -486,8 +485,8 @@ public:void refresh_computed_style(Layout::BegunRead const&, Optional<CSS::PseudoElement>, CSS::InstalledStyle);// Install the custom properties beside a pseudo-element record the style engine derived.void install_engine_pseudo_element_custom_property_data(Layout::BegunRead const& read, CSS::PseudoElement, u64 environment);- void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, Optional<CSS::PseudoElement>, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&);- void update_animated_properties_for_abstract_element(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&);+ void update_animated_properties(Badge<Web::Animations::EffectRef> const&, Optional<CSS::PseudoElement>, Web::Animations::EffectRef const&, Web::Animations::AnimationUpdateContext&);+ void update_animated_properties_for_abstract_element(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement, Web::Animations::EffectRef const&, Web::Animations::AnimationUpdateContext&);Optional<SyntheticPseudoElement&> get_synthetic_pseudo_element(CSS::PseudoElement) const;Optional<PseudoElement&> get_pseudo_element(CSS::PseudoElement) const;diff --git a/Libraries/LibWeb/DOM/Node.cpp b/Libraries/LibWeb/DOM/Node.cppindex 936aef57d95..aa5e711eeaf 100644--- a/Libraries/LibWeb/DOM/Node.cpp+++ b/Libraries/LibWeb/DOM/Node.cpp@@ -18,7 +18,7 @@#include <LibGC/Heap.h>#include <LibGC/RootVector.h>#include <LibJS/Runtime/ExternalMemory.h>-#include <LibWeb/Animations/Animation.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/Bindings/Node.h>#include <LibWeb/Bindings/Sanitizer.h>#include <LibWeb/CSS/ComputedValues.h>diff --git a/Libraries/LibWeb/DOM/PseudoElement.cpp b/Libraries/LibWeb/DOM/PseudoElement.cppindex ec64cecf2d4..6425028066c 100644--- a/Libraries/LibWeb/DOM/PseudoElement.cpp+++ b/Libraries/LibWeb/DOM/PseudoElement.cpp@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/CSS/ComputedValues.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/DOM/AbstractElement.h>@@ -73,11 +73,11 @@ Node& SyntheticPseudoElement::root() constreturn m_originating_element->root();}-void SyntheticPseudoElement::update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement abstract_element, Web::Animations::KeyframeEffect& effect, Web::Animations::AnimationUpdateContext& context)+void SyntheticPseudoElement::update_animated_properties(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement abstract_element, Web::Animations::EffectRef const& effect, Web::Animations::AnimationUpdateContext& context){if (!m_installed_style.record())return;- effect.update_computed_properties_for_style(context, abstract_element);+ context.add_effect(abstract_element, effect);}void SyntheticPseudoElement::replace_installed_style(Layout::BegunRead const& read, CSS::InstalledStyle style)@@ -170,7 +170,7 @@ CSS::InstalledStyle const& ElementReferencePseudoElement::installed_style() consreturn m_referenced_element->installed_style({});}-void ElementReferencePseudoElement::update_animated_properties(Badge<Web::Animations::KeyframeEffect> const& badge, DOM::AbstractElement abstract_element, Web::Animations::KeyframeEffect& effect, Web::Animations::AnimationUpdateContext& context)+void ElementReferencePseudoElement::update_animated_properties(Badge<Web::Animations::EffectRef> const& badge, DOM::AbstractElement abstract_element, Web::Animations::EffectRef const& effect, Web::Animations::AnimationUpdateContext& context){m_referenced_element->update_animated_properties_for_abstract_element(badge, abstract_element, effect, context);}diff --git a/Libraries/LibWeb/DOM/PseudoElement.h b/Libraries/LibWeb/DOM/PseudoElement.hindex 808edc15d0b..90f57cc6806 100644--- a/Libraries/LibWeb/DOM/PseudoElement.h+++ b/Libraries/LibWeb/DOM/PseudoElement.h@@ -20,7 +20,6 @@namespace Web::Animations {struct AnimationUpdateContext;-class KeyframeEffect;}@@ -38,7 +37,7 @@ public:virtual CSS::InstalledStyle const& installed_style() const = 0;CSS::StyleRecordID style_record_identity() const { return installed_style().record(); }- virtual void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&) = 0;+ virtual void update_animated_properties(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement, Web::Animations::EffectRef const&, Web::Animations::AnimationUpdateContext&) = 0;};class WEB_API SyntheticPseudoElement : public PseudoElement {@@ -58,7 +57,7 @@ public:virtual Node& root() const override;virtual CSS::InstalledStyle const& installed_style() const override { return m_installed_style; }- void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&) override;+ void update_animated_properties(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement, Web::Animations::EffectRef const&, Web::Animations::AnimationUpdateContext&) override;void set_computed_style(Layout::BegunRead const&, CSS::InstalledStyle);// Swaps in a record a style installation installs, which the render side noted the pseudo-element holds, unless// `tell_render_side` asks.@@ -113,7 +112,7 @@ class WEB_API ElementReferencePseudoElement : public PseudoElement {virtual Node& root() const override;virtual CSS::InstalledStyle const& installed_style() const override;- void update_animated_properties(Badge<Web::Animations::KeyframeEffect> const&, DOM::AbstractElement, Web::Animations::KeyframeEffect&, Web::Animations::AnimationUpdateContext&) override;+ void update_animated_properties(Badge<Web::Animations::EffectRef> const&, DOM::AbstractElement, Web::Animations::EffectRef const&, Web::Animations::AnimationUpdateContext&) override;GC::Ref<Element> const& referenced_element() const { return m_referenced_element; }diff --git a/Libraries/LibWeb/DOM/ShadowRoot.cpp b/Libraries/LibWeb/DOM/ShadowRoot.cppindex ba37ce4ebae..7ed784cb5c5 100644--- a/Libraries/LibWeb/DOM/ShadowRoot.cpp+++ b/Libraries/LibWeb/DOM/ShadowRoot.cpp@@ -298,12 +298,6 @@ void ShadowRoot::for_each_active_css_style_sheet(Function<void(CSS::StyleSheetSt}}-WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animations::Animation>>> ShadowRoot::get_animations()-{- document().update_style();- return calculate_get_animations(*this);-}-ElementByIdMap& ShadowRoot::element_by_id() const{if (!m_element_by_id)diff --git a/Libraries/LibWeb/DOM/ShadowRoot.h b/Libraries/LibWeb/DOM/ShadowRoot.hindex 78eb7bea95d..0bf04bfe807 100644--- a/Libraries/LibWeb/DOM/ShadowRoot.h+++ b/Libraries/LibWeb/DOM/ShadowRoot.h@@ -82,8 +82,6 @@ public:void for_each_css_style_sheet(Function<void(CSS::StyleSheetState&)>&& callback) const;void for_each_active_css_style_sheet(Function<void(CSS::StyleSheetState&)> const& callback) const;- WebIDL::ExceptionOr<GC::RootVector<GC::Ref<Animations::Animation>>> get_animations();-ElementByIdMap& element_by_id() const;AnchorNameMap& anchor_name_map() { return m_anchor_name_map; }diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.hindex ecfbc32ea6a..c1a3640db7a 100644--- a/Libraries/LibWeb/Forward.h+++ b/Libraries/LibWeb/Forward.h@@ -96,15 +96,12 @@ struct PatternPaintStyle;namespace Web::Animations {class Animatable;-class Animation;-class AnimationEffect;-class AnimationPlaybackEvent;+class AnimationRef;class AnimationTimeline;-class DocumentTimeline;-class KeyframeEffect;+class EffectRef;+class KeyframeSetView;class NamedTimelines;-class ScrollTimeline;-class ViewTimeline;+class WeakAnimationSetView;}@@ -1097,7 +1094,6 @@ class StorageManager;namespace Web::SVG {class Path;-class SMILAnimation;class SMILTimeContainer;class SVGAnimatedEnumeration;class SVGAnimatedInteger;diff --git a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cppindex 3ab017aa39d..be8f58d427c 100644--- a/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/ClockPlan.cpp@@ -4,14 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <AK/AnyOf.h>#include <AK/Math.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/DocumentTimeline.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/Animations/ScrollTimeline.h>-#include <LibWeb/Animations/ViewTimeline.h>-#include <LibWeb/CSS/CSSTransition.h>+#include <LibWeb/Animations/AnimationEffect.h>+#include <LibWeb/Animations/AnimationTimeline.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/CSS/StyleEngineBridge.h>#include <LibWeb/Compositor/RenderClock.h>@@ -31,102 +27,25 @@namespace Web::HTML {-// Whether the timing of `effect` is in time values of `type` throughout: milliseconds on the document timeline, and-// percentages of progress on a scroll timeline.-static bool timing_is_in(Animations::KeyframeEffect const& effect, Animations::TimeValue::Type type)-{- return effect.start_delay().type == type && effect.iteration_duration().type == type && effect.active_duration().type == type;-}--// How much of `edge` is a percentage of the scrollport's size, which a tick that resizes the scrollport resolves again.-static double inset_percentage(Animations::ViewTimeline::InsetEdge const& edge)-{- return edge.is_auto ? 0 : edge.percentage;-}--// Whether `edge` is a length plus a percentage, which is all a tick that resizes the scrollport can resolve again.-static bool inset_is_linear(Animations::ViewTimeline::InsetEdge const& edge)-{- return !edge.calculated || CSS::ComputedValuesFFI::rust_length_percentage_is_linear(edge.calculated.data());-}--// Adds the scroll timeline `timeline` that `effect` runs on, at `local_time`, to `scroll_timelines`, whose last entry-// is the timeline's where an effect of it was planned before. Answers whether a tick may sample it.-static bool plan_scroll_timeline(Vector<Layout::RustFFI::FfiPlannedScrollTimeline>& scroll_timelines, Animations::ScrollTimeline const& timeline, Animations::KeyframeEffect const& effect, Optional<Animations::TimeValue> local_time)-{- auto const& scroller = timeline.followed_scroller();- auto progress = timeline.current_time();- if (!scroller.has_value() || !progress.has_value() || progress->type != Animations::TimeValue::Type::Percentage- || !local_time.has_value() || local_time->type != Animations::TimeValue::Type::Percentage- || !timing_is_in(effect, Animations::TimeValue::Type::Percentage))- return false;- // A tick finds the subject of a view timeline by its box, which a pseudo-element does not name.- auto const* view_timeline = as_if<Animations::ViewTimeline>(timeline);- if (view_timeline && (view_timeline->subject_internal().pseudo_element().has_value() || !view_timeline->subject_internal().element().style_node_id() || !view_timeline->last_metrics().has_value()))- return false;- // A tick resolves the insets of a view timeline as a length plus a percentage, which not every calculation is.- if (view_timeline && (!inset_is_linear(view_timeline->inset().start) || !inset_is_linear(view_timeline->inset().end)))- return false;- if (scroll_timelines.is_empty() || scroll_timelines.last().timeline != timeline.clock_identity()) {- scroll_timelines.append({- .timeline = timeline.clock_identity(),- .scroller = scroller->scroll_node.node_id.value(),- .scroller_element = scroller->scroller_style_node,- .vertical = scroller->vertical,- .scroll_offset = scroller->scroll_offset,- .max_scroll_offset = scroller->max_scroll_offset,- .view = view_timeline- ? Layout::RustFFI::FfiPlannedViewTimeline {- .subject = view_timeline->subject_internal().element().style_node_id().value(),- .scrollport_size = view_timeline->last_metrics()->scrollport_size,- .inset_start = view_timeline->last_metrics()->inset_start,- .inset_end = view_timeline->last_metrics()->inset_end,- .inset_start_percentage = inset_percentage(view_timeline->inset().start),- .inset_end_percentage = inset_percentage(view_timeline->inset().end),- .subject_offset = view_timeline->last_metrics()->subject_offset,- .subject_size = view_timeline->last_metrics()->subject_size,- }- : Layout::RustFFI::FfiPlannedViewTimeline {},- });- }- return true;-}-// Whether the keyframes of `effect` animate a property a clock tick cannot sample: a custom property, or one that changes// the layout tree's shape or what the main thread observes of an element's box.-static bool animates_what_a_tick_cannot(Animations::KeyframeEffect const& effect)+static bool animates_what_a_tick_cannot(Animations::EffectRef const& effect){- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set)- return false;- for (auto const& keyframe : key_frame_set->keyframes_by_key) {- for (auto const& [property, value] : keyframe.properties) {- if (property.is_custom_property() || first_is_one_of(property.id(), CSS::PropertyID::Display, CSS::PropertyID::Visibility, CSS::PropertyID::ContentVisibility))- return true;- }- }- return false;+ auto const& keyframe_set = effect.keyframe_set();+ return keyframe_set && keyframe_set.facts().animates_what_a_tick_cannot;}// Whether the keyframes of `effect` animate a property that the children of its target inherit.-static bool animates_an_inherited_property(Animations::KeyframeEffect const& effect)+static bool animates_an_inherited_property(Animations::EffectRef const& effect){- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set)- return false;- for (auto const& keyframe : key_frame_set->keyframes_by_key) {- for (auto const& [property, value] : keyframe.properties) {- if (property.is_custom_property() || CSS::is_inherited_property(property.id()))- return true;- }- }- return false;+ auto const& keyframe_set = effect.keyframe_set();+ return keyframe_set && keyframe_set.facts().animates_an_inherited_property;}// Whether no box shows anything of the animation of `effect` on `target`: the target has no box, as under// `display: none`, or it is `display: contents`, and the effect animates neither one of its pseudo-elements nor what its// children inherit, or those have no boxes either.-static bool no_box_shows(Animations::KeyframeEffect const& effect, DOM::Element const& target, Layout::BegunRead const& read)+static bool no_box_shows(Animations::EffectRef const& effect, DOM::Element const& target, Layout::BegunRead const& read){if (target.unsafe_layout_node(read))return false;@@ -144,7 +63,7 @@ static bool no_box_shows(Animations::KeyframeEffect const& effect, DOM::Element}// Whether a tick can sample the animation of `effect` on `target`.-static bool tick_can_sample(DOM::Document const& document, Animations::KeyframeEffect const& effect, DOM::Element const& target, Layout::BegunRead const& read)+static bool tick_can_sample(DOM::Document const& document, Animations::EffectRef const& effect, DOM::Element const& target, Layout::BegunRead const& read){// The root element and the body paint the background the canvas may take over, which only the host resolves.auto const* layout_node = target.unsafe_layout_node(read);@@ -153,15 +72,14 @@ static bool tick_can_sample(DOM::Document const& document, Animations::KeyframeE&& layout_node && Painting::has_committed_box(*layout_node) && !animates_what_a_tick_cannot(effect);}-// An animation of a scroll timeline that finished runs again as the scroll goes back.-static bool runs_for_clock_plan(Animations::Animation const& animation, bool on_scroll_timeline)+// NB: An animation of a scroll timeline that finished runs again as the scroll goes back.+static bool runs_for_clock_plan(Animations::RustFFI::FfiAnimationTimingState const& state, bool on_scroll_timeline){- auto play_state = animation.play_state();- return play_state == Bindings::AnimationPlayState::Running || (on_scroll_timeline && play_state == Bindings::AnimationPlayState::Finished);+ return state.play_state == Animations::RustFFI::AnimationPlayState::Running || (on_scroll_timeline && state.play_state == Animations::RustFFI::AnimationPlayState::Finished);}// The compositor runs these on its own, so the render clock does not sample them.-static bool runs_on_compositor(Animations::KeyframeEffect const& effect)+static bool runs_on_compositor(Animations::EffectRef const& effect){return effect.is_compositor_driven() || effect.is_compositor_replaced();}@@ -218,7 +136,7 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)// main thread sends as it gets to them.Vector<u32> elements;double last_end = -AK::Infinity<double>;- Vector<Layout::RustFFI::FfiPlannedScrollTimeline> scroll_timelines;+ Vector<Animations::RustFFI::TimelineCell const*> scroll_timelines;Vector<u32> held_elements;auto plan = [&] {if (!document.is_fully_active() || document.hidden() || !document.window())@@ -227,58 +145,49 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)auto timeline_time = timeline->current_time();if (!timeline_time.has_value() || timeline_time->type != Animations::TimeValue::Type::Milliseconds)return false;- auto plan_animation = [&](Animations::Animation const& animation, Animations::ScrollTimeline const* scroll_timeline, Animations::KeyframeEffect const& effect, DOM::Element const& target) {- // A tick moves the document's timeline, at the rate it runs, and the scroll timelines, to where the- // compositor has scrolled. What the compositor runs already runs there while its play is pending.- // Anything else holds still while its play is pending, until the host makes it ready, as it does in- // the boxes of the host's frame: the ticks sample nothing of its element.- if (animation.pending() && !runs_on_compositor(effect)) {+ auto plan_animation = [&](Animations::AnimationRef const& animation, Animations::RustFFI::FfiAnimationTimingState const& state, Animations::AnimationTimeline const* scroll_timeline, Animations::EffectRef const& effect, DOM::Element const& target) {+ // NB: The record decides what the plan makes of the animation as far as its timing goes. One whose play+ // is pending holds still, and the ticks sample nothing of its element.+ auto planned = Animations::RustFFI::animations_animation_clock_plan(&animation.record());+ if (planned.kind == Animations::RustFFI::FfiClockPlanAnimationKind::Held) {if (!effect.pseudo_element_type().has_value())held_elements.append(target.style_node_id().value());return true;}- if (!(animation.playback_rate() > 0))- return false;- // A scroll timeline with nothing to scroll holds still, and so do its animations.- if (scroll_timeline && !scroll_timeline->followed_scroller().has_value())+ // NB: Nor does a tick move one it cannot, as one of a scroll timeline with nothing to scroll, or one that a+ // tick cannot follow.+ if (planned.kind == Animations::RustFFI::FfiClockPlanAnimationKind::NotTicked)return false;// What the compositor runs, what the main thread does not sample per frame either, or what no box shows,// a tick does not sample.bool const tick_samples = !runs_on_compositor(effect) && !effect.can_skip_per_frame_style_update() && !no_box_shows(effect, target, read);if (tick_samples && !tick_can_sample(document, effect, target, read))return false;- auto local_time = effect.local_time();- if (scroll_timeline) {- if (!plan_scroll_timeline(scroll_timelines, *scroll_timeline, effect, local_time))- return false;- } else if (!local_time.has_value() || local_time->type != Animations::TimeValue::Type::Milliseconds- || !timing_is_in(effect, Animations::TimeValue::Type::Milliseconds)- || local_time->value >= effect.start_delay().value + effect.active_duration().value) {- return false;- }+ // NB: The plan takes the scroll timelines a tick follows as they are when it is sealed.+ if (scroll_timeline && (scroll_timelines.is_empty() || scroll_timelines.last() != &scroll_timeline->record()))+ scroll_timelines.append(&scroll_timeline->record());if (!tick_samples)return true;- if (!scroll_timeline) {- auto active_end = effect.start_delay().value + effect.active_duration().value;- last_end = max(last_end, timeline_time->value + (active_end - local_time->value) / animation.playback_rate());- }+ if (!scroll_timeline)+ last_end = max(last_end, timeline_time->value + (planned.active_end.value - planned.local_time.value) / state.playback.playback_rate);auto element = target.style_node_id().value();if (!elements.contains_slow(element))elements.append(element);return true;};for (auto const& associated_timeline : document.associated_animation_timelines()) {- auto const* scroll_timeline = as_if<Animations::ScrollTimeline>(*associated_timeline);- for (auto& animation : associated_timeline->associated_animations()) {- if (!runs_for_clock_plan(animation, scroll_timeline != nullptr))+ Animations::AnimationTimeline const* scroll_timeline = associated_timeline->is_scroll_timeline() ? associated_timeline.ptr() : nullptr;+ for (auto const& animation : associated_timeline->associated_animations()) {+ auto const state = animation.timing_state();+ if (!runs_for_clock_plan(state, scroll_timeline != nullptr))continue;- auto const* effect = as_if<Animations::KeyframeEffect>(animation.effect().ptr());- auto target = effect ? effect->target() : nullptr;+ auto effect = animation.effect();+ auto* target = effect.has_value() ? effect->target() : nullptr;if (!target || &target->document() != &document || !target->is_connected())continue;// A tick moves the document's timeline and the scroll timelines alone.bool const on_a_ticked_timeline = associated_timeline.ptr() == timeline.ptr() || scroll_timeline;- if (on_a_ticked_timeline && plan_animation(animation, scroll_timeline, *effect, *target))+ if (on_a_ticked_timeline && plan_animation(animation, state, scroll_timeline, *effect, *target))continue;// The boxes of an element with an animation a tick cannot sample show what the host's frame shows// of it, while the ticks sample the others on.@@ -297,30 +206,22 @@ bool seal_clock_plan(DOM::Document& document, bool may_plan, u64 update_serial)// The lane's ticks may also follow the pointer, and hover what is under it while a task runs.Optional<Layout::RustFFI::FfiHoverPlanInputs> hover;Vector<u32> effect_timing_nodes;- Vector<u64> effect_timing_identities;+ Vector<Animations::RustFFI::AnimationEffectId> effect_timing_identities;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.for (auto const& associated_timeline : document.associated_animation_timelines()) {- for (auto& animation : associated_timeline->associated_animations()) {- auto const* effect = as_if<Animations::KeyframeEffect>(animation.effect().ptr());- auto target = effect ? effect->target() : nullptr;- if (!effect || !target || effect->pseudo_element_type().has_value() || !target->style_node_id()+ for (auto const& animation : associated_timeline->associated_animations()) {+ auto effect = animation.effect();+ auto* target = effect.has_value() ? effect->target() : nullptr;+ if (!target || effect->pseudo_element_type().has_value() || !target->style_node_id()|| !effect->can_skip_per_frame_style_update())continue;- 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, 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.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({});- }+ // NB: The record decides the timing the hover runs the animation with.effect_timing_nodes.append(target->style_node_id().value());- effect_timing_identities.append(effect->animation_preparation_identity());- effect_timings.append(timing);+ effect_timing_identities.append(effect->id());+ effect_timings.append(Animations::RustFFI::animations_animation_hover_timing(&animation.record()));}}Optional<Web::EventHandler::SelectionDragForLanes> selection_drag;diff --git a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cppindex 147d06c328a..8df6dedf765 100644--- a/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp+++ b/Libraries/LibWeb/HTML/EventLoop/EventLoop.cpp@@ -14,8 +14,8 @@#include <LibGC/Heap.h>#include <LibGC/HeapAccess.h>#include <LibJS/Runtime/VM.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/Animations/NamedTimelines.h>-#include <LibWeb/Animations/ScrollTimeline.h>#include <LibWeb/Bindings/MainThreadVM.h>#include <LibWeb/CSS/CSSTransition.h>#include <LibWeb/CSS/FontFaceSet.h>@@ -771,18 +771,23 @@ void EventLoop::finish_rendering_update(double update_start_time)// Whether `animation` is a CSS animation or transition that the style of a rendering update began, which the update// makes ready once its style and layout are done.-static bool rendering_update_makes_ready(Animations::Animation const& animation)+static bool rendering_update_makes_ready(Animations::AnimationRef const& animation){- auto const* effect = as_if<Animations::KeyframeEffect>(animation.effect().ptr());- return animation.pending() && (animation.is_css_animation() || animation.is_css_transition()) && effect && !effect->may_run_on_the_compositor();+ auto effect = animation.effect();+ if (!effect.has_value())+ return false;+ auto const state = animation.timing_state();+ return (state.playback.has_pending_play_task || state.playback.has_pending_pause_task)+ && (state.kind == Animations::RustFFI::FfiAnimationKind::CssAnimation || state.kind == Animations::RustFFI::FfiAnimationKind::CssTransition)+ && !effect->may_run_on_the_compositor();}// Whether `animation` runs on the compositor, whose animations, the wake-ups they arm and the ones that leave it, a// rendering update publishes with its frame.-static bool runs_on_the_compositor(Animations::Animation const& animation)+static bool runs_on_the_compositor(Animations::AnimationRef const& animation){- auto const* effect = as_if<Animations::KeyframeEffect>(animation.effect().ptr());- return effect && effect->is_compositor_driven();+ auto effect = animation.effect();+ return effect.has_value() && effect->is_compositor_driven();}enum class StyleTakenIn : u8 {@@ -1336,17 +1341,18 @@ static void update_style_and_layout_for_rendering(DOM::Document& document, u64 uGC::RootVector timelines = { document.associated_animation_timelines().values() };for (auto const& timeline : timelines) {- auto* scroll_timeline = as_if<Animations::ScrollTimeline>(*timeline);-- if (!scroll_timeline)+ if (!timeline->is_scroll_timeline())continue;- if (!animations_changed_timeline && !scroll_timeline->is_stale())+ if (animations_changed_timeline) {+ // NB: The passed timestamp is ignored for ScrollTimelines so we can just use 0.+ timeline->update_current_time(0);+ requires_style_and_layout_update = true;continue;+ }- // NB: The passed timestamp is ignored for ScrollTimelines so we can just use 0.- timeline->update_current_time(0);- requires_style_and_layout_update = true;+ if (timeline->update_current_time_if_stale())+ requires_style_and_layout_update = true;}if (requires_style_and_layout_update)@@ -1370,13 +1376,14 @@ void EventLoop::update_the_rendering_after_style_and_layout(Vector<GC::Root<DOM:TemporaryExecutionContext execution_context { document->relevant_settings_object() };GC::RootVector timelines = { document->associated_animation_timelines().values() };for (auto const& timeline : timelines) {- GC::RootVector<GC::Ref<Animations::Animation>> pending_css_animations;- for (auto& animation : timeline->associated_animations()) {+ // NB: Running a play task can run script, which the animations stay alive through.+ GC::RootVector<Animations::AnimationRef> pending_css_animations;+ for (auto const& animation : timeline->associated_animations()) {if (rendering_update_makes_ready(animation))pending_css_animations.append(animation);}- for (auto& animation : pending_css_animations)- animation->run_pending_play_task_if_ready();+ for (auto const& animation : pending_css_animations)+ animation.run_pending_play_task_if_ready();}}@@ -1529,7 +1536,7 @@ Layout::RustFFI::FfiFlightBlocker EventLoop::style_flight_blocker(DOM::Document&if (document.has_boxes_with_auto_content_visibility())return Blocker::ContentVisibilityAuto;for (auto const& timeline : document.associated_animation_timelines()) {- if (is<Animations::ScrollTimeline>(*timeline))+ if (timeline->is_scroll_timeline())return Blocker::ScrollTimeline;}// The animations that name their timeline look it up again after style and layout.diff --git a/Libraries/LibWeb/Internals/InternalAnimationTimeline.cpp b/Libraries/LibWeb/Internals/InternalAnimationTimeline.cppdeleted file mode 100644index 9eb80670e95..00000000000--- a/Libraries/LibWeb/Internals/InternalAnimationTimeline.cpp+++ /dev/null@@ -1,45 +0,0 @@-/*- * Copyright (c) 2024, Matthew Olsson <[email protected]>.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibGC/Heap.h>-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/DOM/Document.h>-#include <LibWeb/HTML/Window.h>-#include <LibWeb/Internals/InternalAnimationTimeline.h>--namespace Web::Internals {--GC_DEFINE_ALLOCATOR(InternalAnimationTimeline);--GC::Ref<InternalAnimationTimeline> InternalAnimationTimeline::create(GC::Ref<DOM::Document> document)-{- return GC::Heap::the().allocate<InternalAnimationTimeline>(document);-}--void InternalAnimationTimeline::update_current_time(double)-{- update_associated_animations();-}--void InternalAnimationTimeline::set_time(Optional<double> time)-{- set_current_time(time.map([](double value) -> Animations::TimeValue { return { Animations::TimeValue::Type::Milliseconds, value }; }));-}--void InternalAnimationTimeline::set_time_for_observation(double time)-{- m_time_for_observation = Animations::TimeValue { Animations::TimeValue::Type::Milliseconds, time };- m_last_current_time_update_task_generation = {};-}--InternalAnimationTimeline::InternalAnimationTimeline(GC::Ref<DOM::Document> document)- : AnimationTimeline(document)-{- m_current_time = { Animations::TimeValue::Type::Milliseconds, 0.0 };- m_is_monotonically_increasing = true;-}--}diff --git a/Libraries/LibWeb/Internals/InternalAnimationTimeline.h b/Libraries/LibWeb/Internals/InternalAnimationTimeline.hindex 4d72e8b58b4..52d39b70f3d 100644--- a/Libraries/LibWeb/Internals/InternalAnimationTimeline.h+++ b/Libraries/LibWeb/Internals/InternalAnimationTimeline.h@@ -6,35 +6,14 @@#pragma once-#include <LibWeb/Animations/AnimationTimeline.h>+#include <LibWeb/Bindings/InternalAnimationTimeline.h>+#include <LibWeb/Bindings/RustInterface.h>namespace Web::Internals {-class InternalAnimationTimeline : public Web::Animations::AnimationTimeline {-public:- WEB_WRAPPABLE(InternalAnimationTimeline, Web::Animations::AnimationTimeline);- GC_DECLARE_ALLOCATOR(InternalAnimationTimeline);-- [[nodiscard]] static GC::Ref<InternalAnimationTimeline> create(GC::Ref<DOM::Document>);-- virtual Optional<Animations::TimeValue> duration() const override { return {}; }-- virtual Optional<double> convert_a_timeline_time_to_an_origin_relative_time(Optional<Animations::TimeValue>) override { return {}; }-- virtual void update_current_time(double timestamp) override;-- void set_time(Optional<double> time);- void set_time_for_observation(double time);--protected:- virtual bool can_sample_current_time_at_timestamp() const override { return m_time_for_observation.has_value(); }- virtual Optional<Animations::TimeValue> current_time_at_timestamp(double) const override { return m_time_for_observation; }--private:- explicit InternalAnimationTimeline(GC::Ref<DOM::Document>);- virtual ~InternalAnimationTimeline() override = default;-- Optional<Animations::TimeValue> m_time_for_observation;+// The cell of an InternalAnimationTimeline, which Bindings/Rust/src/internals implements.+class InternalAnimationTimeline final : public Bindings::RustInterfaceCell {+ WEB_RUST_INTERFACE(InternalAnimationTimeline, internal_animation_timeline)};}diff --git a/Libraries/LibWeb/Internals/InternalAnimationTimeline.idl b/Libraries/LibWeb/Internals/InternalAnimationTimeline.idlindex 049a870a384..c6c30729e36 100644--- a/Libraries/LibWeb/Internals/InternalAnimationTimeline.idl+++ b/Libraries/LibWeb/Internals/InternalAnimationTimeline.idl@@ -1,4 +1,4 @@-[Exposed=Nobody]+[Exposed=Nobody, ImplementedIn=Rust]interface InternalAnimationTimeline : AnimationTimeline {undefined setTime(double? time);undefined setTimeForObservation(double time);diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 548e3f66d3a..f55a5588deb 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -33,7 +33,7 @@#include <LibURL/Parser.h>#include <LibWeb/ARIA/AriaData.h>#include <LibWeb/ARIA/StateAndProperties.h>-#include <LibWeb/Animations/DocumentTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/Bindings/Internals.h>#include <LibWeb/Bindings/Intrinsics.h>#include <LibWeb/Bindings/MainThreadVM.h>@@ -1342,7 +1342,7 @@ void Internals::load_url(Utf16String const& url_string)GC::Ref<InternalAnimationTimeline> Internals::create_internal_animation_timeline(){- return InternalAnimationTimeline::create(window().associated_document());+ return static_cast<InternalAnimationTimeline&>(static_cast<Bindings::RustInterfaceCell&>(*Animations::AnimationTimeline::create_internal_timeline(window().associated_document())));}WebIDL::ExceptionOr<void> Internals::simulate_drag_start(double x, double y, Utf16String const& name, Utf16String const& contents)@@ -3118,6 +3118,41 @@ void Internals::force_parallel_layout()Layout::RustFFI::render_state_force_parallel_layout(window().associated_document().layout_node_arena().host());}+// NB: The Animation objects of the animations associated with the document's elements, which a CSS animation or+// transition only has once script asks for it.+static u64 animation_object_bytes(DOM::Document& document)+{+ u64 bytes = 0;+ document.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {+ for (auto const& animation : element.associated_animations_unordered())+ bytes += Animations::object_memory_size(animation);+ return TraversalDecision::Continue;+ });+ return bytes;+}++// The records the C++ animation objects keep their state in, the keyframe sets they run, each counted once however+// many effects share it, and each element's lists of its animations and transitions.+static u64 animation_record_bytes(DOM::Document& document)+{+ u64 bytes = 0;+ HashTable<Animations::RustFFI::KeyframeSet const*> counted_keyframe_sets;+ document.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {+ bytes += element.animation_lists_memory_size();+ for (auto const& animation : element.associated_animations_unordered()) {+ bytes += Animations::RustFFI::animations_animation_memory_size(&animation.record());+ auto effect = animation.effect();+ if (!effect.has_value())+ continue;+ bytes += Animations::RustFFI::animations_effect_memory_size(&effect->record());+ if (auto const* keyframe_set = effect->keyframe_set().ptr(); keyframe_set && counted_keyframe_sets.set(keyframe_set) == HashSetResult::InsertedNewEntry)+ bytes += Animations::RustFFI::animations_keyframe_set_memory_size(keyframe_set);+ }+ return TraversalDecision::Continue;+ });+ return bytes;+}+GC::Ref<JS::Object> Internals::style_memory_report(){auto& document = window().associated_document();@@ -3156,6 +3191,8 @@ GC::Ref<JS::Object> Internals::style_memory_report()});define(*owners, "cppInstalledStyles"sv, installed_style_bytes);define(*owners, "cppHintProperties"sv, hint_bytes);+ define(*owners, "animationObjects"sv, animation_object_bytes(document));+ define(*owners, "animationRecords"sv, animation_record_bytes(document));auto object = JS::Object::create(realm, nullptr);object->define_direct_property("owners"_utf16_fly_string, owners, JS::default_attributes);diff --git a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cppindex 7f33d3cf1a5..7486f19fa16 100644--- a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp+++ b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.cpp@@ -4,9 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Animations/KeyframeEffect.h>-#include <LibWeb/CSS/CSSAnimation.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/CSS/ComputedValues.h>#include <LibWeb/CSS/EasingFunction.h>#include <LibWeb/CSS/StyleComputer.h>@@ -26,99 +24,50 @@ namespace Web::Painting {struct CompositorAnimationKeyframes::Data {AK_ALLOC_WITH_KMALLOC;- Data(Animations::KeyframeEffect const& effect, Animations::Animation const& animation, DOM::AbstractElement target)- : effect(effect)- , animation(animation)+ Data(Animations::EffectRef effect, Animations::AnimationRef animation, DOM::AbstractElement target)+ : effect(move(effect))+ , animation(move(animation)), target(target){}- GC::Ref<Animations::KeyframeEffect const> effect;- GC::Ref<Animations::Animation const> animation;+ Animations::EffectRef effect;+ Animations::AnimationRef animation;DOM::AbstractElement target;- // The linear easing control points each keyframe's descriptor borrows.- Vector<Vector<Compositing::RustFFI::FfiLinearEasingPoint>> linear_easing_points;- Vector<Layout::RustFFI::FfiCompositorAnimationKeyframe> keyframes;- Vector<Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame const*> entries;+ // The keyframes the builder reads, which the build keeps live.+ Animations::KeyframeSetHandle keyframe_set;+ // The easing a keyframe that declares none runs, with the linear easing control points its descriptor borrows.+ Vector<Compositing::RustFFI::FfiLinearEasingPoint> default_easing_points;+ Compositing::RustFFI::FfiEasingDescriptor default_easing {};};-static Layout::RustFFI::FfiCompositorKeyframeValueState keyframe_value_state(Animations::KeyframeEffect::KeyFrameSet::ResolvedKeyFrame const& entry, CSS::PropertyID property_id)-{- auto value = entry.properties.get(CSS::PropertyNameAndID::from_id(property_id));- if (!value.has_value())- return Layout::RustFFI::FfiCompositorKeyframeValueState::Absent;- if (value->has<Animations::KeyframeEffect::KeyFrameSet::UseInitial>())- return Layout::RustFFI::FfiCompositorKeyframeValueState::UsesUnderlyingStyle;- return Layout::RustFFI::FfiCompositorKeyframeValueState::Present;-}--CompositorAnimationKeyframes::CompositorAnimationKeyframes(Animations::KeyframeEffect const& effect, Animations::Animation const& animation, DOM::AbstractElement target)+CompositorAnimationKeyframes::CompositorAnimationKeyframes(Animations::EffectRef const& effect, Animations::AnimationRef const& animation, DOM::AbstractElement target): m_data(make<Data>(effect, animation, target)){- auto const* key_frame_set = effect.key_frame_set();- if (!key_frame_set)+ m_data->keyframe_set = Animations::KeyframeSetHandle::retained(effect.keyframe_set().ptr());+ if (animation.timing_state().kind != Animations::RustFFI::FfiAnimationKind::CssAnimation) {+ m_data->default_easing = CSS::EasingFunction::linear().descriptor_with_points_in(m_data->default_easing_points);return;- auto keyframe_count = key_frame_set->keyframes_by_key.size();- m_data->linear_easing_points.ensure_capacity(keyframe_count);- m_data->keyframes.ensure_capacity(keyframe_count);- m_data->entries.ensure_capacity(keyframe_count);- for (auto it = key_frame_set->keyframes_by_key.begin(); it != key_frame_set->keyframes_by_key.end(); ++it) {- auto const& entry = *it;- m_data->entries.unchecked_append(&entry);- Layout::RustFFI::FfiCompositorAnimationKeyframe keyframe {};- keyframe.offset = static_cast<double>(it.key()) / (100.0 * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor);- auto composite = [&] {- switch (entry.composite) {- case Bindings::CompositeOperationOrAuto::Replace:- return Bindings::CompositeOperation::Replace;- case Bindings::CompositeOperationOrAuto::Add:- return Bindings::CompositeOperation::Add;- case Bindings::CompositeOperationOrAuto::Accumulate:- return Bindings::CompositeOperation::Accumulate;- case Bindings::CompositeOperationOrAuto::Auto:- return effect.composite();- }- VERIFY_NOT_REACHED();- }();- keyframe.composite_is_replace = composite == Bindings::CompositeOperation::Replace;- m_data->linear_easing_points.unchecked_append({});- auto& linear_easing_points = m_data->linear_easing_points.last();- auto describe_easing = [&](CSS::EasingFunction const& easing) {- return easing.descriptor_with_points_in(linear_easing_points);- };- keyframe.easing_is_supported = entry.easing.visit(- [&](Empty) {- auto easing = animation.is_css_animation()- ? static_cast<CSS::CSSAnimation const&>(animation).default_easing()- : CSS::EasingFunction::linear();- keyframe.easing = describe_easing(easing);- return true;- },- [&](CSS::EasingFunction const& easing) {- keyframe.easing = describe_easing(easing);- return true;- },- [&](CSS::RustStyleValueHandle const&) {- keyframe.easing = describe_easing(CSS::EasingFunction::linear());- return false;- });- keyframe.opacity = keyframe_value_state(entry, CSS::PropertyID::Opacity);- keyframe.background_color = keyframe_value_state(entry, CSS::PropertyID::BackgroundColor);- keyframe.filter = keyframe_value_state(entry, CSS::PropertyID::Filter);- keyframe.translate = keyframe_value_state(entry, CSS::PropertyID::Translate);- keyframe.rotate = keyframe_value_state(entry, CSS::PropertyID::Rotate);- keyframe.scale = keyframe_value_state(entry, CSS::PropertyID::Scale);- keyframe.transform = keyframe_value_state(entry, CSS::PropertyID::Transform);- m_data->keyframes.unchecked_append(keyframe);}+ auto default_easing = Animations::RustFFI::animations_css_animation_state(&animation.record()).default_easing;+ m_data->default_easing_points.append(default_easing.linear_points, default_easing.linear_point_count);+ default_easing.linear_points = m_data->default_easing_points.data();+ m_data->default_easing = default_easing;}CompositorAnimationKeyframes::~CompositorAnimationKeyframes() = default;-static RefPtr<CSS::StyleValue const> resolved_compositor_animation_style_value(Layout::BegunRead const& read, CSS::PropertyID property_id, CSS::RustStyleValueHandle const& value, DOM::AbstractElement target)+void CompositorAnimationKeyframes::visit_edges(GC::Cell::Visitor& visitor) const+{+ m_data->effect.visit_edges(visitor);+ m_data->animation.visit_edges(visitor);+ m_data->target.visit_edges(visitor);+}++static RefPtr<CSS::StyleValue const> resolved_compositor_animation_style_value(Layout::BegunRead const& read, CSS::PropertyID property_id, CSS::StyleValueFFI::StyleValueData const* value, DOM::AbstractElement target){HTML::note_rendering_trace_event("compositor keyframe values resolved"sv);- auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value.data()));+ auto style_value = CSS::StyleValue::adopt_rust_style_value_data(CSS::StyleValueFFI::rust_style_value_retain(value));if (style_value->is_unresolved()) {// The engine substitutes the value as a sample on the main thread would, against the custom properties the// element holds and inherits.@@ -132,7 +81,7 @@ static RefPtr<CSS::StyleValue const> resolved_compositor_animation_style_value(Lcustom_property_data ? custom_property_data->rust_store() : nullptr,inheritance_custom_property_data ? inheritance_custom_property_data->rust_store() : nullptr,to_underlying(property_id),- value.data());+ value);if (!substituted)return nullptr;style_value = CSS::StyleValue::adopt_rust_style_value_data(substituted);@@ -156,22 +105,19 @@ struct CompositorAnimationBuild {Layout::BegunRead const& read;};-static void const* resolved_compositor_keyframe_value(void* context, size_t keyframe_index, u16 property_id, bool uses_underlying_style)+static void const* resolved_compositor_keyframe_value(void* context, u16 property_id, void const* declared_value){auto& [data, read] = *static_cast<CompositorAnimationBuild*>(context);auto property = static_cast<CSS::PropertyID>(property_id);RefPtr<CSS::StyleValue const> style_value;- if (uses_underlying_style) {+ if (!declared_value) {// NB: Synthesized endpoints use the underlying style, just as main-thread keyframe sampling does.auto computed_style = data.target.computed_style();if (!computed_style)return nullptr;style_value = computed_style->computed_style_value(property, CSS::ComputedValues::WithAnimationsApplied::No);} else {- auto value = data.entries[keyframe_index]->properties.get(CSS::PropertyNameAndID::from_id(property));- if (!value.has_value() || !value->has<CSS::RustStyleValueHandle>())- return nullptr;- style_value = resolved_compositor_animation_style_value(read, property, value->get<CSS::RustStyleValueHandle>(), data.target);+ style_value = resolved_compositor_animation_style_value(read, property, static_cast<CSS::StyleValueFFI::StyleValueData const*>(declared_value), data.target);}if (!style_value)return nullptr;@@ -188,16 +134,16 @@ static Layout::RustFFI::FfiCompositorAnimationHost compositor_animation_host(Comstatic Layout::RustFFI::FfiCompositorAnimationRequest compositor_animation_request(CompositorAnimationKeyframes::Data const& data, Layout::Node const& layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind){- auto const& effect = *data.effect;+ auto const& effect = data.effect;Layout::RustFFI::FfiCompositorAnimationRequest request {};request.target_kind = target_kind;request.layout_node = Layout::Node::slot_id(&layout_node);auto target_color_resolution_style = CSS::ColorResolutionStyle::for_element(data.target);request.target_inherited_ui_values = target_color_resolution_style.inherited_ui_values;request.target_inherited_text_values = target_color_resolution_style.inherited_text_values;- request.keyframes = data.keyframes.data();- request.keyframe_count = data.keyframes.size();- request.key_frame_set_identity = reinterpret_cast<uintptr_t>(effect.key_frame_set());+ request.keyframe_set = data.keyframe_set.ptr();+ request.effect_composite_is_replace = effect.composite_is_replace();+ request.default_easing = data.default_easing;request.target_style_generation = data.target.element().animation_style_generation();request.style_environment_version = data.target.document().style_computer().style_environment_version_for_sharing();if (target_kind == Compositing::RustFFI::FfiVisualAnimationTargetKind::Transform) {@@ -250,27 +196,17 @@ static Layout::RustFFI::DocumentHost* document_host(DOM::Document& document)return document.layout_node_arena().host();}-CompositorAnimationEffectState::CompositorAnimationEffectState()- : m_handle(Layout::RustFFI::compositor_animation_effect_state_create())-{-}--CompositorAnimationEffectState::~CompositorAnimationEffectState()-{- Layout::RustFFI::compositor_animation_effect_state_destroy(m_handle);-}-CompositorAnimationEffectState::BuildOutcome CompositorAnimationEffectState::build(Layout::BegunRead const& read, CompositorAnimationKeyframes const& keyframes, Layout::Node const& layout_node, Compositing::RustFFI::FfiVisualAnimationTargetKind target_kind, TimingAnchor timing_anchor){auto& data = *keyframes.m_data;- auto const& effect = *data.effect;+ auto const& effect = data.effect;auto request = compositor_animation_request(data, layout_node, target_kind);Vector<Compositing::RustFFI::FfiLinearEasingPoint> effect_easing_points;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.effect = effect.effect_timing(effect.fill_mode());- request.timing.easing = effect.timing_function().descriptor_with_points_in(effect_easing_points);+ request.timing.playback_rate = Animations::RustFFI::animations_animation_playback(&data.animation.record()).playback_rate;+ request.timing.effect = effect.timing();+ request.timing.easing = effect.timing_function_with_points_in(effect_easing_points);CompositorAnimationBuild lent { data, read };auto host = compositor_animation_host(lent);@@ -312,9 +248,4 @@ void CompositorAnimationEffectState::clear_retained()Layout::RustFFI::compositor_animation_effect_clear_retained(m_handle);}-void CompositorAnimationEffectState::reset()-{- Layout::RustFFI::compositor_animation_effect_reset(m_handle);-}-}diff --git a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.hindex ba64649b18c..860cbcf110c 100644--- a/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h+++ b/Libraries/LibWeb/Painting/CompositorAnimationEffectState.h@@ -10,6 +10,7 @@#include <AK/NonnullOwnPtr.h>#include <AK/Optional.h>#include <AK/Types.h>+#include <LibGC/Cell.h>#include <LibWeb/Export.h>#include <LibWeb/Forward.h>@@ -21,10 +22,9 @@ enum class FfiVisualAnimationTargetKind : u8;namespace Web::Painting {-// The keyframes of an effect as the compositor animation builder reads them: which properties each-// keyframe gives a value, the easing descriptors with the storage they borrow, and the keyframe set-// entries the builder resolves values from by index, against the effect's target. An update pass-// builds them once for each effect it asks about.+// The keyframes of an effect as the compositor animation builder reads them: the effect's keyframe+// set, with the easing a keyframe that declares none runs, and the target the builder resolves the+// values they declare against. An update pass builds them once for each effect it asks about.class WEB_API CompositorAnimationKeyframes {AK_MAKE_NONCOPYABLE(CompositorAnimationKeyframes);AK_MAKE_NONMOVABLE(CompositorAnimationKeyframes);@@ -32,9 +32,12 @@ class WEB_API CompositorAnimationKeyframes {public:AK_ALLOC_WITH_KMALLOC;- CompositorAnimationKeyframes(Animations::KeyframeEffect const&, Animations::Animation const&, DOM::AbstractElement target);+ CompositorAnimationKeyframes(Animations::EffectRef const&, Animations::AnimationRef const&, DOM::AbstractElement target);~CompositorAnimationKeyframes();+ // Visits what keeps the effect, its animation and the target alive, which the holder of the keyframes traces.+ void visit_edges(GC::Cell::Visitor&) const;+// Whether the transforms the effect animates keep the axes in place: it does not rotate, and// its transform keyframes only translate and scale.bool transform_preserves_axes(Layout::Node const&) const;@@ -49,17 +52,15 @@ private:NonnullOwnPtr<Data> m_data;};-// What a keyframe effect has built for the compositor, kept in Rust: the values lowered from its-// keyframes, the animations built in the current update pass, and the ones it published last.+// What a keyframe effect has built for the compositor, which the effect's record keeps in Rust: the values lowered+// from its keyframes, the animations built in the current update pass, and the ones it published last. This borrows+// it from the record, which keeps it for as long as the effect lives and forgets it as the effect changes.class WEB_API CompositorAnimationEffectState {- AK_MAKE_NONCOPYABLE(CompositorAnimationEffectState);- AK_MAKE_NONMOVABLE(CompositorAnimationEffectState);-public:- AK_ALLOC_WITH_KMALLOC;-- CompositorAnimationEffectState();- ~CompositorAnimationEffectState();+ explicit CompositorAnimationEffectState(void* handle)+ : m_handle(handle)+ {+ }struct BuildOutcome {// The animation is built and waits with the effect's other pending animations.@@ -95,9 +96,6 @@ public:bool has_retained() const;void clear_retained();- // The keyframes changed: everything lowered from them is stale.- void reset();-private:void* m_handle { nullptr };};diff --git a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp b/Libraries/LibWeb/Painting/PaintingRustBridge.cppindex 50a6f30d31b..dd9d1495fac 100644--- a/Libraries/LibWeb/Painting/PaintingRustBridge.cpp+++ b/Libraries/LibWeb/Painting/PaintingRustBridge.cpp@@ -12,7 +12,7 @@#include <LibGfx/GradientInterpolation.h>#include <LibGfx/Matrix4x4.h>#include <LibGfx/TextLayout.h>-#include <LibWeb/Animations/DocumentTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/CSS/Enums.h>#include <LibWeb/CSS/StyleValues/AbstractImageStyleValue.h>#include <LibWeb/CSS/VisualViewport.h>diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex a9e94d6bc34..4b2f58b80d6 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -1712,6 +1712,26 @@ fn generate_property_metadata(manifest_dir: &Path, out_dir: &Path) -> Result<(),idl_names.len(),idl_names));+ // The IDL attribute names of the properties and of their legacy aliases, ASCII-lowercased and sorted, with the+ // ids they name, as the C++ generator's case-insensitive table of them looks them up. A later name wins where two+ // lowercase alike, as it does in that table.+ let mut camel_case_lookup: Vec<(String, u16)> = Vec::new();+ for (name, value) in &properties {+ let object = value.as_object().unwrap();+ let target = object+ .get("legacy-alias-for")+ .and_then(serde_json::Value::as_str)+ .unwrap_or(name);+ let key = camel_case_property_name(name).to_ascii_lowercase();+ camel_case_lookup.retain(|(existing, _)| *existing != key);+ camel_case_lookup.push((key, ids[target]));+ }+ camel_case_lookup.sort_unstable_by(|left, right| left.0.cmp(&right.0));+ output.push_str(&format!(+ "pub(crate) static PROPERTY_CAMEL_CASE_LOOKUP: [(&str, u16); {}] = {:?};\n",+ camel_case_lookup.len(),+ camel_case_lookup+ ));output.push_str(&format!("pub(crate) const PROPERTY_IS_LOGICAL_ALIAS: [bool; {}] = {:?};\n\n",logical_aliases.len(),@@ -2455,6 +2475,19 @@ fn expose_compositing_types_as_cpp_types(config: &mut cbindgen::Config) {.push("LibCompositing/Scrolling/ScrollSnapSelection.h".to_string());}+/// Names an animation effect's identity as the animations header does, which declares it the same way.+fn declare_animation_effect_id_of_animations_header(config: &mut cbindgen::Config) {+ config.export.exclude.push("AnimationEffectId".to_string());+ config.export.rename.insert(+ "AnimationEffectId".to_string(),+ "Web::Animations::RustFFI::AnimationEffectId".to_string(),+ );+ config+ .after_includes+ .get_or_insert_with(String::new)+ .push_str("\nnamespace Web::Animations::RustFFI { using AnimationEffectId = uint64_t; }");+}+/// Names the document host and the begun read as the layout header declares them, for a header whose entries take them.fn declare_document_host_of_layout_header(config: &mut cbindgen::Config) {for name in ["DocumentHost", "BegunRead"] {@@ -2666,6 +2699,8 @@ fn main() -> Result<(), Box<dyn Error>> {// A compositor keyframe value is substituted by the document's style engine, which the document host reaches.declare_document_host_of_layout_header(&mut style_value_config);+ // The effects whose descriptions and samples cross here are named by their identities.+ declare_animation_effect_id_of_animations_header(&mut style_value_config);generate_ffi_header(style_value_config,&[@@ -2782,7 +2817,6 @@ fn main() -> Result<(), Box<dyn Error>> {style_engine_config.namespaces = Some(vec!["Web".to_string(), "CSS".to_string(), "StyleEngineFFI".to_string()]);style_engine_config.export.include = vec![// Taken only by an entry of the boundary table, which cbindgen does not see.- "FfiAppliedAnimationDefinition".to_string(),"FfiFrameSetDimension".to_string(),"FfiFrameSetBorder".to_string(),// Named by no exported signature: a replaced content input crosses as its raw values.@@ -2797,11 +2831,20 @@ fn main() -> Result<(), Box<dyn Error>> {"FfiResolvedFont".to_string(),"FontResolutionFeatureInput".to_string(),];- // A published keyframe's composite operation is the one the animation sampler composes with.+ // A published effect's composite operation is the one the animation sampler composes with.style_engine_config.export.rename.insert("FfiCompositeOperation".to_string(),"Web::CSS::StyleValueFFI::FfiCompositeOperation".to_string(),);+ // A published effect's default easing is described as the compositing header describes one.+ style_engine_config+ .export+ .exclude+ .push("FfiEasingDescriptor".to_string());+ style_engine_config.export.rename.insert(+ "FfiEasingDescriptor".to_string(),+ "Compositing::RustFFI::FfiEasingDescriptor".to_string(),+ );// A transition step's decision is asked of the engine in the style value header's terms.for name in ["FfiTransitionInput", "FfiTransitionAction", "FfiLaneTransition"] {style_engine_config@@ -2858,6 +2901,8 @@ fn main() -> Result<(), Box<dyn Error>> {"\nnamespace Web::CSS::Parser::ValueParserFFI { struct DeclarationBlock; struct NativeRule; struct NativeStyleSheet; }",);+ // The effects whose descriptions and samples cross here are named by their identities.+ declare_animation_effect_id_of_animations_header(&mut style_engine_config);generate_ffi_header(style_engine_config,&[@@ -2952,13 +2997,12 @@ 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);- // 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.+ // The custom property registry and stores and a sample's animated custom properties are opaque to C++, which holds+ // each by pointer.for name in ["CustomPropertyRegistry","CustomPropertyStore","AnimatedCustomPropertyResults",- "ShorthandExpansion",] {computed_values_config.export@@ -2994,15 +3038,15 @@ 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(),- );+ // The effects the host samples, and the animations of the element they belong to, are as the animations header+ // describes them.+ for name in ["FfiSampledEffect", "ElementAnimations"] {+ computed_values_config.export.exclude.push(name.to_string());+ computed_values_config+ .export+ .rename+ .insert(name.to_string(), format!("Web::Animations::RustFFI::{name}"));+ }computed_values_config.includes.push("LibWeb/Animations/RustFFI.h".to_string());@@ -3018,6 +3062,8 @@ fn main() -> Result<(), Box<dyn Error>> {let libgfx_font_source = manifest_dir.join("../../LibGfx/Rust/src/font.rs");println!("cargo:rerun-if-changed={}", libgfx_font_source.display());+ // The effects whose descriptions and samples cross here are named by their identities.+ declare_animation_effect_id_of_animations_header(&mut computed_values_config);generate_ffi_header(computed_values_config,&[@@ -3124,11 +3170,80 @@ fn main() -> Result<(), Box<dyn Error>> {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.+ // A keyframe set notes the attributes its values read through the document's host, and a scroll timeline measures+ // the boxes it follows there.+ declare_document_host_of_layout_header(&mut animations_config);+ animations_config.export.exclude.push("NodeSlotId".to_string());+ animations_config+ .export+ .rename+ .insert("NodeSlotId".to_string(), "Compositing::RustFFI::NodeSlotId".to_string());+ // The host defines what the reflection of the keyframes of CSS asks of the style of their target.+ for name in [+ "web_animation_compute_css_keyframe_values",+ "web_animation_effective_zoom_of_target",+ ] {+ animations_config.export.exclude.push(name.to_string());+ }+ // An effect's composite operation is the style value header's.+ animations_config+ .export+ .exclude+ .push("FfiCompositeOperation".to_string());+ animations_config.export.rename.insert(+ "FfiCompositeOperation".to_string(),+ "Web::CSS::StyleValueFFI::FfiCompositeOperation".to_string(),+ );+ animations_config+ .after_includes+ .get_or_insert_with(String::new)+ .push_str("\nnamespace Web::CSS::StyleValueFFI { enum class FfiCompositeOperation : uint8_t; }");+ // The definition a style computation applies to a CSS animation is the computed values header's.+ animations_config+ .export+ .exclude+ .push("FfiComputedAnimation".to_string());+ animations_config.export.rename.insert(+ "FfiComputedAnimation".to_string(),+ "Web::CSS::ComputedValuesFFI::FfiComputedAnimation".to_string(),+ );+ animations_config+ .after_includes+ .get_or_insert_with(String::new)+ .push_str("\nnamespace Web::CSS::ComputedValuesFFI { struct FfiComputedAnimation; }");+ // A transition the hover of a clock lane leaves running, and one a style change event reads, are the style value+ // header's.+ for name in ["FfiLaneTransition", "FfiExistingTransition"] {+ animations_config.export.exclude.push(name.to_string());+ animations_config+ .export+ .rename+ .insert(name.to_string(), format!("Web::CSS::StyleValueFFI::{name}"));+ animations_config+ .after_includes+ .get_or_insert_with(String::new)+ .push_str(&format!("\nnamespace Web::CSS::StyleValueFFI {{ struct {name}; }}"));+ }+ // What an effect built for the compositor is opaque to C++, which hands it to the layout header's functions.+ animations_config+ .export+ .exclude+ .push("CompositorAnimationEffectState".to_string());+ animations_config+ .export+ .rename+ .insert("CompositorAnimationEffectState".to_string(), "void".to_string());+ // The host defines what the timeline records ask of documents, which the tests stub.+ animations_config+ .export+ .exclude+ .push("ladybird_animations_document_is_active".to_string());+ // The timing the host publishes of an effect it samples, an effect it samples, and a timeline it creates through+ // the bindings, which no function here takes.animations_config.export.include- .push("EffectTimingSnapshot".to_string());+ .extend(["EffectTimingSnapshot", "FfiSampledEffect", "FfiTimelineDescription"].map(String::from));let animation_timing_dir = manifest_dir.join("../../LibCompositing/Rust/src/animation_timing");println!("cargo:rerun-if-changed={}", animation_timing_dir.display());generate_ffi_header(@@ -3137,8 +3252,19 @@ fn main() -> Result<(), Box<dyn Error>> {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/animation.rs"),+ manifest_dir.join("src/animations/effect.rs"),+ manifest_dir.join("src/animations/document_animations.rs"),+ manifest_dir.join("src/animations/element_animations.rs"),manifest_dir.join("src/animations/ffi.rs"),+ manifest_dir.join("src/animations/host_effects.rs"),+ manifest_dir.join("src/animations/host_timing.rs"),+ manifest_dir.join("src/animations/css_events.rs"),+ manifest_dir.join("src/animations/keyframes.rs"),+ manifest_dir.join("src/animations/pending_animation_events.rs"),manifest_dir.join("src/animations/snapshot.rs"),+ manifest_dir.join("src/animations/timeline.rs"),+ manifest_dir.join("src/animations/transitions.rs"),],&out_dir,Path::new("Animations/RustFFI.h"),@@ -3209,6 +3335,12 @@ fn main() -> Result<(), Box<dyn Error>> {"Web::Animations::RustFFI::AnimationEffectTiming".to_string(),);layout_config.includes.push("LibWeb/Animations/RustFFI.h".to_string());+ // The render clock's plan takes the scroll timelines it follows as the animations header declares them.+ layout_config.export.exclude.push("TimelineCell".to_string());+ layout_config.export.rename.insert(+ "TimelineCell".to_string(),+ "Web::Animations::RustFFI::TimelineCell".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 [@@ -3219,6 +3351,8 @@ fn main() -> Result<(), Box<dyn Error>> {layout_config.export.rename.insert(name.to_string(), "void".to_string());layout_config.export.exclude.push(name.to_string());}+ // The effects whose descriptions and samples cross here are named by their identities.+ declare_animation_effect_id_of_animations_header(&mut layout_config);generate_ffi_header(layout_config,&[diff --git a/Libraries/LibWeb/Rust/src/animations/animation.rs b/Libraries/LibWeb/Rust/src/animations/animation.rsnew file mode 100644index 00000000000..4a37dd23dc5--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/animation.rs@@ -0,0 +1,808 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Animations.+//! https://www.w3.org/TR/web-animations-1/#animations++use super::easing::CompactEasing;+use super::effect::EffectHandle;+use super::timeline::TimelineHandle;+use super::timeline_state::TimelineState;+use super::timing::{AnimationPlayState, AnimationPlayback, TimeValue};+use super::weak_record_set::WeakRecordSet;+use crate::css::property_metadata::property_name;+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style::animations::AppliedAnimationDefinition;+use crate::css::style::effect_descriptions::{EffectAnimation, TransitionReversing};+use crate::css::style_value::{RetainedStyleValueData, optional_style_values_equal};+use std::borrow::Cow;+use std::cell::{Cell, Ref, RefCell, RefMut};+use std::ffi::c_void;+use std::num::NonZeroU64;+use std::ptr::NonNull;+use std::rc::{Rc, Weak};+use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};++/// The position of an animation in the global animation list, which orders animations by when they were created.+/// https://www.w3.org/TR/web-animations-1/#global-animation-list+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub struct GlobalAnimationListOrder(pub u64);++impl GlobalAnimationListOrder {+ fn mint() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ Self(NEXT.fetch_add(1, Ordering::Relaxed))+ }+}++/// The host's identity of a task it queued for an animation.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct HostTaskId(pub(crate) NonZeroU64);++/// The offset of one edge of an attachment range from the start of its named timeline range: a length plus a+/// percentage of the range, or a calculation only the size of the range resolves.+/// https://drafts.csswg.org/scroll-animations-1/#animation-range-start+#[derive(Clone)]+pub(crate) struct AttachmentRangeEdgeOffset {+ pub(crate) px: f64,+ pub(crate) percentage: f64,+ /// A calculation the offset resolves against the size of its range, or none, which `px` and `percentage` then+ /// describe as it resolves against 0px and 100px.+ pub(crate) calculated: RetainedStyleValueData,+}++impl AttachmentRangeEdgeOffset {+ fn equals(&self, other: &Self) -> bool {+ self.px == other.px+ && self.percentage == other.percentage+ && optional_style_values_equal(self.calculated.optional_data(), other.calculated.optional_data())+ }+}++/// The edge of an attachment range: the host's `TimelineRangeName` it is measured from, and its offset.+pub(crate) struct AttachmentRangeEdge {+ pub(crate) name: u8,+ pub(crate) offset: AttachmentRangeEdgeOffset,+}++/// The owning element of a CSS animation or transition: the host's `DOM::Element`, which the host's animation keeps+/// alive, and the host's `PseudoElement` where the owner is one of its pseudo-elements.+/// https://www.w3.org/TR/css-animations-2/#owning-element-section+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) struct OwningElement {+ pub(crate) element: NonNull<c_void>,+ pub(crate) pseudo_element: Option<u8>,+}++/// What the host's `CSSAnimation` notes of what script did to it and what it is doing, by bit.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CssAnimationFlag {+ /// Script changed the play state, which `animation-play-state` no longer changes.+ ScriptOverrodePlayState = 1 << 0,+ /// Script set the timeline, which `animation-timeline` no longer changes.+ ScriptSetTimeline = 1 << 1,+ /// Script set the start of the attachment range, which `animation-range-start` no longer changes.+ ScriptSetRangeStart = 1 << 2,+ /// Script set the end of the attachment range, which `animation-range-end` no longer changes.+ ScriptSetRangeEnd = 1 << 3,+}++/// The state of a CSS animation.+/// https://drafts.csswg.org/css-animations-2/#the-CSSAnimation-interface+pub(crate) struct CssAnimationState {+ /// https://drafts.csswg.org/css-animations-2/#dom-cssanimation-animationname+ pub(crate) name: RetainedUtf16FlyString,+ /// https://drafts.csswg.org/css-animations-1/#animation-timing-function+ /// The easing a keyframe that declares none of its own runs, from the `animation-timing-function` of the owning+ /// element.+ pub(crate) default_easing: CompactEasing,+ /// The definition the style computation last applied to the animation, which the style engine shares, or none where+ /// none has been applied yet.+ pub(crate) applied_definition: Option<Arc<AppliedAnimationDefinition>>,+ /// The name of the named timeline the animation follows, which it looks up from its owning element again as the+ /// timelines its document declares change, or none where its `animation-timeline` names none or it was removed+ /// from its owning element.+ /// https://drafts.csswg.org/scroll-animations-1/#timeline-scoping+ pub(crate) named_timeline: RetainedUtf16FlyString,+ /// The position of the animation in the computed value of `animation-name` of its owning element.+ pub(crate) name_index: u32,+ /// The host's `AnimationPlayState` that `animation-play-state` last computed for the animation, if any.+ pub(crate) last_css_play_state: Option<u8>,+ /// The `CssAnimationFlag`s set.+ pub(crate) flags: u8,+}++/// The host's `CSS::AnimationPlayState::Paused` and `CSS::AnimationPlayState::Running`.+pub(crate) const CSS_ANIMATION_PLAY_STATE_PAUSED: u8 = 0;+pub(crate) const CSS_ANIMATION_PLAY_STATE_RUNNING: u8 = 1;++/// The host's `CSSTransition::Phase::Idle`.+pub(crate) const CSS_TRANSITION_PHASE_IDLE: u8 = 3;++/// The state of a CSS transition.+/// https://drafts.csswg.org/css-transitions-2/#the-CSSTransition-interface+pub(crate) struct CssTransitionState {+ /// The name of the custom property the transition runs, or none where it runs the longhand `property_id` names.+ pub(crate) custom_property_name: RetainedUtf16FlyString,+ /// https://drafts.csswg.org/css-transitions-2/#transition-generation+ pub(crate) generation: u64,+ /// https://drafts.csswg.org/css-transitions/#transition-start-time+ pub(crate) start_time: f64,+ /// https://drafts.csswg.org/css-transitions/#transition-end-time+ pub(crate) end_time: f64,+ /// https://drafts.csswg.org/css-transitions/#transition-start-value+ pub(crate) start_value: RetainedStyleValueData,+ /// https://drafts.csswg.org/css-transitions/#transition-end-value+ pub(crate) end_value: RetainedStyleValueData,+ /// https://drafts.csswg.org/css-transitions/#transition-reversing-adjusted-start-value+ pub(crate) reversing_adjusted_start_value: RetainedStyleValueData,+ /// https://drafts.csswg.org/css-transitions/#transition-reversing-shortening-factor+ pub(crate) reversing_shortening_factor: f64,+ /// The host's `PropertyID` of the property the transition runs.+ pub(crate) property_id: u16,+ /// The host's `CSSTransition::Phase` the transition was in when the host last dispatched its events.+ pub(crate) previous_phase: u8,+ /// Whether the transition was started provisionally and is neither committed nor discarded yet.+ pub(crate) provisional: bool,+ /// Whether the transition is one the hover of a clock lane started, which the host took in.+ pub(crate) adopted_from_lane: bool,+ /// The effect the transition was started with, which it keeps whatever script sets as its associated effect. Its+ /// timing function shapes the transition's interval.+ pub(crate) effect_started_with: Option<EffectHandle>,+}++impl CssTransitionState {+ /// The expanded name of the property the transition runs.+ pub(crate) fn property_name(&self) -> Cow<'_, [u16]> {+ if self.custom_property_name.raw() != 0 {+ return self.custom_property_name.to_utf16();+ }+ Cow::Owned(property_name(self.property_id).encode_utf16().collect())+ }+}++/// What kind of animation an animation is, with the state of its kind.+pub(crate) enum AnimationKind {+ /// An animation script created.+ Script,+ CssAnimation(CssAnimationState),+ CssTransition(CssTransitionState),+ /// The animation of an SVG animation element, which has no `Animation` of the host.+ /// https://www.w3.org/TR/smil-animation/#AnimationSandwichModel+ Smil {+ /// The time the animation begins at, which orders it among the animations of its time container.+ begin_time: f64,+ /// The host's `SVGAnimationElement` whose animation it is, which whatever the GC traces of the host that holds+ /// the record keeps alive.+ animation_element: NonNull<c_void>,+ /// The `SmilHolders` that hold the animation.+ holders: u8,+ },+}++/// What a pointer to a GC cell of the host points at.+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum HostCellKind {+ /// A `GC::Cell`.+ Cell,+ /// A `DOM::Element`.+ Element,+}++/// What of the host holds the animation of an SVG animation element, by bit. The animation is alive to the host while+/// one does, as each lets go of it when it is done with it or the host finalizes it.+#[derive(Clone, Copy)]+#[repr(u8)]+pub(crate) enum SmilHolder {+ /// Its animation element, until it lets go of the animation or is finalized.+ AnimationElement = 1 << 0,+ /// The list of the animations of the target of its effect, until the animation leaves it or the target is+ /// finalized.+ TargetList = 1 << 1,+}++/// The timeline times of the start and the end of an attachment range.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct AttachmentInterval {+ pub(crate) start: TimeValue,+ pub(crate) end: TimeValue,+}++/// The state of an animation.+/// https://www.w3.org/TR/web-animations-1/#the-animation-interface+pub(crate) struct AnimationRecord {+ /// https://www.w3.org/TR/web-animations-1/#animation-associated-effect+ effect: Option<EffectHandle>,+ /// https://www.w3.org/TR/web-animations-1/#animation-timeline+ timeline: Option<TimelineHandle>,+ /// The start time, hold time, playback rate, pending playback rate, pending tasks, whether the animation was last+ /// found finished, and the replace state.+ playback: AnimationPlayback,+ /// https://www.w3.org/TR/web-animations-1/#previous-current-time+ previous_current_time: Option<TimeValue>,+ /// The current time of the associated effect where the animation was last cancelled, until the host takes it.+ saved_cancel_time: Option<TimeValue>,+ /// The attachment interval the effect's timing was last normalized against.+ normalized_attachment_interval: Option<AttachmentInterval>,+ /// The play state the animation was in when it was disassociated from its target as inert.+ play_state_when_disassociated_from_target: Option<AnimationPlayState>,+ /// https://drafts.csswg.org/web-animations-2/#auto-align-start-time+ auto_align_start_time: bool,+ /// Whether the animation is disassociated from its target once it is inert.+ disassociation_from_target_pending: bool,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-id+ /// None where it is the empty string.+ dom_id: RetainedUtf16FlyString,+ /// https://www.w3.org/TR/web-animations-1/#global-animation-list+ global_animation_list_order: GlobalAnimationListOrder,+ /// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range+ /// The offsets of the start and the end edge, and the host's `TimelineRangeName` of each.+ range_offsets: [AttachmentRangeEdgeOffset; 2],+ range_names: [u8; 2],+ /// https://www.w3.org/TR/css-animations-2/#owning-element-section+ owning_element: Option<NonNull<c_void>>,+ owning_pseudo_element: Option<u8>,+ /// The task the host last queued to run the finish notification steps of the animation, or to dispatch its finish+ /// event, if any.+ /// NB: Nothing forgets the task once it ran or was cancelled, which keeps a later finish notification task from+ /// being queued, as the host's `Animation` did before the record kept it.+ finish_notification_task: Option<HostTaskId>,+ kind: AnimationKind,+}++impl AnimationRecord {+ fn new(kind: AnimationKind) -> Self {+ Self {+ effect: None,+ timeline: None,+ playback: AnimationPlayback::default(),+ previous_current_time: None,+ saved_cancel_time: None,+ normalized_attachment_interval: None,+ play_state_when_disassociated_from_target: None,+ auto_align_start_time: false,+ disassociation_from_target_pending: false,+ dom_id: RetainedUtf16FlyString::none(),+ global_animation_list_order: GlobalAnimationListOrder::mint(),+ // NB: The initial edges, normal, are the start and the end of the entire timeline.+ range_offsets: [+ AttachmentRangeEdgeOffset {+ px: 0.0,+ percentage: 0.0,+ calculated: RetainedStyleValueData::none(),+ },+ AttachmentRangeEdgeOffset {+ px: 0.0,+ percentage: 100.0,+ calculated: RetainedStyleValueData::none(),+ },+ ],+ range_names: [0, 0],+ owning_element: None,+ owning_pseudo_element: None,+ finish_notification_task: None,+ kind,+ }+ }++ #[must_use]+ pub(crate) fn effect(&self) -> Option<&EffectHandle> {+ self.effect.as_ref()+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-timeline+ #[must_use]+ pub(crate) fn timeline(&self) -> Option<&TimelineHandle> {+ self.timeline.as_ref()+ }++ /// Sets the timeline, handing back the old one.+ pub(crate) fn replace_timeline(&mut self, timeline: Option<TimelineHandle>) -> Option<TimelineHandle> {+ std::mem::replace(&mut self.timeline, timeline)+ }++ /// The timeline, if any, as the animation, attached to its attachment range on it, reads it now.+ #[must_use]+ pub(crate) fn timeline_state(&self) -> Option<TimelineState> {+ self.timeline.as_ref().map(|timeline| timeline.state_for(&self.range()))+ }++ /// Sets the associated effect, describing the old one as associated with no animation and the new one as+ /// associated with this one.+ pub(crate) fn set_effect(&mut self, effect: Option<EffectHandle>) {+ if let Some(old_effect) = &self.effect {+ old_effect+ .borrow_mut()+ .set_described_animation(EffectAnimation::Unassociated);+ }+ if let Some(effect) = &effect {+ effect.borrow_mut().set_described_animation(self.described_animation());+ }+ self.effect = effect;+ }++ /// What the animation is, as far as describing its effect for the style engine goes.+ fn described_animation(&self) -> EffectAnimation {+ match &self.kind {+ AnimationKind::CssAnimation(state) => EffectAnimation::Animation(state.default_easing.clone()),+ AnimationKind::CssTransition(state) => EffectAnimation::Transition(TransitionReversing {+ adjusted_start_value: state.reversing_adjusted_start_value.clone(),+ shortening_factor: state.reversing_shortening_factor,+ }),+ AnimationKind::Script | AnimationKind::Smil { .. } => EffectAnimation::Animation(CompactEasing::Linear),+ }+ }++ /// Sets the easing a keyframe of a CSS animation's effect that declares none runs.+ pub(crate) fn set_css_animation_default_easing(&mut self, easing: CompactEasing) {+ let state = self.css_animation_mut();+ if state.default_easing == easing {+ return;+ }+ state.default_easing = easing;+ if let Some(effect) = &self.effect {+ effect.borrow_mut().set_described_animation(self.described_animation());+ }+ }++ #[must_use]+ pub(crate) fn playback(&self) -> &AnimationPlayback {+ &self.playback+ }++ pub(crate) fn playback_mut(&mut self) -> &mut AnimationPlayback {+ &mut self.playback+ }++ #[must_use]+ pub(crate) fn previous_current_time(&self) -> Option<TimeValue> {+ self.previous_current_time+ }++ pub(crate) fn set_previous_current_time(&mut self, time: Option<TimeValue>) {+ self.previous_current_time = time;+ }++ pub(crate) fn set_saved_cancel_time(&mut self, time: Option<TimeValue>) {+ self.saved_cancel_time = time;+ }++ pub(crate) fn take_saved_cancel_time(&mut self) -> Option<TimeValue> {+ self.saved_cancel_time.take()+ }++ #[must_use]+ pub(crate) fn normalized_attachment_interval(&self) -> Option<AttachmentInterval> {+ self.normalized_attachment_interval+ }++ pub(crate) fn set_normalized_attachment_interval(&mut self, interval: Option<AttachmentInterval>) {+ self.normalized_attachment_interval = interval;+ }++ pub(crate) fn set_play_state_when_disassociated_from_target(&mut self, play_state: Option<AnimationPlayState>) {+ self.play_state_when_disassociated_from_target = play_state;+ }++ #[must_use]+ pub(crate) fn play_state_when_disassociated_from_target(&self) -> Option<AnimationPlayState> {+ self.play_state_when_disassociated_from_target+ }++ /// Notes that the animation was associated with the target of its associated effect again. Joining a target does+ /// not make an animation that was disassociated from it as inert relevant, so whether it is inert is checked again.+ pub(crate) fn did_associate_with_target(&mut self) {+ if self.play_state_when_disassociated_from_target.take().is_some() {+ self.disassociation_from_target_pending = true;+ }+ }++ #[must_use]+ pub(crate) fn auto_align_start_time(&self) -> bool {+ self.auto_align_start_time+ }++ pub(crate) fn set_auto_align_start_time(&mut self, value: bool) {+ self.auto_align_start_time = value;+ }++ #[must_use]+ pub(crate) fn disassociation_from_target_pending(&self) -> bool {+ self.disassociation_from_target_pending+ }++ pub(crate) fn set_disassociation_from_target_pending(&mut self, value: bool) {+ self.disassociation_from_target_pending = value;+ }++ #[must_use]+ pub(crate) fn dom_id(&self) -> &RetainedUtf16FlyString {+ &self.dom_id+ }++ pub(crate) fn set_dom_id(&mut self, id: RetainedUtf16FlyString) {+ self.dom_id = id;+ }++ #[must_use]+ pub(crate) fn global_animation_list_order(&self) -> GlobalAnimationListOrder {+ self.global_animation_list_order+ }++ /// The start and the end edge of the attachment range.+ #[must_use]+ pub(crate) fn range(&self) -> [AttachmentRangeEdge; 2] {+ [0, 1].map(|index| AttachmentRangeEdge {+ name: self.range_names[index],+ offset: self.range_offsets[index].clone(),+ })+ }++ /// Sets the attachment range to the start and the end edge `range`, answering whether that changed it.+ pub(crate) fn set_range(&mut self, range: [AttachmentRangeEdge; 2]) -> bool {+ let changed = range.iter().enumerate().any(|(index, edge)| {+ edge.name != self.range_names[index] || !edge.offset.equals(&self.range_offsets[index])+ });+ if changed {+ for (index, edge) in range.into_iter().enumerate() {+ self.range_names[index] = edge.name;+ self.range_offsets[index] = edge.offset;+ }+ }+ changed+ }++ #[must_use]+ pub(crate) fn owning_element(&self) -> Option<OwningElement> {+ self.owning_element.map(|element| OwningElement {+ element,+ pseudo_element: self.owning_pseudo_element,+ })+ }++ pub(crate) fn set_owning_element(&mut self, owning_element: Option<OwningElement>) {+ self.owning_element = owning_element.map(|owner| owner.element);+ self.owning_pseudo_element = owning_element.and_then(|owner| owner.pseudo_element);+ }++ #[must_use]+ pub(crate) fn finish_notification_task(&self) -> Option<HostTaskId> {+ self.finish_notification_task+ }++ pub(crate) fn set_finish_notification_task(&mut self, task: HostTaskId) {+ self.finish_notification_task = Some(task);+ }++ #[must_use]+ pub(crate) fn kind(&self) -> &AnimationKind {+ &self.kind+ }++ /// The state of the CSS animation the record is of.+ #[must_use]+ pub(crate) fn css_animation(&self) -> &CssAnimationState {+ match &self.kind {+ AnimationKind::CssAnimation(state) => state,+ _ => unreachable!("the animation is a CSS animation"),+ }+ }++ pub(crate) fn css_animation_mut(&mut self) -> &mut CssAnimationState {+ match &mut self.kind {+ AnimationKind::CssAnimation(state) => state,+ _ => unreachable!("the animation is a CSS animation"),+ }+ }++ /// The state of the CSS transition the record is of.+ #[must_use]+ pub(crate) fn css_transition(&self) -> &CssTransitionState {+ match &self.kind {+ AnimationKind::CssTransition(state) => state,+ _ => unreachable!("the animation is a CSS transition"),+ }+ }++ /// The time of the style change event that started the CSS transition the record is of.+ /// https://drafts.csswg.org/css-transitions/#style-change-event+ #[must_use]+ pub(crate) fn css_transition_style_change_event_time(&self) -> f64 {+ let start_delay = self+ .effect+ .as_ref()+ .map_or(0.0, |effect| effect.borrow().timing().start_delay.value);+ self.css_transition().start_time - start_delay+ }++ pub(crate) fn css_transition_mut(&mut self) -> &mut CssTransitionState {+ match &mut self.kind {+ AnimationKind::CssTransition(state) => state,+ _ => unreachable!("the animation is a CSS transition"),+ }+ }++ /// The bytes the record holds beyond itself.+ fn heap_size(&self) -> usize {+ match &self.kind {+ AnimationKind::CssAnimation(state) => {+ state.default_easing.heap_size()+ + state.applied_definition.as_ref().map_or(0, |definition| {+ crate::heap_size::ARC_HEADER_BYTES + size_of_val::<AppliedAnimationDefinition>(definition)+ })+ }+ AnimationKind::Script | AnimationKind::CssTransition(_) | AnimationKind::Smil { .. } => 0,+ }+ }+}++/// An animation's record, which every handle to the animation shares, and the host's `Animation` of it.+pub struct AnimationCell {+ record: RefCell<AnimationRecord>,+ /// The GC cell of the object script sees of the animation, which holds a reference to the record until it is+ /// finalized and clears this as it does.+ facade: Cell<Option<NonNull<c_void>>>,+}++impl AnimationCell {+ pub(crate) fn borrow(&self) -> Ref<'_, AnimationRecord> {+ self.record.borrow()+ }++ pub(crate) fn borrow_mut(&self) -> RefMut<'_, AnimationRecord> {+ self.record.borrow_mut()+ }++ /// The host's `Animation` of the animation, while it is alive.+ pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {+ self.facade.get()+ }++ /// Whether the host may reach the animation and the elements its record names. One with an object script sees is+ /// alive until the host finalizes that object. Something that holds the record of a dead animation lets go of it+ /// only as the host sweeps it.+ /// NB: A CSS animation or transition gets an object only once script asks for one. Until then it is alive while it+ /// has its owning element, which whatever holds the record keeps alive. The animation of an SVG animation+ /// element never has an object. It is alive while a holder its record notes holds it, each of which keeps the+ /// elements the record names alive while it does.+ pub(crate) fn is_alive(&self) -> bool {+ if self.facade().is_some() {+ return true;+ }+ let record = self.borrow();+ match record.kind() {+ AnimationKind::Smil { holders, .. } => *holders != 0,+ AnimationKind::CssAnimation(_) | AnimationKind::CssTransition(_) => record.owning_element.is_some(),+ AnimationKind::Script => false,+ }+ }++ /// Notes whether `holder` holds the animation, where it is the animation of an SVG animation element.+ pub(crate) fn note_smil_holder(&self, holder: SmilHolder, holds: bool) {+ if let AnimationKind::Smil { holders, .. } = &mut self.borrow_mut().kind {+ if holds {+ *holders |= holder as u8;+ } else {+ *holders &= !(holder as u8);+ }+ }+ }++ /// Calls `visit` with each GC cell of the host that keeps alive the elements the record names: the animation's+ /// object, or, for an animation without one, the cells the record names.+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ if let Some(facade) = self.facade() {+ visit(facade, HostCellKind::Cell);+ return;+ }+ let record = self.borrow();+ if let AnimationKind::Smil { animation_element, .. } = record.kind() {+ visit(*animation_element, HostCellKind::Element);+ if let Some(target) = record.effect().and_then(|effect| effect.borrow().target_element()) {+ visit(target, HostCellKind::Element);+ }+ return;+ }+ drop(record);+ self.for_each_named_cell(visit);+ }++ /// Calls `visit` with each GC cell of the host the record names, which the animation's object keeps alive: its+ /// owning element, the object of its associated effect, or the target of an effect without one, and the object of+ /// its timeline.+ pub(crate) fn for_each_named_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ let record = self.borrow();+ if let Some(owner) = record.owning_element {+ visit(owner, HostCellKind::Element);+ }+ if let Some(effect) = record.effect() {+ match effect.facade() {+ Some(facade) => visit(facade, HostCellKind::Cell),+ None => {+ if let Some(target) = effect.borrow().target_element() {+ visit(target, HostCellKind::Element);+ }+ }+ }+ }+ if let Some(timeline) = record.timeline().and_then(|timeline| timeline.facade()) {+ visit(timeline, HostCellKind::Cell);+ }+ }++ pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.facade.set(facade);+ }++ /// The bytes of the allocation every handle shares, and those the record holds beyond it.+ pub(crate) fn memory_size(&self) -> usize {+ 2 * size_of::<usize>() + size_of::<Self>() + self.borrow().heap_size()+ }+}++/// A strong reference to an animation, as what libweb_bindings_rust holds of one.+#[derive(Clone)]+pub struct AnimationRecordRef(AnimationHandle);++impl AnimationRecordRef {+ pub(crate) fn from_handle(animation: AnimationHandle) -> Self {+ Self(animation)+ }++ /// Takes a reference of its own to an animation the host holds a reference to.+ ///+ /// # Safety+ /// `animation` must be an animation the host holds a reference to.+ pub unsafe fn retained_from_host(animation: *const c_void) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { AnimationHandle::retained_from_host(animation.cast()) })+ }++ /// The animation, as the host names it.+ #[must_use]+ pub fn as_host_ptr(&self) -> *const c_void {+ Rc::as_ptr(&self.0.0).cast()+ }++ pub(crate) fn cell(&self) -> &AnimationCell {+ &self.0.0+ }+}++/// A strong reference to an animation.+#[derive(Clone)]+pub(crate) struct AnimationHandle(Rc<AnimationCell>);++impl AnimationHandle {+ /// A new idle animation of `kind` with no associated effect.+ pub(crate) fn new(kind: AnimationKind) -> Self {+ Self(Rc::new(AnimationCell {+ record: RefCell::new(AnimationRecord::new(kind)),+ facade: Cell::new(None),+ }))+ }++ /// Whether both handles are to the same animation.+ pub(crate) fn ptr_eq(&self, other: &Self) -> bool {+ Rc::ptr_eq(&self.0, &other.0)+ }++ /// A reference to the animation that does not keep it alive.+ pub(crate) fn downgrade(&self) -> WeakAnimationHandle {+ WeakAnimationHandle(Rc::downgrade(&self.0))+ }++ /// Whether the handle is to `animation`.+ pub(crate) fn is(&self, animation: &AnimationCell) -> bool {+ std::ptr::eq(Rc::as_ptr(&self.0), animation)+ }++ /// Takes a reference of its own to an animation the host holds a reference to.+ ///+ /// # Safety+ /// `cell` must be an animation the host holds a reference to.+ pub(crate) unsafe fn retained_from_host(cell: *const AnimationCell) -> Self {+ // SAFETY: Guaranteed by the caller.+ unsafe {+ Rc::increment_strong_count(cell);+ Self(Rc::from_raw(cell))+ }+ }++ /// Hands the reference to the host, which gives it back to `from_raw`.+ pub(crate) fn into_raw(self) -> *const AnimationCell {+ Rc::into_raw(self.0)+ }++ /// Takes back a reference the host was handed.+ ///+ /// # Safety+ /// `cell` must be a reference `into_raw` handed out, which the host gives up.+ pub(crate) unsafe fn from_raw(cell: *const AnimationCell) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { Rc::from_raw(cell) })+ }+}++impl std::fmt::Debug for AnimationHandle {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_tuple("AnimationHandle")+ .field(&self.borrow().global_animation_list_order())+ .finish()+ }+}++/// A reference to an animation that does not keep it alive, or to none.+#[derive(Clone, Default)]+pub(crate) struct WeakAnimationHandle(Weak<AnimationCell>);++impl WeakAnimationHandle {+ /// The animation, while it is alive.+ pub(crate) fn upgrade(&self) -> Option<AnimationHandle> {+ self.0.upgrade().map(AnimationHandle)+ }+}++/// A set of animations that keeps none of them alive.+///+/// NB: An animation that is no longer alive to the host is dead to the set, though what else holds its record may only+/// let go of it as the host sweeps what holds it, so that the host never meets an animation it finalized.+pub struct WeakAnimationSet(WeakRecordSet<AnimationCell>);++impl Default for WeakAnimationSet {+ fn default() -> Self {+ Self(WeakRecordSet::new(AnimationCell::is_alive))+ }+}++impl WeakAnimationSet {+ /// Adds `animation` to the set, answering whether the set did not hold it yet.+ pub(crate) fn insert(&mut self, animation: &AnimationHandle) -> bool {+ self.0.insert(&animation.0)+ }++ /// Removes `animation` from the set, answering whether the set held it.+ pub(crate) fn remove(&mut self, animation: &AnimationCell) -> bool {+ self.0.remove(animation)+ }++ /// Whether the set holds `animation`.+ pub(crate) fn contains(&self, animation: &AnimationCell) -> bool {+ self.0.contains(animation)+ }++ /// Drops the entries of animations that died.+ pub(crate) fn prune(&mut self) {+ self.0.prune();+ }++ /// The number of entries, live or dead, which enumeration runs over.+ pub(crate) fn entry_count(&self) -> usize {+ self.0.entry_count()+ }++ /// The animation of the entry at `index`, where it is alive.+ pub(crate) fn get(&self, index: usize) -> Option<AnimationHandle> {+ self.0.get(index).map(AnimationHandle)+ }++ /// Removes every animation.+ pub(crate) fn clear(&mut self) {+ self.0.clear();+ }+}++impl std::ops::Deref for AnimationHandle {+ type Target = AnimationCell;++ fn deref(&self) -> &AnimationCell {+ &self.0+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/bindings_api.rs b/Libraries/LibWeb/Rust/src/animations/bindings_api.rsnew file mode 100644index 00000000000..1320d87f468--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/bindings_api.rs@@ -0,0 +1,1314 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What libweb_bindings_rust, which implements the interfaces of Web Animations, uses of the records of animation+//! effects and of the parsing their attributes do.++use std::ffi::c_void;+use std::ptr::NonNull;+use std::sync::Arc;++use super::animation::{AnimationCell, AnimationHandle, AnimationKind, AnimationRecordRef};+use super::composite_order::composite_order;+use super::easing::CompactEasing;+use super::effect::{AnimationEffectCell, EffectHandle};+use super::ffi::{FfiResolvedEffectTiming, FfiTreeOrder, animations_effect_resolve_timing, host_tree_order};+use super::ffi::{FfiScrollTimelineSource, FfiTimelineDescription, create_timeline};+use super::ffi::{invalidate, run_procedure_on};+use super::keyframes::{KEY_SCALE_FACTOR, KeyframeProperty, KeyframeSet, ProcessedKeyframe};+use super::procedures::AnimationError;+use super::timeline::{TimelineHandle, TimelineKind, ViewTimelineInset, ViewTimelineInsetEdge};+use super::timing::{AnimationEffectTiming, FillMode, SpecifiedEffectTiming, TimeValue};+use crate::css::animation::FfiCompositeOperation;+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style::effect_descriptions::easing_from_computed_timing_function;+use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};+use crate::css::typed_om::parse_value_for_property;+use libcompositing_rust::easing::{Easing, FfiEasingKind};++pub use super::ffi::{FfiHostEffect as HostEffect, HostEffectPerformer};+pub use super::keyframes::CompositeOperationOrAuto;+pub use crate::css::animation::FfiCompositeOperation as CompositeOperation;+pub use libcompositing_rust::animation_timing::{AnimationPlayState, AnimationReplaceState};++/// The resolved timing of an effect, as https://www.w3.org/TR/web-animations-1/#calculating-the-active-time and the+/// sections around it define it.+pub type ResolvedEffectTiming = FfiResolvedEffectTiming;++/// An easing function parsed from script, with the serialization the effect reports it as.+#[derive(Clone)]+pub struct ParsedEasing {+ easing: Easing,+ serialization: ak::Utf16String,+}++impl ParsedEasing {+ #[must_use]+ pub fn serialization(&self) -> &ak::Utf16String {+ &self.serialization+ }++ /// The `linear` keyword.+ pub(crate) fn linear() -> Self {+ Self {+ easing: Easing::default(),+ serialization: ak::Utf16String::from_ascii(b"linear"),+ }+ }++ /// The `ease` keyword.+ pub(crate) fn ease() -> Self {+ Self {+ easing: super::easing::keyword_cubic_bezier(0),+ serialization: ak::Utf16String::from_ascii(b"ease"),+ }+ }++ /// The easing the computed value of a timing function `value` describes, serialized as a script reads it, or none+ /// where it describes none.+ pub(crate) fn of_timing_function(value: &RetainedStyleValueData) -> Option<Self> {+ let easing = crate::css::style::effect_descriptions::easing_from_computed_timing_function(value.data())?;+ let mode = if matches!(value.data(), StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {+ SERIALIZATION_MODE_NORMAL+ } else {+ SERIALIZATION_MODE_RESOLVED_VALUE+ };+ Some(Self {+ easing,+ serialization: value.serialize(mode),+ })+ }+}++// NB: The numeric values of the C++ enum SerializationMode.+const SERIALIZATION_MODE_NORMAL: u8 = 0;+const SERIALIZATION_MODE_RESOLVED_VALUE: u8 = 1;++/// The easing function the text parses as, as the easing member of EffectTiming is parsed using the+/// <easing-function> production [CSS-EASING-1].+pub fn parse_easing_function(text: &ak::Utf16String) -> Option<ParsedEasing> {+ use crate::css::property_metadata::property_id;+ let value = parse_value_for_property(property_id::ANIMATION_TIMING_FUNCTION, text)?;+ if value.is_unresolved() || value.is_css_wide_keyword() {+ return None;+ }+ let items = value.value_list_items()?;+ let [item] = items.as_slice() else {+ return None;+ };+ // FIXME: We should absolutize the style value to resolve relative lengths within calcs+ let easing = easing_from_computed_timing_function(item.data())?;+ let mode = if matches!(item.data(), StyleValueData::Easing(_)) && easing.kind() == FfiEasingKind::CubicBezier {+ SERIALIZATION_MODE_NORMAL+ } else {+ SERIALIZATION_MODE_RESOLVED_VALUE+ };+ Some(ParsedEasing {+ easing,+ serialization: item.serialize(mode),+ })+}++/// A pseudo-element selector parsed from script: the host's `CSS::PseudoElement`, and its serialization.+#[derive(Clone)]+pub struct ParsedPseudoElement {+ kind: u8,+ serialization: ak::Utf16String,+}++/// The pseudo-element the text parses as, as a <pseudo-element-selector>.+pub fn parse_pseudo_element_selector(text: &ak::Utf16String) -> Option<ParsedPseudoElement> {+ use crate::css::selector::PseudoElementType;+ let units = text.to_utf16();+ let (selector, pseudo_element) =+ crate::css::selector_parser::parse_pseudo_element_selector_from_utf16(&units).ok()?;+ // NB: The host's enum has KnownPseudoElementCount between the known pseudo-elements and UnknownWebKit.+ let kind = if pseudo_element == PseudoElementType::UnknownWebKit {+ pseudo_element as u8 + 1+ } else {+ pseudo_element as u8+ };+ Some(ParsedPseudoElement {+ kind,+ serialization: crate::css::selector_serialization::serialize_selector_ref(&selector),+ })+}++/// The id of the property the IDL attribute name names, ignoring ASCII case, as the C++ property_id_from_camel_case_string()+/// finds it, with legacy aliases mapping to the property they alias.+pub fn property_id_from_camel_case(name: &ak::Utf16String) -> Option<u16> {+ use crate::css::property_metadata::PROPERTY_CAMEL_CASE_LOOKUP;+ let units = name.to_utf16();+ let lowercase: Vec<u16> = units+ .iter()+ .map(|&unit| crate::css::ffi_support::ascii_lowercase(unit))+ .collect();+ PROPERTY_CAMEL_CASE_LOOKUP+ .binary_search_by(|(candidate, _)| candidate.bytes().map(u16::from).cmp(lowercase.iter().copied()))+ .ok()+ .map(|index| PROPERTY_CAMEL_CASE_LOOKUP[index].1)+}++/// The IDL attribute name of the property, https://drafts.csswg.org/cssom/#css-property-to-idl-attribute+pub fn camel_case_property_name(property_id: u16) -> &'static str {+ crate::css::property_metadata::property_idl_name(property_id)+}++/// Whether the property, by its id, can be animated.+pub fn is_animatable_property(property_id: u16) -> bool {+ super::keyframes::is_animatable_property(property_id)+}++/// The id of the float property.+pub const PROPERTY_ID_FLOAT: u16 = crate::css::property_metadata::property_id::FLOAT;+/// The id of the offset property.+pub const PROPERTY_ID_OFFSET: u16 = crate::css::property_metadata::property_id::OFFSET;+/// The id custom properties share.+pub const PROPERTY_ID_CUSTOM: u16 = crate::css::property_metadata::property_id::CUSTOM;++/// A property a processed keyframe declares: a longhand or shorthand by its id, or a custom property by its name.+#[derive(Clone)]+pub enum KeyframePropertyName {+ Id(u16),+ Custom(ak::Utf16String),+}++/// A value of a property in a processed keyframe.+pub type StyleValue = RetainedStyleValueData;++/// The value the text parses as for the property, with no document to parse it for, or none where the value is+/// invalid according to the syntax for the property.+pub fn parse_property_value(property_id: u16, text: &ak::Utf16String) -> Option<StyleValue> {+ parse_value_for_property(property_id, text)+}++/// Another reference to a value of a property.+#[must_use]+pub fn clone_property_value(value: &StyleValue) -> StyleValue {+ value.clone_retained()+}++/// The serialization of a value of a property, as script reads it.+pub fn serialize_property_value(value: &StyleValue) -> ak::Utf16String {+ value.serialize(SERIALIZATION_MODE_NORMAL)+}++/// One keyframe a keyframe set is built from: its computed keyframe offset, its composite operation, its easing and+/// the properties it declares.+pub struct KeyframeSetInput<'a> {+ pub computed_offset: f64,+ pub composite: CompositeOperationOrAuto,+ pub easing: &'a ParsedEasing,+ pub properties: &'a [(KeyframePropertyName, StyleValue)],+}++/// A keyframe of CSS as script reads it: its offset, easing and composite operation, and the properties it declares.+pub struct CssKeyframeValues {+ pub offset: f64,+ pub easing: ParsedEasing,+ pub composite: CompositeOperationOrAuto,+ pub properties: Vec<(KeyframePropertyName, StyleValue)>,+}++impl From<super::keyframe_reflection::CssKeyframe> for CssKeyframeValues {+ fn from(keyframe: super::keyframe_reflection::CssKeyframe) -> Self {+ Self {+ offset: keyframe.offset,+ easing: keyframe.easing,+ composite: keyframe.composite,+ properties: keyframe+ .properties+ .into_iter()+ .map(|(property, value)| {+ let property = match property {+ KeyframeProperty::Id(property_id) => KeyframePropertyName::Id(property_id),+ KeyframeProperty::Custom(name) => {+ KeyframePropertyName::Custom(ak::Utf16String::from_utf16(&name.to_utf16()))+ }+ };+ (property, value)+ })+ .collect(),+ }+ }+}++/// The keyframe set the style engine runs of keyframes script gave a KeyframeEffect.+pub struct KeyframeSetRef(Arc<KeyframeSet>);++impl KeyframeSetRef {+ pub fn from_keyframes(keyframes: &[KeyframeSetInput<'_>]) -> Self {+ Self::from_keyframes_with_resource_context(keyframes, None)+ }++ /// The set of keyframes a copy of the effect `source` takes, whose URLs resolve against the style sheet the+ /// keyframes of `source` come from.+ pub fn from_keyframes_of_copy(keyframes: &[KeyframeSetInput<'_>], source: &EffectRecordRef) -> Self {+ Self::from_keyframes_with_resource_context(+ keyframes,+ super::keyframe_reflection::resource_context(&source.0.borrow()),+ )+ }++ fn from_keyframes_with_resource_context(+ keyframes: &[KeyframeSetInput<'_>],+ resource_context: Option<super::keyframes::ResourceContext>,+ ) -> Self {+ let keyframes = keyframes+ .iter()+ .map(|keyframe| ProcessedKeyframe {+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]+ key: (keyframe.computed_offset * 100.0 * KEY_SCALE_FACTOR) as u64,+ composite: keyframe.composite,+ easing: Some(keyframe.easing.easing.clone()),+ declarations: keyframe+ .properties+ .iter()+ .map(|(property, value)| {+ let property = match property {+ KeyframePropertyName::Id(property_id) => KeyframeProperty::Id(*property_id),+ KeyframePropertyName::Custom(name) => {+ KeyframeProperty::Custom(RetainedUtf16FlyString::from_utf16(&name.to_utf16()))+ }+ };+ (property, value.clone_retained())+ })+ .collect(),+ })+ .collect();+ Self(Arc::new(KeyframeSet::from_processed_keyframes(+ keyframes,+ resource_context,+ )))+ }++ /// Hands the reference to the host.+ #[must_use]+ pub fn into_host_ptr(self) -> *const c_void {+ Arc::into_raw(self.0).cast()+ }+}++/// A strong reference to an animation effect, as what libweb_bindings_rust holds of one.+#[derive(Clone)]+pub struct EffectRecordRef(EffectHandle);++impl Default for EffectRecordRef {+ fn default() -> Self {+ Self::new()+ }+}++impl EffectRecordRef {+ /// A new effect with the default timing, no keyframes and no target.+ #[must_use]+ pub fn new() -> Self {+ Self(EffectHandle::new())+ }++ /// Takes a reference of its own to an effect the host holds a reference to.+ ///+ /// # Safety+ /// `effect` must be an effect the host holds a reference to.+ pub unsafe fn retained_from_host(effect: *const c_void) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { EffectHandle::retained_from_host(effect.cast()) })+ }++ /// The effect, as the host names it.+ #[must_use]+ pub fn as_host_ptr(&self) -> *const c_void {+ std::ptr::from_ref::<AnimationEffectCell>(&self.0).cast()+ }++ /// Notes the cell of the object script sees of the effect, or that it has none, which the host's code reaches it+ /// through.+ pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.0.set_facade(facade);+ }++ #[must_use]+ pub fn specified_timing(&self) -> SpecifiedEffectTiming {+ *self.0.borrow().specified_timing()+ }++ pub fn set_specified_timing(&self, specified: SpecifiedEffectTiming) {+ self.0.borrow_mut().set_specified_timing(specified);+ }++ // https://drafts.csswg.org/web-animations-2/#normalize-specified-timing+ pub fn normalize_specified_timing(&self) {+ let animation = self.0.borrow().associated_animation();+ let timeline = animation.and_then(|animation| animation.borrow().timeline_state());+ self.0.borrow_mut().normalize_specified_timing(timeline.as_ref());+ }++ /// The normalized timing the timing model reads of the effect.+ #[must_use]+ pub fn timing(&self) -> AnimationEffectTiming {+ self.0.borrow().timing()+ }++ /// The serialization of the value the timing function was made from.+ #[must_use]+ pub fn timing_function_serialization(&self) -> ak::Utf16String {+ ak::Utf16String::from_utf16(&self.0.borrow().timing_function_serialization().to_utf16())+ }++ pub fn set_timing_function(&self, timing_function: &ParsedEasing) {+ self.0.borrow_mut().set_timing_function(+ CompactEasing::of(timing_function.easing.clone()),+ RetainedUtf16FlyString::from_utf16(&timing_function.serialization.to_utf16()),+ );+ }++ /// Sets the specified timing and the timing function of the effect to those of `source`.+ pub fn copy_specified_timing_and_timing_function_from(&self, source: &Self) {+ let (specified, timing_function, serialization) = {+ let source = source.0.borrow();+ (+ *source.specified_timing(),+ source.timing_function().clone(),+ source.timing_function_serialization().clone(),+ )+ };+ let mut effect = self.0.borrow_mut();+ effect.set_specified_timing(specified);+ effect.set_timing_function(timing_function, serialization);+ }++ /// The animation whose associated effect this effect is.+ #[must_use]+ pub fn associated_animation(&self) -> Option<AnimationRecordRef> {+ self.0+ .borrow()+ .associated_animation()+ .map(AnimationRecordRef::from_handle)+ }++ /// The timing of the effect at `local_time` with `fill_mode`, on the timeline of its associated animation, if any,+ /// with its transformed progress where `with_transformed_progress`.+ #[must_use]+ pub fn resolve_timing(+ &self,+ local_time: Option<TimeValue>,+ fill_mode: FillMode,+ with_transformed_progress: bool,+ ) -> ResolvedEffectTiming {+ let animation = self.0.borrow().associated_animation();+ animations_effect_resolve_timing(+ &self.0,+ local_time.into(),+ fill_mode,+ animation.as_deref().map(|animation: &AnimationCell| animation),+ with_transformed_progress,+ )+ }++ /// The host's `DOM::Element` the effect targets.+ #[must_use]+ pub fn target_element(&self) -> Option<NonNull<c_void>> {+ self.0.borrow().target_element()+ }++ /// The serialization of the target pseudo-selector of the effect, if it has one.+ #[must_use]+ pub fn pseudo_element_serialization(&self) -> Option<ak::Utf16String> {+ self.0+ .borrow()+ .pseudo_element()+ .map(|pseudo_element| ak::Utf16String::from_utf16(&pseudo_element.serialization.to_utf16()))+ }++ /// Sets the target pseudo-selector of the effect.+ pub fn set_pseudo_element(&self, pseudo_element: Option<&ParsedPseudoElement>) {+ match pseudo_element {+ Some(pseudo_element) => self.0.borrow_mut().set_pseudo_element(+ pseudo_element.kind,+ RetainedUtf16FlyString::from_utf16(&pseudo_element.serialization.to_utf16()),+ ),+ None => self+ .0+ .borrow_mut()+ .set_pseudo_element(0, RetainedUtf16FlyString::none()),+ }+ }++ /// Sets the target pseudo-selector of the effect to that of `source`.+ pub fn copy_pseudo_element_from(&self, source: &Self) {+ let (kind, serialization) = {+ let source = source.0.borrow();+ match source.pseudo_element() {+ Some(pseudo_element) => (pseudo_element.kind, pseudo_element.serialization.clone()),+ None => (0, RetainedUtf16FlyString::none()),+ }+ };+ self.0.borrow_mut().set_pseudo_element(kind, serialization);+ }++ #[must_use]+ pub fn composite(&self) -> FfiCompositeOperation {+ self.0.borrow().composite()+ }+}++/// https://www.w3.org/TR/web-animations-1/#animation-composite-order+/// Sorts the animations in composite order, with `tree_order` comparing elements in tree order.+pub fn sort_in_composite_order(animations: &mut [AnimationRecordRef], tree_order: FfiTreeOrder) {+ let mut tree_order = host_tree_order(tree_order);+ animations.sort_by(|a, b| {+ if std::ptr::eq(a.cell(), b.cell()) {+ return std::cmp::Ordering::Equal;+ }+ composite_order(&a.cell().borrow(), &b.cell().borrow(), &mut tree_order)+ });+}++/// What script makes a timeline of.+pub enum TimelineDescription {+ /// https://www.w3.org/TR/web-animations-1/#document-timelines+ Document { origin_time: f64 },+ /// https://drafts.csswg.org/scroll-animations-1/#scrolltimeline+ /// The host's `DOM::Element` that is its source, if any, and its axis, the host's `ScrollAxis`.+ Scroll { source: Option<NonNull<c_void>>, axis: u8 },+ /// https://drafts.csswg.org/scroll-animations-1/#viewtimeline+ /// The host's `DOM::Element` that is its subject, its axis and its inset.+ View {+ subject: NonNull<c_void>,+ axis: u8,+ inset: ViewTimelineInsetValue,+ },+ /// The timeline of the Internals interface, whose time tests set.+ Internal,+}++/// The interface a timeline is an object of.+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum TimelineInterfaceKind {+ Document,+ Scroll,+ View,+ Internal,+}++/// A strong reference to a timeline, as what libweb_bindings_rust holds of one.+#[derive(Clone)]+pub struct TimelineRecordRef(TimelineHandle);++/// The host's `CSS::Scroller::Nearest`, which a view timeline finds its source from its subject with.+const SCROLLER_NEAREST: u8 = 1;++impl TimelineRecordRef {+ /// A new timeline associated with the host's `DOM::Document` `document`.+ #[must_use]+ pub fn new(document: NonNull<c_void>, description: TimelineDescription) -> Self {+ let scroll = |source, axis| super::timeline::ScrollTimelineState {+ source,+ axis,+ last_max_scroll_offset: None,+ followed_scroller: None,+ view: None,+ };+ let kind = match description {+ TimelineDescription::Document { origin_time } => TimelineKind::Document { origin_time },+ TimelineDescription::Scroll { source, axis } => TimelineKind::Scroll(Box::new(scroll(+ super::timeline::ScrollTimelineSource::Element(source),+ axis,+ ))),+ TimelineDescription::View { subject, axis, inset } => {+ let mut state = scroll(+ super::timeline::ScrollTimelineSource::Anonymous {+ scroller: SCROLLER_NEAREST,+ target: subject,+ pseudo_element: None,+ },+ axis,+ );+ state.view = Some(super::timeline::ViewTimelineState {+ inset: inset.0,+ last_metrics: None,+ subject_style_node: None,+ });+ TimelineKind::Scroll(Box::new(state))+ }+ TimelineDescription::Internal => TimelineKind::Internal {+ time_for_observation: None,+ },+ };+ Self(TimelineHandle::new(document, kind))+ }++ /// A new timeline associated with the host's `DOM::Document` `document`, as the host describes it.+ ///+ /// # Safety+ /// The calculations of a view timeline's inset must be null or live style values.+ #[must_use]+ pub unsafe fn from_host_description(document: NonNull<c_void>, description: *const c_void) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { create_timeline(document, &*description.cast::<FfiTimelineDescription>()) })+ }++ /// The timeline, as the host names it.+ #[must_use]+ pub fn as_host_ptr(&self) -> *const c_void {+ std::ptr::from_ref::<super::timeline::TimelineCell>(&self.0).cast()+ }++ /// The cell of the object script sees of the timeline, while it is alive.+ #[must_use]+ pub fn facade(&self) -> Option<NonNull<c_void>> {+ self.0.facade()+ }++ /// Notes the cell of the object script sees of the timeline, or that it has none, which the host's code reaches it+ /// through.+ pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.0.set_facade(facade);+ }++ /// Calls `visit` with each GC cell of the host the record names.+ pub fn for_each_host_cell(&self, visit: impl FnMut(NonNull<c_void>)) {+ self.0.for_each_host_cell(visit);+ }++ /// The host's `DOM::Document` the timeline is associated with.+ #[must_use]+ pub fn document(&self) -> NonNull<c_void> {+ self.0.document()+ }++ /// Which interface the timeline is an object of.+ #[must_use]+ pub fn kind(&self) -> TimelineInterfaceKind {+ match &self.0.borrow().kind {+ TimelineKind::Document { .. } => TimelineInterfaceKind::Document,+ TimelineKind::Scroll(scroll) if scroll.view.is_some() => TimelineInterfaceKind::View,+ TimelineKind::Scroll(_) => TimelineInterfaceKind::Scroll,+ TimelineKind::Internal { .. } => TimelineInterfaceKind::Internal,+ }+ }++ /// https://drafts.csswg.org/web-animations-2/#timeline-duration+ #[must_use]+ pub fn duration(&self) -> Option<TimeValue> {+ self.0.borrow().duration()+ }++ /// The axis of a scroll timeline, the host's `ScrollAxis`.+ #[must_use]+ pub fn axis(&self) -> u8 {+ self.0.borrow().scroll().map_or(0, |scroll| scroll.axis)+ }++ /// The host's `DOM::Element` that is the subject of a view timeline.+ #[must_use]+ pub fn subject(&self) -> Option<NonNull<c_void>> {+ let record = self.0.borrow();+ let scroll = record.scroll()?;+ scroll.view.as_ref()?;+ let source: FfiScrollTimelineSource = scroll.source.into();+ NonNull::new(source.target)+ }++ /// The scroll offsets at the start and at the end of the cover range of a view timeline as its progress was last+ /// calculated, in CSS pixels: none while it was inactive.+ #[must_use]+ pub fn cover_range(&self) -> Option<(f64, f64)> {+ let record = self.0.borrow();+ let metrics = record.scroll()?.view.as_ref()?.last_metrics?;+ Some((metrics.cover_start(), metrics.cover_end()))+ }+}++/// One side of the view progress visibility range of a view timeline that script describes.+/// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset+#[derive(Clone)]+pub struct ViewTimelineInsetEdgeValue(ViewTimelineInsetEdge);++impl ViewTimelineInsetEdgeValue {+ /// The inset auto.+ #[must_use]+ pub fn auto() -> Self {+ Self(ViewTimelineInsetEdge {+ is_auto: true,+ px: 0.0,+ percentage: 0.0,+ calculated: RetainedStyleValueData::none(),+ })+ }+}++/// The start and the end inset of the view progress visibility range of a view timeline that script describes.+pub struct ViewTimelineInsetValue(ViewTimelineInset);++impl ViewTimelineInsetValue {+ #[must_use]+ pub fn from_edges(start: ViewTimelineInsetEdgeValue, end: ViewTimelineInsetEdgeValue) -> Self {+ Self(ViewTimelineInset {+ start: start.0,+ end: end.0,+ })+ }++ #[must_use]+ pub fn into_start(self) -> ViewTimelineInsetEdgeValue {+ ViewTimelineInsetEdgeValue(self.0.start)+ }++ /// The insets a computed `view-timeline-inset` value describes.+ #[must_use]+ pub fn from_computed_value(value: &StyleValue) -> Self {+ let inset = crate::css::style_compute::script_view_timeline_inset(value.data());+ // SAFETY: The calculations are null or style values that the value holds.+ let edge = |is_auto, px, percentage, calculated: *const c_void| ViewTimelineInsetEdge {+ is_auto,+ px,+ percentage,+ calculated: if calculated.is_null() {+ RetainedStyleValueData::none()+ } else {+ // SAFETY: The value holds the calculation.+ unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(calculated.cast())) }+ },+ };+ Self(ViewTimelineInset {+ start: edge(+ inset.start_is_auto,+ inset.start_px,+ inset.start_percentage,+ inset.start_calculated,+ ),+ end: edge(+ inset.end_is_auto,+ inset.end_px,+ inset.end_percentage,+ inset.end_calculated,+ ),+ })+ }+}++/// Whether a parsed `view-timeline-inset` value has a length in a unit that is not absolute.+#[must_use]+pub fn view_timeline_inset_has_relative_length(value: &StyleValue) -> bool {+ crate::css::style_compute::view_timeline_inset_has_relative_length(value.data())+}++/// The id of the `view-timeline-inset` property.+pub const PROPERTY_ID_VIEW_TIMELINE_INSET: u16 = crate::css::property_metadata::property_id::VIEW_TIMELINE_INSET;++/// Takes over one reference to a style value the host hands over.+///+/// # Safety+/// `value` must be a live style value whose reference the caller hands over.+#[must_use]+pub unsafe fn style_value_from_host(value: *const c_void) -> StyleValue {+ // SAFETY: Guaranteed by the caller.+ unsafe { RetainedStyleValueData::from_retained_pointer(value.cast()) }+}++/// The style value, as the host names it, which keeps its own reference.+#[must_use]+pub fn style_value_as_host_ptr(value: &StyleValue) -> *const c_void {+ value.pointer().cast()+}++/// An exception a procedure of an animation throws.+pub enum AnimationException {+ /// An "InvalidStateError" DOMException.+ InvalidState(&'static str),+ TypeError(&'static str),+}++impl From<AnimationError> for AnimationException {+ fn from(error: AnimationError) -> Self {+ match error {+ AnimationError::InvalidState(message) => Self::InvalidState(message),+ AnimationError::TypeError(message) => Self::TypeError(message),+ }+ }+}++/// A procedure that script runs on an animation through the Animation interface.+#[derive(Clone, Copy)]+pub enum AnimationProcedure {+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel+ Cancel,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-finish+ Finish,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-play+ Play,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-pause+ Pause,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-reverse+ Reverse,+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-updateplaybackrate+ UpdatePlaybackRate(f64),+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-playbackrate+ SetPlaybackRate(f64),+ /// https://www.w3.org/TR/web-animations-1/#dom-animation-persist+ Persist,+}++impl AnimationRecordRef {+ /// Runs `procedure` on the animation, and then has the host perform what it asked for through `perform`.+ pub fn run(&self, procedure: AnimationProcedure, perform: HostEffectPerformer) -> Result<(), AnimationException> {+ run_procedure_on(self.cell(), perform, |procedures| match procedure {+ AnimationProcedure::Cancel => {+ procedures.cancel(invalidate(true));+ Ok(())+ }+ AnimationProcedure::Finish => procedures.finish_an_animation(),+ AnimationProcedure::Play => procedures.play(invalidate(true)),+ AnimationProcedure::Pause => procedures.pause(),+ AnimationProcedure::Reverse => procedures.reverse(),+ AnimationProcedure::UpdatePlaybackRate(playback_rate) => procedures.update_playback_rate(playback_rate),+ AnimationProcedure::SetPlaybackRate(playback_rate) => procedures.set_playback_rate(playback_rate),+ AnimationProcedure::Persist => {+ // Sets this animation’s replace state to persisted.+ procedures.set_replace_state(AnimationReplaceState::Persisted);+ Ok(())+ }+ })+ .map_err(AnimationException::from)+ }++ /// Whether the animation is idle. A cancel of one that is not settles its promises and creates its cancel event.+ #[must_use]+ pub fn is_idle(&self) -> bool {+ self.cell().borrow().timing_state(None).play_state == AnimationPlayState::Idle+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-id+ #[must_use]+ pub fn dom_id(&self) -> ak::Utf16String {+ ak::Utf16String::from_utf16(&self.cell().borrow().dom_id().to_utf16())+ }++ pub fn set_dom_id(&self, id: &ak::Utf16String) {+ self.cell()+ .borrow_mut()+ .set_dom_id(RetainedUtf16FlyString::from_utf16(&id.to_utf16()));+ }++ /// https://www.w3.org/TR/web-animations-1/#playback-rate+ #[must_use]+ pub fn playback_rate(&self) -> f64 {+ self.cell().borrow().playback().playback_rate+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-replace-state+ #[must_use]+ pub fn replace_state(&self) -> AnimationReplaceState {+ self.cell().borrow().playback().replace_state+ }++ /// https://www.w3.org/TR/web-animations-1/#play-states+ /// At `current_time`, the current time of the animation.+ #[must_use]+ pub fn play_state_at(&self, current_time: Option<TimeValue>) -> AnimationPlayState {+ let record = self.cell().borrow();+ // The associated effect end of an animation is equal to the end time of the animation’s associated effect. If+ // the animation has no associated effect, the associated effect end is zero.+ let associated_effect_end = match record.effect() {+ Some(effect) => super::timing::end_time(&effect.borrow().timing()),+ None => {+ let progress_based = record+ .timeline()+ .is_some_and(|timeline| timeline.borrow().is_progress_based());+ TimeValue::zero(if progress_based {+ super::timing::TimeValueType::Percentage+ } else {+ super::timing::TimeValueType::Milliseconds+ })+ }+ };+ super::timing::play_state_at(record.playback(), current_time, associated_effect_end)+ }++ /// https://drafts.csswg.org/css-animations-2/#dom-cssanimation-animationname+ #[must_use]+ pub fn css_animation_name(&self) -> ak::Utf16String {+ ak::Utf16String::from_utf16(&self.cell().borrow().css_animation().name.to_utf16())+ }++ /// https://drafts.csswg.org/css-transitions-2/#dom-csstransition-transitionproperty+ #[must_use]+ pub fn css_transition_property(&self) -> ak::Utf16String {+ ak::Utf16String::from_utf16(&self.cell().borrow().css_transition().property_name())+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-pending+ #[must_use]+ pub fn pending(&self) -> bool {+ let record = self.cell().borrow();+ let playback = record.playback();+ playback.has_pending_play_task || playback.has_pending_pause_task+ }+}++/// What kind of animation an animation is, which picks the interface of the object script sees of it.+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum AnimationInterfaceKind {+ /// An animation script created, an Animation.+ Script,+ /// A CSSAnimation.+ CssAnimation,+ /// A CSSTransition.+ CssTransition,+ /// The animation of an SVG animation element, which script never sees.+ Smil,+}++/// The kind of a GC cell of the host an animation record names.+pub use super::animation::HostCellKind;++/// One edge of an attachment range: the host's `TimelineRangeName` it is measured from, a length plus a percentage of+/// the range, and a calculation only the size of the range resolves, if any.+/// https://drafts.csswg.org/scroll-animations-1/#animation-range-start+#[derive(Clone)]+pub struct AttachmentRangeEdgeValue {+ pub name: u8,+ pub px: f64,+ pub percentage: f64,+ pub calculated: Option<StyleValue>,+}++impl AttachmentRangeEdgeValue {+ /// The edge `normal`, which is the start of the entire timeline, or its end where `is_end`.+ #[must_use]+ pub fn normal(is_end: bool) -> Self {+ Self {+ name: 0,+ px: 0.0,+ percentage: if is_end { 100.0 } else { 0.0 },+ calculated: None,+ }+ }++ /// Whether the edge is `normal`, the start of the entire timeline, or its end where `is_end`.+ #[must_use]+ pub fn is_normal(&self, is_end: bool) -> bool {+ self.name == 0+ && self.px == 0.0+ && self.percentage == if is_end { 100.0 } else { 0.0 }+ && self.calculated.is_none()+ }+}++/// The edge of the computed value of `animation-range-start`, or of `animation-range-end` where `is_end`, that `value`+/// is, absolutized, if it is one.+#[must_use]+pub fn attachment_range_edge_from_computed_value(value: &StyleValue, is_end: bool) -> Option<AttachmentRangeEdgeValue> {+ let mut edge = crate::css::style_compute::FfiAnimationRangeEdge {+ name: 0,+ offset_px: 0.0,+ offset_percentage: 0.0,+ offset_calculated: std::ptr::null(),+ };+ if !crate::css::style_compute::rust_animation_range_edge(value.data(), is_end, &mut edge) {+ return None;+ }+ // SAFETY: The calculation is null or one `value` holds, which this takes a reference of its own to.+ let calculated = unsafe { retain_style_value(edge.offset_calculated.cast()) };+ Some(AttachmentRangeEdgeValue {+ name: edge.name,+ px: edge.offset_px,+ percentage: edge.offset_percentage,+ calculated: (!calculated.is_null())+ // SAFETY: The reference was just taken.+ .then(|| unsafe { RetainedStyleValueData::from_retained_pointer(calculated) }),+ })+}++impl AnimationRecordRef {+ /// A new idle animation script creates, with no associated effect and no timeline.+ #[must_use]+ pub fn new_script_animation() -> Self {+ Self::from_handle(AnimationHandle::new(AnimationKind::Script))+ }++ /// Whether both references are to the same animation.+ #[must_use]+ pub fn ptr_eq(&self, other: &Self) -> bool {+ std::ptr::eq(self.cell(), other.cell())+ }++ /// Which interface the object script sees of the animation is an object of.+ #[must_use]+ pub fn kind(&self) -> AnimationInterfaceKind {+ match self.cell().borrow().kind() {+ AnimationKind::Script => AnimationInterfaceKind::Script,+ AnimationKind::CssAnimation(_) => AnimationInterfaceKind::CssAnimation,+ AnimationKind::CssTransition(_) => AnimationInterfaceKind::CssTransition,+ AnimationKind::Smil { .. } => AnimationInterfaceKind::Smil,+ }+ }++ /// The cell of the object script sees of the animation, while it has one.+ #[must_use]+ pub fn facade(&self) -> Option<NonNull<c_void>> {+ self.cell().facade()+ }++ /// Notes the cell of the object script sees of the animation, or that it has none.+ pub fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.cell().set_facade(facade);+ }++ /// Calls `visit` with each GC cell of the host that keeps alive the elements the record names.+ pub fn for_each_host_cell(&self, visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ self.cell().for_each_host_cell(visit);+ }++ /// Calls `visit` with each GC cell of the host the record names, which the object of the animation keeps alive.+ pub fn for_each_named_cell(&self, visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ self.cell().for_each_named_cell(visit);+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-associated-effect+ #[must_use]+ pub fn effect(&self) -> Option<EffectRecordRef> {+ self.cell().borrow().effect().cloned().map(EffectRecordRef)+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-timeline+ #[must_use]+ pub fn timeline(&self) -> Option<TimelineRecordRef> {+ self.cell().borrow().timeline().cloned().map(TimelineRecordRef)+ }++ /// https://www.w3.org/TR/css-animations-2/#owning-element-section+ /// The host's `DOM::Element`, and its `PseudoElement` where the owner is one of its pseudo-elements.+ #[must_use]+ pub fn owning_element(&self) -> Option<(NonNull<c_void>, Option<u8>)> {+ self.cell()+ .borrow()+ .owning_element()+ .map(|owner| (owner.element, owner.pseudo_element))+ }++ /// The host's `SVGAnimationElement` of the animation of an SVG animation element.+ #[must_use]+ pub fn smil_animation_element(&self) -> Option<NonNull<c_void>> {+ match self.cell().borrow().kind() {+ AnimationKind::Smil { animation_element, .. } => Some(*animation_element),+ _ => None,+ }+ }++ /// The start time, hold time, playback rate, pending playback rate, pending tasks, whether the animation was last+ /// found finished, and the replace state.+ #[must_use]+ pub fn playback(&self) -> super::timing::AnimationPlayback {+ *self.cell().borrow().playback()+ }++ /// Whether the timeline of the animation is a progress-based timeline.+ #[must_use]+ pub fn has_progress_based_timeline(&self) -> bool {+ self.cell()+ .borrow()+ .timeline()+ .is_some_and(|timeline| timeline.borrow().is_progress_based())+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-current-time+ /// With its timeline at `timeline_time`, which is unresolved where the animation has no timeline.+ #[must_use]+ pub fn current_time_at(&self, timeline_time: Option<TimeValue>) -> Option<TimeValue> {+ let record = self.cell().borrow();+ let timeline_time = record.timeline().and(timeline_time);+ super::timing::current_time_at(record.playback(), timeline_time)+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-set-the-associated-effect-of-an-animation+ pub fn set_effect(&self, effect: Option<&EffectRecordRef>, perform: HostEffectPerformer) {+ let effect = effect.map(|effect| effect.0.clone());+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.set_the_associated_effect(effect.as_ref(), invalidate(true));+ Ok(())+ });+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation+ pub fn set_timeline(&self, timeline: Option<&TimelineRecordRef>, perform: HostEffectPerformer) {+ let timeline = timeline.map(|timeline| timeline.0.clone());+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.set_timeline(timeline);+ Ok(())+ });+ }++ /// https://www.w3.org/TR/web-animations-1/#set-the-start-time+ /// To the validated `start_time`.+ pub fn set_start_time(&self, start_time: Option<TimeValue>, perform: HostEffectPerformer) {+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.set_start_time_for_bindings(start_time);+ Ok(())+ });+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time+ /// To the validated `seek_time`.+ pub fn set_current_time(+ &self,+ seek_time: Option<TimeValue>,+ perform: HostEffectPerformer,+ ) -> Result<(), AnimationException> {+ run_procedure_on(self.cell(), perform, |procedures| {+ procedures.set_current_time_for_bindings(seek_time)+ })+ .map_err(AnimationException::from)+ }++ /// https://www.w3.org/TR/web-animations-1/#play-an-animation+ /// With the auto-rewind flag set to true.+ pub fn play_an_animation(&self, perform: HostEffectPerformer) -> Result<(), AnimationException> {+ run_procedure_on(self.cell(), perform, |procedures| {+ procedures.play_an_animation(super::procedures::AutoRewind::Yes, invalidate(true))+ })+ .map_err(AnimationException::from)+ }++ /// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state+ /// With the did seek flag false and the synchronously notify flag true, where `observed_current_time`, if resolved,+ /// is the unconstrained current time.+ pub fn update_finished_state(+ &self,+ should_invalidate: bool,+ observed_current_time: Option<TimeValue>,+ perform: HostEffectPerformer,+ ) {+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.update_finished_state(+ super::procedures::DidSeek::No,+ super::procedures::SynchronouslyNotify::Yes,+ invalidate(should_invalidate),+ observed_current_time,+ );+ Ok(())+ });+ }++ /// Runs the finish notification steps of the animation from the task the host queued.+ pub fn run_finish_notification_steps(&self, perform: HostEffectPerformer) {+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.finish_notification_steps();+ Ok(())+ });+ }++ /// Notes `task`, the host's identity of the task it queued to run the finish notification steps of the animation,+ /// or to dispatch its finish event.+ pub fn set_finish_notification_task(&self, task: u64) {+ let task = super::animation::HostTaskId(std::num::NonZeroU64::new(task).expect("tasks have nonzero ids"));+ self.cell().borrow_mut().set_finish_notification_task(task);+ }++ /// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range+ /// The start and the end edge.+ #[must_use]+ pub fn range(&self) -> [AttachmentRangeEdgeValue; 2] {+ self.cell().borrow().range().map(|edge| AttachmentRangeEdgeValue {+ name: edge.name,+ px: edge.offset.px,+ percentage: edge.offset.percentage,+ calculated: edge+ .offset+ .calculated+ .optional_data()+ .is_some()+ .then(|| edge.offset.calculated.clone_retained()),+ })+ }++ /// Sets the start edge of the attachment range, or the end edge where `is_end`, taking in what that changes.+ pub fn set_range_edge(&self, is_end: bool, edge: AttachmentRangeEdgeValue, perform: HostEffectPerformer) {+ let mut range = self.cell().borrow().range();+ range[usize::from(is_end)] = super::animation::AttachmentRangeEdge {+ name: edge.name,+ offset: super::animation::AttachmentRangeEdgeOffset {+ px: edge.px,+ percentage: edge.percentage,+ calculated: edge.calculated.unwrap_or_else(RetainedStyleValueData::none),+ },+ };+ if !self.cell().borrow_mut().set_range(range) {+ return;+ }+ let _ = run_procedure_on(self.cell(), perform, |procedures| {+ procedures.attachment_range_changed();+ Ok(())+ });+ }++ /// Notes that script overrode what `flag` names of the CSS animation.+ pub fn set_css_animation_flag(&self, flag: super::animation::CssAnimationFlag) {+ self.cell().borrow_mut().css_animation_mut().flags |= flag as u8;+ }++ /// The bytes of the allocation every handle shares, and those the record holds beyond it.+ #[must_use]+ pub fn memory_size(&self) -> usize {+ self.cell().memory_size()+ }+}++impl EffectRecordRef {+ /// The cell of the object script sees of the effect, while it has one.+ #[must_use]+ pub fn facade(&self) -> Option<NonNull<c_void>> {+ self.0.facade()+ }++ /// Whether both references are to the same effect.+ #[must_use]+ pub fn ptr_eq(&self, other: &Self) -> bool {+ std::ptr::eq(self.as_host_ptr(), other.as_host_ptr())+ }++ /// Whether the effect's keyframes come from CSS: from a `@keyframes` rule, or a CSS transition.+ #[must_use]+ pub fn keyframes_from_css(&self) -> bool {+ self.0.borrow().keyframes_from_css()+ }++ /// Notes that script is about to set the effect's keyframes, which keeps those it replaces of CSS from coming back.+ pub fn note_keyframes_set_by_script(&self) {+ self.0.borrow_mut().note_keyframes_set_by_script();+ }++ /// The keyframes of CSS the effect runs as `getKeyframes()` returns them.+ #[must_use]+ pub fn computed_css_keyframes(&self) -> Vec<CssKeyframeValues> {+ let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());+ super::keyframe_reflection::computed_css_keyframes(&effect)+ .into_iter()+ .map(Into::into)+ .collect()+ }++ /// The keyframes of CSS a copy of the effect takes.+ #[must_use]+ pub fn css_keyframes_of_copy(&self) -> Vec<CssKeyframeValues> {+ let effect = super::keyframe_reflection::ReflectedEffect::of(&self.0.borrow());+ super::keyframe_reflection::css_keyframes_of_copy(&effect)+ .into_iter()+ .map(Into::into)+ .collect()+ }+}++impl TimelineRecordRef {+ /// Whether both references are to the same timeline.+ #[must_use]+ pub fn ptr_eq(&self, other: &Self) -> bool {+ std::ptr::eq(self.as_host_ptr(), other.as_host_ptr())+ }++ /// Whether the timeline is a progress-based timeline.+ #[must_use]+ pub fn is_progress_based(&self) -> bool {+ self.0.borrow().is_progress_based()+ }++ /// The current time of the timeline, or none where it is inactive.+ #[must_use]+ pub fn current_time(&self) -> Option<TimeValue> {+ self.0.sample().current_time.get()+ }++ /// The current time style sampling reads in place of the timeline's own, if any.+ #[must_use]+ pub fn style_sampling_override(&self) -> Option<Option<TimeValue>> {+ self.0.borrow().style_sampling_override()+ }++ pub fn set_style_sampling_override(&self, current_time: Option<Option<TimeValue>>) {+ self.0.borrow_mut().set_style_sampling_override(current_time);+ }++ /// Whether the timeline is inactive.+ #[must_use]+ pub fn is_inactive(&self) -> bool {+ self.0.is_inactive()+ }++ /// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time+ /// Where the timeline can convert one, which only a document timeline can.+ #[must_use]+ pub fn convert_a_timeline_time_to_an_origin_relative_time(&self, timeline_time: TimeValue) -> Option<f64> {+ if !matches!(self.0.borrow().kind, TimelineKind::Document { .. }) {+ return None;+ }+ self.0+ .convert_a_timeline_time_to_an_origin_relative_time(Some(timeline_time))+ }+}++/// The ids of the `animation-range-start` and `animation-range-end` properties.+pub const PROPERTY_ID_ANIMATION_RANGE_START: u16 = crate::css::property_metadata::property_id::ANIMATION_RANGE_START;+pub const PROPERTY_ID_ANIMATION_RANGE_END: u16 = crate::css::property_metadata::property_id::ANIMATION_RANGE_END;++pub use super::animation::CssAnimationFlag;+pub use super::ffi::FfiHostEffectKind as HostEffectKind;++/// The time a calculation of the numeric type gives: milliseconds of a number or a time, or a percentage, where it gives+/// one of those.+#[must_use]+pub fn time_value_of_calculation(+ calculation: Arc<crate::css::typed_om::CalcNode>,+ numeric_type: crate::css::typed_om::NumericType,+) -> Option<TimeValue> {+ use super::timing::TimeValueType;+ use crate::css::calc::{CanonicalNumericType, resolve_calculated_canonically};+ let calculated = crate::css::typed_om::calculated_value(+ crate::css::property_metadata::property_id::CUSTOM,+ calculation,+ numeric_type,+ );+ let (canonical_type, value) = resolve_calculated_canonically(calculated.data(), None)?;+ Some(match canonical_type {+ CanonicalNumericType::Number => TimeValue {+ r#type: TimeValueType::Milliseconds,+ value,+ },+ // NB: The canonical unit of a time is the second.+ CanonicalNumericType::Time => TimeValue {+ r#type: TimeValueType::Milliseconds,+ value: value * 1000.0,+ },+ CanonicalNumericType::Percentage => TimeValue {+ r#type: TimeValueType::Percentage,+ value,+ },+ _ => return None,+ })+}++/// Whether the numeric type matches a time.+#[must_use]+pub fn numeric_type_matches_time(numeric_type: &crate::css::typed_om::NumericType) -> bool {+ numeric_type.matches_dimension(crate::css::typed_om::BASE_TYPE_TIME, None)+}++/// https://drafts.csswg.org/scroll-animations-1/#typedef-timeline-range-name+/// The name of the host's `TimelineRangeName`, or none for an edge measured along the entire timeline.+#[must_use]+pub fn timeline_range_name_to_string(name: u8) -> Option<&'static str> {+ Some(match name {+ 0 => return None,+ 1 => "cover",+ 2 => "contain",+ 3 => "entry",+ 4 => "exit",+ 5 => "entry-crossing",+ 6 => "exit-crossing",+ 7 => "scroll",+ _ => unreachable!("the host names a timeline range it knows"),+ })+}diff --git a/Libraries/LibWeb/Rust/src/animations/clock_plan.rs b/Libraries/LibWeb/Rust/src/animations/clock_plan.rsnew file mode 100644index 00000000000..987dbd87994--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/clock_plan.rs@@ -0,0 +1,176 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the render clock's plan for a rendering update makes of an animation, as far as its record decides: whether a+//! tick holds its element still, cannot move it, or moves it, and the timing a hover of the clock's lane runs a+//! transition with.++use super::animation::{AnimationKind, AnimationRecord};+use super::effect::{AnimationEffectRecord, EffectFlag};+use super::snapshot::{EffectTimingSnapshot, TimelineClock, TimelineClockSource};+use super::timing::{self, TimeValue, TimeValueType, TimelineSample};++/// What the render clock's plan makes of an animation of a keyframe effect with a target, as far as its record+/// decides.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) enum ClockPlanAnimation {+ /// The animation's play is pending and the compositor does not run it: it holds still until the host makes it+ /// ready, so the ticks sample nothing of its element.+ Held,+ /// A tick cannot move the animation.+ NotTicked,+ /// A tick moves the animation, whose effect is at `local_time` and, on a document timeline, ends its active+ /// interval at `active_end`.+ Ticked {+ local_time: TimeValue,+ active_end: TimeValue,+ },+}++/// Whether a compositor animation runs `effect`, or what it animates in its place, which the render clock then does not+/// sample.+pub(crate) fn runs_on_compositor(effect: &AnimationEffectRecord) -> bool {+ effect.has_flag(EffectFlag::CompositorDriven) || effect.has_flag(EffectFlag::CompositorReplaced)+}++impl AnimationRecord {+ /// What the render clock's plan makes of the animation, whose timeline is at `timeline_time` and is a scroll+ /// timeline where `on_scroll_timeline`.+ pub(crate) fn clock_plan(&self, timeline_time: Option<TimeValue>, on_scroll_timeline: bool) -> ClockPlanAnimation {+ let effect = self+ .effect()+ .expect("the plan runs on animations of keyframe effects")+ .borrow();+ let playback = self.playback();+ // NB: A tick moves the document's timeline, at the rate it runs, and the scroll timelines, to where the+ // compositor has scrolled. What the compositor runs already runs there while its play is pending. Anything+ // else holds still while its play is pending, until the host makes it ready, as it does in the boxes of+ // the host's frame.+ if playback.pending() && !runs_on_compositor(&effect) {+ return ClockPlanAnimation::Held;+ }+ if playback.playback_rate.is_nan() || playback.playback_rate <= 0.0 {+ return ClockPlanAnimation::NotTicked;+ }+ // NB: Times on a document timeline are in milliseconds, and those on a scroll timeline percentages of its+ // progress, throughout.+ let unit = if on_scroll_timeline {+ TimeValueType::Percentage+ } else {+ TimeValueType::Milliseconds+ };+ let timing = effect.timing();+ let Some(local_time) = timing::current_time_at(playback, timeline_time) else {+ return ClockPlanAnimation::NotTicked;+ };+ if local_time.r#type != unit+ || timing.start_delay.r#type != unit+ || timing.iteration_duration.r#type != unit+ || timing::active_duration(&timing).r#type != unit+ {+ return ClockPlanAnimation::NotTicked;+ }+ let active_end = timing.start_delay + timing::active_duration(&timing);+ // NB: An animation of a scroll timeline that finished runs again as the scroll goes back.+ if !on_scroll_timeline && local_time.value >= active_end.value {+ return ClockPlanAnimation::NotTicked;+ }+ ClockPlanAnimation::Ticked { local_time, active_end }+ }++ /// The timing a hover of the render clock's lane runs the animation with, on its timeline at `timeline`, where+ /// `has_timeline`, which `clock` moves.+ pub(crate) fn hover_timing(+ &self,+ timeline: TimelineSample,+ has_timeline: bool,+ clock: TimelineClock,+ ) -> EffectTimingSnapshot {+ let effect = self+ .effect()+ .expect("the hover runs animations of keyframe effects")+ .borrow();+ let mut playback = *self.playback();+ // NB: The compositor runs a transition whose play is still pending from the time of the style change event+ // that started it, on the document timeline.+ if matches!(self.kind(), AnimationKind::CssTransition(_))+ && playback.pending()+ && playback.start_time.get().is_none()+ && effect.has_flag(EffectFlag::CompositorDriven)+ && clock.source == TimelineClockSource::Document+ {+ playback.start_time = Some(TimeValue::milliseconds(self.css_transition_style_change_event_time())).into();+ playback.hold_time = None.into();+ }+ EffectTimingSnapshot {+ effect: effect.timing(),+ playback,+ timeline,+ has_timeline,+ clock,+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::animations::animation::AnimationHandle;+ use crate::animations::effect::EffectHandle;+ use timing::{SpecifiedEffectTiming, SpecifiedIterationDuration};++ /// A script animation of a one second effect on a document timeline, started at `start_time`, or pending.+ fn animation_started_at(start_time: Option<f64>) -> AnimationHandle {+ let effect = EffectHandle::new();+ effect.borrow_mut().set_specified_timing(SpecifiedEffectTiming {+ iteration_duration: SpecifiedIterationDuration {+ is_auto: false,+ milliseconds: 1000.0,+ },+ ..SpecifiedEffectTiming::default()+ });+ effect.borrow_mut().normalize_specified_timing(None);+ let animation = AnimationHandle::new(AnimationKind::Script);+ animation.borrow_mut().set_effect(Some(effect));+ let mut record = animation.borrow_mut();+ let playback = record.playback_mut();+ match start_time {+ Some(start_time) => playback.start_time = Some(TimeValue::milliseconds(start_time)).into(),+ None => {+ playback.hold_time = Some(TimeValue::milliseconds(0.0)).into();+ playback.has_pending_play_task = true;+ }+ }+ drop(record);+ animation+ }++ #[test]+ fn a_tick_moves_a_running_animation_until_its_active_interval_ends() {+ let animation = animation_started_at(Some(100.0));+ let plan = animation+ .borrow()+ .clock_plan(Some(TimeValue::milliseconds(600.0)), false);+ assert_eq!(+ plan,+ ClockPlanAnimation::Ticked {+ local_time: TimeValue::milliseconds(500.0),+ active_end: TimeValue::milliseconds(1000.0),+ }+ );+ let plan = animation+ .borrow()+ .clock_plan(Some(TimeValue::milliseconds(1100.0)), false);+ assert_eq!(plan, ClockPlanAnimation::NotTicked);+ }++ #[test]+ fn a_pending_animation_holds_still() {+ let animation = animation_started_at(None);+ let plan = animation.borrow().clock_plan(Some(TimeValue::milliseconds(0.0)), false);+ assert_eq!(plan, ClockPlanAnimation::Held);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/composite_order.rs b/Libraries/LibWeb/Rust/src/animations/composite_order.rsnew file mode 100644index 00000000000..2c00a6414e7--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/composite_order.rs@@ -0,0 +1,290 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The composite order of animations.+//! https://www.w3.org/TR/web-animations-1/#animation-composite-order++use super::animation::{AnimationKind, AnimationRecord, OwningElement};+use crate::css::selector::{PseudoElementType, pseudo_element_from_ffi};+use std::cmp::Ordering;+use std::ffi::c_void;+use std::ptr::NonNull;++/// The classes of animations, in their composite order.+/// https://www.w3.org/TR/css-animations-2/#animation-composite-order+#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]+enum AnimationClass {+ Smil,+ CssAnimationWithOwningElement,+ CssTransition,+ CssAnimationWithoutOwningElement,+ /// An animation without a specific animation class.+ None,+}++fn animation_class(animation: &AnimationRecord) -> AnimationClass {+ match animation.kind() {+ AnimationKind::Smil { .. } => AnimationClass::Smil,+ AnimationKind::CssAnimation(_) if animation.owning_element().is_some() => {+ AnimationClass::CssAnimationWithOwningElement+ }+ AnimationKind::CssAnimation(_) => AnimationClass::CssAnimationWithoutOwningElement,+ AnimationKind::CssTransition(_) => AnimationClass::CssTransition,+ AnimationKind::Script => AnimationClass::None,+ }+}++/// Compares two of the host's `DOM::Element`s in tree order.+pub(crate) trait TreeOrder {+ fn compare(&mut self, first: NonNull<c_void>, second: NonNull<c_void>) -> Ordering;+}++impl<F: FnMut(NonNull<c_void>, NonNull<c_void>) -> Ordering> TreeOrder for F {+ fn compare(&mut self, first: NonNull<c_void>, second: NonNull<c_void>) -> Ordering {+ self(first, second)+ }+}++/// https://www.w3.org/TR/web-animations-1/#animation-composite-order+/// The relative composite order of the animations `a` and `b`, which `tree_order` resolves where it depends on the+/// order of elements in the document.+pub(crate) fn composite_order(a: &AnimationRecord, b: &AnimationRecord, tree_order: &mut impl TreeOrder) -> Ordering {+ // The relative composite order of any two keyframe effects A and B within an effect stack is established by+ // comparing their properties as follows:++ // 1. Sort A and B by applying the following conditions in turn until the order is resolved,++ // 1. If A and B’s associated animations differ by class, sort by any inter-class composite order defined for+ // the corresponding classes.+ // From https://www.w3.org/TR/css-animations-2/#animation-composite-order:+ // "CSS Animations with an owning element have a later composite order than CSS Transitions but an earlier+ // composite order than animations without a specific animation class."+ let class = animation_class(a);+ let other_class = animation_class(b);+ if class != other_class {+ return class.cmp(&other_class);+ }++ // 2. If A and B are still not sorted, sort by any class-specific composite order defined by the common class of+ // A and B’s associated animations.+ let order = class_specific_composite_order(a, b, tree_order);+ if order != Ordering::Equal {+ return order;+ }++ // 3. If A and B are still not sorted, sort by the position of their associated animations in the global+ // animation list.+ a.global_animation_list_order().cmp(&b.global_animation_list_order())+}++fn class_specific_composite_order(+ a: &AnimationRecord,+ b: &AnimationRecord,+ tree_order: &mut impl TreeOrder,+) -> Ordering {+ match (a.kind(), b.kind()) {+ (AnimationKind::CssAnimation(a_state), AnimationKind::CssAnimation(b_state)) => {+ // https://www.w3.org/TR/css-animations-2/#animation-composite-order+ // Within the set of CSS Animations with an owning element, two animations A and B are sorted in composite+ // order (first to last) as follows:+ let (Some(owner), Some(other_owner)) = (a.owning_element(), b.owning_element()) else {+ // The composite order of CSS Animations without an owning element is based on their position in the+ // global animation list.+ return Ordering::Equal;+ };++ // 1. If the owning element of A and B differs, sort A and B by tree order of their corresponding owning+ // elements. With regard to pseudo-elements, the sort order is as follows:+ // - element+ // - ::marker+ // - ::before+ // - any other pseudo-elements not mentioned specifically in this list, sorted in ascending order by the+ // Unicode codepoints that make up each selector+ // - ::after+ // - element children+ if owner != other_owner {+ return owning_element_order(owner, other_owner, tree_order);+ }++ // 2. Otherwise, sort A and B based on their position in the computed value of the animation-name property+ // of the (common) owning element.+ a_state.name_index.cmp(&b_state.name_index)+ }+ (AnimationKind::CssTransition(a_state), AnimationKind::CssTransition(b_state)) => {+ // https://drafts.csswg.org/css-transitions-2/#animation-composite-order+ // Within the set of CSS Transitions, two animations A and B are sorted in composite order (first to last)+ // as follows:+ match (a.owning_element(), b.owning_element()) {+ // 1. If neither A nor B has an owning element, sort based on their relative position in the global+ // animation list.+ (None, None) => return a.global_animation_list_order().cmp(&b.global_animation_list_order()),+ // 2. Otherwise, if only one of A or B has an owning element, let the animation with an owning element+ // sort first.+ (Some(_), None) => return Ordering::Less,+ (None, Some(_)) => return Ordering::Greater,+ // 3. Otherwise, if the owning element of A and B differs, sort A and B by tree order of their+ // corresponding owning elements. With regard to pseudo-elements, the sort order is as follows:+ // - element+ // - ::marker+ // - ::before+ // - any other pseudo-elements not mentioned specifically in this list, sorted in ascending order by+ // the Unicode codepoints that make up each selector+ // - ::after+ // - element children+ (Some(owner), Some(other_owner)) if owner != other_owner => {+ return owning_element_order(owner, other_owner, tree_order);+ }+ (Some(_), Some(_)) => {}+ }++ // 4. Otherwise, if A and B have different transition generation values, sort by their corresponding+ // transition generation in ascending order.+ if a_state.generation != b_state.generation {+ return a_state.generation.cmp(&b_state.generation);+ }++ // 5. Otherwise, sort A and B in ascending order by the Unicode codepoints that make up the expanded+ // transition property name of each transition (i.e. without attempting case conversion and such that+ // ‘-moz-column-width’ sorts before ‘column-width’).+ a_state.property_name().cmp(&b_state.property_name())+ }+ (+ AnimationKind::Smil {+ begin_time,+ animation_element,+ ..+ },+ AnimationKind::Smil {+ begin_time: other_begin_time,+ animation_element: other_animation_element,+ ..+ },+ ) => {+ // https://www.w3.org/TR/smil-animation/#AnimationSandwichModel+ // Within an OM, animations are prioritized according to when each begins. The animation first begun has+ // lowest priority and the most recently begun animation has highest priority. When two animations start at+ // the same moment in time, the activation order is resolved as follows:+ // ...+ // If two animations share no time dependency relationship (e.g., neither is defined relative to the other,+ // even indirectly) the element that appears first in the document has lower priority.+ if begin_time != other_begin_time {+ return begin_time.total_cmp(other_begin_time);+ }+ // NB: Begin times only come from offsets and DOM method calls for now, so no animation is defined relative+ // to another.+ if animation_element == other_animation_element {+ return Ordering::Equal;+ }+ tree_order.compare(*animation_element, *other_animation_element)+ }+ _ => Ordering::Equal,+ }+}++/// The order of two different owning elements: the tree order of their elements, and for the element itself and its+/// pseudo-elements, the order the CSS animations and transitions composite order gives them.+fn owning_element_order(owner: OwningElement, other_owner: OwningElement, tree_order: &mut impl TreeOrder) -> Ordering {+ // NB: An element's pseudo-elements sort with it, so before its children.+ if owner.element != other_owner.element {+ return tree_order.compare(owner.element, other_owner.element);+ }+ let pseudo_element = owner.pseudo_element.map(pseudo_element_from_ffi);+ let other_pseudo_element = other_owner.pseudo_element.map(pseudo_element_from_ffi);+ pseudo_element_rank(pseudo_element)+ .cmp(&pseudo_element_rank(other_pseudo_element))+ .then_with(|| {+ let name = |pseudo_element: Option<PseudoElementType>| pseudo_element.map_or("", PseudoElementType::name);+ name(pseudo_element).cmp(name(other_pseudo_element))+ })+}++fn pseudo_element_rank(pseudo_element: Option<PseudoElementType>) -> u8 {+ match pseudo_element {+ None => 0,+ Some(PseudoElementType::Marker) => 1,+ Some(PseudoElementType::Before) => 2,+ Some(PseudoElementType::After) => 4,+ Some(_) => 3,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::animations::animation::{AnimationHandle, CssTransitionState};+ use crate::css::retained_fly_string::RetainedUtf16FlyString;+ use crate::css::style_value::RetainedStyleValueData;++ fn element(address: usize) -> NonNull<c_void> {+ NonNull::new(address as *mut c_void).unwrap()+ }++ fn by_address(first: NonNull<c_void>, second: NonNull<c_void>) -> Ordering {+ first.cmp(&second)+ }++ fn transition(owner: Option<OwningElement>, generation: u64, property_id: u16) -> AnimationHandle {+ let animation = AnimationHandle::new(AnimationKind::CssTransition(CssTransitionState {+ custom_property_name: RetainedUtf16FlyString::none(),+ generation,+ start_time: 0.0,+ end_time: 0.0,+ start_value: RetainedStyleValueData::none(),+ end_value: RetainedStyleValueData::none(),+ reversing_adjusted_start_value: RetainedStyleValueData::none(),+ reversing_shortening_factor: 1.0,+ property_id,+ previous_phase: 0,+ provisional: false,+ adopted_from_lane: false,+ effect_started_with: None,+ }));+ animation.borrow_mut().set_owning_element(owner);+ animation+ }++ fn order(a: &AnimationHandle, b: &AnimationHandle) -> Ordering {+ composite_order(&a.borrow(), &b.borrow(), &mut by_address)+ }++ #[test]+ fn classes_sort_before_script_animations() {+ let script = AnimationHandle::new(AnimationKind::Script);+ let smil = AnimationHandle::new(AnimationKind::Smil {+ begin_time: 0.0,+ animation_element: element(8),+ holders: 0,+ });+ let transition = transition(None, 0, 1);+ assert_eq!(order(&script, &smil), Ordering::Greater);+ assert_eq!(order(&smil, &transition), Ordering::Less);+ assert_eq!(order(&transition, &script), Ordering::Less);+ }++ #[test]+ fn transitions_sort_by_owner_then_generation() {+ let owner = |address, pseudo_element| {+ Some(OwningElement {+ element: element(address),+ pseudo_element,+ })+ };+ let later_element = transition(owner(16, None), 0, 1);+ let earlier_element = transition(owner(8, None), 1, 1);+ assert_eq!(order(&later_element, &earlier_element), Ordering::Greater);++ let after = transition(owner(8, Some(PseudoElementType::After as u8)), 0, 1);+ let before = transition(owner(8, Some(PseudoElementType::Before as u8)), 0, 1);+ assert_eq!(order(&after, &before), Ordering::Greater);+ assert_eq!(order(&earlier_element, &before), Ordering::Less);++ let later_generation = transition(owner(8, None), 2, 1);+ assert_eq!(order(&earlier_element, &later_generation), Ordering::Less);++ let unowned = transition(None, 0, 1);+ assert_eq!(order(&unowned, &earlier_element), Ordering::Greater);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/css_events.rs b/Libraries/LibWeb/Rust/src/animations/css_events.rsnew file mode 100644index 00000000000..c4ed7b3865a--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/css_events.rs@@ -0,0 +1,449 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The events of a CSS animation or a CSS transition that a new animation frame establishes, which the record decides+//! from the phases its animation and associated effect go through.++use super::animation::{AnimationKind, AnimationRecord};+use super::host_timing::FfiAnimationKind;+use super::timing::time_value::{max, min};+use super::timing::{self, AnimationEffectPhase, OptionalNumber, TimeValue, TimeValueType};++/// The type of an event of a CSS animation or a CSS transition.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FfiCssEventType {+ AnimationStart,+ AnimationEnd,+ AnimationIteration,+ AnimationCancel,+ TransitionRun,+ TransitionStart,+ TransitionEnd,+ TransitionCancel,+}++/// An event to dispatch, with its elapsed time in seconds.+#[repr(C)]+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct FfiCssEvent {+ pub r#type: FfiCssEventType,+ pub elapsed_time: f64,+}++/// The events an animation frame establishes for an animation, in the order they are dispatched, and the time they+/// were scheduled at. A frame establishes at most three, the run, start and end events of a transition that went from+/// idle to after.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct FfiCssEvents {+ /// What made the animation, which only has events where it is a CSS animation or a CSS transition.+ pub kind: FfiAnimationKind,+ pub count: u8,+ pub events: [FfiCssEvent; 3],+ /// The origin-relative time of the current time of the timeline, where it has one.+ pub scheduled_event_time: OptionalNumber,+}++impl FfiCssEvents {+ fn new(kind: FfiAnimationKind) -> Self {+ Self {+ kind,+ count: 0,+ events: [FfiCssEvent {+ r#type: FfiCssEventType::AnimationStart,+ elapsed_time: 0.0,+ }; 3],+ scheduled_event_time: None.into(),+ }+ }++ fn push(&mut self, r#type: FfiCssEventType, elapsed_time: TimeValue) {+ let elapsed_time = match elapsed_time.r#type {+ TimeValueType::Milliseconds => elapsed_time.value / 1000.0,+ // FIXME: The spec doesn't specify how to handle this case+ TimeValueType::Percentage => 0.0,+ };+ self.events[usize::from(self.count)] = FfiCssEvent { r#type, elapsed_time };+ self.count += 1;+ }++ #[cfg(test)]+ fn as_slice(&self) -> &[FfiCssEvent] {+ &self.events[..usize::from(self.count)]+ }+}++/// https://drafts.csswg.org/css-transitions-2/#transition-phase+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum TransitionPhase {+ Before,+ Active,+ After,+ Idle,+ Pending,+}++impl TransitionPhase {+ fn from_stored(phase: u8) -> Self {+ match phase {+ 0 => Self::Before,+ 1 => Self::Active,+ 2 => Self::After,+ 3 => Self::Idle,+ 4 => Self::Pending,+ _ => unreachable!("a stored transition phase"),+ }+ }++ fn of_effect(phase: AnimationEffectPhase) -> Self {+ match phase {+ AnimationEffectPhase::Before => Self::Before,+ AnimationEffectPhase::Active => Self::Active,+ AnimationEffectPhase::After => Self::After,+ AnimationEffectPhase::Idle => Self::Idle,+ }+ }+}++/// The intervals whose boundaries give the elapsed time of a transition event.+#[derive(Clone, Copy)]+enum Interval {+ Start,+ End,+ ActiveTime,+}++impl AnimationRecord {+ /// The events of a CSS animation or a CSS transition that the animation frame just established, recording the+ /// phases they were decided from for the next frame. Other animations have none.+ pub(crate) fn take_css_events(&mut self) -> FfiCssEvents {+ let mut events = FfiCssEvents::new(self.ffi_kind());+ match self.kind() {+ AnimationKind::CssTransition(_) => self.establish_transition_events(&mut events),+ AnimationKind::CssAnimation(_) => self.establish_css_animation_events(&mut events),+ AnimationKind::Script | AnimationKind::Smil { .. } => {}+ }+ if events.count > 0 {+ events.scheduled_event_time = self+ .timeline()+ .and_then(|timeline| {+ timeline.convert_a_timeline_time_to_an_origin_relative_time(timeline.current_time())+ })+ .into();+ }+ events+ }++ /// A zero time in the unit of the times of the timeline of the animation.+ fn zero_time(&self) -> TimeValue {+ let progress_based = self+ .timeline()+ .is_some_and(|timeline| timeline.borrow().is_progress_based());+ TimeValue::zero(if progress_based {+ TimeValueType::Percentage+ } else {+ TimeValueType::Milliseconds+ })+ }++ // https://drafts.csswg.org/css-transitions-2/#event-dispatch+ fn establish_transition_events(&mut self, events: &mut FfiCssEvents) {+ let previous_phase = TransitionPhase::from_stored(self.css_transition().previous_phase);+ let playback = *self.playback();+ let timeline = self.timeline();+ let current_time = timing::current_time_at(&playback, timeline.and_then(|timeline| timeline.current_time()));+ let sample = timeline.map(|timeline| timeline.sample());+ let effect_timing = self.effect().map(|effect| effect.borrow().timing());++ // The transition phase of a transition is initially ‘idle’ and is updated on each+ // animation frame according to the first matching condition from below:+ let transition_phase = match &effect_timing {+ // If the transition has no associated effect,+ None => match current_time {+ // If the transition has an unresolved current time,+ // The transition phase is ‘idle’.+ None => TransitionPhase::Idle,+ // If the transition has a current time < 0,+ // The transition phase is ‘before’.+ Some(current_time) if current_time.value < 0.0 => TransitionPhase::Before,+ // Otherwise,+ // The transition phase is ‘after’.+ Some(_) => TransitionPhase::After,+ },+ // If the transition has a pending play task or a pending pause task+ // and its phase was previously ‘idle’ or ‘pending’,+ // The transition phase is ‘pending’.+ Some(_)+ if playback.pending() && matches!(previous_phase, TransitionPhase::Idle | TransitionPhase::Pending) =>+ {+ TransitionPhase::Pending+ }+ // Otherwise,+ // The transition phase is the phase of its associated effect.+ Some(effect_timing) => TransitionPhase::of_effect(+ timing::resolve_timing(effect_timing, current_time, Some(&playback), sample.as_ref()).phase,+ ),+ };++ // The target for a transition event is the transition’s owning element. If there is no owning element,+ // no transition events are dispatched.+ let effect_timing = effect_timing.filter(|_| self.owning_element().is_some());+ let zero = self.zero_time();+ let mut dispatch_event = |r#type: FfiCssEventType, interval: Interval| {+ let Some(effect_timing) = &effect_timing else {+ return;+ };+ let active_duration = timing::active_duration(effect_timing);+ let elapsed_time = match interval {+ Interval::Start => max(min(-effect_timing.start_delay, active_duration), zero),+ Interval::End => max(+ min(+ timing::end_time(effect_timing) - effect_timing.start_delay,+ active_duration,+ ),+ zero,+ ),+ // The active time of the animation at the moment it was canceled calculated using a fill mode of both.+ // FIXME: Compute this properly.+ Interval::ActiveTime => zero,+ };+ events.push(r#type, elapsed_time);+ };++ use FfiCssEventType::{TransitionCancel, TransitionEnd, TransitionRun, TransitionStart};+ use TransitionPhase::{Active, After, Before, Idle, Pending};+ match (previous_phase, transition_phase) {+ (Idle, Pending | Before) => dispatch_event(TransitionRun, Interval::Start),+ (Idle, Active) => {+ dispatch_event(TransitionRun, Interval::Start);+ dispatch_event(TransitionStart, Interval::Start);+ }+ (Idle, After) => {+ dispatch_event(TransitionRun, Interval::Start);+ dispatch_event(TransitionStart, Interval::Start);+ dispatch_event(TransitionEnd, Interval::End);+ }+ (Pending | Before, Active) => dispatch_event(TransitionStart, Interval::Start),+ (Pending | Before, After) => {+ dispatch_event(TransitionStart, Interval::Start);+ dispatch_event(TransitionEnd, Interval::End);+ }+ (Active, After) => dispatch_event(TransitionEnd, Interval::End),+ (Active, Before) => dispatch_event(TransitionEnd, Interval::Start),+ (After, Active) => dispatch_event(TransitionStart, Interval::End),+ (After, Before) => {+ dispatch_event(TransitionStart, Interval::End);+ dispatch_event(TransitionEnd, Interval::Start);+ }+ _ => {}+ }++ if transition_phase == Idle && previous_phase != Idle && previous_phase != After {+ dispatch_event(TransitionCancel, Interval::ActiveTime);+ }++ self.css_transition_mut().previous_phase = transition_phase as u8;+ }++ // https://www.w3.org/TR/css-animations-2/#event-dispatch+ fn establish_css_animation_events(&mut self, events: &mut FfiCssEvents) {+ // Each time a new animation frame is established and the animation does not have a pending play task or pending+ // pause task, the events to dispatch are determined by comparing the animation’s phase before and after+ // establishing the new animation frame as follows:+ let playback = *self.playback();+ if playback.pending() || self.owning_element().is_none() {+ return;+ }+ let Some(effect) = self.effect().cloned() else {+ return;+ };+ let timeline = self.timeline();+ let current_time = timing::current_time_at(&playback, timeline.and_then(|timeline| timeline.current_time()));+ let sample = timeline.map(|timeline| timeline.sample());+ let (effect_timing, previous_phase, previous_current_iteration) = {+ let effect = effect.borrow();+ (+ effect.timing(),+ effect.previous_phase(),+ effect.previous_current_iteration(),+ )+ };+ let resolved = timing::resolve_timing(&effect_timing, current_time, Some(&playback), sample.as_ref());+ let current_phase = resolved.phase;+ let current_iteration = timing::current_iteration(&effect_timing, &resolved).unwrap_or(0.0);+ let zero = self.zero_time();++ // For calculating the elapsedTime of each event, the following definitions are used:++ // - interval start = max(min(-start delay, active duration), 0)+ let active_duration = timing::active_duration(&effect_timing);+ let interval_start = max(min(-effect_timing.start_delay, active_duration), zero);++ // - interval end = max(min(associated effect end - start delay, active duration), 0)+ let interval_end = max(+ min(+ timing::end_time(&effect_timing) - effect_timing.start_delay,+ active_duration,+ ),+ zero,+ );++ use AnimationEffectPhase::{Active, After, Before, Idle};+ use FfiCssEventType::{AnimationCancel, AnimationEnd, AnimationIteration, AnimationStart};+ match (previous_phase, current_phase) {+ (Before | Idle, Active) => events.push(AnimationStart, interval_start),+ (Before | Idle, After) => {+ events.push(AnimationStart, interval_start);+ events.push(AnimationEnd, interval_end);+ }+ (Active, Before) => events.push(AnimationEnd, interval_start),+ (Active, Active) if previous_current_iteration != current_iteration => {+ // The elapsed time for an animationiteration event is defined as follows:++ // 1. Let previous current iteration be the current iteration from the previous animation frame.++ // 2. If previous current iteration is greater than current iteration, let iteration boundary be current iteration + 1,+ // otherwise let it be current iteration.+ let iteration_boundary = if previous_current_iteration > current_iteration {+ current_iteration + 1.0+ } else {+ current_iteration+ };++ // 3. The elapsed time is the result of evaluating (iteration boundary - iteration start) × iteration duration).+ let elapsed_time =+ effect_timing.iteration_duration * (iteration_boundary - effect_timing.iteration_start);++ events.push(AnimationIteration, elapsed_time);+ }+ (Active, After) => events.push(AnimationEnd, interval_end),+ (After, Active) => events.push(AnimationStart, interval_end),+ (After, Before) => {+ events.push(AnimationStart, interval_end);+ events.push(AnimationEnd, interval_start);+ }+ _ => {}+ }++ if current_phase == Idle && previous_phase != Idle && previous_phase != After {+ // FIXME: Calculate a non-zero time when the animation is cancelled by means other than calling cancel()+ let cancel_time = self.take_saved_cancel_time().unwrap_or(zero);+ events.push(AnimationCancel, cancel_time);+ }++ let mut effect = effect.borrow_mut();+ effect.set_previous_phase(current_phase);+ effect.set_previous_current_iteration(current_iteration);+ }+}++#[cfg(test)]+mod tests {+ use core::ffi::c_void;+ use core::ptr::NonNull;++ use super::*;+ use crate::animations::animation::{AnimationHandle, CSS_TRANSITION_PHASE_IDLE, CssTransitionState, OwningElement};+ use crate::animations::effect::EffectHandle;+ use crate::css::retained_fly_string::RetainedUtf16FlyString;+ use crate::css::style_value::RetainedStyleValueData;+ use timing::{SpecifiedEffectTiming, SpecifiedIterationDuration};++ /// A transition of a second after a delay of 100 milliseconds on an element, held at `current_time`.+ fn transition_held_at(current_time: f64) -> AnimationHandle {+ let effect = EffectHandle::new();+ effect.borrow_mut().set_specified_timing(SpecifiedEffectTiming {+ iteration_duration: SpecifiedIterationDuration {+ is_auto: false,+ milliseconds: 1000.0,+ },+ start_delay: 100.0,+ ..SpecifiedEffectTiming::default()+ });+ effect.borrow_mut().normalize_specified_timing(None);+ let animation = AnimationHandle::new(AnimationKind::CssTransition(CssTransitionState {+ custom_property_name: RetainedUtf16FlyString::none(),+ generation: 0,+ start_time: 0.0,+ end_time: 0.0,+ start_value: RetainedStyleValueData::none(),+ end_value: RetainedStyleValueData::none(),+ reversing_adjusted_start_value: RetainedStyleValueData::none(),+ reversing_shortening_factor: 1.0,+ property_id: 1,+ previous_phase: CSS_TRANSITION_PHASE_IDLE,+ provisional: false,+ adopted_from_lane: false,+ effect_started_with: None,+ }));+ animation.borrow_mut().set_owning_element(Some(OwningElement {+ element: NonNull::<c_void>::dangling(),+ pseudo_element: None,+ }));+ animation.borrow_mut().set_effect(Some(effect));+ animation.borrow_mut().playback_mut().hold_time = Some(TimeValue::milliseconds(current_time)).into();+ animation+ }++ fn event(r#type: FfiCssEventType, elapsed_time: f64) -> FfiCssEvent {+ FfiCssEvent { r#type, elapsed_time }+ }++ #[test]+ fn a_transition_that_finished_within_a_frame_runs_starts_and_ends() {+ let animation = transition_held_at(2000.0);+ let events = animation.borrow_mut().take_css_events();+ assert_eq!(events.kind, FfiAnimationKind::CssTransition);+ assert_eq!(+ events.as_slice(),+ [+ event(FfiCssEventType::TransitionRun, 0.0),+ event(FfiCssEventType::TransitionStart, 0.0),+ event(FfiCssEventType::TransitionEnd, 1.0),+ ]+ );+ assert_eq!(events.scheduled_event_time.get(), None);+ assert_eq!(animation.borrow_mut().take_css_events().count, 0);+ }++ #[test]+ fn a_transition_moving_back_before_its_start_ends_at_its_start() {+ let animation = transition_held_at(500.0);+ let events = animation.borrow_mut().take_css_events();+ assert_eq!(+ events.as_slice(),+ [+ event(FfiCssEventType::TransitionRun, 0.0),+ event(FfiCssEventType::TransitionStart, 0.0)+ ]+ );+ animation.borrow_mut().playback_mut().hold_time = Some(TimeValue::milliseconds(50.0)).into();+ let events = animation.borrow_mut().take_css_events();+ assert_eq!(events.as_slice(), [event(FfiCssEventType::TransitionEnd, 0.0)]);+ }++ #[test]+ fn a_transition_without_an_owning_element_has_no_events_but_keeps_its_phase() {+ let animation = transition_held_at(500.0);+ animation.borrow_mut().set_owning_element(None);+ assert_eq!(animation.borrow_mut().take_css_events().count, 0);+ animation.borrow_mut().set_owning_element(Some(OwningElement {+ element: NonNull::<c_void>::dangling(),+ pseudo_element: None,+ }));+ assert_eq!(animation.borrow_mut().take_css_events().count, 0);+ }++ #[test]+ fn script_animations_have_no_events() {+ let animation = AnimationHandle::new(AnimationKind::Script);+ let events = animation.borrow_mut().take_css_events();+ assert_eq!(events.kind, FfiAnimationKind::Script);+ assert_eq!(events.count, 0);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/document_animations.rs b/Libraries/LibWeb/Rust/src/animations/document_animations.rsnew file mode 100644index 00000000000..1e79ece3cbe--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/document_animations.rs@@ -0,0 +1,109 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a document knows of the animations associated with it.++use super::animation::WeakAnimationSet;+use super::effect::WeakEffectSet;+use super::pending_animation_events::PendingAnimationEvents;++/// The animations a document knows of, none of which it keeps alive.+#[derive(Default)]+pub struct DocumentAnimations {+ /// The animations associated with the elements of the document, those of its shadow trees included.+ associated: WeakAnimationSet,+ /// The animations associated with the document while style and layout feedback is provisional, whose events+ /// stay provisional with them until the outermost style stabilization epoch commits.+ created_in_stabilization_epoch: WeakAnimationSet,+ /// The CSS animations of the elements of the document that follow a named timeline, which look it up again as+ /// the timelines the document declares change.+ following_named_timelines: WeakAnimationSet,+ /// The effects whose animated style the next animated style update samples.+ needing_animated_style_update: WeakEffectSet,+ /// The effects asked for an observation sample while an animated style update ran, which they are asked for as it+ /// finishes.+ needing_animated_style_update_after_current_update: WeakEffectSet,+ /// The effects dirtied beside the transaction of a style update that flew, which the next style update samples.+ needing_animated_style_update_beside_flown_style_update: WeakEffectSet,+ /// https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue+ pub(crate) pending_events: PendingAnimationEvents,+}++/// One of the sets of animations a document knows of.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum DocumentAnimationSetKind {+ /// The animations associated with the elements of the document.+ Associated,+ /// The animations associated with the document during the current style stabilization epoch.+ CreatedInStabilizationEpoch,+ /// The CSS animations of the elements of the document that follow a named timeline.+ FollowingNamedTimelines,+}++/// One of the sets of effects a document knows of.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum DocumentEffectSetKind {+ /// The effects whose animated style the next animated style update samples.+ NeedingAnimatedStyleUpdate,+ /// The effects to ask for an observation sample as the current animated style update finishes.+ NeedingAnimatedStyleUpdateAfterCurrentUpdate,+ /// The effects dirtied beside the transaction of a style update that flew, which the next style update samples.+ SetAsideWhileFlownStyleUpdateDrains,+}++impl DocumentAnimations {+ pub(crate) fn effect_set_mut(&mut self, kind: DocumentEffectSetKind) -> &mut WeakEffectSet {+ match kind {+ DocumentEffectSetKind::NeedingAnimatedStyleUpdate => &mut self.needing_animated_style_update,+ DocumentEffectSetKind::NeedingAnimatedStyleUpdateAfterCurrentUpdate => {+ &mut self.needing_animated_style_update_after_current_update+ }+ DocumentEffectSetKind::SetAsideWhileFlownStyleUpdateDrains => {+ &mut self.needing_animated_style_update_beside_flown_style_update+ }+ }+ }++ /// Begins the outermost style stabilization epoch, during which the document has created no animations and queued+ /// no events yet.+ pub(crate) fn begin_style_stabilization_epoch(&mut self) {+ assert!(+ !self.pending_events.has_provisional_events(),+ "no events are provisional outside a style stabilization epoch"+ );+ self.created_in_stabilization_epoch.prune();+ assert!(+ self.created_in_stabilization_epoch.entry_count() == 0,+ "no animations are created in a style stabilization epoch before it begins"+ );+ }++ /// Commits the events queued during the outermost style stabilization epoch to the pending animation event queue,+ /// as the epoch commits, and forgets which animations it created, answering how many events it committed.+ pub(crate) fn commit_provisional_events(&mut self) -> usize {+ let created_in_epoch = &self.created_in_stabilization_epoch;+ // An animation created and cancelled inside this epoch was never part of an externally committed style. Its+ // cancellation is provisional too, so no observer may receive it.+ let committed = self.pending_events.commit_provisional_events(|animation| {+ created_in_epoch.contains(animation)+ && animation.borrow().timing_state(None).play_state == super::timing::AnimationPlayState::Idle+ });+ self.created_in_stabilization_epoch.clear();+ committed+ }++ pub(crate) fn set_mut(&mut self, kind: DocumentAnimationSetKind) -> &mut WeakAnimationSet {+ match kind {+ DocumentAnimationSetKind::Associated => &mut self.associated,+ DocumentAnimationSetKind::CreatedInStabilizationEpoch => &mut self.created_in_stabilization_epoch,+ DocumentAnimationSetKind::FollowingNamedTimelines => &mut self.following_named_timelines,+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/easing.rs b/Libraries/LibWeb/Rust/src/animations/easing.rsnew file mode 100644index 00000000000..87897fb9f0a--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/easing.rs@@ -0,0 +1,129 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Easing functions as animations hold them.++use crate::css::easing::{Easing, FfiEasingDescriptor, FfiEasingKind, FfiLinearEasingPoint};++/// The easing keywords that name cubic Bézier curves, with the control points of each.+/// https://drafts.csswg.org/css-easing-1/#cubic-bezier-easing-functions+pub(crate) const KEYWORD_CUBIC_BEZIERS: [(u16, [f64; 4]); 4] = {+ use crate::css::css_enums::keyword;+ [+ (keyword::EASE, [0.25, 0.1, 0.25, 1.0]),+ (keyword::EASE_IN, [0.42, 0.0, 1.0, 1.0]),+ (keyword::EASE_OUT, [0.0, 0.0, 0.58, 1.0]),+ (keyword::EASE_IN_OUT, [0.42, 0.0, 0.58, 1.0]),+ ]+};++/// The cubic Bézier curve of the keyword at `index` of [`KEYWORD_CUBIC_BEZIERS`].+pub(crate) const fn keyword_cubic_bezier(index: usize) -> Easing {+ let [x1, y1, x2, y2] = KEYWORD_CUBIC_BEZIERS[index].1;+ Easing::CubicBezier { x1, y1, x2, y2 }+}++/// The control points of `linear`.+static LINEAR_POINTS: [FfiLinearEasingPoint; 2] = [+ FfiLinearEasingPoint {+ input: 0.0,+ output: 0.0,+ },+ FfiLinearEasingPoint {+ input: 1.0,+ output: 1.0,+ },+];++/// An easing function, held without an allocation of its own where it is `linear` or one of the easings the other+/// keywords name.+#[derive(Clone, PartialEq)]+pub(crate) enum CompactEasing {+ Linear,+ /// The cubic Bézier curve of the keyword at this index of [`KEYWORD_CUBIC_BEZIERS`].+ Keyword(u8),+ Other(Box<Easing>),+}++impl CompactEasing {+ pub(crate) fn of(easing: Easing) -> Self {+ if easing == Easing::default() {+ return Self::Linear;+ }+ let keyword = match &easing {+ &Easing::CubicBezier { x1, y1, x2, y2 } => KEYWORD_CUBIC_BEZIERS+ .iter()+ .position(|(_, control_points)| *control_points == [x1, y1, x2, y2]),+ Easing::Linear(_) | Easing::Steps { .. } => None,+ };+ match keyword {+ #[expect(clippy::cast_possible_truncation)]+ Some(index) => Self::Keyword(index as u8),+ None => Self::Other(Box::new(easing)),+ }+ }++ /// The function, which a keyword's easing lends from a table of them.+ #[must_use]+ pub(crate) fn as_easing(&self) -> &Easing {+ /// `linear`, as `Easing::default()` builds it.+ static LINEAR: std::sync::LazyLock<Easing> = std::sync::LazyLock::new(Easing::default);+ /// The cubic Bézier curves of [`KEYWORD_CUBIC_BEZIERS`], in order.+ static KEYWORD_EASINGS: [Easing; KEYWORD_CUBIC_BEZIERS.len()] = [+ keyword_cubic_bezier(0),+ keyword_cubic_bezier(1),+ keyword_cubic_bezier(2),+ keyword_cubic_bezier(3),+ ];+ match self {+ Self::Linear => &LINEAR,+ Self::Keyword(index) => &KEYWORD_EASINGS[usize::from(*index)],+ Self::Other(easing) => easing,+ }+ }++ #[must_use]+ pub(crate) fn easing(&self) -> Easing {+ match self {+ Self::Linear => Easing::default(),+ Self::Keyword(index) => keyword_cubic_bezier(usize::from(*index)),+ Self::Other(easing) => Easing::clone(easing),+ }+ }++ /// The descriptor of the function, which borrows its control points.+ #[must_use]+ pub(crate) fn descriptor(&self) -> FfiEasingDescriptor {+ match self {+ Self::Linear => FfiEasingDescriptor {+ kind: FfiEasingKind::Linear,+ linear_points: LINEAR_POINTS.as_ptr(),+ linear_point_count: LINEAR_POINTS.len(),+ x1: 0.0,+ y1: 0.0,+ x2: 0.0,+ y2: 0.0,+ interval_count: 0,+ step_position: 0,+ },+ Self::Keyword(index) => keyword_cubic_bezier(usize::from(*index)).descriptor(),+ Self::Other(easing) => easing.descriptor(),+ }+ }++ pub(crate) fn heap_size(&self) -> usize {+ match self {+ Self::Linear | Self::Keyword(_) => 0,+ Self::Other(easing) => {+ size_of::<Easing>()+ + match &**easing {+ Easing::Linear(points) => crate::heap_size::vec_bytes(points),+ Easing::CubicBezier { .. } | Easing::Steps { .. } => 0,+ }+ }+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/effect.rs b/Libraries/LibWeb/Rust/src/animations/effect.rsnew file mode 100644index 00000000000..74dde96f271--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/effect.rs@@ -0,0 +1,649 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Animation effects.+//! https://www.w3.org/TR/web-animations-1/#animation-effects++use super::animation::{AnimationHandle, WeakAnimationHandle};+use super::easing::CompactEasing;+use super::keyframes::{KeyframeOrigin, KeyframeSet};+use super::timeline_state::{TimelineState, time_unit};+use super::timing::{self, AnimationEffectPhase, AnimationEffectTiming, SpecifiedEffectTiming, TimeValue};+use super::weak_record_set::WeakRecordSet;+use crate::css::animation::FfiCompositeOperation;+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style::effect_descriptions::{EffectAnimation, EffectDescription};+use crate::painting::visual_animation_builder::CompositorAnimationEffectState;+use std::cell::{Cell, Ref, RefCell, RefMut};+use std::ffi::c_void;+use std::ptr::NonNull;+use std::rc::Rc;+use std::sync::Arc;+use std::sync::atomic::{AtomicU64, Ordering};++/// The identity of an animation effect, which no other effect of the process shares.+#[repr(transparent)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct AnimationEffectId(pub u64);++impl AnimationEffectId {+ fn mint() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(1);+ Self(NEXT.fetch_add(1, Ordering::Relaxed))+ }+}++/// What the host notes of an effect as it runs it on the compositor, throttles it, or samples it for script, by bit.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum EffectFlag {+ /// A compositor animation runs the effect.+ CompositorDriven = 1 << 0,+ /// A compositor animation runs what the effect animates in its place.+ CompositorReplaced = 1 << 1,+ /// Nothing the effect animates shows, as its target is offscreen.+ OffscreenThrottled = 1 << 2,+ /// Script can observe what the compositor animation running the effect shows.+ ObservationRelevantCompositorAnimation = 1 << 3,+ /// Script asked for a sample of the effect, which the next style update takes.+ NeedsObservationSample = 1 << 4,+ /// A frame skipped its tick of the effect.+ PerFrameAnimationTickWasSkipped = 1 << 5,+}++impl EffectFlag {+ /// Whether the flag decides whether a frame can skip the style update of the effect.+ fn decides_per_frame_style_update_skip(self) -> bool {+ matches!(+ self,+ Self::CompositorDriven | Self::CompositorReplaced | Self::OffscreenThrottled+ )+ }+}++/// What the host found whether a frame can skip the style update of an effect from, besides the effect itself: the+/// generations of the style of its target and of the target's subtree, the identity of the target's layout node, and+/// whether the target was connected.+#[repr(C)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct PerFrameStyleUpdateSkipKey {+ pub target_style_generation: u64,+ pub target_subtree_style_generation: u64,+ pub layout_node: usize,+ pub target_is_connected: bool,+}++/// Whether a frame can skip the style update of an effect, and what the host found that from.+/// NB: The fields of the key are kept apart, so that the decision fits in the padding the key leaves.+#[derive(Clone, Copy)]+struct RememberedPerFrameStyleUpdateSkipDecision {+ target_style_generation: u64,+ target_subtree_style_generation: u64,+ layout_node: usize,+ target_is_connected: bool,+ can_skip: bool,+}++impl RememberedPerFrameStyleUpdateSkipDecision {+ fn key(&self) -> PerFrameStyleUpdateSkipKey {+ PerFrameStyleUpdateSkipKey {+ target_style_generation: self.target_style_generation,+ target_subtree_style_generation: self.target_subtree_style_generation,+ layout_node: self.layout_node,+ target_is_connected: self.target_is_connected,+ }+ }+}++/// What an effect remembers of whether a frame can skip its style update, for a key.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PerFrameStyleUpdateSkipDecision {+ /// The effect remembers no decision.+ Unknown,+ /// The effect remembers a decision for another key.+ Stale,+ /// A frame can skip the style update of the effect.+ CanSkip,+ /// A frame cannot skip the style update of the effect.+ CannotSkip,+}++/// What became of a request that the next style update take an observation sample of an effect, at most once in a+/// task.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ObservationSampleRequest {+ /// The effect was already asked for a sample in the task.+ AlreadyRequestedInTask,+ /// The effect is asked for a sample, which it already was.+ Requested,+ /// The effect is asked for a sample, which it was not before.+ NewlyRequested,+}++/// How to reach the compositor animations of an effect.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CompositorAnimationStateAccess {+ /// Only where the effect built any before.+ Existing,+ /// Making the state where the effect has none yet.+ CreateIfMissing,+}++/// The pseudo-element an effect targets, by the host's `PseudoElement`, and its serialization.+pub(crate) struct EffectPseudoElement<'a> {+ pub(crate) kind: u8,+ pub(crate) serialization: &'a RetainedUtf16FlyString,+}++/// The state of an animation effect.+/// https://www.w3.org/TR/web-animations-1/#the-animationeffect-interface+/// https://www.w3.org/TR/web-animations-1/#the-keyframeeffect-interface+pub(crate) struct AnimationEffectRecord {+ id: AnimationEffectId,+ /// https://www.w3.org/TR/web-animations-1/#the-effecttiming-dictionaries+ specified: SpecifiedEffectTiming,+ /// The start delay, end delay and iteration duration, as normalizing the specified timing last made them.+ /// https://www.w3.org/TR/web-animations-1/#start-delay+ start_delay: TimeValue,+ /// https://www.w3.org/TR/web-animations-1/#end-delay+ end_delay: TimeValue,+ /// https://www.w3.org/TR/web-animations-1/#iteration-duration+ iteration_duration: TimeValue,+ /// The keyframes, timing function and composite operation, and what the associated animation is, which the+ /// effect keeps in its description for the style engine, whose lists of the effects of elements share it.+ description: Arc<EffectDescription>,+ /// The serialization of the value the timing function was made from, which script reads.+ timing_function_serialization: RetainedUtf16FlyString,+ /// https://www.w3.org/TR/web-animations-1/#animation-associated-effect+ /// The animation whose associated effect the effect is, if any, which keeps the effect alive.+ associated_animation: WeakAnimationHandle,+ /// https://www.w3.org/TR/web-animations-1/#effect-target-target-element+ /// The host's `DOM::Element`, which the host's effect keeps alive.+ target_element: Option<NonNull<c_void>>,+ /// The serialization of the target pseudo-selector, or none where the effect has none.+ /// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-pseudoelement+ pseudo_element_serialization: RetainedUtf16FlyString,+ /// The current iteration the effect was at when the host last dispatched its style events.+ previous_current_iteration: f64,+ /// The host's `PseudoElement` of the target pseudo-selector.+ pseudo_element_kind: u8,+ /// The phase the effect was in when the host last dispatched its style events.+ previous_phase: AnimationEffectPhase,+ /// The `EffectFlag`s set.+ flags: u8,+ /// Whether script replaced keyframes the effect took from CSS, after which it takes no more from CSS.+ ignores_css_keyframes: bool,+ /// Whether a frame can skip the style update of the effect, as the host last found it, and what from.+ per_frame_style_update_skip_decision: Option<RememberedPerFrameStyleUpdateSkipDecision>,+ /// The generation of the task in which the host last asked for an observation sample of the effect on behalf of a+ /// read of an element.+ observation_sample_task_generation: Option<u64>,+ /// What the host built of the effect for the compositor, made when it first builds anything.+ compositor_animation_state: Option<Box<CompositorAnimationEffectState>>,+}++impl AnimationEffectRecord {+ fn new() -> Self {+ let timing = AnimationEffectTiming::default();+ let id = AnimationEffectId::mint();+ Self {+ id,+ specified: SpecifiedEffectTiming::default(),+ start_delay: timing.start_delay,+ end_delay: timing.end_delay,+ iteration_duration: timing.iteration_duration,+ description: Arc::new(EffectDescription::new(id)),+ timing_function_serialization: RetainedUtf16FlyString::from_utf16(+ &"linear".encode_utf16().collect::<Vec<_>>(),+ ),+ associated_animation: WeakAnimationHandle::default(),+ target_element: None,+ pseudo_element_serialization: RetainedUtf16FlyString::none(),+ previous_current_iteration: 0.0,+ pseudo_element_kind: 0,+ previous_phase: AnimationEffectPhase::Idle,+ flags: 0,+ ignores_css_keyframes: false,+ per_frame_style_update_skip_decision: None,+ observation_sample_task_generation: None,+ compositor_animation_state: None,+ }+ }++ #[must_use]+ pub(crate) fn id(&self) -> AnimationEffectId {+ self.id+ }++ #[must_use]+ pub(crate) fn specified_timing(&self) -> &SpecifiedEffectTiming {+ &self.specified+ }++ /// Sets the specified timing, which takes effect on the start delay, end delay and iteration duration once it is+ /// normalized.+ pub(crate) fn set_specified_timing(&mut self, specified: SpecifiedEffectTiming) {+ // NB: Whether a frame can skip the style update of the effect depends on its iteration count.+ if self.specified.iteration_count.to_bits() != specified.iteration_count.to_bits() {+ self.per_frame_style_update_skip_decision = None;+ }+ self.specified = specified;+ }++ /// The timing the timing model reads of the effect.+ #[must_use]+ pub(crate) fn timing(&self) -> AnimationEffectTiming {+ AnimationEffectTiming {+ start_delay: self.start_delay,+ end_delay: self.end_delay,+ iteration_duration: self.iteration_duration,+ iteration_start: self.specified.iteration_start,+ iteration_count: self.specified.iteration_count,+ fill_mode: self.specified.fill_mode,+ playback_direction: self.specified.playback_direction,+ }+ }++ /// https://drafts.csswg.org/web-animations-2/#normalize-specified-timing+ /// Against `timeline`, the timeline of the associated animation as the animation sees it, if any.+ pub(crate) fn normalize_specified_timing(&mut self, timeline: Option<&TimelineState>) {+ let timeline_duration = timeline.and_then(TimelineState::duration_for_attachment_range);+ let timing = timing::normalize_specified_timing(&self.specified, timeline_duration, time_unit(timeline));+ self.start_delay = timing.start_delay;+ self.end_delay = timing.end_delay;+ self.iteration_duration = timing.iteration_duration;+ }++ #[must_use]+ pub(crate) fn timing_function(&self) -> &CompactEasing {+ &self.description.timing_function+ }++ #[must_use]+ pub(crate) fn timing_function_serialization(&self) -> &RetainedUtf16FlyString {+ &self.timing_function_serialization+ }++ pub(crate) fn set_timing_function(+ &mut self,+ timing_function: CompactEasing,+ serialization: RetainedUtf16FlyString,+ ) {+ self.describe().timing_function = timing_function;+ self.timing_function_serialization = serialization;+ }++ #[must_use]+ pub(crate) fn keyframes(&self) -> Option<&Arc<KeyframeSet>> {+ self.description.keyframe_set.as_ref()+ }++ /// Whether the compositor may run all the effect animates.+ #[must_use]+ pub(crate) fn may_run_on_the_compositor(&self) -> bool {+ self.keyframes()+ .is_none_or(|keyframes| keyframes.may_run_on_the_compositor())+ }++ pub(crate) fn set_keyframes(&mut self, keyframes: Option<Arc<KeyframeSet>>) {+ self.describe().keyframe_set = keyframes;+ }++ /// Whether the effect's keyframes come from CSS: from a `@keyframes` rule, or a CSS transition.+ #[must_use]+ pub(crate) fn keyframes_from_css(&self) -> bool {+ self.keyframes()+ .is_some_and(|keyframes| keyframes.origin() != KeyframeOrigin::Script)+ }++ /// Notes that script is about to set the effect's keyframes, which keeps those it replaces of CSS from coming back.+ pub(crate) fn note_keyframes_set_by_script(&mut self) {+ self.ignores_css_keyframes |= self.keyframes_from_css();+ }++ /// Whether script replaced keyframes the effect took from CSS, after which it takes no more from CSS.+ #[must_use]+ pub(crate) fn ignores_css_keyframes(&self) -> bool {+ self.ignores_css_keyframes+ }++ #[must_use]+ pub(crate) fn composite(&self) -> FfiCompositeOperation {+ self.description.composite+ }++ pub(crate) fn set_composite(&mut self, composite: FfiCompositeOperation) {+ if self.description.composite != composite {+ self.describe().composite = composite;+ }+ }++ /// The description of the effect for the style engine.+ #[must_use]+ pub(crate) fn description(&self) -> &Arc<EffectDescription> {+ &self.description+ }++ /// Sets what the associated animation is, as far as describing the effect goes, or that it has none.+ pub(crate) fn set_described_animation(&mut self, animation: EffectAnimation) {+ self.describe().animation = animation;+ }++ /// Describes the effect anew, so that whatever the style engine kept of the description before stops applying to+ /// it: interval values it retained, and preparations for sampling it.+ pub(crate) fn describe_anew(&mut self) {+ self.describe();+ }++ /// The description to change, which is a new one wherever anything but the record holds the current one.+ fn describe(&mut self) -> &mut EffectDescription {+ Arc::make_mut(&mut self.description)+ }++ /// The animation whose associated effect the effect is, if any.+ #[must_use]+ pub(crate) fn associated_animation(&self) -> Option<AnimationHandle> {+ self.associated_animation.upgrade()+ }++ /// Notes that the effect is the associated effect of `animation`, or of none, and normalizes its specified timing+ /// against `timeline`, the timeline of that animation as the animation sees it, if any.+ /// NB: The normalization of the specified timing depends on the timeline of the associated animation.+ pub(crate) fn set_associated_animation(+ &mut self,+ animation: Option<&AnimationHandle>,+ timeline: Option<&TimelineState>,+ ) {+ self.associated_animation = animation.map(AnimationHandle::downgrade).unwrap_or_default();+ self.normalize_specified_timing(timeline);+ }++ #[must_use]+ pub(crate) fn target_element(&self) -> Option<NonNull<c_void>> {+ self.target_element+ }++ pub(crate) fn set_target_element(&mut self, element: Option<NonNull<c_void>>) {+ self.target_element = element;+ // NB: What the engine kept of the description was kept for the element the effect targeted.+ self.describe_anew();+ }++ #[must_use]+ pub(crate) fn pseudo_element(&self) -> Option<EffectPseudoElement<'_>> {+ (self.pseudo_element_serialization.raw() != 0).then_some(EffectPseudoElement {+ kind: self.pseudo_element_kind,+ serialization: &self.pseudo_element_serialization,+ })+ }++ /// Sets the target pseudo-selector to the pseudo-element of the host's `PseudoElement` `kind`, serialized as+ /// `serialization`, or to none where `serialization` is none.+ pub(crate) fn set_pseudo_element(&mut self, kind: u8, serialization: RetainedUtf16FlyString) {+ self.pseudo_element_kind = kind;+ self.pseudo_element_serialization = serialization;+ // NB: What the engine kept of the description was kept for the pseudo-element the effect targeted.+ self.describe_anew();+ }++ #[must_use]+ pub(crate) fn previous_phase(&self) -> AnimationEffectPhase {+ self.previous_phase+ }++ #[must_use]+ pub(crate) fn previous_current_iteration(&self) -> f64 {+ self.previous_current_iteration+ }++ pub(crate) fn set_previous_phase(&mut self, phase: AnimationEffectPhase) {+ self.previous_phase = phase;+ }++ pub(crate) fn set_previous_current_iteration(&mut self, current_iteration: f64) {+ self.previous_current_iteration = current_iteration;+ }++ #[must_use]+ pub(crate) fn has_flag(&self, flag: EffectFlag) -> bool {+ self.flags & flag as u8 != 0+ }++ /// Sets or clears `flag`, answering whether that changed it.+ pub(crate) fn set_flag(&mut self, flag: EffectFlag, value: bool) -> bool {+ let flags = if value {+ self.flags | flag as u8+ } else {+ self.flags & !(flag as u8)+ };+ let changed = std::mem::replace(&mut self.flags, flags) != flags;+ if changed && flag.decides_per_frame_style_update_skip() {+ self.per_frame_style_update_skip_decision = None;+ }+ changed+ }++ /// What the effect remembers of whether a frame can skip its style update, for `key`.+ #[must_use]+ pub(crate) fn per_frame_style_update_skip_decision(+ &self,+ key: &PerFrameStyleUpdateSkipKey,+ ) -> PerFrameStyleUpdateSkipDecision {+ match &self.per_frame_style_update_skip_decision {+ None => PerFrameStyleUpdateSkipDecision::Unknown,+ Some(decision) if decision.key() != *key => PerFrameStyleUpdateSkipDecision::Stale,+ Some(decision) if decision.can_skip => PerFrameStyleUpdateSkipDecision::CanSkip,+ Some(_) => PerFrameStyleUpdateSkipDecision::CannotSkip,+ }+ }++ /// Remembers whether a frame can skip the style update of the effect, as the host found it from `key`.+ pub(crate) fn note_per_frame_style_update_skip_decision(+ &mut self,+ key: PerFrameStyleUpdateSkipKey,+ can_skip: bool,+ ) {+ self.per_frame_style_update_skip_decision = Some(RememberedPerFrameStyleUpdateSkipDecision {+ target_style_generation: key.target_style_generation,+ target_subtree_style_generation: key.target_subtree_style_generation,+ layout_node: key.layout_node,+ target_is_connected: key.target_is_connected,+ can_skip,+ });+ }++ /// Asks the next style update for an observation sample of the effect on behalf of a read of an element in the+ /// task of generation `task_generation`, unless the effect was already asked for one in that task.+ pub(crate) fn request_observation_sample_in_task(&mut self, task_generation: u64) -> ObservationSampleRequest {+ if self.observation_sample_task_generation == Some(task_generation) {+ return ObservationSampleRequest::AlreadyRequestedInTask;+ }+ self.observation_sample_task_generation = Some(task_generation);+ if self.set_flag(EffectFlag::NeedsObservationSample, true) {+ ObservationSampleRequest::NewlyRequested+ } else {+ ObservationSampleRequest::Requested+ }+ }++ /// What the host built of the effect for the compositor, reached as `access` says.+ pub(crate) fn compositor_animation_state(+ &mut self,+ access: CompositorAnimationStateAccess,+ ) -> Option<&mut CompositorAnimationEffectState> {+ if access == CompositorAnimationStateAccess::CreateIfMissing {+ self.compositor_animation_state.get_or_insert_default();+ }+ self.compositor_animation_state.as_deref_mut()+ }++ /// Forgets what the host concluded of the effect as it was, since the effect changed: what it built for the+ /// compositor from the keyframes, how it ran or throttled the effect, and whether a frame can skip its style update.+ pub(crate) fn forget_what_the_host_concluded(&mut self) {+ if let Some(state) = &mut self.compositor_animation_state {+ state.reset();+ }+ for flag in [+ EffectFlag::CompositorDriven,+ EffectFlag::CompositorReplaced,+ EffectFlag::OffscreenThrottled,+ EffectFlag::ObservationRelevantCompositorAnimation,+ ] {+ self.set_flag(flag, false);+ }+ self.per_frame_style_update_skip_decision = None;+ }+}++/// An animation effect's record, which every handle to the effect shares, and the host's `AnimationEffect` of it.+pub struct AnimationEffectCell {+ record: RefCell<AnimationEffectRecord>,+ /// The host's `AnimationEffect`, which holds a reference to the record until it is finalized and clears this as it+ /// does.+ facade: Cell<Option<NonNull<c_void>>>,+}++impl AnimationEffectCell {+ pub(crate) fn borrow(&self) -> Ref<'_, AnimationEffectRecord> {+ self.record.borrow()+ }++ pub(crate) fn borrow_mut(&self) -> RefMut<'_, AnimationEffectRecord> {+ self.record.borrow_mut()+ }++ /// The host's `AnimationEffect` of the effect, while it is alive.+ pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {+ self.facade.get()+ }++ pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.facade.set(facade);+ }++ /// Whether the host may reach the effect and the element it targets: while the object script sees of it is, or,+ /// for an effect without one, while its associated animation is.+ pub(crate) fn is_alive(&self) -> bool {+ if self.facade().is_some() {+ return true;+ }+ let animation = self.borrow().associated_animation();+ animation.is_some_and(|animation| animation.is_alive())+ }++ /// The bytes of the allocation every handle shares. The description the record holds counts toward the style+ /// engine's descriptions of the effects of elements, which share it.+ pub(crate) fn memory_size(&self) -> usize {+ 2 * size_of::<usize>() + size_of::<Self>()+ }+}++/// A strong reference to an animation effect.+#[derive(Clone)]+pub(crate) struct EffectHandle(Rc<AnimationEffectCell>);++impl EffectHandle {+ /// A new effect with the default timing, no keyframes and no target.+ pub(crate) fn new() -> Self {+ Self(Rc::new(AnimationEffectCell {+ record: RefCell::new(AnimationEffectRecord::new()),+ facade: Cell::new(None),+ }))+ }++ /// Whether both handles are to the same effect.+ pub(crate) fn ptr_eq(&self, other: &Self) -> bool {+ Rc::ptr_eq(&self.0, &other.0)+ }++ /// Hands the reference to the host, which gives it back to `from_raw`.+ pub(crate) fn into_raw(self) -> *const AnimationEffectCell {+ Rc::into_raw(self.0)+ }++ /// Takes a reference of its own to an effect the host holds a reference to.+ ///+ /// # Safety+ /// `cell` must be an effect the host holds a reference to.+ pub(crate) unsafe fn retained_from_host(cell: *const AnimationEffectCell) -> Self {+ // SAFETY: Guaranteed by the caller.+ unsafe {+ Rc::increment_strong_count(cell);+ Self(Rc::from_raw(cell))+ }+ }++ /// Takes back a reference the host was handed.+ ///+ /// # Safety+ /// `cell` must be a reference `into_raw` handed out, which the host gives up.+ pub(crate) unsafe fn from_raw(cell: *const AnimationEffectCell) -> Self {+ // SAFETY: Guaranteed by the caller.+ Self(unsafe { Rc::from_raw(cell) })+ }+}++/// A set of effects that keeps none of them alive.+///+/// NB: An effect that is no longer alive to the host is dead to the set, though what else holds its record may only let+/// go of it as the host sweeps what holds it, so that the host never meets an effect it finalized.+pub struct WeakEffectSet(WeakRecordSet<AnimationEffectCell>);++impl Default for WeakEffectSet {+ fn default() -> Self {+ Self(WeakRecordSet::new(AnimationEffectCell::is_alive))+ }+}++impl WeakEffectSet {+ /// Adds `effect` to the set, answering whether the set did not hold it yet.+ pub(crate) fn insert(&mut self, effect: &EffectHandle) -> bool {+ self.0.insert(&effect.0)+ }++ /// Removes `effect` from the set, answering whether the set held it.+ pub(crate) fn remove(&mut self, effect: &AnimationEffectCell) -> bool {+ self.0.remove(effect)+ }++ /// Whether the set holds `effect`.+ pub(crate) fn contains(&self, effect: &AnimationEffectCell) -> bool {+ self.0.contains(effect)+ }++ /// Empties the set, calling `callback` with each effect alive to it, in insertion order.+ pub(crate) fn take_each(&mut self, mut callback: impl FnMut(&EffectHandle)) {+ self.0.take_each(|effect| callback(&EffectHandle(effect)));+ }+}++impl PartialEq for EffectHandle {+ fn eq(&self, other: &Self) -> bool {+ self.ptr_eq(other)+ }+}++impl std::fmt::Debug for EffectHandle {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_tuple("EffectHandle")+ .field(&self.borrow().id())+ .finish()+ }+}++impl std::ops::Deref for EffectHandle {+ type Target = AnimationEffectCell;++ fn deref(&self) -> &AnimationEffectCell {+ &self.0+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/element_animations.rs b/Libraries/LibWeb/Rust/src/animations/element_animations.rsnew file mode 100644index 00000000000..f63f8d13d4b--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/element_animations.rs@@ -0,0 +1,419 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The animations of an element: those associated with it, the CSS animations and transitions it and its+//! pseudo-elements own, and the descriptions of the effects of each it last published to the style engine. The lists+//! publish what the style engine reads of them to the engine the host names as it changes them.+//! https://www.w3.org/TR/web-animations-1/#the-animatable-interface-mixin++use super::animation::{AnimationCell, AnimationHandle, AnimationRecord, HostCellKind, SmilHolder};+use super::composite_order::{TreeOrder, composite_order};+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style::animations::CssDefinedAnimation;+use crate::css::style::effect_descriptions::EffectDescription;+use crate::css::style::engine_calls::EngineWrite;+use crate::css::style::tree::StyleNodeID;+use crate::heap_size::small_vec_bytes;+use crate::render_state::{ArenaChange, DocumentHost};+use smallvec::SmallVec;+use std::cmp::Ordering;+use std::ffi::c_void;+use std::ptr::NonNull;+use std::sync::Arc;++/// The element or one of its pseudo-elements, as one of the lists of the CSS animations and transitions it owns, and of+/// the effects that target it: 0 for the element, and the host's `PseudoElement` plus one for a pseudo-element.+#[repr(transparent)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct AnimationOwnerSlot(pub u8);++/// The style engine that reads an element's lists, by the document host the host names it by and the element's identity+/// in it, as the host passes them each time it changes the lists, since the element's identity there changes over its+/// life and the lists follow the element from document to document.+#[derive(Clone, Copy)]+pub(crate) struct StyleEngineTarget<'a> {+ pub(crate) host: &'a DocumentHost,+ pub(crate) node: StyleNodeID,+}++/// The property a CSS transition runs: the host's `PropertyID` of a longhand, or the raw fly string of a custom+/// property's name where it is not zero.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct TransitionProperty {+ pub(crate) property_id: u16,+ pub(crate) custom_name: usize,+}++impl TransitionProperty {+ fn of(animation: &AnimationRecord) -> Self {+ let state = animation.css_transition();+ Self {+ property_id: state.property_id,+ custom_name: state.custom_property_name.raw(),+ }+ }+}++/// The CSS animations and transitions of one owner, and the effects that target it as the style engine has them.+struct OwnedAnimations {+ slot: AnimationOwnerSlot,+ /// The CSS animations, in the order of the owner's `animation-name`.+ css_animations: SmallVec<[AnimationHandle; 1]>,+ /// The running or completed transition of each property, which runs no other.+ transitions: SmallVec<[AnimationHandle; 1]>,+ /// The descriptions of the effects that target the owner, in composite order, as the host last published them to+ /// the style engine.+ published_effects: Box<[Arc<EffectDescription>]>,+}++impl OwnedAnimations {+ fn is_empty(&self) -> bool {+ self.css_animations.is_empty() && self.transitions.is_empty() && self.published_effects.is_empty()+ }+}++/// The animations of an element, which holds them strongly.+#[derive(Default)]+pub struct ElementAnimations {+ /// The animations whose effects target the element or one of its pseudo-elements.+ associated: SmallVec<[AnimationHandle; 1]>,+ /// The lists of the owners that own any CSS animation or transition.+ owners: SmallVec<[OwnedAnimations; 1]>,+ /// Whether `associated` is in composite order.+ is_sorted_by_composite_order: bool,+ /// Whether any owner has had a CSS animation since the element last cancelled them all.+ has_css_defined_animations: bool,+}++impl Drop for ElementAnimations {+ fn drop(&mut self) {+ for animation in &self.associated {+ animation.note_smil_holder(SmilHolder::TargetList, false);+ }+ }+}++impl ElementAnimations {+ fn owner(&self, slot: AnimationOwnerSlot) -> Option<&OwnedAnimations> {+ self.owners.iter().find(|owner| owner.slot == slot)+ }++ fn ensure_owner(&mut self, slot: AnimationOwnerSlot) -> &mut OwnedAnimations {+ let index = match self.owners.iter().position(|owner| owner.slot == slot) {+ Some(index) => index,+ None => {+ self.owners.push(OwnedAnimations {+ slot,+ css_animations: SmallVec::new(),+ transitions: SmallVec::new(),+ published_effects: Box::default(),+ });+ self.owners.len() - 1+ }+ };+ &mut self.owners[index]+ }++ fn remove_empty_owners(&mut self) {+ self.owners.retain(|owner| !owner.is_empty());+ }++ /// Associates `animation` with the element, answering whether it was not associated yet.+ pub(crate) fn associate(&mut self, animation: AnimationHandle) -> bool {+ if self.associated.iter().any(|associated| associated.ptr_eq(&animation)) {+ return false;+ }+ animation.note_smil_holder(SmilHolder::TargetList, true);+ self.associated.push(animation);+ self.is_sorted_by_composite_order = false;+ true+ }++ /// Disassociates `animation` from the element, answering whether it was associated.+ pub(crate) fn disassociate(&mut self, animation: &AnimationCell) -> bool {+ self.is_sorted_by_composite_order = false;+ let Some(index) = self.associated.iter().position(|associated| associated.is(animation)) else {+ return false;+ };+ self.associated+ .remove(index)+ .note_smil_holder(SmilHolder::TargetList, false);+ true+ }++ pub(crate) fn associated(&self) -> &[AnimationHandle] {+ &self.associated+ }++ pub(crate) fn invalidate_composite_order(&mut self) {+ self.is_sorted_by_composite_order = false;+ }++ /// Sorts the associated animations in composite order, with `tree_order` comparing elements in tree order.+ pub(crate) fn sort_in_composite_order(&mut self, tree_order: &mut impl TreeOrder) {+ if self.is_sorted_by_composite_order {+ return;+ }+ // NB: An animation without an effect has no place in an effect stack, and sorts first by its position in the+ // global animation list.+ self.associated.sort_by(|a, b| {+ let (a, b) = (a.borrow(), b.borrow());+ match (a.effect().is_some(), b.effect().is_some()) {+ (true, true) => composite_order(&a, &b, tree_order),+ (false, true) => Ordering::Less,+ (true, false) => Ordering::Greater,+ (false, false) => a.global_animation_list_order().cmp(&b.global_animation_list_order()),+ }+ });+ self.is_sorted_by_composite_order = true;+ }++ /// The CSS animations of the first owner after `slot`, or of the first owner without one, by the order of their+ /// slots, which is the element's and then each pseudo-element's in the order of the host's `PseudoElement`.+ pub(crate) fn css_animations_after(+ &self,+ slot: Option<AnimationOwnerSlot>,+ ) -> Option<(AnimationOwnerSlot, SmallVec<[AnimationHandle; 1]>)> {+ self.owners+ .iter()+ .filter(|owner| slot.is_none_or(|slot| owner.slot.0 > slot.0) && !owner.css_animations.is_empty())+ .min_by_key(|owner| owner.slot.0)+ .map(|owner| (owner.slot, owner.css_animations.clone()))+ }++ pub(crate) fn css_animations(&self, slot: AnimationOwnerSlot) -> &[AnimationHandle] {+ self.owner(slot).map_or(&[], |owner| &owner.css_animations)+ }++ /// Sets the CSS animations of the owner at `slot`, and publishes them to `engine`, if any, where the owner had or+ /// now has any.+ pub(crate) fn set_css_animations(+ &mut self,+ slot: AnimationOwnerSlot,+ animations: impl ExactSizeIterator<Item = AnimationHandle>,+ engine: Option<StyleEngineTarget<'_>>,+ ) {+ // NB: The flag says the element has animations to play or cancel, not that it has been through the step that+ // would have registered some. It stays set once any list is non-empty, since the lists are per owner and+ // this is one flag for all of them.+ if animations.len() != 0 {+ self.has_css_defined_animations = true;+ }+ let owner = self.ensure_owner(slot);+ let had_animations = !owner.css_animations.is_empty();+ let animations: SmallVec<[AnimationHandle; 1]> = animations.collect();+ // https://drafts.csswg.org/css-animations-1/#animations+ // Once an animation has started it continues until it ends or the animation-name is removed+ // NB: An animation removed from its owning element no longer follows its named timeline.+ for removed in &owner.css_animations {+ if !animations.iter().any(|animation| animation.ptr_eq(removed)) {+ removed.borrow_mut().css_animation_mut().named_timeline = RetainedUtf16FlyString::none();+ }+ }+ owner.css_animations = animations;+ let publishes = had_animations || !owner.css_animations.is_empty();+ self.remove_empty_owners();+ if publishes && let Some(engine) = engine {+ publish_css_defined_animations(engine, slot, self.css_animations(slot));+ }+ }++ pub(crate) fn has_css_animations_or_transitions(&self) -> bool {+ self.has_css_defined_animations || self.owners.iter().any(|owner| !owner.transitions.is_empty())+ }++ pub(crate) fn transitions(&self, slot: AnimationOwnerSlot) -> &[AnimationHandle] {+ self.owner(slot).map_or(&[], |owner| &owner.transitions)+ }++ /// The running or completed transition of `property` the owner at `slot` has, if any.+ pub(crate) fn transition(+ &self,+ slot: AnimationOwnerSlot,+ property: TransitionProperty,+ ) -> Option<&AnimationHandle> {+ self.transitions(slot)+ .iter()+ .find(|transition| TransitionProperty::of(&transition.borrow()) == property)+ }++ /// Gives the owner at `slot` the transition `transition` of a property it has no transition of.+ pub(crate) fn add_transition(&mut self, slot: AnimationOwnerSlot, transition: AnimationHandle) {+ let property = TransitionProperty::of(&transition.borrow());+ assert!(+ self.transition(slot, property).is_none(),+ "the owner has no transition of the property yet"+ );+ self.ensure_owner(slot).transitions.push(transition);+ }++ /// Removes the transition of `property` the owner at `slot` has, which is disassociated from its target once it is+ /// inert.+ pub(crate) fn remove_transition(&mut self, slot: AnimationOwnerSlot, property: TransitionProperty) {+ let owner = self.ensure_owner(slot);+ let index = owner+ .transitions+ .iter()+ .position(|transition| TransitionProperty::of(&transition.borrow()) == property)+ .expect("the owner has a transition of the property");+ let transition = owner.transitions.remove(index);+ self.remove_empty_owners();+ transition.borrow_mut().set_disassociation_from_target_pending(true);+ }++ /// Takes the CSS animations and transitions of every owner, answering them, and publishes to `engine`, if any, that+ /// the owners that had CSS animations have none.+ pub(crate) fn take_css_animations_and_transitions(+ &mut self,+ engine: Option<StyleEngineTarget<'_>>,+ ) -> Vec<AnimationHandle> {+ let mut animations = Vec::new();+ for owner in &mut self.owners {+ if !owner.css_animations.is_empty()+ && let Some(engine) = engine+ {+ publish_css_defined_animations(engine, owner.slot, &[]);+ }+ // NB: An animation removed from its owning element no longer follows its named timeline.+ for animation in std::mem::take(&mut owner.css_animations) {+ animation.borrow_mut().css_animation_mut().named_timeline = RetainedUtf16FlyString::none();+ animations.push(animation);+ }+ animations.extend(std::mem::take(&mut owner.transitions));+ }+ self.remove_empty_owners();+ self.has_css_defined_animations = false;+ animations+ }++ /// Notes that the host publishes `descriptions` as the effects that target the owner at `slot`, answering whether+ /// that publishes anything the style engine does not have: whether they differ, description by description, from+ /// what the host last published for it.+ pub(crate) fn publish_effect_descriptions(+ &mut self,+ slot: AnimationOwnerSlot,+ descriptions: &[Arc<EffectDescription>],+ ) -> bool {+ let published = self.owner(slot).map_or(&[][..], |owner| &owner.published_effects);+ if published.len() == descriptions.len()+ && published+ .iter()+ .zip(descriptions)+ .all(|(published, description)| Arc::ptr_eq(published, description))+ {+ return false;+ }+ self.ensure_owner(slot).published_effects = descriptions.into();+ self.remove_empty_owners();+ true+ }++ /// Forgets what the host published to the style engine, whose lists of the element's effects are those of the+ /// identity the element no longer has.+ pub(crate) fn forget_published_effect_descriptions(&mut self) {+ for owner in &mut self.owners {+ owner.published_effects = Box::default();+ }+ self.remove_empty_owners();+ }++ /// Calls `visit` with each GC cell of the host that keeps alive what an animation in the lists names.+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ let owned = self+ .owners+ .iter()+ .flat_map(|owner| owner.css_animations.iter().chain(&owner.transitions));+ for animation in self.associated.iter().chain(owned) {+ animation.for_each_host_cell(&mut visit);+ }+ }++ /// The bytes of the lists, without the animations and the descriptions of their effects.+ pub(crate) fn memory_size(&self) -> usize {+ size_of::<Self>()+ + small_vec_bytes(&self.associated)+ + small_vec_bytes(&self.owners)+ + self+ .owners+ .iter()+ .map(|owner| {+ small_vec_bytes(&owner.css_animations)+ + small_vec_bytes(&owner.transitions)+ + size_of_val::<[Arc<EffectDescription>]>(&owner.published_effects)+ })+ .sum::<usize>()+ }+}++/// Publishes `animations` to `engine` as the CSS animations the owner at `slot` holds, in its order: the name of each and+/// the definition last applied to it, which the computation of the owner's animation definitions matches its+/// definitions against.+fn publish_css_defined_animations(+ engine: StyleEngineTarget<'_>,+ slot: AnimationOwnerSlot,+ animations: &[AnimationHandle],+) {+ engine+ .host+ .queue_change(ArenaChange::Engine(EngineWrite::CssDefinedAnimations {+ node: engine.node,+ slot: slot.0,+ animations: animations+ .iter()+ .map(|animation| CssDefinedAnimation::of(animation))+ .collect(),+ }));+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::animations::animation::AnimationKind;++ fn by_address(first: NonNull<c_void>, second: NonNull<c_void>) -> Ordering {+ first.cmp(&second)+ }++ #[test]+ fn an_animation_is_associated_once() {+ let mut animations = ElementAnimations::default();+ let animation = AnimationHandle::new(AnimationKind::Script);+ assert!(animations.associate(animation.clone()));+ assert!(!animations.associate(animation.clone()));+ assert_eq!(animations.associated().len(), 1);+ assert!(animations.disassociate(&animation));+ assert!(!animations.disassociate(&animation));+ assert!(animations.associated().is_empty());+ }++ #[test]+ fn animations_without_an_effect_sort_first_in_creation_order() {+ let mut animations = ElementAnimations::default();+ let first = AnimationHandle::new(AnimationKind::Script);+ let second = AnimationHandle::new(AnimationKind::Script);+ animations.associate(second.clone());+ animations.associate(first.clone());+ animations.sort_in_composite_order(&mut by_address);+ assert!(animations.associated()[0].ptr_eq(&first));+ assert!(animations.associated()[1].ptr_eq(&second));+ }++ #[test]+ fn cancelling_css_animations_clears_what_the_element_had() {+ let mut animations = ElementAnimations::default();+ let slot = AnimationOwnerSlot(3);+ // SAFETY: The test takes over the one reference to the new animation.+ let animation = unsafe { AnimationHandle::from_raw(super::super::ffi::animations_css_animation_create()) };+ animations.set_css_animations(slot, [animation].into_iter(), None);+ assert_eq!(animations.css_animations(slot).len(), 1);+ assert!(animations.css_animations(AnimationOwnerSlot(0)).is_empty());+ animations.set_css_animations(slot, std::iter::empty(), None);+ assert!(animations.css_animations(slot).is_empty());+ assert!(animations.has_css_animations_or_transitions());+ assert!(animations.take_css_animations_and_transitions(None).is_empty());+ assert!(!animations.has_css_animations_or_transitions());+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/ffi.rs b/Libraries/LibWeb/Rust/src/animations/ffi.rsindex abb30e63c65..6dcc891d3e2 100644--- a/Libraries/LibWeb/Rust/src/animations/ffi.rs+++ b/Libraries/LibWeb/Rust/src/animations/ffi.rs@@ -6,22 +6,56 @@//! The C ABI through which the C++ animation classes reach the timing model, until they move to Rust.+use super::animation::{+ AnimationCell, AnimationHandle, AnimationKind, AttachmentRangeEdge, AttachmentRangeEdgeOffset,+ CSS_ANIMATION_PLAY_STATE_PAUSED, CSS_ANIMATION_PLAY_STATE_RUNNING, CSS_TRANSITION_PHASE_IDLE, CssAnimationFlag,+ CssAnimationState, CssTransitionState, HostCellKind, HostTaskId, OwningElement, SmilHolder, WeakAnimationSet,+};+use super::clock_plan::ClockPlanAnimation;+use super::composite_order::composite_order;+use super::document_animations::{DocumentAnimationSetKind, DocumentAnimations, DocumentEffectSetKind};+use super::easing::CompactEasing;+use super::effect::{+ AnimationEffectCell, AnimationEffectId, CompositorAnimationStateAccess, EffectFlag, EffectHandle,+ ObservationSampleRequest, PerFrameStyleUpdateSkipDecision, PerFrameStyleUpdateSkipKey,+};+use super::element_animations::{AnimationOwnerSlot, ElementAnimations, StyleEngineTarget, TransitionProperty};+use super::host_effects::{HostEffectKind, HostEffects, PlaybackEventType};+use super::host_timing::{FfiAnimationKind, FfiAnimationTimingState};+use super::keyframes::{+ CompositeOperationOrAuto, KeyframeOrigin, KeyframeProperty, KeyframeSet, KeyframeValue, ProcessedKeyframe,+ ResourceContext,+};+use super::pending_animation_events::{+ FfiPendingAnimationEvent, PendingAnimationEvent, PendingAnimationEventKind, TimeEventType,+};+use super::procedures::{self, AnimationError, DidSeek, Invalidate, Procedures, SynchronouslyNotify};+use super::snapshot::TimelineClock;+use super::timeline::{+ AnimationTimelineId, ScrollNodeStableId, ScrollTimelineBoxes, ScrollTimelineSource, ScrollTimelineState,+ TimelineCell, TimelineHandle, TimelineKind, TimelineUpdate, ViewTimelineInset, ViewTimelineInsetEdge,+ ViewTimelineState,+};use super::timing::{- self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, OptionalNumber,- OptionalTimeValue, SpecifiedEffectTiming, TimeValue, TimeValueType, TimelineSample,+ self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, FillMode, OptionalNumber,+ OptionalTimeValue, SpecifiedEffectTiming, TimeValue, 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)-}+use super::transitions::{self, LaneAdoption, ProvisionalTransitionTiming, TransitionOrigin};+use crate::css::animation::FfiCompositeOperation;+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style::animations::AppliedAnimationDefinition;+use crate::css::style::tree::StyleNodeID;+use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};+use crate::css::transition::{FfiExistingTransition, FfiLaneTransition};+use crate::layout::node_data::NodeSlotId;+use crate::painting::visual_animation_builder::CompositorAnimationEffectState;+use crate::render_state::{BegunRead, DocumentHost};+use libcompositing_rust::easing::{Easing, FfiEasingDescriptor, evaluate_easing_descriptor};+use std::cmp::Ordering;+use std::ffi::c_void;+use std::num::NonZeroU64;+use std::ptr::NonNull;+use std::sync::Arc;/// The timing of an effect at one local time, and what follows from its timing alone.#[repr(C)]@@ -31,7 +65,7 @@ pub struct FfiResolvedEffectTiming {pub active_time: OptionalTimeValue,pub overall_progress: OptionalNumber,pub current_iteration: OptionalNumber,- /// Unresolved where no timing function was given.+ /// Unresolved where it was not asked for.pub transformed_progress: OptionalNumber,pub is_current: bool,pub is_in_effect: bool,@@ -41,84 +75,2886 @@ pub struct FfiResolvedEffectTiming {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.+/// The timing of `effect` at `local_time` with `fill_mode` as its fill mode, associated with `animation`, if any, on+/// its timeline, if it has one, and with its transformed progress through its timing function where+/// `with_transformed_progress`.#[unsafe(no_mangle)]-pub unsafe extern "C" fn animations_resolve_effect_timing(- timing: &AnimationEffectTiming,+pub extern "C" fn animations_effect_resolve_timing(+ effect: &AnimationEffectCell,local_time: OptionalTimeValue,- animation: Option<&AnimationPlayback>,- timeline: Option<&TimelineSample>,- timing_function: Option<&FfiEasingDescriptor>,- endpoint_inclusive: bool,+ fill_mode: FillMode,+ animation: Option<&AnimationCell>,+ with_transformed_progress: 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)+ let timeline = animation.and_then(timeline_sample_of);+ let timeline = timeline.as_ref();+ let animation = animation.map(|animation| *animation.borrow().playback());+ let animation = animation.as_ref();+ let effect = effect.borrow();+ let timing = AnimationEffectTiming {+ fill_mode,+ ..effect.timing()+ };+ let resolved = timing::resolve_timing(&timing, local_time.get(), animation, timeline);+ let transformed_progress = with_transformed_progress+ .then(|| {+ let timing_function = effect.timing_function().descriptor();+ timing::transformed_progress_with(&timing, &resolved, |input_progress, before_flag| {+ evaluate_easing_descriptor(&timing_function, input_progress, before_flag)+ })})- });+ .flatten();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(),+ current_iteration: timing::current_iteration(&timing, &resolved).into(),transformed_progress: transformed_progress.into(),- is_current: timing::is_current(timing, resolved.phase, animation, timeline),+ 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),+ 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.+/// What the timing model reads of the timeline of `animation` now, if it has one.+fn timeline_sample_of(animation: &AnimationCell) -> Option<TimelineSample> {+ animation.borrow().timeline().map(|timeline| timeline.sample())+}++/// Whether `animation`, on its timeline, if it has one, is relevant, with its associated effect, if any, at the local+/// time `local_time`.#[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()+pub extern "C" fn animations_is_relevant(animation: &AnimationCell, local_time: OptionalTimeValue) -> bool {+ let timeline = timeline_sample_of(animation);+ let timeline = timeline.as_ref();+ let animation = animation.borrow();+ let effect_timing = animation.effect().map(|effect| effect.borrow().timing());+ timing::is_relevant(animation.playback(), timeline, effect_timing.as_ref(), local_time.get())+}++/// What a procedure threw, as the host throws it: nothing, an "InvalidStateError" DOMException, or a TypeError, with+/// its message.+#[repr(C)]+pub struct FfiAnimationError {+ pub kind: FfiAnimationErrorKind,+ pub message: *const u8,+ pub message_length: usize,+}++#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum FfiAnimationErrorKind {+ None,+ InvalidState,+ TypeError,+}++impl From<Result<(), AnimationError>> for FfiAnimationError {+ fn from(result: Result<(), AnimationError>) -> Self {+ let (kind, message) = match result {+ Ok(()) => (FfiAnimationErrorKind::None, ""),+ Err(AnimationError::InvalidState(message)) => (FfiAnimationErrorKind::InvalidState, message),+ Err(AnimationError::TypeError(message)) => (FfiAnimationErrorKind::TypeError, message),+ };+ Self {+ kind,+ message: message.as_ptr(),+ message_length: message.len(),+ }+ }+}++/// One thing a procedure asks the host to do for the animation `animation`, and what it needs to do it.+#[repr(C)]+pub struct FfiHostEffect {+ pub animation: NonNull<AnimationCell>,+ pub kind: FfiHostEffectKind,+ /// For `QueuePlaybackEvent`.+ pub playback_event_type: PlaybackEventType,+ /// For `InvalidateEffect`.+ pub changes_plan: bool,+ /// For `InvalidateUnlessThrottled`.+ pub invalidate: bool,+ /// For `QueuePlaybackEvent`.+ pub current_time: OptionalTimeValue,+ pub timeline_time: OptionalTimeValue,+ pub scheduled_timeline_time: OptionalTimeValue,+ /// For `ScheduleWakeup`, in milliseconds.+ pub delay: f64,+ /// For `CancelFinishNotificationTask`, the host's identity of the task to cancel.+ pub task: u64,+ /// For `AssociateWithTarget` and `DisassociateFromTarget`, the host's `DOM::Element`.+ pub element: *mut c_void,+ /// For `DisassociateFromTarget` and `RecomputeEffectStyle`, the effect, which lives as long as the host performs+ /// this.+ pub effect: *const AnimationEffectCell,+}++/// What a procedure asks the host to do, as `HostEffectKind` describes it.+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum FfiHostEffectKind {+ ReplaceReadyPromise,+ ResolveReadyPromise,+ RejectReadyPromise,+ ReplaceFinishedPromise,+ ResolveFinishedPromise,+ RejectFinishedPromise,+ QueueFinishNotificationTask,+ CancelFinishNotificationTask,+ QueuePlaybackEvent,+ InvalidateEffect,+ InvalidateUnlessThrottled,+ AssociateWithTarget,+ DisassociateFromTarget,+ RecomputeEffectStyle,+ RequestRepaint,+ ScheduleWakeup,+}++impl FfiHostEffect {+ fn new(animation: &AnimationHandle, kind: &HostEffectKind, task: Option<HostTaskId>) -> Self {+ let mut effect = Self {+ animation: NonNull::from(&**animation),+ kind: FfiHostEffectKind::ReplaceReadyPromise,+ playback_event_type: PlaybackEventType::Finish,+ changes_plan: false,+ invalidate: false,+ current_time: OptionalTimeValue::UNRESOLVED,+ timeline_time: OptionalTimeValue::UNRESOLVED,+ scheduled_timeline_time: OptionalTimeValue::UNRESOLVED,+ delay: 0.0,+ task: task.map_or(0, |task| task.0.get()),+ element: std::ptr::null_mut(),+ effect: std::ptr::null(),+ };+ effect.kind = match *kind {+ HostEffectKind::ReplaceReadyPromise => FfiHostEffectKind::ReplaceReadyPromise,+ HostEffectKind::ResolveReadyPromise => FfiHostEffectKind::ResolveReadyPromise,+ HostEffectKind::RejectReadyPromise => FfiHostEffectKind::RejectReadyPromise,+ HostEffectKind::ReplaceFinishedPromise => FfiHostEffectKind::ReplaceFinishedPromise,+ HostEffectKind::ResolveFinishedPromise => FfiHostEffectKind::ResolveFinishedPromise,+ HostEffectKind::RejectFinishedPromise => FfiHostEffectKind::RejectFinishedPromise,+ HostEffectKind::QueueFinishNotificationTask => FfiHostEffectKind::QueueFinishNotificationTask,+ HostEffectKind::CancelFinishNotificationTask => FfiHostEffectKind::CancelFinishNotificationTask,+ HostEffectKind::QueuePlaybackEvent {+ r#type,+ current_time,+ timeline_time,+ scheduled_timeline_time,+ } => {+ effect.playback_event_type = r#type;+ effect.current_time = current_time.into();+ effect.timeline_time = timeline_time.into();+ effect.scheduled_timeline_time = scheduled_timeline_time.into();+ FfiHostEffectKind::QueuePlaybackEvent+ }+ HostEffectKind::InvalidateEffect { changes_plan } => {+ effect.changes_plan = changes_plan;+ FfiHostEffectKind::InvalidateEffect+ }+ HostEffectKind::InvalidateUnlessThrottled { invalidate } => {+ effect.invalidate = invalidate;+ FfiHostEffectKind::InvalidateUnlessThrottled+ }+ HostEffectKind::AssociateWithTarget { element } => {+ effect.element = element.as_ptr();+ FfiHostEffectKind::AssociateWithTarget+ }+ HostEffectKind::DisassociateFromTarget {+ element,+ effect: ref animation_effect,+ } => {+ effect.element = element.as_ptr();+ effect.effect = &raw const **animation_effect;+ FfiHostEffectKind::DisassociateFromTarget+ }+ HostEffectKind::RecomputeEffectStyle {+ effect: ref animation_effect,+ } => {+ effect.effect = &raw const **animation_effect;+ FfiHostEffectKind::RecomputeEffectStyle+ }+ HostEffectKind::RequestRepaint => FfiHostEffectKind::RequestRepaint,+ HostEffectKind::ScheduleWakeup { delay } => {+ effect.delay = delay;+ FfiHostEffectKind::ScheduleWakeup+ }+ };+ effect+ }+}++/// The host's function that performs what a procedure asks of it.+pub type HostEffectPerformer = extern "C" fn(effect: &FfiHostEffect);++/// Runs `procedure` on `animation` and then has the host perform what it asked for through `perform`, in order, holding+/// no borrow of any record.+fn run_procedure(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+ procedure: impl FnOnce(&mut Procedures<'_>) -> Result<(), AnimationError>,+) -> FfiAnimationError {+ run_procedure_on(animation, perform, procedure).into()+}++/// Runs `procedure` on `animation` and then has the host perform what it asked for through `perform`, in order, holding+/// no borrow of any record.+pub(crate) fn run_procedure_on(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+ procedure: impl FnOnce(&mut Procedures<'_>) -> Result<(), AnimationError>,+) -> Result<(), AnimationError> {+ // SAFETY: The host holds a reference to every animation it runs a procedure on.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ let ((), effects) = procedures::run(&animation, procedure)?;+ perform_host_effects(effects, perform);+ Ok(())+}++/// Has the host perform `effects` through `perform`, in order, holding no borrow of any record.+fn perform_host_effects(effects: HostEffects, perform: HostEffectPerformer) {+ for (animation, kind) in effects {+ // NB: A procedure may name an animation that is no longer alive to the host, whose record the host only lets go+ // of as it sweeps.+ if !animation.is_alive() {+ continue;+ }+ // NB: The record keeps the task the host queued, which the host then neither queues again nor cancels without.+ let task = animation.borrow().finish_notification_task();+ match kind {+ HostEffectKind::QueueFinishNotificationTask if task.is_some() => continue,+ HostEffectKind::CancelFinishNotificationTask if task.is_none() => continue,+ _ => {}+ }+ perform(&FfiHostEffect::new(&animation, &kind, task));+ }}-/// 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`.+/// Notes `task`, the host's identity of the task it queued to run the finish notification steps of `animation`, or to+/// dispatch its finish event.#[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)+pub extern "C" fn animations_animation_set_finish_notification_task(animation: &AnimationCell, task: u64) {+ let task = HostTaskId(NonZeroU64::new(task).expect("the host's tasks have nonzero identities"));+ animation.borrow_mut().set_finish_notification_task(task);+}++pub(crate) fn invalidate(invalidate: bool) -> Invalidate {+ if invalidate { Invalidate::Yes } else { Invalidate::No }}-/// Whether `animation`, on `timeline`, if any, is relevant, with its associated effect, if any, of-/// `effect_timing` at the local time `local_time`.+/// Runs the finish notification steps of `animation` on its timeline, if it has one, from the task the host queued.#[unsafe(no_mangle)]-pub extern "C" fn animations_is_relevant(- animation: &AnimationPlayback,- timeline: Option<&TimelineSample>,- effect_timing: Option<&AnimationEffectTiming>,- local_time: OptionalTimeValue,+pub extern "C" fn animations_animation_run_finish_notification_steps(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+) {+ run_procedure(animation, perform, |procedures| {+ procedures.finish_notification_steps();+ Ok(())+ });+}++/// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_cancel(+ animation: &AnimationCell,+ should_invalidate: bool,+ perform: HostEffectPerformer,+) {+ run_procedure(animation, perform, |procedures| {+ procedures.cancel(invalidate(should_invalidate));+ Ok(())+ });+}++/// https://www.w3.org/TR/web-animations-1/#dom-animation-finish+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_finish(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+) -> FfiAnimationError {+ run_procedure(animation, perform, |procedures| procedures.finish_an_animation())+}++/// https://www.w3.org/TR/web-animations-1/#dom-animation-starttime+/// To the validated `start_time`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_set_start_time(+ animation: &AnimationCell,+ start_time: OptionalTimeValue,+ perform: HostEffectPerformer,+) {+ run_procedure(animation, perform, |procedures| {+ procedures.set_start_time_for_bindings(start_time.get());+ Ok(())+ });+}++/// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation+/// Of `animation` to `timeline`, or to none where it is null.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_set_timeline(+ animation: &AnimationCell,+ timeline: Option<&TimelineCell>,+ perform: HostEffectPerformer,+) {+ // SAFETY: The host holds a reference to the timeline it passes.+ let timeline = timeline.map(|timeline| unsafe { TimelineHandle::retained_from_host(timeline) });+ run_procedure(animation, perform, |procedures| {+ procedures.set_timeline(timeline);+ Ok(())+ });+}++/// The host's timeline of `animation`, or null where it has none.+/// https://www.w3.org/TR/web-animations-1/#animation-timeline+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_timeline(animation: &AnimationCell) -> *mut c_void {+ animation+ .borrow()+ .timeline()+ .and_then(|timeline| timeline.facade())+ .map_or(std::ptr::null_mut(), NonNull::as_ptr)+}++/// Updates `animation` as its timeline updated its current time.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_update(animation: &AnimationCell, perform: HostEffectPerformer) {+ run_procedure(animation, perform, |procedures| {+ procedures.update();+ Ok(())+ });+}++/// Runs the pending play task of `animation` where it has one and is ready.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_run_pending_play_task_if_ready(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+) {+ run_procedure(animation, perform, |procedures| {+ procedures.run_pending_play_task_if_ready();+ Ok(())+ });+}++/// The keyframe set `set` names, borrowed for as long as the reference the host holds.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to.+unsafe fn borrowed_keyframe_set<'a>(set: *const KeyframeSet) -> &'a KeyframeSet {+ // SAFETY: Guaranteed by the caller.+ unsafe { &*set }+}++/// Hands the host the one reference to a new keyframe set.+fn into_host(set: KeyframeSet) -> *const KeyframeSet {+ Arc::into_raw(Arc::new(set))+}++/// Takes another reference to a keyframe set the host holds one to.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_retain(set: *const KeyframeSet) {+ // SAFETY: Guaranteed by the caller.+ unsafe { Arc::increment_strong_count(set) };+}++/// Gives up one of the references the host holds to a keyframe set.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to, which it gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_release(set: *const KeyframeSet) {+ // SAFETY: Guaranteed by the caller.+ unsafe { Arc::decrement_strong_count(set) };+}++/// The keyframe set of the `@keyframes` rule `rule` views, a `ValueParserFFI::NativeRuleView`, from a style sheet+/// whose base URL, where `has_resource_context`, is `base_url`, with the reference to it the host takes over.+///+/// # Safety+/// `rule` must view a live `@keyframes` rule for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_from_keyframes_rule(+ rule: *const c_void,+ has_resource_context: bool,+ base_url: ak::Span<'_, u8>,+ origin_clean: bool,+) -> *const KeyframeSet {+ // SAFETY: Guaranteed by the caller.+ let rule = unsafe { &*rule.cast::<crate::css::rule::read::NativeRuleView<'_>>() };+ let resource_context = has_resource_context.then(|| ResourceContext {+ base_url: base_url.as_slice().into(),+ origin_clean,+ });+ let mut blocks = Vec::new();+ rule.for_each_keyframe(|keys, declarations| blocks.push((keys.to_vec(), declarations)));+ into_host(KeyframeSet::from_keyframes_rule(+ blocks+ .iter()+ .map(|(keys, declarations)| (keys.as_slice(), &**declarations)),+ resource_context,+ ))+}++/// One keyframe script gave a `KeyframeEffect`, as processing the keyframes argument made it: its computed offset,+/// scaled to a key, its composite operation, its easing where it has one, and the range of the properties it+/// declares.+#[repr(C)]+pub struct FfiProcessedKeyframe {+ pub key: u64,+ pub composite: CompositeOperationOrAuto,+ pub has_easing: bool,+ pub easing: FfiEasingDescriptor,+ pub first_property: u32,+ pub property_count: u32,+}++/// One property a processed keyframe declares: a longhand or shorthand by its id, or, where `custom_name` is not+/// zero, the custom property of that raw fly string, with its value.+#[repr(C)]+pub struct FfiProcessedKeyframeProperty {+ pub property_id: u16,+ pub custom_name: usize,+ pub value: *const c_void,+}++/// The property a host names by its id, or by the raw fly string of a custom property's name where that is not zero.+///+/// # Safety+/// `custom_name` must be zero or a live raw fly string.+unsafe fn keyframe_property(property_id: u16, custom_name: usize) -> KeyframeProperty {+ match custom_name {+ 0 => KeyframeProperty::Id(property_id),+ // SAFETY: Guaranteed by the caller.+ name => KeyframeProperty::Custom(unsafe { RetainedUtf16FlyString::from_borrowed_raw(name) }),+ }+}++/// # Safety+/// `value` must be null or a live style value.+unsafe fn retained_optional_value(value: *const c_void) -> RetainedStyleValueData {+ if value.is_null() {+ return RetainedStyleValueData::none();+ }+ // SAFETY: Guaranteed by the caller.+ unsafe { retained_value(value) }+}++/// # Safety+/// `value` must be a live style value.+unsafe fn retained_value(value: *const c_void) -> RetainedStyleValueData {+ // SAFETY: Guaranteed by the caller.+ unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(value.cast::<StyleValueData>())) }+}++/// The keyframe set of the keyframes script gave a `KeyframeEffect`, in the order it gave them, with the reference to+/// it the host takes over.+///+/// # Safety+/// Every value, custom-property name and linear easing point the keyframes name must be live for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_from_processed_keyframes(+ keyframes: ak::Span<'_, FfiProcessedKeyframe>,+ properties: ak::Span<'_, FfiProcessedKeyframeProperty>,+) -> *const KeyframeSet {+ let properties = properties.as_slice();+ let keyframes = keyframes+ .as_slice()+ .iter()+ .map(|keyframe| {+ let first = keyframe.first_property as usize;+ ProcessedKeyframe {+ key: keyframe.key,+ composite: keyframe.composite,+ // SAFETY: Guaranteed by the caller.+ easing: keyframe+ .has_easing+ .then(|| unsafe { Easing::from_descriptor(&keyframe.easing) }),+ declarations: properties[first..first + keyframe.property_count as usize]+ .iter()+ // SAFETY: Guaranteed by the caller.+ .map(|property| unsafe {+ (+ keyframe_property(property.property_id, property.custom_name),+ retained_value(property.value),+ )+ })+ .collect(),+ }+ })+ .collect();+ into_host(KeyframeSet::from_processed_keyframes(keyframes, None))+}++/// The keyframe set of a CSS transition of the property `property_id`, or of the custom property whose name is the+/// raw fly string `custom_name` where that is not zero, from `start` to `end`, computed at the effective zoom+/// `computed_value_zoom`, with the reference to it the host takes over.+///+/// # Safety+/// `custom_name` must be zero or a live raw fly string, and `start` and `end` live style values.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_for_transition(+ property_id: u16,+ custom_name: usize,+ start: *const c_void,+ end: *const c_void,+ computed_value_zoom: f32,+) -> *const KeyframeSet {+ // SAFETY: Guaranteed by the caller.+ unsafe {+ into_host(KeyframeSet::for_transition(+ keyframe_property(property_id, custom_name),+ retained_value(start),+ retained_value(end),+ computed_value_zoom,+ ))+ }+}++/// What a keyframe declares for a property, as the host reads it.+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum FfiKeyframeValueState {+ Absent,+ /// The element's own value, which a generated initial or final keyframe holds.+ ElementValue,+ Declared,+}++/// What a keyframe declares for a property, with the value it declares, borrowed from the set, where it declares one.+#[repr(C)]+pub struct FfiKeyframeValue {+ pub state: FfiKeyframeValueState,+ pub value: *const c_void,+}++/// What the keyframe of a set at `index` declares for the property `property_id`.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to, and `index` one of its keyframes.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_value(+ set: *const KeyframeSet,+ index: usize,+ property_id: u16,+) -> FfiKeyframeValue {+ // SAFETY: Guaranteed by the caller.+ let set = unsafe { borrowed_keyframe_set(set) };+ let declaration = set+ .declarations_of(&set.keyframes()[index])+ .iter()+ .find(|declaration| declaration.property_id == property_id);+ match declaration.map(|declaration| &declaration.value) {+ None => FfiKeyframeValue {+ state: FfiKeyframeValueState::Absent,+ value: std::ptr::null(),+ },+ Some(KeyframeValue::ElementValue) => FfiKeyframeValue {+ state: FfiKeyframeValueState::ElementValue,+ value: std::ptr::null(),+ },+ Some(KeyframeValue::Declared(value)) => FfiKeyframeValue {+ state: FfiKeyframeValueState::Declared,+ value: value.pointer().cast(),+ },+ }+}++/// What follows from a set's keyframes alone, borrowed from the set: how many there are, the longhands they animate,+/// sorted, the raw fly strings of the names of the custom properties they animate, and what the set answers of them.+#[repr(C)]+pub struct FfiKeyframeSetFacts {+ pub keyframe_count: usize,+ pub target_properties: *const u16,+ pub target_property_count: usize,+ pub target_custom_properties: *const usize,+ pub target_custom_property_count: usize,+ pub animates_what_a_tick_cannot: bool,+ pub animates_an_inherited_property: bool,+ pub has_additive_keyframe: bool,+}++/// What follows from the keyframes of a set alone.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_facts(set: *const KeyframeSet) -> FfiKeyframeSetFacts {+ // SAFETY: Guaranteed by the caller.+ let set = unsafe { borrowed_keyframe_set(set) };+ FfiKeyframeSetFacts {+ keyframe_count: set.keyframes().len(),+ target_properties: set.target_properties().as_ptr(),+ target_property_count: set.target_properties().len(),+ target_custom_properties: set.target_custom_properties().as_ptr().cast::<usize>(),+ target_custom_property_count: set.target_custom_properties().len(),+ animates_what_a_tick_cannot: set.animates_what_a_tick_cannot(),+ animates_an_inherited_property: set.animates_an_inherited_property(),+ has_additive_keyframe: set.has_additive_keyframe(),+ }+}++/// The bytes a keyframe set holds, with the allocation the host's references share.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_keyframe_set_memory_size(set: *const KeyframeSet) -> usize {+ // SAFETY: Guaranteed by the caller.+ let set = unsafe { borrowed_keyframe_set(set) };+ crate::heap_size::ARC_HEADER_BYTES + size_of::<KeyframeSet>() + set.heap_size()+}++/// Notes what the `attr()`s of the values a keyframe set declares can read, answering whether they can read a name+/// none could before.+///+/// # Safety+/// `set` must be a keyframe set the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_note_attr_names_read_by_keyframe_set(+ host: &DocumentHost,+ set: *const KeyframeSet,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let set = unsafe { borrowed_keyframe_set(set) };+ let before = crate::css::style::host_atoms::attr_names_read_generation(host);+ crate::css::style::host_atoms::note_attr_names_read_by(host, set.declared_values());+ crate::css::style::host_atoms::attr_names_read_generation(host) != before+}++/// Takes a reference of its own to `effect`, which the host gives up with `animations_effect_release`.+///+/// # Safety+/// `effect` must be an effect the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_effect_retain(effect: *const AnimationEffectCell) {+ // SAFETY: Guaranteed by the caller.+ let _ = unsafe { EffectHandle::retained_from_host(effect) }.into_raw();+}++/// The host's `AnimationEffect` of `effect`, while it is alive.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_facade(effect: &AnimationEffectCell) -> *mut c_void {+ effect.facade().map_or(std::ptr::null_mut(), NonNull::as_ptr)+}++/// Gives up a reference the host holds to an effect.+///+/// # Safety+/// `effect` must be an effect the host holds a reference to, which it gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_effect_release(effect: *const AnimationEffectCell) {+ // SAFETY: Guaranteed by the caller.+ drop(unsafe { EffectHandle::from_raw(effect) });+}++#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_id(effect: &AnimationEffectCell) -> AnimationEffectId {+ effect.borrow().id()+}++/// The normalized timing the timing model reads of `effect`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_timing(effect: &AnimationEffectCell) -> AnimationEffectTiming {+ effect.borrow().timing()+}++/// The timing function of an effect, whose control points it borrows, and the raw fly string of its serialization,+/// which it borrows, until the timing function changes.+#[repr(C)]+pub struct FfiEffectTimingFunction {+ pub descriptor: FfiEasingDescriptor,+ pub serialization: usize,+}++/// The timing function of `effect`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_timing_function(effect: &AnimationEffectCell) -> FfiEffectTimingFunction {+ let effect = effect.borrow();+ FfiEffectTimingFunction {+ descriptor: effect.timing_function().descriptor(),+ serialization: effect.timing_function_serialization().raw(),+ }+}++/// The keyframe set `effect` runs, borrowed until its keyframes change, or null where it has none.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_keyframe_set(effect: &AnimationEffectCell) -> *const KeyframeSet {+ effect.borrow().keyframes().map_or(std::ptr::null(), Arc::as_ptr)+}++/// Whether the compositor may run all `effect` animates.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_may_run_on_the_compositor(effect: &AnimationEffectCell) -> bool {+ effect.borrow().may_run_on_the_compositor()+}++/// Sets the keyframe set `effect` runs to `set`, which it takes a reference of its own to, or to none where `set` is+/// null, answering whether it did. An effect whose keyframes from CSS script replaced takes no keyframes of CSS.+///+/// # Safety+/// `set` must be null or a keyframe set the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_effect_set_keyframe_set(+ effect: &AnimationEffectCell,+ set: *const KeyframeSet,) -> bool {- timing::is_relevant(animation, timeline, effect_timing, local_time.get())+ // SAFETY: Guaranteed by the caller.+ let keyframes = (!set.is_null()).then(|| unsafe { KeyframeSet::retained_from_host(set) });+ let mut effect = effect.borrow_mut();+ if effect.ignores_css_keyframes()+ && keyframes+ .as_ref()+ .is_some_and(|keyframes| keyframes.origin() != KeyframeOrigin::Script)+ {+ return false;+ }+ effect.set_keyframes(keyframes);+ true+}++#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_composite(effect: &AnimationEffectCell) -> FfiCompositeOperation {+ effect.borrow().composite()+}++#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_set_composite(effect: &AnimationEffectCell, composite: FfiCompositeOperation) {+ effect.borrow_mut().set_composite(composite);+}++/// Sets the host's `DOM::Element` that `effect` targets, which the host keeps alive while the effect targets it, or+/// none where `element` is null, and has the host associate the associated animation of `effect`, if any, with it+/// through `perform`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_set_target_element(+ effect: &AnimationEffectCell,+ element: *mut c_void,+ perform: HostEffectPerformer,+) {+ // SAFETY: The host holds a reference to the effect it passes.+ let effect = unsafe { EffectHandle::retained_from_host(effect) };+ perform_host_effects(procedures::set_effect_target(&effect, NonNull::new(element)), perform);+}++/// The animation whose associated effect `effect` is, which it borrows for as long as it is, or null where it is the+/// associated effect of none.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_associated_animation(effect: &AnimationEffectCell) -> *const AnimationCell {+ effect+ .borrow()+ .associated_animation()+ .map_or(std::ptr::null(), |animation| {+ std::ptr::from_ref::<AnimationCell>(&animation)+ })+}++/// The target pseudo-selector of an effect: the host's `PseudoElement`, and the raw fly string of its serialization,+/// or zero where the effect has none.+#[repr(C)]+pub struct FfiEffectPseudoElement {+ pub kind: u8,+ pub serialization: usize,+}++/// The target of an effect: the host's `DOM::Element` it targets, or null where it targets none, and its target+/// pseudo-selector.+#[repr(C)]+pub struct FfiEffectTarget {+ pub element: *mut c_void,+ pub pseudo_element: FfiEffectPseudoElement,+}++/// The target of `effect`, whose pseudo-selector's serialization it borrows until it changes.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_target(effect: &AnimationEffectCell) -> FfiEffectTarget {+ let effect = effect.borrow();+ FfiEffectTarget {+ element: effect+ .target_element()+ .map_or(std::ptr::null_mut(), std::ptr::NonNull::as_ptr),+ pseudo_element: effect.pseudo_element().map_or(+ FfiEffectPseudoElement {+ kind: 0,+ serialization: 0,+ },+ |pseudo_element| FfiEffectPseudoElement {+ kind: pseudo_element.kind,+ serialization: pseudo_element.serialization.raw(),+ },+ ),+ }+}++/// Sets the target pseudo-selector of `effect`.+///+/// # Safety+/// The serialization of `pseudo_element` must be zero or a live raw fly string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_effect_set_pseudo_element(+ effect: &AnimationEffectCell,+ pseudo_element: FfiEffectPseudoElement,+) {+ // SAFETY: Guaranteed by the caller.+ let serialization = unsafe { RetainedUtf16FlyString::from_borrowed_raw(pseudo_element.serialization) };+ effect+ .borrow_mut()+ .set_pseudo_element(pseudo_element.kind, serialization);+}++/// Sets the phase and the current iteration `effect` had when the host last dispatched its events.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_set_previous_phase_and_current_iteration(+ effect: &AnimationEffectCell,+ phase: AnimationEffectPhase,+ current_iteration: f64,+) {+ let mut effect = effect.borrow_mut();+ effect.set_previous_phase(phase);+ effect.set_previous_current_iteration(current_iteration);+}++#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_has_flag(effect: &AnimationEffectCell, flag: EffectFlag) -> bool {+ effect.borrow().has_flag(flag)+}++/// Sets or clears `flag` of `effect`, answering whether that changed it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_set_flag(effect: &AnimationEffectCell, flag: EffectFlag, value: bool) -> bool {+ effect.borrow_mut().set_flag(flag, value)+}++/// Has `effect` forget what the host concluded of it as it was, since it changed: what the host built of it for the+/// compositor, how the host ran or throttled it, and whether a frame can skip its style update.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_forget_what_the_host_concluded(effect: &AnimationEffectCell) {+ effect.borrow_mut().forget_what_the_host_concluded();+}++/// What `effect` remembers of whether a frame can skip its style update, for `key`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_per_frame_style_update_skip_decision(+ effect: &AnimationEffectCell,+ key: &PerFrameStyleUpdateSkipKey,+) -> PerFrameStyleUpdateSkipDecision {+ effect.borrow().per_frame_style_update_skip_decision(key)+}++/// Has `effect` remember whether a frame can skip its style update, as the host found it from `key`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_note_per_frame_style_update_skip_decision(+ effect: &AnimationEffectCell,+ key: &PerFrameStyleUpdateSkipKey,+ can_skip: bool,+) {+ effect+ .borrow_mut()+ .note_per_frame_style_update_skip_decision(*key, can_skip);+}++/// Asks the next style update for an observation sample of `effect` on behalf of a read of an element in the task of+/// generation `task_generation`, unless it was already asked for one in that task.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_request_observation_sample_in_task(+ effect: &AnimationEffectCell,+ task_generation: u64,+) -> ObservationSampleRequest {+ effect.borrow_mut().request_observation_sample_in_task(task_generation)+}++/// What the host built of `effect` for the compositor, reached as `access` says, or null where it built nothing and+/// `access` makes nothing. The state lives as long as the effect.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_compositor_animation_state(+ effect: &AnimationEffectCell,+ access: CompositorAnimationStateAccess,+) -> *mut CompositorAnimationEffectState {+ effect+ .borrow_mut()+ .compositor_animation_state(access)+ .map_or(std::ptr::null_mut(), std::ptr::from_mut)+}++/// The bytes the record of `effect` holds, without the keyframe set, which others share.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_memory_size(effect: &AnimationEffectCell) -> usize {+ effect.memory_size()+}++/// A new idle CSS animation with no associated effect, with the one reference to it the host takes over.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_animation_create() -> *const AnimationCell {+ AnimationHandle::new(AnimationKind::CssAnimation(CssAnimationState {+ name: RetainedUtf16FlyString::none(),+ // https://drafts.csswg.org/css-animations-1/#animation-timing-function+ // The initial value of animation-timing-function is ease.+ default_easing: CompactEasing::of(super::easing::keyword_cubic_bezier(0)),+ applied_definition: None,+ named_timeline: RetainedUtf16FlyString::none(),+ name_index: 0,+ last_css_play_state: None,+ flags: 0,+ }))+ .into_raw()+}++/// What a CSS transition is of and runs between, as the host starts one and reads it: the longhand by its id, or, where+/// `custom_name` is not zero, the custom property of that raw fly string, and the values, which a transition the host+/// reads lends it for as long as it holds the transition.+#[repr(C)]+pub struct FfiCssTransition {+ pub generation: u64,+ pub start_time: f64,+ pub end_time: f64,+ pub reversing_shortening_factor: f64,+ pub custom_name: usize,+ pub start_value: *const c_void,+ pub end_value: *const c_void,+ pub reversing_adjusted_start_value: *const c_void,+ pub property_id: u16,+}++/// A new idle CSS transition `transition` describes, with no associated effect, with the one reference to it the host+/// takes over. It is provisional until the host commits or discards it.+///+/// # Safety+/// `transition` must name live style values and a live raw fly string or zero.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_transition_create(transition: &FfiCssTransition) -> *const AnimationCell {+ // SAFETY: Guaranteed by the caller.+ let state = unsafe {+ CssTransitionState {+ custom_property_name: RetainedUtf16FlyString::from_borrowed_raw(transition.custom_name),+ generation: transition.generation,+ start_time: transition.start_time,+ end_time: transition.end_time,+ start_value: retained_value(transition.start_value),+ end_value: retained_value(transition.end_value),+ reversing_adjusted_start_value: retained_value(transition.reversing_adjusted_start_value),+ reversing_shortening_factor: transition.reversing_shortening_factor,+ property_id: transition.property_id,+ previous_phase: CSS_TRANSITION_PHASE_IDLE,+ provisional: true,+ adopted_from_lane: false,+ effect_started_with: None,+ }+ };+ AnimationHandle::new(AnimationKind::CssTransition(state)).into_raw()+}++/// What the host describes of the animation of an SVG animation element as it creates it.+#[repr(C)]+pub struct FfiSmilAnimation {+ /// The host's `SVGAnimationElement` whose animation it is, which holds the animation until it lets go of it.+ pub animation_element: NonNull<c_void>,+ /// The host's `DOM::Element` the effect of the animation targets.+ pub target: NonNull<c_void>,+ /// The keyframes the effect runs, which the host holds a reference to.+ pub keyframes: *const KeyframeSet,+ pub timing: SpecifiedEffectTiming,+ /// The timing function of the effect and the serialization of the value it was made from, or null for linear.+ pub timing_function: *const FfiEasingDescriptor,+ pub timing_function_serialization: usize,+ /// The time the animation begins at, which orders it among the animations of its time container.+ pub begin_time: f64,+}++/// A new animation of an SVG animation element on `timeline`, whose associated effect is a new keyframe effect as+/// `description` describes, with the one reference to it the host takes over. The host makes no `Animation` of it, and+/// its animation element holds it until it lets go of it.+///+/// # Safety+/// `description` must name live host objects and keyframes, `timeline` a timeline the host holds a reference to, and a+/// timing function, if any, must be live.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_smil_animation_create(+ description: &FfiSmilAnimation,+ timeline: &TimelineCell,+ perform: HostEffectPerformer,+) -> *const AnimationCell {+ let effect = EffectHandle::new();+ {+ let mut record = effect.borrow_mut();+ record.set_specified_timing(description.timing);+ // SAFETY: Guaranteed by the caller.+ if let Some(timing_function) = unsafe { description.timing_function.as_ref() } {+ // SAFETY: Guaranteed by the caller.+ let (timing_function, serialization) = unsafe {+ (+ CompactEasing::of(Easing::from_descriptor(timing_function)),+ RetainedUtf16FlyString::from_borrowed_raw(description.timing_function_serialization),+ )+ };+ record.set_timing_function(timing_function, serialization);+ }+ record.normalize_specified_timing(None);+ // SAFETY: Guaranteed by the caller.+ record.set_keyframes(Some(unsafe { KeyframeSet::retained_from_host(description.keyframes) }));+ }+ perform_host_effects(+ procedures::set_effect_target(&effect, Some(description.target)),+ perform,+ );++ let animation = AnimationHandle::new(AnimationKind::Smil {+ begin_time: description.begin_time,+ animation_element: description.animation_element,+ holders: SmilHolder::AnimationElement as u8,+ });+ // SAFETY: The host holds a reference to the timeline it passes.+ let timeline = unsafe { TimelineHandle::retained_from_host(timeline) };+ run_procedure(&animation, perform, |procedures| {+ procedures.set_timeline(Some(timeline));+ Ok(())+ });+ run_procedure(&animation, perform, |procedures| {+ procedures.set_the_associated_effect(Some(&effect), Invalidate::Yes);+ Ok(())+ });+ animation.into_raw()+}++/// Notes that the SVG animation element of `animation` lets go of it, as it is done with it or as the host finalizes the+/// element.+#[unsafe(no_mangle)]+pub extern "C" fn animations_smil_animation_let_go(animation: &AnimationCell) {+ animation.note_smil_holder(SmilHolder::AnimationElement, false);+}++/// Calls `visit` with `context` and each GC cell of the host that keeps alive the elements the record of `animation`+/// names, which a holder of the record the GC traces visits.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_visit_host_cells(+ animation: &AnimationCell,+ context: *mut c_void,+ visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),+) {+ animation.for_each_host_cell(|cell, kind| {+ // SAFETY: The host visits a cell of an animation it holds.+ unsafe { visit(context, cell.as_ptr(), kind) }+ });+}++/// Calls `visit` with `context` and each GC cell of the host the record of `animation` names, which the object of the+/// animation visits.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_visit_named_cells(+ animation: &AnimationCell,+ context: *mut c_void,+ visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),+) {+ animation.for_each_named_cell(|cell, kind| {+ // SAFETY: The host visits a cell of an animation its object holds.+ unsafe { visit(context, cell.as_ptr(), kind) }+ });+}++/// A new effect with the default timing, no keyframes and no target, with the one reference to it the host takes over,+/// as a CSS animation or transition creates its associated effect.+#[unsafe(no_mangle)]+pub extern "C" fn animations_effect_create() -> *const AnimationEffectCell {+ EffectHandle::new().into_raw()+}++/// The host's effect of an effect the host passes, which is null or one it holds a reference to.+///+/// # Safety+/// `effect` must be null or an effect the host holds a reference to.+unsafe fn effect_from_host(effect: *const AnimationEffectCell) -> Option<EffectHandle> {+ // SAFETY: Guaranteed by the caller.+ (!effect.is_null()).then(|| unsafe { EffectHandle::retained_from_host(effect) })+}++/// https://www.w3.org/TR/web-animations-1/#setting-the-associated-effect+/// Sets the associated effect of `animation` to `effect`, or to none where it is null.+///+/// # Safety+/// `effect` must be null or an effect the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_animation_set_effect(+ animation: &AnimationCell,+ effect: *const AnimationEffectCell,+ should_invalidate: bool,+ perform: HostEffectPerformer,+) {+ // SAFETY: Guaranteed by the caller.+ let effect = unsafe { effect_from_host(effect) };+ run_procedure(animation, perform, |procedures| {+ procedures.set_the_associated_effect(effect.as_ref(), invalidate(should_invalidate));+ Ok(())+ });+}++/// The associated effect of `animation`, which it borrows for as long as the animation holds it, or null where it has+/// none.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_effect(animation: &AnimationCell) -> *const AnimationEffectCell {+ animation.borrow().effect().map_or(std::ptr::null(), |effect| {+ std::ptr::from_ref::<AnimationEffectCell>(effect)+ })+}++/// What the host's per-frame decisions read of `animation` now, with its current time at `timestamp` where+/// `has_timestamp`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_timing_state(+ animation: &AnimationCell,+ has_timestamp: bool,+ timestamp: f64,+) -> FfiAnimationTimingState {+ animation.borrow().timing_state(has_timestamp.then_some(timestamp))+}++/// The playback state of `animation`, which the timing model reads.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_playback(animation: &AnimationCell) -> AnimationPlayback {+ *animation.borrow().playback()+}++/// The host's function that keeps `animation`, which it holds a reference to, alive to it with `context` until the call+/// that handed it the function returns, since what it performs for the animation can run the GC.+pub type FfiKeepAlive = unsafe extern "C" fn(context: *mut c_void, animation: &AnimationCell);++/// Has the host keep alive, through `keep_alive` with `context`, every animation `effects` names.+fn keep_alive_for_host_effects(effects: &HostEffects, keep_alive: FfiKeepAlive, context: *mut c_void) {+ let mut previous: Option<&AnimationHandle> = None;+ for (animation, _) in effects.iter() {+ if previous.is_some_and(|previous| previous.ptr_eq(animation)) {+ continue;+ }+ // SAFETY: The host keeps alive an animation it is handed for as long as the call that handed it lasts.+ unsafe { keep_alive(context, animation) };+ previous = Some(animation);+ }+}++/// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations+/// For the host's `DOM::Document` `document`, whose associated timelines are the `timeline_count` of `timelines`,+/// comparing elements in tree order with `tree_order`, and has the host keep each animation it removes alive through+/// `keep_alive` with `context` and perform what that asks of it through `perform`.+///+/// # Safety+/// `timelines` must point to `timeline_count` timelines the host holds references to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_remove_replaced_animations(+ document: NonNull<c_void>,+ timelines: *const &TimelineCell,+ timeline_count: usize,+ tree_order: FfiTreeOrder,+ keep_alive: FfiKeepAlive,+ context: *mut c_void,+ perform: HostEffectPerformer,+) {+ // SAFETY: Guaranteed by the caller.+ let timelines = unsafe { ak::slice_from_raw_parts(timelines, timeline_count) };+ let effects = procedures::remove_replaced_animations(+ timelines.iter().copied(),+ |element| element_node_document(element) == document,+ &mut host_tree_order(tree_order),+ );+ keep_alive_for_host_effects(&effects, keep_alive, context);+ perform_host_effects(effects, perform);+}++/// Disassociates `animation`, on its timeline, if it has one, from the target of its associated effect where it is+/// inert, where a procedure scheduled that.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_disassociate_from_target_if_inert(+ animation: &AnimationCell,+ perform: HostEffectPerformer,+) {+ if !animation.borrow().disassociation_from_target_pending() {+ return;+ }+ run_procedure(animation, perform, |procedures| {+ procedures.disassociate_from_target_if_inert();+ Ok(())+ });+}++/// Keeps the animation of an SVG animation element, on its timeline, if it has one, at the time of its time container,+/// which began at `zero_time` of the document timeline and, where `is_paused`, is paused at `paused_time`, in+/// milliseconds.+#[unsafe(no_mangle)]+pub extern "C" fn animations_smil_animation_synchronize(+ animation: &AnimationCell,+ zero_time: f64,+ is_paused: bool,+ paused_time: f64,+ perform: HostEffectPerformer,+) {+ run_procedure(animation, perform, |procedures| {+ procedures.synchronize_with_smil_time_container(zero_time, is_paused.then_some(paused_time));+ Ok(())+ });+}++/// What the render clock's plan makes of `animation`: its play is pending and a tick holds its element still, a tick+/// cannot move it, or a tick moves it.+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum FfiClockPlanAnimationKind {+ Held,+ NotTicked,+ Ticked,+}++/// What the render clock's plan makes of an animation, and, where a tick moves it, the local time of its effect and,+/// on a document timeline, the time its active interval ends at.+#[repr(C)]+pub struct FfiClockPlanAnimation {+ pub kind: FfiClockPlanAnimationKind,+ pub local_time: TimeValue,+ pub active_end: TimeValue,+}++/// What the render clock's plan makes of `animation`, of a keyframe effect with a target, on its timeline.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_clock_plan(animation: &AnimationCell) -> FfiClockPlanAnimation {+ let unresolved = TimeValue::milliseconds(0.0);+ let animation = animation.borrow();+ let timeline = animation.timeline().expect("the plan runs on animations of timelines");+ let on_scroll_timeline = timeline.borrow().scroll().is_some();+ let plan = match animation.clock_plan(timeline.current_time(), on_scroll_timeline) {+ // NB: A tick moves an animation of a scroll timeline only where it follows the timeline as the plan seals it.+ ClockPlanAnimation::Ticked { .. } if on_scroll_timeline && timeline.clock_snapshot().is_none() => {+ ClockPlanAnimation::NotTicked+ }+ plan => plan,+ };+ match plan {+ ClockPlanAnimation::Held => FfiClockPlanAnimation {+ kind: FfiClockPlanAnimationKind::Held,+ local_time: unresolved,+ active_end: unresolved,+ },+ ClockPlanAnimation::NotTicked => FfiClockPlanAnimation {+ kind: FfiClockPlanAnimationKind::NotTicked,+ local_time: unresolved,+ active_end: unresolved,+ },+ ClockPlanAnimation::Ticked { local_time, active_end } => FfiClockPlanAnimation {+ kind: FfiClockPlanAnimationKind::Ticked,+ local_time,+ active_end,+ },+ }+}++/// The timing a hover of the render clock's lane runs `animation`, of a keyframe effect, with, on its timeline.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_hover_timing(+ animation: &AnimationCell,+) -> super::snapshot::EffectTimingSnapshot {+ let animation = animation.borrow();+ let timeline = animation.timeline().expect("the hover runs animations of timelines");+ animation.hover_timing(timeline.sample(), true, timeline.clock())+}++/// The owning element of a CSS animation or transition: the host's `DOM::Element`, or null where it has none, and the+/// host's `PseudoElement`, where `has_pseudo_element`.+#[repr(C)]+pub struct FfiOwningElement {+ pub element: *mut c_void,+ pub pseudo_element: u8,+ pub has_pseudo_element: bool,+}++/// https://www.w3.org/TR/css-animations-2/#owning-element-section+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_owning_element(animation: &AnimationCell) -> FfiOwningElement {+ match animation.borrow().owning_element() {+ Some(owner) => FfiOwningElement {+ element: owner.element.as_ptr(),+ pseudo_element: owner.pseudo_element.unwrap_or(0),+ has_pseudo_element: owner.pseudo_element.is_some(),+ },+ None => FfiOwningElement {+ element: std::ptr::null_mut(),+ pseudo_element: 0,+ has_pseudo_element: false,+ },+ }+}++/// Sets the owning element of `animation`, which the host keeps alive while the animation holds it, or to none where+/// its element is null.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_set_owning_element(animation: &AnimationCell, owner: FfiOwningElement) {+ animation+ .borrow_mut()+ .set_owning_element(std::ptr::NonNull::new(owner.element).map(|element| OwningElement {+ element,+ pseudo_element: owner.has_pseudo_element.then_some(owner.pseudo_element),+ }));+}++/// The state of a CSS animation as the host reads it: the raw fly string of its name, borrowed until it changes, or+/// zero.+#[repr(C)]+pub struct FfiCssAnimationState {+ pub name: usize,+ /// The raw fly string of the name of the named timeline the animation follows, or zero.+ pub named_timeline: usize,+ /// The easing a keyframe of the animation that declares none of its own runs, whose control points it borrows+ /// until the easing changes.+ pub default_easing: FfiEasingDescriptor,+}++/// The state of the CSS animation `animation`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_animation_state(animation: &AnimationCell) -> FfiCssAnimationState {+ let animation = animation.borrow();+ let state = animation.css_animation();+ FfiCssAnimationState {+ name: state.name.raw(),+ named_timeline: state.named_timeline.raw(),+ default_easing: state.default_easing.descriptor(),+ }+}++/// Applies the timing, attachment range, easing, composite operation and play state the style computation computed in+/// `definition` to the CSS animation `animation`, whose timeline the host updated, having the host perform what that+/// asks for through `perform`.+/// https://drafts.csswg.org/css-animations-2/#animations+///+/// # Safety+/// The values `definition` names must be null or live style values.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_animation_apply_properties(+ animation: &AnimationCell,+ definition: &crate::css::style_compute::FfiComputedAnimation,+ perform: HostEffectPerformer,+) {+ use crate::css::css_enums::{animation_composition, animation_direction, animation_fill_mode};+ use libcompositing_rust::animation_timing::effect_timing::{+ FillMode as SpecifiedFillMode, PlaybackDirection, SpecifiedIterationDuration,+ };++ let has_flag = |flag: CssAnimationFlag| animation.borrow().css_animation().flags & flag as u8 != 0;++ // NB: An edge of the range that script set is no longer the style's to change.+ let [current_start, current_end] = animation.borrow().range();+ let edge = |name, px, percentage, calculated| AttachmentRangeEdge {+ name,+ offset: AttachmentRangeEdgeOffset {+ px,+ percentage,+ // SAFETY: Guaranteed by the caller.+ calculated: unsafe { retained_optional_value(calculated) },+ },+ };+ let start = if has_flag(CssAnimationFlag::ScriptSetRangeStart) {+ current_start+ } else {+ edge(+ definition.range_start_name,+ definition.range_start_px,+ definition.range_start_percentage,+ definition.range_start_calculated,+ )+ };+ let end = if has_flag(CssAnimationFlag::ScriptSetRangeEnd) {+ current_end+ } else {+ edge(+ definition.range_end_name,+ definition.range_end_px,+ definition.range_end_percentage,+ definition.range_end_calculated,+ )+ };+ if animation.borrow_mut().set_range([start, end]) {+ run_procedure(animation, perform, |procedures| {+ procedures.attachment_range_changed();+ Ok(())+ });+ }++ let effect = animation+ .borrow()+ .effect()+ .cloned()+ .expect("a CSS animation the style applies to has an associated effect");+ let mut specified = *effect.borrow().specified_timing();+ specified.iteration_duration = if definition.duration_is_auto {+ SpecifiedIterationDuration::AUTO+ } else {+ SpecifiedIterationDuration::milliseconds(definition.duration)+ };+ specified.start_delay = definition.delay;+ specified.iteration_count = definition.iteration_count;+ specified.fill_mode = match definition.fill_mode {+ animation_fill_mode::BACKWARDS => SpecifiedFillMode::Backwards,+ animation_fill_mode::BOTH => SpecifiedFillMode::Both,+ animation_fill_mode::FORWARDS => SpecifiedFillMode::Forwards,+ animation_fill_mode::NONE => SpecifiedFillMode::None,+ fill_mode => unreachable!("animation-fill-mode {fill_mode} is a keyword of the property"),+ };+ specified.playback_direction = match definition.direction {+ animation_direction::ALTERNATE => PlaybackDirection::Alternate,+ animation_direction::ALTERNATE_REVERSE => PlaybackDirection::AlternateReverse,+ animation_direction::NORMAL => PlaybackDirection::Normal,+ animation_direction::REVERSE => PlaybackDirection::Reverse,+ direction => unreachable!("animation-direction {direction} is a keyword of the property"),+ };+ effect.borrow_mut().set_specified_timing(specified);+ // https://drafts.csswg.org/web-animations-2/#updating-animationeffect-timing+ // Timing properties may also be updated due to a style change. Any change to a CSS animation property that affects+ // timing requires rerunning the procedure to normalize specified timing.+ let timeline = animation.borrow().timeline_state();+ effect.borrow_mut().normalize_specified_timing(timeline.as_ref());++ // NB: animation-timing-function is applied per-keyframe, not as the effect-level timing function. The effect-level+ // timing function remains linear. The effect's description for the style engine gives it to every keyframe that+ // declares no easing of its own.+ // SAFETY: Guaranteed by the caller.+ let timing_function = unsafe { definition.timing_function.cast::<StyleValueData>().as_ref() }+ .expect("a computed animation has a timing function");+ let default_easing = crate::css::style::effect_descriptions::easing_from_computed_timing_function(timing_function)+ .expect("a computed animation-timing-function describes an easing");+ animation+ .borrow_mut()+ .set_css_animation_default_easing(CompactEasing::of(default_easing));+ effect.borrow_mut().set_composite(match definition.composition {+ animation_composition::ACCUMULATE => FfiCompositeOperation::Accumulate,+ animation_composition::ADD => FfiCompositeOperation::Add,+ animation_composition::REPLACE => FfiCompositeOperation::Replace,+ composition => unreachable!("animation-composition {composition} is a keyword of the property"),+ });++ // NB: The style changed the timing of the associated effect, and its composite operation, which invalidates the+ // style it produces.+ run_procedure(animation, perform, |procedures| {+ procedures.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);+ Ok(())+ });++ if animation.borrow().css_animation().last_css_play_state == Some(definition.play_state) {+ return;+ }+ if !has_flag(CssAnimationFlag::ScriptOverrodePlayState) {+ let play_state = animation.borrow().timing_state(None).play_state;+ // NB: Neither procedure throws for a CSS animation, which has an associated effect.+ let result = match definition.play_state {+ CSS_ANIMATION_PLAY_STATE_RUNNING if play_state != AnimationPlayState::Running => {+ run_procedure_on(animation, perform, |procedures| procedures.play_from_css())+ }+ CSS_ANIMATION_PLAY_STATE_PAUSED if play_state != AnimationPlayState::Paused => {+ run_procedure_on(animation, perform, |procedures| procedures.pause_from_css())+ }+ _ => Ok(()),+ };+ assert!(result.is_ok(), "playing or pausing a CSS animation throws nothing");+ }+ animation.borrow_mut().css_animation_mut().last_css_play_state = Some(definition.play_state);+}++/// Whether `flag` of the CSS animation `animation` is set.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_animation_has_flag(animation: &AnimationCell, flag: CssAnimationFlag) -> bool {+ animation.borrow().css_animation().flags & flag as u8 != 0+}++/// Sets the name of the CSS animation `animation` to the raw fly string `name`.+///+/// # Safety+/// `name` must be a live raw fly string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_animation_set_name(animation: &AnimationCell, name: usize) {+ // SAFETY: Guaranteed by the caller.+ let name = unsafe { RetainedUtf16FlyString::from_borrowed_raw(name) };+ animation.borrow_mut().css_animation_mut().name = name;+}++/// Sets the position of the CSS animation `animation` in `animation-name`, answering whether that changed it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_animation_set_name_index(animation: &AnimationCell, name_index: u32) -> bool {+ std::mem::replace(&mut animation.borrow_mut().css_animation_mut().name_index, name_index) != name_index+}++/// Notes that the style computation applied `definition` to the CSS animation `animation`, which follows the named+/// timeline of the raw fly string `named_timeline` where that is not zero, answering whether that sets the same+/// properties as the definition it last applied, whatever keyframes each gives the animation's effect.+///+/// # Safety+/// The values `definition` names must be null or live style values, its keyframe set null or one the host holds a+/// reference to, and `named_timeline` zero or a live raw fly string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_animation_apply_definition(+ animation: &AnimationCell,+ definition: &crate::css::style_compute::FfiComputedAnimation,+ named_timeline: usize,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let (definition, named_timeline) = unsafe {+ (+ Arc::new(AppliedAnimationDefinition::retained(definition)),+ RetainedUtf16FlyString::from_borrowed_raw(named_timeline),+ )+ };+ let mut animation = animation.borrow_mut();+ let state = animation.css_animation_mut();+ state.named_timeline = named_timeline;+ let applies_the_same_properties = state+ .applied_definition+ .as_ref()+ .is_some_and(|applied| applied.applies_the_same_properties(&definition));+ state.applied_definition = Some(definition);+ // NB: The effect is described anew under a definition that sets other properties, so that the interval values the+ // style engine retained for its custom properties under the last one are let go of.+ if !applies_the_same_properties && let Some(effect) = animation.effect() {+ effect.borrow_mut().describe_anew();+ }+ applies_the_same_properties+}++/// The CSS transition `animation`, which lends the host its values and the name of its custom property for as long as+/// the host holds it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition(animation: &AnimationCell) -> FfiCssTransition {+ let animation = animation.borrow();+ let state = animation.css_transition();+ FfiCssTransition {+ generation: state.generation,+ start_time: state.start_time,+ end_time: state.end_time,+ reversing_shortening_factor: state.reversing_shortening_factor,+ custom_name: state.custom_property_name.raw(),+ start_value: state.start_value.pointer().cast(),+ end_value: state.end_value.pointer().cast(),+ reversing_adjusted_start_value: state.reversing_adjusted_start_value.pointer().cast(),+ property_id: state.property_id,+ }+}++/// The timing a CSS transition starts with: its delay and duration, in milliseconds, its timing function, and the raw+/// fly string of the serialization of the value that was made from.+#[repr(C)]+pub struct FfiProvisionalTransitionTiming {+ pub delay: f64,+ pub duration: f64,+ pub timing_function: FfiEasingDescriptor,+ pub timing_function_serialization: usize,+}++/// https://drafts.csswg.org/css-transitions/#starting+/// Starts the CSS transition `animation`, on its timeline, provisionally, with `effect`, which targets its owning+/// element and runs its keyframes, and the timing `timing`.+///+/// # Safety+/// The serialization `timing` names must be a live raw fly string.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_transition_start_provisionally(+ animation: &AnimationCell,+ effect: &AnimationEffectCell,+ timing: &FfiProvisionalTransitionTiming,+ perform: HostEffectPerformer,+) {+ // SAFETY: The host holds a reference to the effect it passes, and the caller guarantees the serialization.+ let (effect, timing) = unsafe {+ (+ EffectHandle::retained_from_host(effect),+ ProvisionalTransitionTiming {+ delay: timing.delay,+ duration: timing.duration,+ timing_function: CompactEasing::of(Easing::from_descriptor(&timing.timing_function)),+ timing_function_serialization: RetainedUtf16FlyString::from_borrowed_raw(+ timing.timing_function_serialization,+ ),+ },+ )+ };+ run_procedure(animation, perform, |procedures| {+ procedures.start_a_provisional_transition(&effect, timing);+ Ok(())+ });+}++/// Discards the CSS transition `animation`, which was started provisionally and has no timeline any more.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition_discard_provisional(animation: &AnimationCell) {+ // SAFETY: The host holds a reference to the animation it passes.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ procedures::run(&animation, |procedures| {+ procedures.discard_provisional_transition();+ Ok(())+ })+ .expect("discarding a provisional transition does not throw");+}++/// Commits the CSS transition `animation`, which was started provisionally, as the running transition of its property+/// the owner at `slot` of `animations` holds, where `animations` is not null, which `origin` started, and has the host+/// associate it with its target through `perform`.+///+/// # Safety+/// A non-null `animations` must be lists the host holds, which nothing else refers to for the call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_css_transition_commit_provisional(+ animation: &AnimationCell,+ animations: *mut ElementAnimations,+ slot: AnimationOwnerSlot,+ origin: TransitionOrigin,+ perform: HostEffectPerformer,+) {+ // SAFETY: The host holds a reference to the animation it passes.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ let effects = {+ // SAFETY: Guaranteed by the caller.+ let animations = unsafe { animations.as_mut() };+ transitions::commit_provisional_transition(animations.map(|animations| (animations, slot)), animation, origin)+ };+ // NB: Associating the transition with its target reaches the lists again.+ perform_host_effects(effects, perform);+}++/// Writes to `existing` what a style change event at time `t` of the document timeline reads of the CSS transition+/// `animation`, which its target holds, whose values it lends for as long as the host holds the transition. The host+/// gives the current value of a running transition of a custom property.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition_existing(+ animation: &AnimationCell,+ t: f64,+ existing: &mut FfiExistingTransition,+) {+ *existing = animation.borrow().existing_transition(t);+}++/// Whether the CSS transition `animation` already runs from when the hover of a clock lane started it, as one of the+/// `lane_transitions` the lane leaves its element running does.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition_runs_as_lane_does(+ animation: &AnimationCell,+ lane_transitions: ak::Span<'_, FfiLaneTransition>,+) -> bool {+ animation.borrow().runs_as_lane_does(lane_transitions.as_slice())+}++/// Whether `lane_transition` is the run of the host's CSS transition `animation` by the hover of a clock lane.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition_is_host_transition_of(+ animation: &AnimationCell,+ lane_transition: &FfiLaneTransition,+) -> bool {+ animation.borrow().is_host_transition_of(lane_transition)+}++/// What becomes of the running CSS transition `animation` as the host takes in `lane_transitions`, which the hover of a+/// clock lane leaves its element running, where the lane's steps ended the transitions whose effects `cancelled` names+/// and saw those `seen` names.+#[unsafe(no_mangle)]+pub extern "C" fn animations_css_transition_lane_adoption(+ animation: &AnimationCell,+ lane_transitions: ak::Span<'_, FfiLaneTransition>,+ cancelled: ak::Span<'_, AnimationEffectId>,+ seen: ak::Span<'_, AnimationEffectId>,+) -> LaneAdoption {+ animation+ .borrow()+ .lane_adoption(lane_transitions.as_slice(), cancelled.as_slice(), seen.as_slice())+}++/// The host's `SVGAnimationElement` whose animation the SMIL animation `animation` is.+#[unsafe(no_mangle)]+pub extern "C" fn animations_smil_animation_element(animation: &AnimationCell) -> *mut c_void {+ match animation.borrow().kind() {+ AnimationKind::Smil { animation_element, .. } => animation_element.as_ptr(),+ _ => unreachable!("the animation is an SVG animation element's"),+ }+}++/// Compares two of the host's `DOM::Element`s in tree order, answering a negative number where the first comes first,+/// a positive one where it comes last, and zero where neither does.+pub type FfiTreeOrder = unsafe extern "C" fn(first: *mut c_void, second: *mut c_void) -> i32;++/// The tree order `compare` gives.+pub(crate) fn host_tree_order(compare: FfiTreeOrder) -> impl FnMut(NonNull<c_void>, NonNull<c_void>) -> Ordering {+ move |first, second| {+ // SAFETY: The host compares live elements of its own.+ unsafe { compare(first.as_ptr(), second.as_ptr()) }.cmp(&0)+ }+}++/// https://www.w3.org/TR/web-animations-1/#animation-composite-order+/// The relative composite order of `a` and `b`, as a negative number where `a` sorts first, a positive one where it+/// sorts last, and zero where they are the same animation, with `tree_order` comparing elements in tree order.+#[unsafe(no_mangle)]+pub extern "C" fn animations_composite_order(a: &AnimationCell, b: &AnimationCell, tree_order: FfiTreeOrder) -> i32 {+ if std::ptr::eq(a, b) {+ return 0;+ }+ composite_order(&a.borrow(), &b.borrow(), &mut host_tree_order(tree_order)) as i32+}++/// Takes a reference of the host's own to `animation`, which the host holds a reference to.+///+/// # Safety+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_animation_retain(animation: *const AnimationCell) {+ // SAFETY: Guaranteed by the caller.+ let _ = unsafe { AnimationHandle::retained_from_host(animation) }.into_raw();+}++/// Gives up a reference the host took to `animation` with `animations_animation_retain`, or was handed.+///+/// # Safety+/// `animation` must be an animation the host holds a reference to, which it gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_animation_unretain(animation: *const AnimationCell) {+ // SAFETY: Guaranteed by the caller.+ drop(unsafe { AnimationHandle::from_raw(animation) });+}++/// What a new document knows of animations, which the document owns.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_animations_create() -> *mut DocumentAnimations {+ Box::into_raw(Box::default())+}++/// Destroys what a document knows of animations, which keeps none of them alive.+///+/// # Safety+/// `animations` must be what `animations_document_animations_create` handed out, which the host gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_animations_destroy(animations: *mut DocumentAnimations) {+ // SAFETY: Guaranteed by the caller.+ drop(unsafe { Box::from_raw(animations) });+}++/// The set `kind` of the animations a document knows of, which lives as long as `animations`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_animations_set(+ animations: &mut DocumentAnimations,+ kind: DocumentAnimationSetKind,+) -> *mut WeakAnimationSet {+ animations.set_mut(kind)+}++/// Begins the outermost style stabilization epoch of a document.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_animations_begin_style_stabilization_epoch(animations: &mut DocumentAnimations) {+ animations.begin_style_stabilization_epoch();+}++/// Commits the events a document queued during its outermost style stabilization epoch to its pending animation event+/// queue as the epoch commits, answering how many it committed.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_animations_commit_provisional_events(+ animations: &mut DocumentAnimations,+) -> usize {+ animations.commit_provisional_events()+}++/// Appends `event` of `animation` to the pending animation event queue of a document, or, where `provisional`, to the+/// events it queues during its style stabilization epoch.+/// https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue+///+/// # Safety+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_animations_append_event(+ animations: &mut DocumentAnimations,+ animation: *const AnimationCell,+ event: &FfiPendingAnimationEvent,+ provisional: bool,+) {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ animations.pending_events.append(+ PendingAnimationEvent {+ animation,+ event: *event,+ },+ provisional,+ );+}++/// What queueing the events an animation frame established for an animation did: what made the animation, which only+/// has events where it is a CSS animation or a CSS transition, and how many it queued.+#[repr(C)]+pub struct FfiQueuedCssEvents {+ pub kind: FfiAnimationKind,+ pub count: u8,+}++/// https://drafts.csswg.org/css-transitions-2/#event-dispatch+/// https://www.w3.org/TR/css-animations-2/#event-dispatch+/// Appends the events the animation frame just established for `animation` to the pending animation event queue of a+/// document, or, where `provisional`, to the events it queues during its style stabilization epoch, each with the time+/// stamp `time_stamp` answers for the owning element of the animation.+///+/// # Safety+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_animations_queue_css_events(+ animations: &mut DocumentAnimations,+ animation: *const AnimationCell,+ provisional: bool,+ time_stamp: unsafe extern "C" fn(element: NonNull<c_void>) -> f64,+) -> FfiQueuedCssEvents {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ let events = animation.borrow_mut().take_css_events();+ let queued = FfiQueuedCssEvents {+ kind: events.kind,+ count: events.count,+ };+ if events.count == 0 {+ return queued;+ }+ let owner = animation+ .borrow()+ .owning_element()+ .expect("a CSS animation or transition with events has an owning element");+ // SAFETY: The animation keeps its owning element alive, and the host answers the time stamp of a live element.+ let time_stamp = unsafe { time_stamp(owner.element) };+ for css_event in &events.events[..usize::from(events.count)] {+ let event = FfiPendingAnimationEvent {+ kind: PendingAnimationEventKind::Css,+ css_event_type: css_event.r#type,+ playback_event_type: PlaybackEventType::Finish,+ time_event_type: TimeEventType::Begin,+ detail: 0,+ elapsed_time: css_event.elapsed_time,+ current_time: OptionalTimeValue::UNRESOLVED,+ timeline_time: OptionalTimeValue::UNRESOLVED,+ scheduled_event_time: events.scheduled_event_time,+ time_stamp,+ };+ animations.pending_events.append(+ PendingAnimationEvent {+ animation: animation.clone(),+ event,+ },+ provisional,+ );+ }+ queued+}++/// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events+/// Takes the events of the pending animation event queue of a document in the order to dispatch them in, comparing+/// elements in tree order with `tree_order`, has the host keep the animation of each alive through `keep_alive` with+/// `context`, and has it dispatch each through `dispatch` with `context`.+///+/// # Safety+/// `animations` must be what a live document knows of animations, which `dispatch` may reach again, and `context` must+/// be what `keep_alive` and `dispatch` expect.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_animations_dispatch_events(+ animations: *mut DocumentAnimations,+ tree_order: FfiTreeOrder,+ keep_alive: FfiKeepAlive,+ dispatch: unsafe extern "C" fn(context: *mut c_void, animation: &AnimationCell, event: &FfiPendingAnimationEvent),+ context: *mut c_void,+) {+ // NB: Steps 4 to 6 take and sort the events, which dispatching them leaves to the host.+ let events_to_dispatch = {+ // SAFETY: Guaranteed by the caller; nothing else reaches the queue until the events are taken.+ let animations = unsafe { &mut *animations };+ animations+ .pending_events+ .take_events_to_dispatch(&mut host_tree_order(tree_order))+ };+ // NB: Dispatching an event runs script, which can run the GC, which must not collect the animation of an event+ // yet to be dispatched.+ for event in &events_to_dispatch {+ // SAFETY: The host keeps alive an animation it is handed for as long as the call that handed it lasts.+ unsafe { keep_alive(context, &event.animation) };+ }+ // 7. Dispatch each of the events in events to dispatch at their corresponding target using the order established in+ // the previous step.+ for event in &events_to_dispatch {+ // SAFETY: Guaranteed by the caller.+ unsafe { dispatch(context, &event.animation, &event.event) };+ }+}++/// Calls `visit` with `context` and each GC cell of the host that keeps alive the elements the records of the events a+/// document queued name, which the document visits as the GC traces it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_animations_visit_pending_events(+ animations: &DocumentAnimations,+ context: *mut c_void,+ visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),+) {+ animations.pending_events.for_each_host_cell(|cell, kind| {+ // SAFETY: The host visits a cell of an animation it queued an event of.+ unsafe { visit(context, cell.as_ptr(), kind) }+ });+}++/// Adds `effect` to the set `kind` of the effects a document knows of, answering whether the set did not hold it yet.+///+/// # Safety+/// `effect` must be an effect the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_effect_set_insert(+ animations: &mut DocumentAnimations,+ kind: DocumentEffectSetKind,+ effect: *const AnimationEffectCell,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let effect = unsafe { EffectHandle::retained_from_host(effect) };+ animations.effect_set_mut(kind).insert(&effect)+}++/// Removes `effect` from the set `kind` of the effects a document knows of, answering whether the set held it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_effect_set_remove(+ animations: &mut DocumentAnimations,+ kind: DocumentEffectSetKind,+ effect: &AnimationEffectCell,+) -> bool {+ animations.effect_set_mut(kind).remove(effect)+}++/// Whether the set `kind` of the effects a document knows of holds `effect`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_document_effect_set_contains(+ animations: &mut DocumentAnimations,+ kind: DocumentEffectSetKind,+ effect: &AnimationEffectCell,+) -> bool {+ animations.effect_set_mut(kind).contains(effect)+}++/// Empties the set `kind` of the effects a document knows of, calling `callback` with `context` and each effect alive+/// to it, which the effect stays alive for the call of.+///+/// # Safety+/// `callback` must not reach the effects the document knows of, and `context` must be what it expects.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_document_effect_set_take_each(+ animations: &mut DocumentAnimations,+ kind: DocumentEffectSetKind,+ context: *mut c_void,+ callback: unsafe extern "C" fn(*mut c_void, &AnimationEffectCell),+) {+ animations.effect_set_mut(kind).take_each(|effect| {+ // SAFETY: Guaranteed by the caller.+ unsafe { callback(context, effect) };+ });+}++/// Adds `animation` to `set`, answering whether `set` did not hold it yet.+///+/// # Safety+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_weak_animation_set_insert(+ set: &mut WeakAnimationSet,+ animation: *const AnimationCell,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ set.insert(&unsafe { AnimationHandle::retained_from_host(animation) })+}++/// Removes `animation` from `set`, answering whether `set` held it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_remove(set: &mut WeakAnimationSet, animation: &AnimationCell) -> bool {+ set.remove(animation)+}++/// Whether `set` holds `animation`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_contains(set: &WeakAnimationSet, animation: &AnimationCell) -> bool {+ set.contains(animation)+}++/// Drops the entries of the animations in `set` that died, as the host begins to enumerate it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_prune(set: &mut WeakAnimationSet) {+ set.prune();+}++/// The number of entries of `set`, live or dead, which the host enumerates by index.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_entry_count(set: &WeakAnimationSet) -> usize {+ set.entry_count()+}++/// A reference, handed to the host, to the animation of the entry at `index` of `set`, or null where it died.+#[unsafe(no_mangle)]+pub extern "C" fn animations_weak_animation_set_get(set: &WeakAnimationSet, index: usize) -> *const AnimationCell {+ set.get(index).map_or(std::ptr::null(), AnimationHandle::into_raw)+}++/// The bytes the record of `animation` holds, without its associated effect's.+#[unsafe(no_mangle)]+pub extern "C" fn animations_animation_memory_size(animation: &AnimationCell) -> usize {+ animation.memory_size()+}++/// New empty lists of the animations of an element, which the element owns.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_create() -> *mut ElementAnimations {+ Box::into_raw(Box::default())+}++/// Destroys the lists of the animations of an element, giving up the references they hold.+///+/// # Safety+/// `animations` must be lists `animations_element_animations_create` handed out, which the host gives up.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_element_animations_destroy(animations: *mut ElementAnimations) {+ // SAFETY: Guaranteed by the caller.+ drop(unsafe { Box::from_raw(animations) });+}++/// Calls `visit` with `context` and each GC cell of the host that keeps alive what an animation the lists hold names.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_for_each_host_cell(+ animations: &ElementAnimations,+ context: *mut c_void,+ visit: unsafe extern "C" fn(context: *mut c_void, cell: *mut c_void, kind: HostCellKind),+) {+ animations.for_each_host_cell(|cell, kind| {+ // SAFETY: The host visits a cell of an animation it holds.+ unsafe { visit(context, cell.as_ptr(), kind) }+ });+}++/// Associates `animation` with the element, answering whether it was not associated yet.+///+/// # Safety+/// `animation` must be an animation the host holds a reference to.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_element_animations_associate(+ animations: &mut ElementAnimations,+ animation: *const AnimationCell,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let animation = unsafe { AnimationHandle::retained_from_host(animation) };+ if !animations.associate(animation.clone()) {+ return false;+ }+ animation.borrow_mut().did_associate_with_target();+ true+}++/// Disassociates `animation` from the element, answering whether it was associated.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_disassociate(+ animations: &mut ElementAnimations,+ animation: &AnimationCell,+) -> bool {+ animations.disassociate(animation)+}++#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_invalidate_composite_order(animations: &mut ElementAnimations) {+ animations.invalidate_composite_order();+}++/// Sorts the animations associated with the element in composite order, with `tree_order` comparing elements in tree+/// order.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_sort_in_composite_order(+ animations: &mut ElementAnimations,+ tree_order: FfiTreeOrder,+) {+ animations.sort_in_composite_order(&mut host_tree_order(tree_order));+}++/// One of the lists of the animations of an element.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy)]+pub enum ElementAnimationListKind {+ /// The animations associated with the element.+ Associated,+ /// The CSS animations of one owner.+ CssAnimations,+ /// The CSS transitions of one owner.+ Transitions,+}++fn element_animation_list(+ animations: &ElementAnimations,+ kind: ElementAnimationListKind,+ slot: AnimationOwnerSlot,+) -> &[AnimationHandle] {+ match kind {+ ElementAnimationListKind::Associated => animations.associated(),+ ElementAnimationListKind::CssAnimations => animations.css_animations(slot),+ ElementAnimationListKind::Transitions => animations.transitions(slot),+ }+}++/// The number of animations in the list `kind`, of the owner at `slot` where it is one of an owner's.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_count(+ animations: &ElementAnimations,+ kind: ElementAnimationListKind,+ slot: AnimationOwnerSlot,+) -> usize {+ element_animation_list(animations, kind, slot).len()+}++/// The animation at `index` in the list `kind`, of the owner at `slot` where it is one of an owner's, which it borrows+/// for as long as the list holds it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_get(+ animations: &ElementAnimations,+ kind: ElementAnimationListKind,+ slot: AnimationOwnerSlot,+ index: usize,+) -> *const AnimationCell {+ std::ptr::from_ref::<AnimationCell>(&element_animation_list(animations, kind, slot)[index])+}++/// The style engine of `host`, or none where it is null, which knows the element as `node`, or not at all where it is+/// zero.+///+/// # Safety+/// A non-null `host` must be live for the call.+unsafe fn style_engine_target<'a>(host: *const DocumentHost, node: u32) -> Option<StyleEngineTarget<'a>> {+ Some(StyleEngineTarget {+ // SAFETY: Guaranteed by the caller.+ host: unsafe { host.as_ref() }?,+ node: StyleNodeID::from_raw(node)?,+ })+}++/// Sets the CSS animations of the owner at `slot` to `records`, which it takes references of its own to, and publishes+/// them to the style engine of `host`, which knows the element as `node`, where the host names one.+///+/// # Safety+/// Each of `records` must be an animation the host holds a reference to, and a non-null `host` must be live for the+/// call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_element_animations_set_css_animations(+ animations: &mut ElementAnimations,+ slot: AnimationOwnerSlot,+ records: ak::Span<'_, *const AnimationCell>,+ host: *const DocumentHost,+ node: u32,+) {+ animations.set_css_animations(+ slot,+ records+ .as_slice()+ .iter()+ // SAFETY: Guaranteed by the caller.+ .map(|&record| unsafe { AnimationHandle::retained_from_host(record) }),+ // SAFETY: Guaranteed by the caller.+ unsafe { style_engine_target(host, node) },+ );+}++/// Whether the element has had CSS animations since it last cancelled them, or has transitions.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_has_css_animations_or_transitions(+ animations: &ElementAnimations,+) -> bool {+ animations.has_css_animations_or_transitions()+}++/// The property a CSS transition runs: the host's `PropertyID`, and the raw fly string of the name of a custom property,+/// or zero.+#[repr(C)]+pub struct FfiTransitionProperty {+ pub property_id: u16,+ pub custom_name: usize,+}++impl From<FfiTransitionProperty> for TransitionProperty {+ fn from(property: FfiTransitionProperty) -> Self {+ Self {+ property_id: property.property_id,+ custom_name: property.custom_name,+ }+ }+}++/// The record of the transition of `property` the owner at `slot` has, which the lists hold, or null.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_transition(+ animations: &ElementAnimations,+ slot: AnimationOwnerSlot,+ property: FfiTransitionProperty,+) -> *const AnimationCell {+ animations+ .transition(slot, property.into())+ .map_or(std::ptr::null(), |transition| &raw const **transition)+}++/// Removes the transition of `property` the owner at `slot` has, which is disassociated from its target once it is+/// inert.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_remove_transition(+ animations: &mut ElementAnimations,+ slot: AnimationOwnerSlot,+ property: FfiTransitionProperty,+) {+ animations.remove_transition(slot, property.into());+}++/// The host's function that runs `run` with `run_context` in an execution context it opens for `animation`, as its+/// caller, which hands it `context`, asks.+pub type FfiInExecutionContext = unsafe extern "C" fn(+ context: *mut c_void,+ animation: &AnimationCell,+ run: unsafe extern "C" fn(run_context: *mut c_void),+ run_context: *mut c_void,+);++/// Runs `run` in the execution context the host opens for `animation` through `in_execution_context` with `context`.+fn in_host_execution_context<F: FnOnce()>(+ in_execution_context: FfiInExecutionContext,+ context: *mut c_void,+ animation: &AnimationCell,+ run: F,+) {+ unsafe extern "C" fn run_once<F: FnOnce()>(run_context: *mut c_void) {+ // SAFETY: `run_context` is the `Option<F>` below, which outlives the host's call.+ let run = unsafe { &mut *run_context.cast::<Option<F>>() };+ (run.take().expect("the host runs the procedure once"))();+ }+ let mut run = Some(run);+ // SAFETY: The host runs `run_once` with `run_context` before it returns.+ unsafe { in_execution_context(context, animation, run_once::<F>, (&raw mut run).cast()) };+}++/// https://drafts.csswg.org/css-animations-2/#owning-element-section+/// Updating display to a value other than none will start all animations applied to the element by the animation-name+/// property.+/// Plays or pauses each CSS animation the element and its pseudo-elements own as its `animation-play-state` last+/// computed, the element's first and then each pseudo-element's in the order of the host's `PseudoElement`, each in an+/// execution context the host opens through `in_execution_context` with `context`. The host keeps each animation alive+/// through `keep_alive` with `context`, and performs what that asks of it through `perform`.+///+/// # Safety+/// `animations` must be the lists of an element, which live for the call, and which the host may change as it performs.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_element_animations_play_or_pause_css_animations(+ animations: *const ElementAnimations,+ keep_alive: FfiKeepAlive,+ in_execution_context: FfiInExecutionContext,+ context: *mut c_void,+ perform: HostEffectPerformer,+) {+ let mut previous_slot = None;+ // NB: What the host performs can change the lists, which are read anew for each owner and no borrow of which+ // outlives the read.+ // SAFETY: Guaranteed by the caller.+ while let Some((slot, css_animations)) = unsafe { &*animations }.css_animations_after(previous_slot) {+ previous_slot = Some(slot);+ for animation in &css_animations {+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.+ unsafe { keep_alive(context, animation) };+ }+ for animation in &css_animations {+ let play_state = animation.borrow().css_animation().last_css_play_state;+ let plays = match play_state {+ Some(CSS_ANIMATION_PLAY_STATE_RUNNING) => true,+ Some(CSS_ANIMATION_PLAY_STATE_PAUSED) => false,+ _ => unreachable!("a CSS-defined animation has the play state animation-play-state computed for it"),+ };+ in_host_execution_context(in_execution_context, context, animation, || {+ let ((), effects) = procedures::run(animation, |procedures| {+ if plays {+ procedures.play_from_css()+ } else {+ procedures.pause_from_css()+ }+ })+ .expect("playing or pausing an animation from CSS does not throw");+ perform_host_effects(effects, perform);+ });+ }+ }+}++/// https://drafts.csswg.org/css-animations-2/#owning-element-section+/// If the display property of an element is set to none and its display value would compute to none when ignoring the+/// Transitions and Animations cascade origins, then terminate running animations with this owning element.+/// Takes the CSS animations and transitions of the element and its pseudo-elements, publishes that the element and its+/// pseudo-elements own no CSS animations to the style engine of `host`, which knows the element as `node`, where the+/// host names one, and cancels each, in an execution context the host opens through `in_execution_context` with+/// `context` where it is not idle. The host keeps each animation alive through `keep_alive` with `context`, and+/// performs what that asks of it through `perform`.+///+/// # Safety+/// `animations` must be the lists of an element, which live for the call, and a non-null `host` must be live for the+/// call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_element_animations_cancel_css_animations_and_transitions(+ animations: *mut ElementAnimations,+ host: *const DocumentHost,+ node: u32,+ keep_alive: FfiKeepAlive,+ in_execution_context: FfiInExecutionContext,+ context: *mut c_void,+ perform: HostEffectPerformer,+) {+ // SAFETY: Guaranteed by the caller, and the borrow of the lists ends before the host performs anything.+ let taken =+ unsafe { &mut *animations }.take_css_animations_and_transitions(unsafe { style_engine_target(host, node) });+ for animation in &taken {+ // SAFETY: The host keeps alive an animation it is handed for as long as this call lasts.+ unsafe { keep_alive(context, animation) };+ }+ for animation in &taken {+ let cancel = || {+ let ((), effects) = procedures::run(animation, |procedures| {+ procedures.cancel(Invalidate::No);+ Ok(())+ })+ .expect("cancelling an animation does not throw");+ perform_host_effects(effects, perform);+ };+ // NB: Cancelling an animation that is not idle settles its promises and creates its cancel event.+ let (play_state, _) = procedures::run(animation, |procedures| Ok(procedures.play_state()))+ .expect("reading the play state does not throw");+ if play_state == AnimationPlayState::Idle {+ cancel();+ } else {+ in_host_execution_context(in_execution_context, context, animation, cancel);+ }+ }+}++/// The bytes the lists of the animations of an element hold, without the animations.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_memory_size(animations: &ElementAnimations) -> usize {+ animations.memory_size()+}++/// Forgets the descriptions of the effects of the element `animations` belongs to that the host published to the style+/// engine, as the element's identity in the engine changes.+#[unsafe(no_mangle)]+pub extern "C" fn animations_element_animations_forget_published_effect_descriptions(+ animations: &mut ElementAnimations,+) {+ animations.forget_published_effect_descriptions();+}++/// One effect the host samples on an element, by its record, with the record of its associated animation, or null+/// where it has none, which the host describes but does not sample.+#[repr(C)]+pub struct FfiSampledEffect {+ pub effect: *const AnimationEffectCell,+ pub animation: *const AnimationCell,+}++/// What the host samples of one element's effects: the description of each effect, in composite order, and the+/// effects it samples, each with the timing it samples it with.+pub(crate) struct SampledEffectDescriptions {+ pub(crate) descriptions: smallvec::SmallVec<[Arc<crate::css::style::effect_descriptions::EffectDescription>; 4]>,+ pub(crate) sampled: crate::css::style_compute::HostSampledEffects,+}++/// The descriptions of `effects` and the timing the host samples each with an animation with.+///+/// # Safety+/// Each effect and non-null animation `effects` names must be one the host holds a reference to.+pub(crate) unsafe fn describe_sampled_effects(effects: &[FfiSampledEffect]) -> SampledEffectDescriptions {+ let mut described = SampledEffectDescriptions {+ descriptions: smallvec::SmallVec::with_capacity(effects.len()),+ sampled: smallvec::SmallVec::with_capacity(effects.len()),+ };+ for sampled in effects {+ // SAFETY: Guaranteed by the caller.+ let (effect, animation) = unsafe { (&*sampled.effect, sampled.animation.as_ref()) };+ let effect = effect.borrow();+ let description = effect.description().clone();+ described.descriptions.push(description.clone());+ let Some(animation) = animation else {+ continue;+ };+ // NB: The style engine samples the animation's timeline as the timing model reads it now, with what moves it+ // as a clock tick samples it.+ let animation = animation.borrow();+ let timeline = animation.timeline();+ let timing = super::snapshot::EffectTimingSnapshot {+ effect: effect.timing(),+ playback: *animation.playback(),+ timeline: timeline.map(|timeline| timeline.sample()).unwrap_or_default(),+ has_timeline: timeline.is_some(),+ clock: timeline.map(|timeline| timeline.clock()).unwrap_or_default(),+ };+ described.sampled.push(crate::css::style_compute::HostSampledEffect {+ description,+ timing: (&timing).into(),+ });+ }+ described+}++unsafe extern "C" {+ fn ladybird_animations_document_is_active(document: NonNull<c_void>) -> bool;+ fn ladybird_animations_element_node_document(element: NonNull<c_void>) -> NonNull<c_void>;+}++/// The host's `DOM::Document` that is the node document of the host's `DOM::Element` `element`, which something the+/// caller holds keeps alive.+/// https://dom.spec.whatwg.org/#concept-node-document+fn element_node_document(element: NonNull<c_void>) -> NonNull<c_void> {+ // SAFETY: Guaranteed by the caller, and the host only reads the element.+ unsafe { ladybird_animations_element_node_document(element) }+}++/// Whether the host's `DOM::Document` `document`, which something the caller holds keeps alive, is an active document.+/// https://html.spec.whatwg.org/multipage/document-sequences.html#active-document+pub(super) fn document_is_active(document: NonNull<c_void>) -> bool {+ // SAFETY: Guaranteed by the caller, and the host only reads the document.+ unsafe { ladybird_animations_document_is_active(document) }+}++#[cfg(test)]+mod ffi_test_stubs {+ #[unsafe(no_mangle)]+ extern "C" fn ladybird_animations_document_is_active(_document: std::ptr::NonNull<std::ffi::c_void>) -> bool {+ true+ }++ #[unsafe(no_mangle)]+ extern "C" fn ladybird_animations_element_node_document(+ element: std::ptr::NonNull<std::ffi::c_void>,+ ) -> std::ptr::NonNull<std::ffi::c_void> {+ element+ }+}++/// What kind of timeline the host makes.+#[repr(u8)]+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum FfiTimelineKind {+ Document,+ Scroll,+ View,+ Internal,+}++/// One side of the view progress visibility range of a view timeline, as `ViewTimelineInsetEdge` describes it, whose+/// calculation, if any, is a style value or null.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiViewTimelineInsetEdge {+ pub is_auto: bool,+ pub px: f64,+ pub percentage: f64,+ pub calculated: *const c_void,+}++/// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiViewTimelineInset {+ pub start: FfiViewTimelineInsetEdge,+ pub end: FfiViewTimelineInsetEdge,+}++impl FfiViewTimelineInset {+ /// # Safety+ /// The calculations must be null or live style values.+ pub(crate) unsafe fn retained(&self) -> ViewTimelineInset {+ let edge = |edge: &FfiViewTimelineInsetEdge| ViewTimelineInsetEdge {+ is_auto: edge.is_auto,+ px: edge.px,+ percentage: edge.percentage,+ // SAFETY: Guaranteed by the caller.+ calculated: unsafe { retained_optional_value(edge.calculated) },+ };+ ViewTimelineInset {+ start: edge(&self.start),+ end: edge(&self.end),+ }+ }++ /// The inset `inset` describes, whose calculations it borrows.+ fn borrowing(inset: &ViewTimelineInset) -> Self {+ let edge = |edge: &ViewTimelineInsetEdge| FfiViewTimelineInsetEdge {+ is_auto: edge.is_auto,+ px: edge.px,+ percentage: edge.percentage,+ calculated: edge.calculated.pointer().cast(),+ };+ Self {+ start: edge(&inset.start),+ end: edge(&inset.end),+ }+ }+}++/// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source+/// The host's `DOM::Element` that is the source of a scroll timeline, or null, or, where `is_anonymous`, the host's+/// `CSS::Scroller` that an anonymous timeline finds from `target`, the host's `DOM::Element`, or from its+/// pseudo-element, the host's `PseudoElement`, where `has_pseudo_element`.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiScrollTimelineSource {+ pub element: *mut c_void,+ pub is_anonymous: bool,+ pub scroller: u8,+ pub target: *mut c_void,+ pub pseudo_element: u8,+ pub has_pseudo_element: bool,+}++impl FfiScrollTimelineSource {+ pub(crate) fn get(&self) -> ScrollTimelineSource {+ if !self.is_anonymous {+ return ScrollTimelineSource::Element(NonNull::new(self.element));+ }+ ScrollTimelineSource::Anonymous {+ scroller: self.scroller,+ target: NonNull::new(self.target).expect("an anonymous timeline has a target"),+ pseudo_element: self.has_pseudo_element.then_some(self.pseudo_element),+ }+ }+}++impl From<ScrollTimelineSource> for FfiScrollTimelineSource {+ fn from(source: ScrollTimelineSource) -> Self {+ let mut ffi = Self {+ element: std::ptr::null_mut(),+ is_anonymous: false,+ scroller: 0,+ target: std::ptr::null_mut(),+ pseudo_element: 0,+ has_pseudo_element: false,+ };+ match source {+ ScrollTimelineSource::Element(element) => {+ ffi.element = element.map_or(std::ptr::null_mut(), NonNull::as_ptr);+ }+ ScrollTimelineSource::Anonymous {+ scroller,+ target,+ pseudo_element,+ } => {+ ffi.is_anonymous = true;+ ffi.scroller = scroller;+ ffi.target = target.as_ptr();+ ffi.pseudo_element = pseudo_element.unwrap_or(0);+ ffi.has_pseudo_element = pseudo_element.is_some();+ }+ }+ ffi+ }+}++/// What the host makes a timeline of: a document timeline's origin time, a scroll timeline's source and axis, and a+/// view timeline's inset besides.+#[repr(C)]+pub struct FfiTimelineDescription {+ pub kind: FfiTimelineKind,+ pub origin_time: f64,+ pub source: FfiScrollTimelineSource,+ /// The host's `ScrollAxis`.+ pub axis: u8,+ pub inset: FfiViewTimelineInset,+}++/// A new timeline associated with the host's `DOM::Document` `document`, as `description` describes it, which has no+/// object script sees of it yet.+///+/// # Safety+/// The calculations of a view timeline's inset must be null or live style values.+pub(crate) unsafe fn create_timeline(+ document: NonNull<c_void>,+ description: &FfiTimelineDescription,+) -> TimelineHandle {+ let scroll = |view| {+ TimelineKind::Scroll(Box::new(ScrollTimelineState {+ source: description.source.get(),+ axis: description.axis,+ last_max_scroll_offset: None,+ followed_scroller: None,+ view,+ }))+ };+ let kind = match description.kind {+ FfiTimelineKind::Document => TimelineKind::Document {+ origin_time: description.origin_time,+ },+ FfiTimelineKind::Scroll => scroll(None),+ FfiTimelineKind::View => scroll(Some(ViewTimelineState {+ // SAFETY: Guaranteed by the caller.+ inset: unsafe { description.inset.retained() },+ last_metrics: None,+ subject_style_node: None,+ })),+ FfiTimelineKind::Internal => TimelineKind::Internal {+ time_for_observation: None,+ },+ };+ TimelineHandle::new(document, kind)+}++/// The host's `DOM::Document` that `timeline` is associated with.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_document(timeline: &TimelineCell) -> *mut c_void {+ timeline.document().as_ptr()+}++/// The scroll offsets at the start and at the end of the cover range of a view timeline, in CSS pixels.+#[repr(C)]+#[derive(Clone, Copy, Default)]+pub struct FfiViewTimelineCoverRange {+ pub start: f64,+ pub end: f64,+}++/// What the host reads of a timeline: what the timing model reads of it, with its duration and what moves it as a+/// clock tick samples it, what script observed of it, and the state of a scroll or view timeline.+#[repr(C)]+pub struct FfiTimeline {+ pub id: AnimationTimelineId,+ pub kind: FfiTimelineKind,+ /// Its current time is unresolved where the timeline is inactive.+ pub sample: TimelineSample,+ pub is_inactive: bool,+ pub duration: OptionalTimeValue,+ pub clock: TimelineClock,+ /// The current time a style sampling reads instead, where `has_style_sampling_override`.+ pub has_style_sampling_override: bool,+ pub style_sampling_override: OptionalTimeValue,+ pub can_sample_current_time_at_timestamp: bool,+ /// The task generation of the event loop in which script last observed the timeline, where+ /// `has_observation_task_generation`, and the current time it observed then.+ pub has_observation_task_generation: bool,+ pub observation_task_generation: u64,+ pub observed_current_time: OptionalTimeValue,+ /// The task generation in which script observed the timeline at a time ahead of its current time, where+ /// `was_observed_ahead`.+ pub was_observed_ahead: bool,+ pub observed_ahead_task_generation: u64,+ pub source: FfiScrollTimelineSource,+ pub axis: u8,+ /// The inset of a view timeline, whose calculations it borrows until the inset changes.+ pub inset: FfiViewTimelineInset,+ /// The cover range of a view timeline as its progress was last calculated, where `has_cover_range`.+ pub has_cover_range: bool,+ pub cover_range: FfiViewTimelineCoverRange,+}++/// What the host reads of `timeline`.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_read(timeline: &TimelineCell) -> FfiTimeline {+ let sample = timeline.sample();+ let is_inactive = timeline.is_inactive();+ let clock = timeline.clock();+ let record = timeline.borrow();+ let observation = record.observed_in_task_generation();+ let observed_ahead = record.observed_ahead_in_task_generation();+ let style_sampling_override = record.style_sampling_override();+ let no_edge = FfiViewTimelineInsetEdge {+ is_auto: true,+ px: 0.0,+ percentage: 0.0,+ calculated: std::ptr::null(),+ };+ let mut read = FfiTimeline {+ id: record.id(),+ kind: match &record.kind {+ TimelineKind::Document { .. } => FfiTimelineKind::Document,+ TimelineKind::Scroll(scroll) if scroll.view.is_some() => FfiTimelineKind::View,+ TimelineKind::Scroll(_) => FfiTimelineKind::Scroll,+ TimelineKind::Internal { .. } => FfiTimelineKind::Internal,+ },+ sample,+ is_inactive,+ duration: record.duration().into(),+ clock,+ has_style_sampling_override: style_sampling_override.is_some(),+ style_sampling_override: style_sampling_override.flatten().into(),+ can_sample_current_time_at_timestamp: record.can_sample_current_time_at_timestamp(),+ has_observation_task_generation: observation.0.is_some(),+ observation_task_generation: observation.0.unwrap_or(0),+ observed_current_time: observation.1.into(),+ was_observed_ahead: observed_ahead.is_some(),+ observed_ahead_task_generation: observed_ahead.unwrap_or(0),+ source: ScrollTimelineSource::Element(None).into(),+ axis: 0,+ inset: FfiViewTimelineInset {+ start: no_edge,+ end: no_edge,+ },+ has_cover_range: false,+ cover_range: FfiViewTimelineCoverRange::default(),+ };+ if let Some(scroll) = record.scroll() {+ read.source = scroll.source.into();+ read.axis = scroll.axis;+ if let Some(view) = &scroll.view {+ read.inset = FfiViewTimelineInset::borrowing(&view.inset);+ if let Some(metrics) = view.last_metrics {+ read.has_cover_range = true;+ read.cover_range = FfiViewTimelineCoverRange {+ start: metrics.cover_start(),+ end: metrics.cover_end(),+ };+ }+ }+ }+ read+}++/// The boxes a scroll timeline follows, as the host found them from its source in the render state of `host`'s+/// document, which it reads in `read`: the box of the scroll container, if any, the viewport's where the source is the+/// root element, its scroll node, where `has_scroll_node`, and the style node of the element whose box scrolls, or 0+/// for the viewport. For a view timeline, the box of its subject, if any, and the style node by which a clock tick finds+/// it, or 0 where the subject is a pseudo-element. `host` and `read` are null where the source has no box.+#[repr(C)]+pub struct FfiScrollTimelineBoxes {+ pub host: *const DocumentHost,+ pub read: *const BegunRead,+ pub scroller: NodeSlotId,+ pub has_scroll_node: bool,+ pub scroll_node: ScrollNodeStableId,+ pub scroller_style_node: u32,+ pub subject: NodeSlotId,+ pub subject_style_node: u32,+}++/// The host's function that updates the animations associated with its timeline `facade`.+pub type TimelineAnimationsUpdater = extern "C" fn(facade: *mut c_void);++/// Updates the current time of `timeline` in the task of `task_generation`: a document timeline's from the now+/// timestamp `timestamp`, and a scroll timeline's from where the render state lays out the boxes it follows, `boxes`,+/// unless that leaves it as it was where `only_if_stale`. Has `update_associated_animations` update the animations+/// associated with the timeline as its current time changes, and answers whether the timeline was updated.+///+/// # Safety+/// The host and the read of `boxes` must be null or a live document host and a read the host began of its render+/// state, in which the slots of `boxes` name its rows.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_timeline_update_current_time(+ timeline: &TimelineCell,+ timestamp: f64,+ boxes: Option<&FfiScrollTimelineBoxes>,+ task_generation: u64,+ only_if_stale: bool,+ update_associated_animations: TimelineAnimationsUpdater,+) -> bool {+ let facade = timeline.facade().expect("the host updates a live timeline");+ let update = || update_associated_animations(facade.as_ptr());+ let Some(boxes) = boxes else {+ timeline.update_current_time(TimelineUpdate::Timestamp(timestamp), task_generation, false, update);+ return true;+ };+ let subject_style_node = StyleNodeID::from_raw(boxes.subject_style_node);+ // SAFETY: Guaranteed by the caller.+ let (scroller, subject) = match unsafe { (boxes.host.as_ref(), boxes.read.as_ref()) } {+ (Some(host), Some(read)) => {+ let found = ScrollTimelineBoxes {+ scroller: boxes.scroller,+ scroll_node: boxes.has_scroll_node.then_some(boxes.scroll_node),+ scroller_style_node: boxes.scroller_style_node,+ subject: boxes.subject,+ };+ let record = timeline.borrow();+ let scroll = record.scroll().expect("the host lays out scroll timelines");+ host.ask(read, |state| {+ let arena = state.arena_mut();+ arena.settle_scrollable_overflow();+ scroll.measure(arena, &found)+ })+ }+ _ => (None, None),+ };+ timeline.update_current_time(+ TimelineUpdate::Layout {+ scroller: scroller.as_ref(),+ subject: subject.as_ref(),+ subject_style_node,+ },+ task_generation,+ only_if_stale,+ update,+ )+}++/// Sets the current time of the Internals interface's timeline `timeline` to `time`, in milliseconds, in the task of+/// `task_generation`, having `update_associated_animations` update its animations, or, where `for_observation`, the+/// time a read of it observes.+#[unsafe(no_mangle)]+pub extern "C" fn animations_internal_timeline_set_time(+ timeline: &TimelineCell,+ time: OptionalNumber,+ for_observation: bool,+ task_generation: u64,+ update_associated_animations: TimelineAnimationsUpdater,+) {+ let facade = timeline.facade().expect("the host sets the time of a live timeline");+ timeline.set_internal_time(time.get(), for_observation, task_generation, || {+ update_associated_animations(facade.as_ptr());+ });+}++/// The current time at the timestamp `timestamp` of `timeline`, where it can sample it there, and its current time+/// otherwise. Where `observed`, script observes it in the task of `task_generation`, which the timeline keeps.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_current_time_at_timestamp(+ timeline: &TimelineCell,+ timestamp: f64,+ observed: bool,+ task_generation: u64,+) -> OptionalTimeValue {+ timeline+ .current_time_at_timestamp(timestamp, observed.then_some(task_generation))+ .into()+}++/// Has a style sampling read `current_time` as the current time of `timeline` where `has_override`, and its current+/// time otherwise.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_set_style_sampling_override(+ timeline: &TimelineCell,+ has_override: bool,+ current_time: OptionalTimeValue,+) {+ timeline+ .borrow_mut()+ .set_style_sampling_override(has_override.then(|| current_time.get()));+}++/// The animations associated with `timeline`, which lives as long as the timeline.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_associated_animations(timeline: &TimelineCell) -> *mut WeakAnimationSet {+ timeline.associated_animations().as_ptr()+}++/// Sets the axis of the scroll timeline `timeline` to `axis`, the host's `ScrollAxis`, and the inset of a view+/// timeline to `inset`, answering whether that changed either.+///+/// # Safety+/// The calculations of `inset` must be null or live style values.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn animations_scroll_timeline_set_axis_and_inset(+ timeline: &TimelineCell,+ axis: u8,+ inset: Option<&FfiViewTimelineInset>,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let inset = inset.map(|inset| unsafe { inset.retained() });+ timeline.set_axis_and_inset(axis, inset)+}++/// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time+/// The origin-relative time of the timeline time `timeline_time` of `timeline`, which is unresolved where the timeline+/// defines no procedure to convert it.+#[unsafe(no_mangle)]+pub extern "C" fn animations_timeline_convert_to_origin_relative_time(+ timeline: &TimelineCell,+ timeline_time: OptionalTimeValue,+) -> OptionalNumber {+ timeline+ .convert_a_timeline_time_to_an_origin_relative_time(timeline_time.get())+ .into()}diff --git a/Libraries/LibWeb/Rust/src/animations/host_effects.rs b/Libraries/LibWeb/Rust/src/animations/host_effects.rsnew file mode 100644index 00000000000..b6e138a8f44--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/host_effects.rs@@ -0,0 +1,116 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the procedures of animations ask the host to do: settle promises, queue tasks and events, and invalidate+//! style. A procedure only records these, in the order its steps take them, and the host performs them once the+//! procedure has returned, holding no borrow of any record.++use super::animation::AnimationHandle;+use super::effect::EffectHandle;+use super::timing::TimeValue;+use smallvec::SmallVec;+use std::ffi::c_void;+use std::ptr::NonNull;++/// The type of an `AnimationPlaybackEvent` a procedure queues.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PlaybackEventType {+ Finish,+ Cancel,+ Remove,+}++/// One thing a procedure asks the host to do for an animation.+#[derive(Clone, Debug, PartialEq)]+pub(crate) enum HostEffectKind {+ /// https://www.w3.org/TR/web-animations-1/#current-ready-promise+ /// Let the current ready promise be a new promise in the relevant Realm of the animation.+ ReplaceReadyPromise,+ /// Resolve the current ready promise with the animation.+ ResolveReadyPromise,+ /// Reject the current ready promise with a DOMException named "AbortError", set its [[PromiseIsHandled]] internal+ /// slot to true, and let the current ready promise be a new resolved promise with the animation.+ RejectReadyPromise,+ /// https://www.w3.org/TR/web-animations-1/#current-finished-promise+ /// Let the current finished promise be a new promise in the relevant Realm of the animation.+ ReplaceFinishedPromise,+ /// Resolve the current finished promise with the animation.+ ResolveFinishedPromise,+ /// Reject the current finished promise with a DOMException named "AbortError", set its [[PromiseIsHandled]]+ /// internal slot to true, and let the current finished promise be a new promise.+ RejectFinishedPromise,+ /// Queue a task to run the finish notification steps of the animation, unless there is one queued already.+ QueueFinishNotificationTask,+ /// Cancel the queued task to run the finish notification steps of the animation, if any.+ CancelFinishNotificationTask,+ /// Create an `AnimationPlaybackEvent` and append it to the pending animation event queue of the animation's+ /// document for timing, or queue a task to dispatch it at the animation without one. Its scheduled event time is+ /// `scheduled_timeline_time` converted to an origin-relative time, where the timeline can convert it.+ QueuePlaybackEvent {+ r#type: PlaybackEventType,+ current_time: Option<TimeValue>,+ timeline_time: Option<TimeValue>,+ scheduled_timeline_time: Option<TimeValue>,+ },+ /// Invalidate the style the associated effect produces. `changes_plan` is whether this changes the animation as+ /// the last rendering update planned it for the render clock, rather than move it on in time, as a rendering+ /// update does.+ InvalidateEffect { changes_plan: bool },+ /// Unless the style the associated effect produces can skip its update for this frame, which the host notes+ /// then, invalidate it as `InvalidateEffect` does without changing the plan, where `invalidate`.+ InvalidateUnlessThrottled { invalidate: bool },+ /// Associate the animation with `element`, the host's `DOM::Element` the animation's associated effect targets.+ AssociateWithTarget { element: NonNull<c_void> },+ /// Disassociate the animation from `element`, the host's `DOM::Element` that `effect`, the animation's associated+ /// effect, targeted.+ DisassociateFromTarget {+ element: NonNull<c_void>,+ effect: EffectHandle,+ },+ /// Recompute the style of the target of `effect`, which no longer applies as it did.+ RecomputeEffectStyle { effect: EffectHandle },+ /// Ask for a repaint of the target of the associated effect.+ RequestRepaint,+ /// Ask the document of the target of the associated effect for a rendering update in `delay` milliseconds, as+ /// the effect begins.+ ScheduleWakeup { delay: f64 },+}++/// What one procedure asks the host to do, in order. Most procedures ask for little or nothing, which needs no+/// allocation.+#[derive(Default)]+pub(crate) struct HostEffects(SmallVec<[(AnimationHandle, HostEffectKind); 4]>);++impl HostEffects {+ pub(crate) fn push(&mut self, animation: &AnimationHandle, kind: HostEffectKind) {+ self.0.push((animation.clone(), kind));+ }++ /// Appends what another procedure asks the host to do after this.+ pub(crate) fn extend(&mut self, other: HostEffects) {+ self.0.extend(other.0);+ }++ /// What the procedures asked for, in order.+ pub(crate) fn iter(&self) -> impl Iterator<Item = &(AnimationHandle, HostEffectKind)> {+ self.0.iter()+ }++ #[cfg(test)]+ pub(crate) fn kinds(&self) -> Vec<HostEffectKind> {+ self.0.iter().map(|(_, kind)| kind.clone()).collect()+ }+}++impl IntoIterator for HostEffects {+ type Item = (AnimationHandle, HostEffectKind);+ type IntoIter = smallvec::IntoIter<[(AnimationHandle, HostEffectKind); 4]>;++ fn into_iter(self) -> Self::IntoIter {+ self.0.into_iter()+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/host_timing.rs b/Libraries/LibWeb/Rust/src/animations/host_timing.rsnew file mode 100644index 00000000000..327228899d1--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/host_timing.rs@@ -0,0 +1,315 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the host's per-frame decisions read of an animation and its associated effect: the throttling of its style+//! updates and ticks, the wakeups it arms, and what the compositor update hands the compositor. The record resolves+//! all of it from one current time, and decides what follows from its timing alone.++use super::animation::{AnimationKind, AnimationRecord, CSS_TRANSITION_PHASE_IDLE};+use super::timing::{+ self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, OptionalNumber,+ OptionalTimeValue, TimeValue, TimeValueType,+};+use crate::css::animation::FfiCompositeOperation;++/// What made an animation.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FfiAnimationKind {+ Script,+ CssAnimation,+ CssTransition,+ Smil,+}++/// The instant a compositor animation of an effect is anchored at, as far as the record decides it.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum FfiCompositorAnchorKind {+ /// The timing of the animation keeps the compositor from running it.+ None,+ /// The animation is anchored at the timestamp of the document's last animation frame.+ LastAnimationFrame,+ /// The animation is anchored at an origin-relative time.+ OriginRelativeTime,+}++/// What the host's per-frame decisions read of an animation and its associated effect, all of it at the current time+/// of the animation.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiAnimationTimingState {+ pub kind: FfiAnimationKind,+ pub playback: AnimationPlayback,+ pub play_state: AnimationPlayState,+ pub has_monotonically_increasing_timeline: bool,+ /// https://www.w3.org/TR/web-animations-1/#animation-current-time+ pub current_time: OptionalTimeValue,+ /// The current time of the animation at the timestamp the host asked about, where it asked about one.+ pub current_time_at_timestamp: OptionalTimeValue,+ /// Whether the animation has an associated effect, which the rest describe.+ pub has_effect: bool,+ pub effect: AnimationEffectTiming,+ pub composite: FfiCompositeOperation,+ pub phase: AnimationEffectPhase,+ pub is_in_effect: bool,+ pub end_time: TimeValue,+ pub previous_current_iteration: f64,+ /// Whether the animation is a CSS transition that has not started yet, whose play is pending until the next+ /// animation update.+ pub is_initial_pending_css_transition: bool,+ /// Where the compositor may run the effect as far as its timing goes, the instant it is anchored at, and the local+ /// time it has there.+ pub compositor_anchor: FfiCompositorAnchorKind,+ pub compositor_anchor_origin_relative_time: f64,+ pub compositor_anchor_local_time: f64,+ /// Whether the timing of the effect lets a paint-only effect that nothing on screen shows skip its updates.+ pub can_throttle_offscreen_effect: bool,+ /// Whether the timing of the effect lets an effect that the winners of all its properties replace skip its+ /// updates.+ pub can_throttle_replaced_effect: bool,+ /// The time until the effect next changes phase, where it is ahead.+ pub next_phase_boundary_delay: OptionalNumber,+ /// The local time of the next iteration event of a CSS animation whose ticks are throttled, as far as its timing+ /// decides.+ pub next_throttled_iteration_event_time: OptionalNumber,+}++fn is_milliseconds(time: TimeValue) -> bool {+ time.r#type == TimeValueType::Milliseconds+}++impl AnimationRecord {+ /// What made the animation.+ pub(crate) fn ffi_kind(&self) -> FfiAnimationKind {+ match self.kind() {+ AnimationKind::Script => FfiAnimationKind::Script,+ AnimationKind::CssAnimation(_) => FfiAnimationKind::CssAnimation,+ AnimationKind::CssTransition(_) => FfiAnimationKind::CssTransition,+ AnimationKind::Smil { .. } => FfiAnimationKind::Smil,+ }+ }++ /// What the host's per-frame decisions read of the animation now, with its current time at `timestamp`, where the+ /// host asks about one.+ pub(crate) fn timing_state(&self, timestamp: Option<f64>) -> FfiAnimationTimingState {+ let playback = *self.playback();+ let timeline = self.timeline();+ let timeline_time = timeline.and_then(|timeline| timeline.current_time());+ let current_time = timing::current_time_at(&playback, timeline_time);+ let current_time_at_timestamp = timestamp.and_then(|timestamp| {+ let timeline_time = timeline.and_then(|timeline| timeline.current_time_at_timestamp(timestamp, None));+ timing::current_time_at(&playback, timeline_time)+ });+ let sample = timeline.map(|timeline| timeline.sample());+ let has_monotonically_increasing_timeline = sample.is_some_and(|sample| sample.is_monotonically_increasing);++ let effect = self.effect().map(|effect| effect.borrow());+ let effect_timing = effect.as_ref().map(|effect| effect.timing());+ let resolved = effect_timing+ .as_ref()+ .map(|effect_timing| timing::resolve_timing(effect_timing, current_time, Some(&playback), sample.as_ref()));+ // https://www.w3.org/TR/web-animations-1/#associated-effect-end+ let associated_effect_end = match &effect_timing {+ Some(effect_timing) => timing::end_time(effect_timing),+ None => {+ let progress_based = timeline.is_some_and(|timeline| timeline.borrow().is_progress_based());+ TimeValue::zero(if progress_based {+ TimeValueType::Percentage+ } else {+ TimeValueType::Milliseconds+ })+ }+ };++ let mut state = FfiAnimationTimingState {+ kind: self.ffi_kind(),+ playback,+ play_state: timing::play_state_at(&playback, current_time, associated_effect_end),+ has_monotonically_increasing_timeline,+ current_time: current_time.into(),+ current_time_at_timestamp: current_time_at_timestamp.into(),+ has_effect: effect.is_some(),+ effect: effect_timing.unwrap_or_default(),+ composite: effect+ .as_ref()+ .map_or(FfiCompositeOperation::Replace, |effect| effect.composite()),+ phase: resolved+ .as_ref()+ .map_or(AnimationEffectPhase::Idle, |resolved| resolved.phase),+ is_in_effect: resolved.as_ref().is_some_and(timing::is_in_effect),+ end_time: associated_effect_end,+ previous_current_iteration: effect+ .as_ref()+ .map_or(0.0, |effect| effect.previous_current_iteration()),+ is_initial_pending_css_transition: playback.pending()+ && playback.has_pending_play_task+ && matches!(self.kind(), AnimationKind::CssTransition(state) if state.previous_phase == CSS_TRANSITION_PHASE_IDLE),+ compositor_anchor: FfiCompositorAnchorKind::None,+ compositor_anchor_origin_relative_time: 0.0,+ compositor_anchor_local_time: 0.0,+ can_throttle_offscreen_effect: false,+ can_throttle_replaced_effect: false,+ next_phase_boundary_delay: None.into(),+ next_throttled_iteration_event_time: None.into(),+ };+ drop(effect);+ if !state.has_effect {+ return state;+ }++ // NB: A compositor animation runs from an anchor on the monotonic clock, at the playback rate, through one+ // iteration or an infinite number of them.+ let timing = state.effect;+ let rate = playback.playback_rate;+ let runs_forward = rate > 0.0 && rate.is_finite();+ let runs_on_a_monotonic_clock = state.play_state == AnimationPlayState::Running+ && !playback.pending()+ && rate > 0.0+ && has_monotonically_increasing_timeline;+ let runs_one_or_infinite_iterations = timing.iteration_count.is_infinite() || timing.iteration_count == 1.0;+ let times_in_milliseconds = is_milliseconds(timing.start_delay) && is_milliseconds(timing.iteration_duration);+ let has_finite_positive_duration =+ timing.iteration_duration.value > 0.0 && timing.iteration_duration.value.is_finite();++ let compositor_may_run_it = state.play_state == AnimationPlayState::Running+ && (!playback.pending() || state.is_initial_pending_css_transition)+ && has_monotonically_increasing_timeline+ && matches!(state.phase, AnimationEffectPhase::Before | AnimationEffectPhase::Active)+ && runs_one_or_infinite_iterations+ && state.composite == FfiCompositeOperation::Replace+ && runs_forward+ && times_in_milliseconds+ && timing.iteration_duration.value > 0.0+ && (state.phase != AnimationEffectPhase::Before+ || timing::before_active_boundary_time(&timing) == timing.start_delay);+ if let Some(local_time) = current_time.filter(|time| compositor_may_run_it && is_milliseconds(*time)) {+ state.compositor_anchor_local_time = local_time.value;+ if !state.is_initial_pending_css_transition {+ state.compositor_anchor = FfiCompositorAnchorKind::LastAnimationFrame;+ } else if let Some(origin_relative_time) = timeline.and_then(|timeline| {+ // OPTIMIZATION: A new CSS transition is play-pending until the next animation update. Start its+ // compositor animation at the style change event time without resolving its pending task.+ timeline.convert_a_timeline_time_to_an_origin_relative_time(Some(TimeValue::milliseconds(+ self.css_transition_style_change_event_time(),+ )))+ }) {+ state.compositor_anchor = FfiCompositorAnchorKind::OriginRelativeTime;+ state.compositor_anchor_origin_relative_time = origin_relative_time;+ }+ }++ state.can_throttle_offscreen_effect = runs_on_a_monotonic_clock+ && rate.is_finite()+ && state.phase == AnimationEffectPhase::Active+ && times_in_milliseconds+ && has_finite_positive_duration+ && timing.end_delay.value == 0.0;+ state.can_throttle_replaced_effect = runs_on_a_monotonic_clock+ && state.phase == AnimationEffectPhase::Active+ && runs_one_or_infinite_iterations+ && times_in_milliseconds;++ if let Some(current_time) =+ current_time.filter(|time| times_in_milliseconds && is_milliseconds(*time) && rate > 0.0)+ {+ let mut next_phase_boundary = timing.start_delay.value;+ let ahead = if current_time.value < next_phase_boundary {+ true+ } else {+ next_phase_boundary += timing.iteration_duration.value * timing.iteration_count;+ !timing.iteration_count.is_infinite()+ };+ let delay = (next_phase_boundary - current_time.value) / rate;+ if ahead && delay > 0.0 {+ state.next_phase_boundary_delay = Some(delay).into();+ }+ }++ // NB: Observable throttled animations need a rendering update at the next iteration boundary, not at every+ // display refresh. Seeking and cancellation already request their own updates.+ if state.kind == FfiAnimationKind::CssAnimation+ && !playback.pending()+ && state.play_state == AnimationPlayState::Running+ && runs_forward+ && has_monotonically_increasing_timeline+ && times_in_milliseconds+ && has_finite_positive_duration+ {+ state.next_throttled_iteration_event_time = Some(+ timing.start_delay.value+ + (state.previous_current_iteration + 1.0 - timing.iteration_start)+ * timing.iteration_duration.value,+ )+ .into();+ }+ state+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::animations::animation::AnimationHandle;+ use crate::animations::effect::EffectHandle;+ use timing::{SpecifiedEffectTiming, SpecifiedIterationDuration};++ /// A script animation of an effect with an iteration duration of a second, `iterations` times, held at+ /// `current_time`.+ fn animation_held_at(current_time: f64, iterations: f64) -> AnimationHandle {+ let effect = EffectHandle::new();+ effect.borrow_mut().set_specified_timing(SpecifiedEffectTiming {+ iteration_duration: SpecifiedIterationDuration {+ is_auto: false,+ milliseconds: 1000.0,+ },+ start_delay: 100.0,+ iteration_count: iterations,+ ..SpecifiedEffectTiming::default()+ });+ effect.borrow_mut().normalize_specified_timing(None);+ let animation = AnimationHandle::new(AnimationKind::Script);+ animation.borrow_mut().set_effect(Some(effect));+ animation.borrow_mut().playback_mut().hold_time = Some(TimeValue::milliseconds(current_time)).into();+ animation+ }++ #[test]+ fn an_animation_without_a_timeline_runs_on_no_clock() {+ let state = animation_held_at(500.0, 1.0).borrow().timing_state(None);+ assert_eq!(state.kind, FfiAnimationKind::Script);+ assert_eq!(state.phase, AnimationEffectPhase::Active);+ assert!(state.is_in_effect);+ assert_eq!(state.current_time.get(), Some(TimeValue::milliseconds(500.0)));+ assert_eq!(state.compositor_anchor, FfiCompositorAnchorKind::None);+ assert!(!state.can_throttle_offscreen_effect);+ assert!(!state.can_throttle_replaced_effect);+ assert_eq!(state.next_throttled_iteration_event_time.get(), None);+ }++ #[test]+ fn the_next_phase_boundary_is_the_start_delay_and_then_the_active_end() {+ let state = animation_held_at(50.0, 2.0).borrow().timing_state(None);+ assert_eq!(state.phase, AnimationEffectPhase::Before);+ assert_eq!(state.next_phase_boundary_delay.get(), Some(50.0));++ let state = animation_held_at(600.0, 2.0).borrow().timing_state(None);+ assert_eq!(state.next_phase_boundary_delay.get(), Some(1500.0));++ let state = animation_held_at(600.0, f64::INFINITY).borrow().timing_state(None);+ assert_eq!(state.next_phase_boundary_delay.get(), None);+ }++ #[test]+ fn an_animation_without_an_effect_has_no_effect_timing() {+ let animation = AnimationHandle::new(AnimationKind::Script);+ let state = animation.borrow().timing_state(Some(0.0));+ assert!(!state.has_effect);+ assert_eq!(state.play_state, AnimationPlayState::Idle);+ assert_eq!(state.phase, AnimationEffectPhase::Idle);+ assert_eq!(state.next_phase_boundary_delay.get(), None);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs b/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rsnew file mode 100644index 00000000000..532c43bf5d4--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/keyframe_reflection.rs@@ -0,0 +1,443 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The keyframes script reads of an effect whose keyframes come from CSS, a `@keyframes` rule or a CSS transition,+//! and those a copy of such an effect takes.+//! https://drafts.csswg.org/css-animations-2/#keyframes++use super::animation::AnimationKind;+use super::bindings_api::ParsedEasing;+use super::effect::AnimationEffectRecord;+use super::keyframes::{+ CompositeOperationOrAuto, KEY_SCALE_FACTOR, KeyframeOrigin, KeyframeProperty, KeyframeSet, ResourceContext,+};+use crate::css::style_compute::{FfiReflectedKeyframeProperty, FfiStyleSheetResourceContext};+use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};+use std::ffi::c_void;+use std::ptr::NonNull;+use std::sync::Arc;++/// A keyframe of CSS as script reads it.+pub(crate) struct CssKeyframe {+ pub(crate) offset: f64,+ pub(crate) easing: ParsedEasing,+ pub(crate) composite: CompositeOperationOrAuto,+ pub(crate) properties: Vec<(KeyframeProperty, RetainedStyleValueData)>,+}++impl CssKeyframe {+ /// Sets the value the keyframe gives `property`, in place of what it gave it before.+ fn set(&mut self, property: KeyframeProperty, value: RetainedStyleValueData) {+ match self.properties.iter_mut().find(|(declared, _)| *declared == property) {+ Some((_, declared_value)) => *declared_value = value,+ None => self.properties.push((property, value)),+ }+ }+}++/// What reading the keyframes of CSS of an effect reads of it, which holds no borrow of its record.+pub(crate) struct ReflectedEffect {+ keyframes: Option<Arc<KeyframeSet>>,+ /// https://drafts.csswg.org/css-animations-2/#keyframes+ /// The easing a keyframe of the effect that declares none of its own runs: the `animation-timing-function` of its+ /// CSS animation, and `linear` for any other.+ default_easing: ParsedEasing,+ target: Option<NonNull<c_void>>,+ /// The host's `PseudoElement` of the target pseudo-selector, if any.+ pseudo_element: Option<u8>,+}++impl ReflectedEffect {+ pub(crate) fn of(effect: &AnimationEffectRecord) -> Self {+ let default_easing = effect+ .associated_animation()+ .map_or_else(ParsedEasing::linear, |animation| {+ let animation = animation.borrow();+ let AnimationKind::CssAnimation(state) = animation.kind() else {+ return ParsedEasing::linear();+ };+ state+ .applied_definition+ .as_ref()+ .and_then(|definition| ParsedEasing::of_timing_function(definition.timing_function()))+ .unwrap_or_else(ParsedEasing::ease)+ });+ Self {+ keyframes: effect.keyframes().cloned(),+ default_easing,+ target: effect.target_element(),+ pseudo_element: effect.pseudo_element().map(|pseudo_element| pseudo_element.kind),+ }+ }+}++/// The keyframes of CSS the effect runs as they are declared: those of each block of its `@keyframes` rule, or those+/// of its CSS transition, with the blocks of one offset, easing and composite operation merged.+fn declared_css_keyframes(effect: &ReflectedEffect) -> Vec<CssKeyframe> {+ let mut frames: Vec<CssKeyframe> = Vec::new();+ let Some(set) = effect.keyframes.as_deref() else {+ return frames;+ };++ let default_easing = &effect.default_easing;+ let mut append_frame =+ |key: u64,+ easing: Option<&RetainedStyleValueData>,+ composite: CompositeOperationOrAuto,+ declarations: &mut dyn Iterator<Item = (KeyframeProperty, &RetainedStyleValueData)>| {+ let offset = key as f64 / (100.0 * KEY_SCALE_FACTOR);+ // AD-HOC: Step 2.2 uses the computed timing function. Substitution-dependent keyframe easings use the+ // animation-wide easing for web compatibility.+ let easing = easing+ .and_then(ParsedEasing::of_timing_function)+ .unwrap_or_else(|| default_easing.clone());+ let index = match frames.iter().position(|frame| {+ frame.offset == offset+ && frame.easing.serialization() == easing.serialization()+ && frame.composite == composite+ }) {+ Some(index) => index,+ None => {+ frames.push(CssKeyframe {+ offset,+ easing,+ composite,+ properties: Vec::new(),+ });+ frames.len() - 1+ }+ };+ for (property, value) in declarations {+ frames[index].set(property, value.clone_retained());+ }+ };+ match set.declared_keyframes() {+ // 2.3.1. Cascade together all of its declaration blocks such that for each CSS property (except those that are+ // "not animatable", which must be ignored) the last declaration among all its <keyframe-block>+ // declarations takes precedence.+ Some(declared) => {+ for keyframe in declared.keyframes() {+ append_frame(+ keyframe.key,+ keyframe.easing.as_ref(),+ keyframe.composite,+ &mut declared+ .declarations_of(keyframe)+ .iter()+ .map(|(property, value)| (property.clone(), value)),+ );+ }+ }+ None => {+ for keyframe in set.keyframes() {+ let declarations = set.declarations_of(keyframe).iter().filter_map(|declaration| {+ Some((+ KeyframeProperty::Id(declaration.property_id),+ declaration.value.declared()?,+ ))+ });+ let custom_declarations = set.custom_declarations_of(keyframe).iter().filter_map(|declaration| {+ Some((+ KeyframeProperty::Custom(declaration.name.clone()),+ declaration.value.declared()?,+ ))+ });+ append_frame(+ keyframe.key,+ None,+ keyframe.composite,+ &mut declarations.chain(custom_declarations),+ );+ }+ }+ }+ frames+}++/// The keyframes of CSS a copy of the effect takes: those it declares, by their offsets, with the values of a CSS+/// transition unscaled by the effective zoom they were computed at.+pub(crate) fn css_keyframes_of_copy(effect: &ReflectedEffect) -> Vec<CssKeyframe> {+ let mut frames = declared_css_keyframes(effect);+ frames.sort_by(|first, second| first.offset.total_cmp(&second.offset));+ if let Some(set) = effect.keyframes.as_deref()+ && set.origin() == KeyframeOrigin::Transition+ {+ unscale_by_zoom(&mut frames, f64::from(set.computed_value_zoom()));+ }+ frames+}++/// The style sheet the keyframes of the effect come from, which a copy of it resolves URLs against.+pub(crate) fn resource_context(effect: &AnimationEffectRecord) -> Option<ResourceContext> {+ effect.keyframes()?.resource_context().cloned()+}++/// https://drafts.csswg.org/css-animations-2/#keyframes+/// The keyframes of CSS the effect runs as `getKeyframes()` returns them: the values a `@keyframes` rule declares+/// computed against the target, with its implicit endpoints taking the target's own values, and those of a CSS+/// transition, each by its offset, and unscaled by the effective zoom they were computed at.+pub(crate) fn computed_css_keyframes(effect: &ReflectedEffect) -> Vec<CssKeyframe> {+ let mut frames = declared_css_keyframes(effect);+ let Some(set) = effect.keyframes.as_deref() else {+ return frames;+ };+ if set.origin() == KeyframeOrigin::Transition {+ unscale_by_zoom(&mut frames, f64::from(set.computed_value_zoom()));+ return frames;+ }+ if set.declared_keyframes().is_none() {+ return frames;+ }+ let mut has_custom_properties = false;+ for frame in &mut frames {+ frame.properties.retain(|(property, _)| {+ let is_custom = matches!(property, KeyframeProperty::Custom(_));+ has_custom_properties |= is_custom;+ !is_custom+ });+ }+ let default_easing = &effect.default_easing;+ if !has_custom_properties && frames.iter().all(|frame| frame.properties.is_empty()) {+ return Vec::new();+ }++ let (target, pseudo_element) = (effect.target, effect.pseudo_element);+ if let Some(target) = target+ && let Some(underlying_values) =+ compute_css_keyframe_values(target, pseudo_element, &mut frames, set.resource_context())+ {+ for offset in [0.0, 1.0] {+ let mut present: Vec<u16> = Vec::new();+ let mut destination = None;+ for (index, frame) in frames.iter().enumerate() {+ if frame.offset != offset {+ continue;+ }+ present.extend(frame.properties.iter().filter_map(|(property, _)| match property {+ KeyframeProperty::Id(property_id) => Some(*property_id),+ KeyframeProperty::Custom(_) => None,+ }));+ // AD-HOC: Step 3.1 uses the default composite. Underlying-value endpoints use "replace", even for an+ // additive effect, so their values aren't added to themselves.+ if destination.is_none()+ && frame.easing.serialization() == default_easing.serialization()+ && matches!(+ frame.composite,+ CompositeOperationOrAuto::Auto | CompositeOperationOrAuto::Replace+ )+ {+ destination = Some(index);+ }+ }+ let missing: Vec<_> = underlying_values+ .iter()+ .filter(|(property_id, _)| !present.contains(property_id))+ .map(|(property_id, value)| (KeyframeProperty::Id(*property_id), value.clone_retained()))+ .collect();+ // AD-HOC: Custom properties contribute keyframe offsets and implicit endpoints, but their values are+ // omitted from CSS keyframe reflection for web compatibility.+ if missing.is_empty() && !has_custom_properties {+ continue;+ }+ // 3.2. For any property in animated properties that is not otherwise present in a keyframe with an offset+ // of 0% or one that would be positioned earlier in the used keyframe order, add the computed value of+ // that property on element to initial keyframe's keyframe values.+ match destination {+ Some(destination) => {+ for (property, value) in missing {+ frames[destination].set(property, value);+ }+ }+ None => {+ // AD-HOC: Step 3.3 prepends the initial keyframe. For web compatibility, reflected synthetic+ // endpoints follow explicitly declared frames at the same offset.+ frames.push(CssKeyframe {+ offset,+ easing: default_easing.clone(),+ composite: CompositeOperationOrAuto::Replace,+ properties: missing,+ });+ }+ }+ }+ }+ // 4. The computed order of keyframes—which is the order returned by getKeyframes()—is found by shifting any+ // keyframes whose offset was specified as a <percentage>, from keyword, or to keyword to the front of the list+ // (after the generated initial keyframe, if any), and performing a stable sort on these keyframes by their+ // keyframe offsets.+ frames.sort_by(|first, second| first.offset.total_cmp(&second.offset));+ let zoom = target.map_or(1.0, |target| {+ // SAFETY: The effect keeps its target alive.+ unsafe { web_animation_effective_zoom_of_target(target, pseudo_element.is_some(), pseudo_element.unwrap_or(0)) }+ });+ unscale_by_zoom(&mut frames, zoom);+ frames+}++/// Unscales the values of the longhands `frames` give by the effective zoom `zoom`.+/// https://drafts.csswg.org/css-viewport/#zoom-om+fn unscale_by_zoom(frames: &mut [CssKeyframe], zoom: f64) {+ use crate::css::property_metadata::property_id;+ for frame in frames {+ for (property, value) in &mut frame.properties {+ if matches!(+ property,+ KeyframeProperty::Id(property_id::ZOOM) | KeyframeProperty::Custom(_)+ ) {+ continue;+ }+ let unscaled = crate::css::style_value::rust_style_value_unscaled_by_zoom(value.data(), zoom);+ if !unscaled.is_null() {+ // SAFETY: The unscaled value is retained for the caller.+ *value = unsafe { RetainedStyleValueData::from_retained_pointer(unscaled) };+ }+ }+ }+}++/// Computes over the style of the host's `DOM::Element` `target`, or its pseudo-element of the host's+/// `PseudoElement` `pseudo_element`, what the longhands `frames` declare compute to, replacing each frame's+/// declarations with those, by their physical longhands, and answers the target's values of each of them, or none+/// where the target has no style to compute them over.+fn compute_css_keyframe_values(+ target: NonNull<c_void>,+ pseudo_element: Option<u8>,+ frames: &mut [CssKeyframe],+ resource_context: Option<&ResourceContext>,+) -> Option<Vec<(u16, RetainedStyleValueData)>> {+ let properties: Vec<FfiReflectedKeyframeProperty> = frames+ .iter()+ .enumerate()+ .flat_map(|(keyframe_index, frame)| {+ frame+ .properties+ .iter()+ .filter_map(move |(property, value)| match property {+ KeyframeProperty::Id(property_id) => Some(FfiReflectedKeyframeProperty {+ keyframe_index,+ property_id: *property_id,+ value: value.pointer(),+ }),+ KeyframeProperty::Custom(_) => None,+ })+ })+ .collect();+ let resource_context = resource_context.map_or(+ FfiStyleSheetResourceContext {+ base_url: std::ptr::null(),+ base_url_length: 0,+ has_value: false,+ origin_clean: false,+ },+ |context| FfiStyleSheetResourceContext {+ base_url: context.base_url.as_ptr(),+ base_url_length: context.base_url.len(),+ has_value: true,+ origin_clean: context.origin_clean,+ },+ );++ struct Computed {+ frames: Vec<Vec<(u16, RetainedStyleValueData)>>,+ underlying: Vec<(u16, RetainedStyleValueData)>,+ }+ unsafe extern "C" fn emit(context: *mut c_void, index: usize, property_id: u16, value: *const StyleValueData) {+ // SAFETY: The context is the computation below, and the value is live for the call.+ let (computed, value) = unsafe {+ (+ &mut *context.cast::<Computed>(),+ RetainedStyleValueData::from_retained_pointer(retain_style_value(value)),+ )+ };+ let values = computed.frames.get_mut(index).unwrap_or(&mut computed.underlying);+ match values.iter_mut().find(|(held, _)| *held == property_id) {+ Some((_, held)) => *held = value,+ None => values.push((property_id, value)),+ }+ }+ let mut computed = Computed {+ frames: frames.iter().map(|_| Vec::new()).collect(),+ underlying: Vec::new(),+ };+ // SAFETY: The effect keeps its target alive, and the declarations and resource context are live for the call.+ let computed_over_style = unsafe {+ web_animation_compute_css_keyframe_values(+ target,+ pseudo_element.is_some(),+ pseudo_element.unwrap_or(0),+ properties.as_ptr().cast(),+ properties.len(),+ frames.len(),+ &resource_context,+ (&raw mut computed).cast(),+ emit,+ )+ };+ if !computed_over_style {+ return None;+ }+ for (frame, values) in frames.iter_mut().zip(computed.frames) {+ frame.properties = values+ .into_iter()+ .map(|(property_id, value)| (KeyframeProperty::Id(property_id), value))+ .collect();+ }+ Some(computed.underlying)+}++unsafe extern "C" {+ /// Computes over the style of the target what the declarations `properties` of `keyframe_count` keyframes, from a+ /// style sheet with `resource_context`, compute to, emitting each computed value with the index of its keyframe and+ /// each value of the target with `keyframe_count`, or answers false where the target has no style. `properties`+ /// points at `property_count` `FfiReflectedKeyframeProperty`s.+ fn web_animation_compute_css_keyframe_values(+ target: NonNull<c_void>,+ has_pseudo_element: bool,+ pseudo_element: u8,+ properties: *const c_void,+ property_count: usize,+ keyframe_count: usize,+ resource_context: &FfiStyleSheetResourceContext,+ context: *mut c_void,+ emit: unsafe extern "C" fn(*mut c_void, usize, u16, *const StyleValueData),+ ) -> bool;++ /// The effective zoom of the computed style of the target, one where it has none.+ fn web_animation_effective_zoom_of_target(+ target: NonNull<c_void>,+ has_pseudo_element: bool,+ pseudo_element: u8,+ ) -> f64;+}++#[cfg(test)]+mod ffi_test_stubs {+ use super::*;++ #[unsafe(no_mangle)]+ extern "C" fn web_animation_compute_css_keyframe_values(+ _target: NonNull<c_void>,+ _has_pseudo_element: bool,+ _pseudo_element: u8,+ _properties: *const c_void,+ _property_count: usize,+ _keyframe_count: usize,+ _resource_context: &FfiStyleSheetResourceContext,+ _context: *mut c_void,+ _emit: unsafe extern "C" fn(*mut c_void, usize, u16, *const StyleValueData),+ ) -> bool {+ false+ }++ #[unsafe(no_mangle)]+ extern "C" fn web_animation_effective_zoom_of_target(+ _target: NonNull<c_void>,+ _has_pseudo_element: bool,+ _pseudo_element: u8,+ ) -> f64 {+ 1.0+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/keyframes.rs b/Libraries/LibWeb/Rust/src/animations/keyframes.rsnew file mode 100644index 00000000000..71d6be1182b--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/keyframes.rs@@ -0,0 +1,944 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Keyframe sets: the keyframes an effect runs, resolved from a `@keyframes` rule, from the keyframes script gave a+//! `KeyframeEffect`, or for a CSS transition.+//!+//! A set is immutable once built and shared by everything that runs it: every effect of one `@keyframes` rule holds+//! the rule's set. What depends on the effect running it, its composite operation and the easing a keyframe that+//! declares none runs, stays with the effect.++use crate::css::easing::Easing;+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::style_value::{RetainedStyleValueData, StyleValueData};+use std::ops::Range;+use std::sync::Arc;++/// What keyframe offsets are scaled by to key a keyframe: `KeyframeEffect::AnimationKeyFrameKeyScaleFactor`, which+/// keys an offset of 100% at 100000.+pub(crate) const KEY_SCALE_FACTOR: f64 = 1000.0;++/// The key of a keyframe at an offset of 0%.+pub(crate) const INITIAL_KEY: u64 = 0;++/// The key of a keyframe at an offset of 100%.+pub(crate) const FINAL_KEY: u64 = 100 * KEY_SCALE_FACTOR as u64;++/// https://drafts.csswg.org/web-animations-1/#enumdef-compositeoperationorauto+/// In the order of the host's `Bindings::CompositeOperationOrAuto`.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum CompositeOperationOrAuto {+ Replace,+ Add,+ Accumulate,+ Auto,+}++/// The easing a keyframe runs to the next one.+#[derive(Clone)]+pub(crate) enum KeyframeEasing {+ /// The keyframe declares none, and runs its effect's.+ None,+ Easing(Easing),+ /// An easing still to be substituted against the element the effect is sampled on.+ Value(RetainedStyleValueData),+}++/// What a keyframe declares for a property.+#[derive(Clone, PartialEq)]+pub(crate) enum KeyframeValue {+ /// The element's own value, held by a keyframe the initial and final keyframes were generated as, which is not+ /// known until the element is sampled.+ ElementValue,+ Declared(RetainedStyleValueData),+}++impl KeyframeValue {+ /// The declared value, or `None` for the element's own value.+ #[must_use]+ pub(crate) fn declared(&self) -> Option<&RetainedStyleValueData> {+ match self {+ Self::ElementValue => None,+ Self::Declared(value) => Some(value),+ }+ }+}++/// A property a keyframe declares, which may be a shorthand.+pub(crate) struct KeyframeDeclaration {+ pub(crate) property_id: u16,+ pub(crate) value: KeyframeValue,+}++/// A custom property a keyframe declares.+pub(crate) struct KeyframeCustomDeclaration {+ pub(crate) name: RetainedUtf16FlyString,+ pub(crate) value: KeyframeValue,+}++/// https://drafts.csswg.org/web-animations-1/#keyframe+pub(crate) struct Keyframe {+ /// The keyframe's offset, scaled by [`KEY_SCALE_FACTOR`].+ pub(crate) key: u64,+ pub(crate) composite: CompositeOperationOrAuto,+ pub(crate) easing: KeyframeEasing,+ declarations: Range<u32>,+ custom_declarations: Range<u32>,+}++/// The style sheet the keyframes of a `@keyframes` rule come from, which their URLs resolve against.+#[derive(Clone)]+pub(crate) struct ResourceContext {+ /// Shared with every resolution of the keyframes' declarations that points into it.+ pub(crate) base_url: Arc<[u8]>,+ pub(crate) origin_clean: bool,+}++/// A property an effect animates: a longhand or shorthand by its id, or a custom property by its name.+#[derive(Clone)]+pub(crate) enum KeyframeProperty {+ Id(u16),+ Custom(RetainedUtf16FlyString),+}++impl PartialEq for KeyframeProperty {+ fn eq(&self, other: &Self) -> bool {+ match (self, other) {+ (Self::Id(first), Self::Id(second)) => first == second,+ // NB: Fly strings are interned, so equal names share their raw representation.+ (Self::Custom(first), Self::Custom(second)) => first.raw() == second.raw(),+ _ => false,+ }+ }+}++/// What the keyframes of a set were made from.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum KeyframeOrigin {+ /// Keyframes script gave a `KeyframeEffect`, or anything else that is not CSS.+ Script,+ /// A `@keyframes` rule.+ KeyframesRule,+ /// A CSS transition.+ Transition,+}++/// https://drafts.csswg.org/css-animations-2/#keyframes+/// A keyframe block of a `@keyframes` rule as the rule declares it, once for each of the block's keys.+pub(crate) struct DeclaredKeyframe {+ /// The keyframe's offset, scaled by [`KEY_SCALE_FACTOR`].+ pub(crate) key: u64,+ pub(crate) composite: CompositeOperationOrAuto,+ /// The `animation-timing-function` the block declares where it names an easing without substituting anything;+ /// a block that declares none, or one that substitutes, runs its animation's.+ pub(crate) easing: Option<RetainedStyleValueData>,+ declarations: Range<u32>,+}++/// The keyframe blocks of a `@keyframes` rule in the order the rule declares them, before the keyframes of one key are+/// cascaded together, which script reads of the keyframes of a CSS animation.+pub(crate) struct DeclaredKeyframes {+ keyframes: Box<[DeclaredKeyframe]>,+ declarations: Box<[(KeyframeProperty, RetainedStyleValueData)]>,+}++impl DeclaredKeyframes {+ #[must_use]+ pub(crate) fn keyframes(&self) -> &[DeclaredKeyframe] {+ &self.keyframes+ }++ /// The properties the keyframe block declares, longhands and custom properties, in the order it declares them.+ #[must_use]+ pub(crate) fn declarations_of(&self, keyframe: &DeclaredKeyframe) -> &[(KeyframeProperty, RetainedStyleValueData)] {+ &self.declarations[keyframe.declarations.start as usize..keyframe.declarations.end as usize]+ }++ fn heap_size(&self) -> usize {+ size_of_val::<[DeclaredKeyframe]>(&self.keyframes)+ + size_of_val::<[(KeyframeProperty, RetainedStyleValueData)]>(&self.declarations)+ }+}++/// Where in a style sheet the keyframes of a set come from, which few sets have and none of a CSS transition does.+#[derive(Default)]+struct StyleSheetSource {+ resource_context: Option<ResourceContext>,+ declared_keyframes: Option<DeclaredKeyframes>,+}++impl StyleSheetSource {+ fn heap_size(&self) -> usize {+ size_of::<Self>()+ + self+ .resource_context+ .as_ref()+ .map_or(0, |context| crate::heap_size::ARC_HEADER_BYTES + context.base_url.len())+ + self.declared_keyframes.as_ref().map_or(0, DeclaredKeyframes::heap_size)+ }+}++/// The keyframes an effect runs, in the order they are used, with what follows from them alone.+pub struct KeyframeSet {+ keyframes: Box<[Keyframe]>,+ declarations: Box<[KeyframeDeclaration]>,+ custom_declarations: Box<[KeyframeCustomDeclaration]>,+ /// The style sheet the keyframes come from, which their URLs resolve against, and the keyframe blocks of the+ /// `@keyframes` rule they were made from, if they were.+ style_sheet_source: Option<Box<StyleSheetSource>>,+ /// The longhands the keyframes animate, sorted: what any shorthand they declare expands to.+ target_properties: Box<[u16]>,+ /// The custom properties the keyframes animate.+ target_custom_properties: Box<[RetainedUtf16FlyString]>,+ /// Whether a keyframe declares a custom property, or one that changes the layout tree's shape or what the main+ /// thread observes of an element's box, which a clock tick cannot sample.+ animates_what_a_tick_cannot: bool,+ /// Whether a keyframe declares a custom property or one the children of the target inherit.+ animates_an_inherited_property: bool,+ /// Whether a keyframe adds to or accumulates onto the value beneath it, whatever its effect does.+ has_additive_keyframe: bool,+ origin: KeyframeOrigin,+ /// The effective zoom the values of a CSS transition's keyframes were computed at, which script reads them+ /// unscaled by.+ computed_value_zoom: f32,+}++/// A keyframe a unit test gives a set: its key, composite operation, easing and declarations.+#[cfg(test)]+pub(crate) type KeyframeAsGiven = (+ u64,+ CompositeOperationOrAuto,+ KeyframeEasing,+ Vec<(KeyframeProperty, KeyframeValue)>,+);++/// A keyframe as a builder collects it, before the set lays its declarations out.+struct PendingKeyframe {+ key: u64,+ composite: CompositeOperationOrAuto,+ easing: KeyframeEasing,+ declarations: Vec<(KeyframeProperty, KeyframeValue)>,+}++impl PendingKeyframe {+ fn new(key: u64) -> Self {+ Self {+ key,+ composite: CompositeOperationOrAuto::Auto,+ easing: KeyframeEasing::None,+ declarations: Vec::new(),+ }+ }++ /// Sets what the keyframe declares for `property`, in place of what it declared before.+ fn set(&mut self, property: KeyframeProperty, value: KeyframeValue) {+ match self.declarations.iter_mut().find(|(declared, _)| *declared == property) {+ Some((_, declared_value)) => *declared_value = value,+ None => self.declarations.push((property, value)),+ }+ }++ /// Whether the keyframe declares `property`, or a shorthand of it.+ fn declares(&self, property: &KeyframeProperty) -> bool {+ use crate::css::property_metadata::{expanded_longhands_for_shorthand, property_is_shorthand};+ self.declarations+ .iter()+ .any(|(declared, _)| match (declared, property) {+ (KeyframeProperty::Id(shorthand), KeyframeProperty::Id(longhand))+ if property_is_shorthand(*shorthand) =>+ {+ expanded_longhands_for_shorthand(*shorthand).contains(longhand)+ }+ (declared, property) => declared == property,+ })+ }+}++/// The scaled key of a keyframe offset given as a percentage.+fn key_of_percentage(percentage: f64) -> u64 {+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]+ let key = (percentage * KEY_SCALE_FACTOR) as u64;+ key+}++/// Whether a property, by its id, can be animated: a longhand whose animation type is not `none`, or a shorthand+/// with such a longhand.+pub(crate) fn is_animatable_property(property_id: u16) -> bool {+ use crate::css::property_metadata::{longhands_for_shorthand, property_animation_type, property_is_shorthand};+ if property_is_shorthand(property_id) {+ return longhands_for_shorthand(property_id)+ .iter()+ .any(|&longhand| is_animatable_property(longhand));+ }+ property_animation_type(property_id) != crate::css::animation::ANIMATION_TYPE_NONE+}++/// The animated properties of a declaration of `property_id` with `value`: the longhands it expands to.+fn expanded_longhands(+ property_id: u16,+ value: &RetainedStyleValueData,+ mut sink: impl FnMut(u16, &RetainedStyleValueData),+) {+ crate::css::style_compute::expand_shorthands_with(property_id, value, false, &mut |longhand, longhand_value, _| {+ sink(longhand, longhand_value);+ });+}++/// The animated properties a builder collected, without duplicates, in the order it found them.+#[derive(Default)]+struct AnimatedProperties(Vec<KeyframeProperty>);++impl AnimatedProperties {+ fn insert(&mut self, property: KeyframeProperty) {+ if !self.0.contains(&property) {+ self.0.push(property);+ }+ }+}++impl KeyframeSet {+ /// The keyframes of a `@keyframes` rule, given as each keyframe block's keys, which are percentages, and its+ /// declarations, from a style sheet with `resource_context`.+ ///+ /// Loosely based on https://drafts.csswg.org/css-animations-2/#keyframe-processing+ pub(crate) fn from_keyframes_rule<'a>(+ blocks: impl IntoIterator<Item = (&'a [f64], &'a crate::css::declaration_block::DeclarationBlockHeader)>,+ resource_context: Option<ResourceContext>,+ ) -> Self {+ use crate::css::css_enums::keyword;+ use crate::css::property_metadata::property_id;++ let mut keyframes: Vec<PendingKeyframe> = Vec::new();+ let mut animated_properties = AnimatedProperties::default();+ let mut declared_keyframes = Vec::new();+ let mut declared_declarations = Vec::new();++ // Forwards pass, resolve all the user-specified keyframe properties.+ for (keys, block) in blocks {+ let mut resolved_keyframe = PendingKeyframe::new(0);+ let mut declared_easing = None;+ for declaration in block.properties() {+ let value = RetainedStyleValueData::from_arc(declaration.value.clone());+ match declaration.property_id {+ property_id::ANIMATION_TIMING_FUNCTION => {+ // animation-timing-function is a list property, but inside @keyframes only a single value is+ // meaningful.+ let value = match value.data() {+ StyleValueData::ValueList { values, .. } => match values.as_slice().first() {+ Some(first) => first.clone_retained(),+ None => continue,+ },+ _ => value,+ };+ if crate::css::style_compute::value_is_css_wide_keyword(value.data()) {+ continue;+ }+ resolved_keyframe.easing = match value.data() {+ StyleValueData::Easing(_) | StyleValueData::Keyword { .. } => {+ declared_easing = Some(value.clone_retained());+ KeyframeEasing::Easing(+ crate::css::style::effect_descriptions::easing_from_computed_timing_function(+ value.data(),+ )+ .expect("an easing or keyword timing function describes an easing"),+ )+ }+ _ => {+ declared_easing = None;+ KeyframeEasing::Value(value)+ }+ };+ }+ property_id::ANIMATION_COMPOSITION => {+ let value = match value.data() {+ StyleValueData::ValueList { values, .. } if values.len() == 1 => {+ values.as_slice()[0].clone_retained()+ }+ _ => value,+ };+ resolved_keyframe.composite = match value.data() {+ StyleValueData::Keyword { keyword: keyword::ADD } => CompositeOperationOrAuto::Add,+ StyleValueData::Keyword {+ keyword: keyword::ACCUMULATE,+ } => CompositeOperationOrAuto::Accumulate,+ _ => CompositeOperationOrAuto::Replace,+ };+ }+ property if !is_animatable_property(property) => {}+ property => {+ // Unresolved properties are resolved when the effect is sampled.+ expanded_longhands(property, &value, |longhand, longhand_value| {+ animated_properties.insert(KeyframeProperty::Id(longhand));+ resolved_keyframe.set(+ KeyframeProperty::Id(longhand),+ KeyframeValue::Declared(longhand_value.clone_retained()),+ );+ });+ }+ }+ }+ for custom_property in block.custom_properties().iter() {+ let name = RetainedUtf16FlyString::from_utf16(custom_property.name.units());+ animated_properties.insert(KeyframeProperty::Custom(name.clone()));+ resolved_keyframe.set(+ KeyframeProperty::Custom(name),+ KeyframeValue::Declared(RetainedStyleValueData::from_arc(+ custom_property.declaration.value.clone(),+ )),+ );+ }++ let first_declaration = declaration_index(declared_declarations.len());+ declared_declarations.extend(+ resolved_keyframe+ .declarations+ .iter()+ .filter_map(|(property, value)| Some((property.clone(), value.declared()?.clone_retained()))),+ );+ let declarations = first_declaration..declaration_index(declared_declarations.len());+ for &key in keys {+ let key = key_of_percentage(key);+ declared_keyframes.push(DeclaredKeyframe {+ key,+ composite: resolved_keyframe.composite,+ easing: declared_easing.as_ref().map(RetainedStyleValueData::clone_retained),+ declarations: declarations.clone(),+ });+ match keyframes.iter_mut().find(|keyframe| keyframe.key == key) {+ Some(existing_keyframe) => {+ for (property, value) in &resolved_keyframe.declarations {+ existing_keyframe.set(property.clone(), value.clone());+ }+ if resolved_keyframe.composite != CompositeOperationOrAuto::Auto {+ existing_keyframe.composite = resolved_keyframe.composite;+ }+ if !matches!(resolved_keyframe.easing, KeyframeEasing::None) {+ existing_keyframe.easing = resolved_keyframe.easing.clone();+ }+ }+ None => keyframes.push(PendingKeyframe {+ key,+ composite: resolved_keyframe.composite,+ easing: resolved_keyframe.easing.clone(),+ declarations: resolved_keyframe.declarations.clone(),+ }),+ }+ }+ }++ let mut set = Self::with_initial_and_final_frames(keyframes, &animated_properties, resource_context);+ set.origin = KeyframeOrigin::KeyframesRule;+ set.style_sheet_source.get_or_insert_default().declared_keyframes = Some(DeclaredKeyframes {+ keyframes: declared_keyframes.into(),+ declarations: declared_declarations.into(),+ });+ set+ }++ /// The keyframes script gave a `KeyframeEffect`, each with its computed offset already scaled to a key, in the+ /// order they were given, from a style sheet with `resource_context` where they were copied from keyframes of CSS.+ pub(crate) fn from_processed_keyframes(+ keyframes: Vec<ProcessedKeyframe>,+ resource_context: Option<ResourceContext>,+ ) -> Self {+ let mut animated_properties = AnimatedProperties::default();+ let keyframes = keyframes+ .into_iter()+ .map(|keyframe| {+ let mut resolved_keyframe = PendingKeyframe::new(keyframe.key);+ resolved_keyframe.composite = keyframe.composite;+ resolved_keyframe.easing = keyframe.easing.map_or(KeyframeEasing::None, KeyframeEasing::Easing);+ for (property, value) in keyframe.declarations {+ match &property {+ KeyframeProperty::Custom(_) => animated_properties.insert(property.clone()),+ &KeyframeProperty::Id(property_id) => expanded_longhands(property_id, &value, |longhand, _| {+ animated_properties.insert(KeyframeProperty::Id(longhand));+ }),+ }+ resolved_keyframe.set(property, KeyframeValue::Declared(value));+ }+ resolved_keyframe+ })+ .collect();+ Self::with_initial_and_final_frames(keyframes, &animated_properties, resource_context)+ }++ /// The keyframes of a computation of the values `frames` declare over an element, each property by its id, keyed+ /// by their position, replacing the value beneath them, from a style sheet with `resource_context`. No initial or+ /// final keyframe is made of what they leave out.+ pub(crate) fn for_value_computation(+ frames: Vec<Vec<(u16, RetainedStyleValueData)>>,+ resource_context: Option<ResourceContext>,+ ) -> Self {+ let mut animated_properties = AnimatedProperties::default();+ let keyframes = frames+ .into_iter()+ .enumerate()+ .map(|(index, declarations)| {+ let mut keyframe = PendingKeyframe::new(index as u64);+ keyframe.composite = CompositeOperationOrAuto::Replace;+ for (property_id, value) in declarations {+ animated_properties.insert(KeyframeProperty::Id(property_id));+ keyframe.set(KeyframeProperty::Id(property_id), KeyframeValue::Declared(value));+ }+ keyframe+ })+ .collect();+ Self::laid_out(keyframes, &animated_properties, resource_context)+ }++ /// The keyframes of a CSS transition of `property` from `start` to `end`, values computed at the effective zoom+ /// `computed_value_zoom`.+ pub(crate) fn for_transition(+ property: KeyframeProperty,+ start: RetainedStyleValueData,+ end: RetainedStyleValueData,+ computed_value_zoom: f32,+ ) -> Self {+ let keyframe = |key, value| {+ let mut keyframe = PendingKeyframe::new(key);+ keyframe.set(property.clone(), KeyframeValue::Declared(value));+ keyframe+ };+ let mut animated_properties = AnimatedProperties::default();+ animated_properties.insert(property.clone());+ let mut set = Self::laid_out(+ vec![keyframe(INITIAL_KEY, start), keyframe(FINAL_KEY, end)],+ &animated_properties,+ None,+ );+ set.origin = KeyframeOrigin::Transition;+ set.computed_value_zoom = computed_value_zoom;+ set+ }++ /// The set of `keyframes`, each given as its key, composite operation, easing and declarations, exactly as given,+ /// for a unit test.+ #[cfg(test)]+ pub(crate) fn from_keyframes_as_given(keyframes: Vec<KeyframeAsGiven>) -> Self {+ let mut animated_properties = AnimatedProperties::default();+ let keyframes = keyframes+ .into_iter()+ .map(|(key, composite, easing, declarations)| {+ for (property, _) in &declarations {+ animated_properties.insert(property.clone());+ }+ PendingKeyframe {+ key,+ composite,+ easing,+ declarations,+ }+ })+ .collect();+ Self::laid_out(keyframes, &animated_properties, None)+ }++ /// The set of `keyframes`, once the initial and final keyframes are generated for `animated_properties`.+ fn with_initial_and_final_frames(+ mut keyframes: Vec<PendingKeyframe>,+ animated_properties: &AnimatedProperties,+ resource_context: Option<ResourceContext>,+ ) -> Self {+ // NB: The keyframes are used in the order of their keys, and those of one key in the order they were given.+ keyframes.sort_by_key(|keyframe| keyframe.key);+ generate_initial_and_final_frames(&mut keyframes, animated_properties);+ Self::laid_out(keyframes, animated_properties, resource_context)+ }++ fn laid_out(+ keyframes: Vec<PendingKeyframe>,+ animated_properties: &AnimatedProperties,+ resource_context: Option<ResourceContext>,+ ) -> Self {+ use crate::css::property_metadata::{property_id, property_is_inherited};++ let mut declarations = Vec::new();+ let mut custom_declarations = Vec::new();+ let mut animates_what_a_tick_cannot = false;+ let mut animates_an_inherited_property = false;+ let mut has_additive_keyframe = false;+ let index = declaration_index;+ let keyframes = keyframes+ .into_iter()+ .map(|keyframe| {+ has_additive_keyframe |= matches!(+ keyframe.composite,+ CompositeOperationOrAuto::Add | CompositeOperationOrAuto::Accumulate+ );+ let first_declaration = index(declarations.len());+ let first_custom_declaration = index(custom_declarations.len());+ for (property, value) in keyframe.declarations {+ match property {+ KeyframeProperty::Id(property_id) => {+ animates_what_a_tick_cannot |= matches!(+ property_id,+ property_id::DISPLAY | property_id::VISIBILITY | property_id::CONTENT_VISIBILITY+ );+ animates_an_inherited_property |= property_is_inherited(property_id);+ declarations.push(KeyframeDeclaration { property_id, value });+ }+ KeyframeProperty::Custom(name) => {+ animates_what_a_tick_cannot = true;+ animates_an_inherited_property = true;+ custom_declarations.push(KeyframeCustomDeclaration { name, value });+ }+ }+ }+ Keyframe {+ key: keyframe.key,+ composite: keyframe.composite,+ easing: keyframe.easing,+ declarations: first_declaration..index(declarations.len()),+ custom_declarations: first_custom_declaration..index(custom_declarations.len()),+ }+ })+ .collect();++ let mut target_properties: Vec<u16> = Vec::new();+ let mut target_custom_properties = Vec::new();+ for property in &animated_properties.0 {+ match property {+ KeyframeProperty::Id(property_id) => target_properties.push(*property_id),+ KeyframeProperty::Custom(name) => target_custom_properties.push(name.clone()),+ }+ }+ target_properties.sort_unstable();+ target_properties.dedup();++ Self {+ keyframes,+ declarations: declarations.into(),+ custom_declarations: custom_declarations.into(),+ style_sheet_source: resource_context.map(|resource_context| {+ Box::new(StyleSheetSource {+ resource_context: Some(resource_context),+ declared_keyframes: None,+ })+ }),+ target_properties: target_properties.into(),+ target_custom_properties: target_custom_properties.into(),+ animates_what_a_tick_cannot,+ animates_an_inherited_property,+ has_additive_keyframe,+ origin: KeyframeOrigin::Script,+ computed_value_zoom: 1.0,+ }+ }++ /// Another reference to the set `set` names.+ ///+ /// # Safety+ /// `set` must be a keyframe set the host holds a reference to.+ #[must_use]+ pub(crate) unsafe fn retained_from_host(set: *const Self) -> Arc<Self> {+ // SAFETY: Guaranteed by the caller.+ unsafe {+ Arc::increment_strong_count(set);+ Arc::from_raw(set)+ }+ }++ /// The keyframes, in the order they are used.+ #[must_use]+ pub(crate) fn keyframes(&self) -> &[Keyframe] {+ &self.keyframes+ }++ #[must_use]+ pub(crate) fn declarations_of(&self, keyframe: &Keyframe) -> &[KeyframeDeclaration] {+ &self.declarations[keyframe.declarations.start as usize..keyframe.declarations.end as usize]+ }++ #[must_use]+ pub(crate) fn custom_declarations_of(&self, keyframe: &Keyframe) -> &[KeyframeCustomDeclaration] {+ &self.custom_declarations+ [keyframe.custom_declarations.start as usize..keyframe.custom_declarations.end as usize]+ }++ /// The custom properties all the keyframes declare, in the order they are used.+ #[must_use]+ pub(crate) fn custom_declarations(&self) -> &[KeyframeCustomDeclaration] {+ &self.custom_declarations+ }++ /// The style sheet the keyframes come from, which their URLs resolve against.+ #[must_use]+ pub(crate) fn resource_context(&self) -> Option<&ResourceContext> {+ self.style_sheet_source.as_ref()?.resource_context.as_ref()+ }++ #[must_use]+ pub(crate) fn origin(&self) -> KeyframeOrigin {+ self.origin+ }++ /// The keyframe blocks of the `@keyframes` rule the keyframes were made from, if they were.+ #[must_use]+ pub(crate) fn declared_keyframes(&self) -> Option<&DeclaredKeyframes> {+ self.style_sheet_source.as_ref()?.declared_keyframes.as_ref()+ }++ /// The effective zoom the values of a CSS transition's keyframes were computed at.+ #[must_use]+ pub(crate) fn computed_value_zoom(&self) -> f32 {+ self.computed_value_zoom+ }++ /// The longhands the keyframes animate, sorted.+ #[must_use]+ pub(crate) fn target_properties(&self) -> &[u16] {+ &self.target_properties+ }++ /// The custom properties the keyframes animate.+ #[must_use]+ pub(crate) fn target_custom_properties(&self) -> &[RetainedUtf16FlyString] {+ &self.target_custom_properties+ }++ /// Whether the compositor may run all the keyframes animate.+ #[must_use]+ pub(crate) fn may_run_on_the_compositor(&self) -> bool {+ use crate::css::property_metadata::property_id;+ self.target_custom_properties.is_empty()+ && self.target_properties.iter().all(|property| {+ matches!(+ *property,+ property_id::OPACITY+ | property_id::BACKGROUND_COLOR+ | property_id::FILTER+ | property_id::TRANSLATE+ | property_id::ROTATE+ | property_id::SCALE+ | property_id::TRANSFORM+ )+ })+ }++ #[must_use]+ pub(crate) fn animates_what_a_tick_cannot(&self) -> bool {+ self.animates_what_a_tick_cannot+ }++ #[must_use]+ pub(crate) fn animates_an_inherited_property(&self) -> bool {+ self.animates_an_inherited_property+ }++ #[must_use]+ pub(crate) fn has_additive_keyframe(&self) -> bool {+ self.has_additive_keyframe+ }++ /// Every value the keyframes declare or run their easing by.+ pub(crate) fn declared_values(&self) -> impl Iterator<Item = &StyleValueData> {+ let declared = self+ .declarations+ .iter()+ .map(|declaration| &declaration.value)+ .chain(self.custom_declarations.iter().map(|declaration| &declaration.value))+ .filter_map(KeyframeValue::declared);+ let easings = self.keyframes.iter().filter_map(|keyframe| match &keyframe.easing {+ KeyframeEasing::Value(value) => Some(value),+ KeyframeEasing::None | KeyframeEasing::Easing(_) => None,+ });+ declared+ .chain(easings)+ .filter_map(RetainedStyleValueData::optional_data)+ }++ /// The bytes the set holds on the heap, beside itself. The values it declares are their rules'.+ #[must_use]+ pub(crate) fn heap_size(&self) -> usize {+ self.style_sheet_source.as_ref().map_or(0, |source| source.heap_size())+ + size_of_val::<[Keyframe]>(&self.keyframes)+ + self+ .keyframes+ .iter()+ .map(|keyframe| match &keyframe.easing {+ KeyframeEasing::Easing(Easing::Linear(points)) => crate::heap_size::vec_bytes(points),+ _ => 0,+ })+ .sum::<usize>()+ + size_of_val::<[KeyframeDeclaration]>(&self.declarations)+ + size_of_val::<[KeyframeCustomDeclaration]>(&self.custom_declarations)+ + size_of_val::<[u16]>(&self.target_properties)+ + size_of_val::<[RetainedUtf16FlyString]>(&self.target_custom_properties)+ }+}++/// The index of the next of a set's declarations, where it holds `length` of them.+fn declaration_index(length: usize) -> u32 {+ u32::try_from(length).expect("a keyframe set holds fewer than 2^32 declarations")+}++/// A keyframe script gave a `KeyframeEffect`, as processing the keyframes argument made it.+pub(crate) struct ProcessedKeyframe {+ /// The computed keyframe offset, scaled by [`KEY_SCALE_FACTOR`] as a percentage.+ pub(crate) key: u64,+ pub(crate) composite: CompositeOperationOrAuto,+ pub(crate) easing: Option<Easing>,+ pub(crate) declarations: Vec<(KeyframeProperty, RetainedStyleValueData)>,+}++// https://drafts.csswg.org/css-animations-2/#keyframe-processing+fn generate_initial_and_final_frames(keyframes: &mut Vec<PendingKeyframe>, animated_properties: &AnimatedProperties) {+ // 1. Find or create the initial keyframe, a keyframe with a keyframe offset of 0%, default timing function+ // as its keyframe timing function, and default composite as its keyframe composite.+ if keyframes.first().is_none_or(|keyframe| keyframe.key != INITIAL_KEY) {+ keyframes.insert(0, PendingKeyframe::new(INITIAL_KEY));+ }++ // 2. For any property in animated properties that is not otherwise present in a keyframe with an offset of+ // 0% or one that would be positioned earlier in the used keyframe order, add the computed value of that+ // property on element to initial keyframe’s keyframe values.+ let initial_keyframes = keyframes+ .iter()+ .take_while(|keyframe| keyframe.key == INITIAL_KEY)+ .count();+ let missing: Vec<_> = animated_properties+ .0+ .iter()+ .filter(|property| {+ !keyframes[..initial_keyframes]+ .iter()+ .any(|keyframe| keyframe.declares(property))+ })+ .cloned()+ .collect();+ for property in missing {+ keyframes[0].set(property, KeyframeValue::ElementValue);+ }++ // 3. If initial keyframe’s keyframe values is not empty, prepend initial keyframe to keyframes.++ // 4. Repeat for final keyframe, using an offset of 100%, considering keyframes positioned later in the used+ // keyframe order, and appending to keyframes.+ if keyframes.last().is_none_or(|keyframe| keyframe.key != FINAL_KEY) {+ keyframes.push(PendingKeyframe::new(FINAL_KEY));+ }+ let final_keyframes = keyframes+ .iter()+ .rev()+ .take_while(|keyframe| keyframe.key == FINAL_KEY)+ .count();+ let first_final_keyframe = keyframes.len() - final_keyframes;+ let missing: Vec<_> = animated_properties+ .0+ .iter()+ .filter(|property| {+ !keyframes[first_final_keyframe..]+ .iter()+ .any(|keyframe| keyframe.declares(property))+ })+ .cloned()+ .collect();+ let final_keyframe = keyframes.last_mut().expect("the final keyframe was found or created");+ for property in missing {+ final_keyframe.set(property, KeyframeValue::ElementValue);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn value(keyword: u16) -> RetainedStyleValueData {+ RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword })+ }++ fn declared_properties(set: &KeyframeSet, keyframe: &Keyframe) -> Vec<(u16, bool)> {+ set.declarations_of(keyframe)+ .iter()+ .map(|declaration| (declaration.property_id, declaration.value.declared().is_some()))+ .collect()+ }++ #[test]+ fn script_keyframes_gain_initial_and_final_keyframes_for_what_they_leave_out() {+ use crate::css::css_enums::keyword;+ use crate::css::property_metadata::property_id;+ let keyframe = |key, property| ProcessedKeyframe {+ key,+ composite: CompositeOperationOrAuto::Auto,+ easing: None,+ declarations: vec![(KeyframeProperty::Id(property), value(keyword::AUTO))],+ };+ let set = KeyframeSet::from_processed_keyframes(+ vec![+ keyframe(50_000, property_id::OPACITY),+ keyframe(FINAL_KEY, property_id::COLOR),+ ],+ None,+ );+ let keys: Vec<_> = set.keyframes().iter().map(|keyframe| keyframe.key).collect();+ assert_eq!(keys, [INITIAL_KEY, 50_000, FINAL_KEY]);+ let mut initial = declared_properties(&set, &set.keyframes()[0]);+ initial.sort_unstable();+ let mut expected = vec![(property_id::OPACITY, false), (property_id::COLOR, false)];+ expected.sort_unstable();+ assert_eq!(initial, expected);+ let mut last = declared_properties(&set, &set.keyframes()[2]);+ last.sort_unstable();+ let mut expected = vec![(property_id::COLOR, true), (property_id::OPACITY, false)];+ expected.sort_unstable();+ assert_eq!(last, expected);+ let mut target_properties = vec![property_id::OPACITY, property_id::COLOR];+ target_properties.sort_unstable();+ assert_eq!(set.target_properties(), target_properties);+ }++ #[test]+ fn keyframes_of_one_offset_keep_their_order() {+ use crate::css::css_enums::keyword;+ use crate::css::property_metadata::property_id;+ let keyframe = |key, composite| ProcessedKeyframe {+ key,+ composite,+ easing: None,+ declarations: vec![(KeyframeProperty::Id(property_id::OPACITY), value(keyword::AUTO))],+ };+ let set = KeyframeSet::from_processed_keyframes(+ vec![+ keyframe(FINAL_KEY, CompositeOperationOrAuto::Add),+ keyframe(INITIAL_KEY, CompositeOperationOrAuto::Replace),+ keyframe(FINAL_KEY, CompositeOperationOrAuto::Accumulate),+ ],+ None,+ );+ let composites: Vec<_> = set.keyframes().iter().map(|keyframe| keyframe.composite).collect();+ assert_eq!(+ composites,+ [+ CompositeOperationOrAuto::Replace,+ CompositeOperationOrAuto::Add,+ CompositeOperationOrAuto::Accumulate+ ]+ );+ assert!(set.has_additive_keyframe());+ }++ #[test]+ fn a_transition_runs_from_its_start_to_its_end_value() {+ use crate::css::css_enums::keyword;+ use crate::css::property_metadata::property_id;+ let set = KeyframeSet::for_transition(+ KeyframeProperty::Id(property_id::OPACITY),+ value(keyword::AUTO),+ value(keyword::NONE),+ 1.0,+ );+ let keys: Vec<_> = set.keyframes().iter().map(|keyframe| keyframe.key).collect();+ assert_eq!(keys, [INITIAL_KEY, FINAL_KEY]);+ for keyframe in set.keyframes() {+ assert_eq!(declared_properties(&set, keyframe), [(property_id::OPACITY, true)]);+ assert_eq!(keyframe.composite, CompositeOperationOrAuto::Auto);+ }+ assert_eq!(set.target_properties(), [property_id::OPACITY]);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/mod.rs b/Libraries/LibWeb/Rust/src/animations/mod.rsindex 27819844163..3bf29a97db3 100644--- a/Libraries/LibWeb/Rust/src/animations/mod.rs+++ b/Libraries/LibWeb/Rust/src/animations/mod.rs@@ -6,7 +6,26 @@//! Web Animations.+pub(crate) mod animation;+pub mod bindings_api;+pub(crate) mod clock_plan;+pub(crate) mod composite_order;+pub(crate) mod css_events;+pub(crate) mod document_animations;+pub(crate) mod easing;+pub(crate) mod effect;+pub(crate) mod element_animations;pub(crate) mod ffi;+pub(crate) mod host_effects;+pub(crate) mod host_timing;+pub(crate) mod keyframe_reflection;+pub(crate) mod keyframes;+pub(crate) mod pending_animation_events;+pub(crate) mod procedures;pub(crate) mod snapshot;+pub(crate) mod timeline;+pub(crate) mod timeline_state;+pub(crate) mod transitions;+pub(crate) mod weak_record_set;pub(crate) use libcompositing_rust::animation_timing as timing;diff --git a/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs b/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rsnew file mode 100644index 00000000000..414593ae1ce--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/pending_animation_events.rs@@ -0,0 +1,153 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The pending animation event queue of a document, which holds what each event is, not the event: the host creates+//! each event as it dispatches it.+//! https://www.w3.org/TR/web-animations-1/#pending-animation-event-queue++use super::animation::{AnimationCell, AnimationHandle, HostCellKind};+use super::composite_order::{TreeOrder, composite_order};+use super::css_events::FfiCssEventType;+use super::host_effects::PlaybackEventType;+use super::timing::{OptionalNumber, OptionalTimeValue};+use std::cmp::Ordering;+use std::ffi::c_void;+use std::ptr::NonNull;++/// The type of a `TimeEvent` an SVG animation element dispatches.+/// https://svgwg.org/specs/animations/#InterfaceTimeEvent+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TimeEventType {+ Begin,+ End,+ Repeat,+}++/// Which interface an event of the pending animation event queue is of.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum PendingAnimationEventKind {+ /// An `AnimationEvent` or a `TransitionEvent` of a CSS animation or transition, dispatched at its owning element.+ Css,+ /// An `AnimationPlaybackEvent`, dispatched at the animation.+ Playback,+ /// A `TimeEvent` of the animation of an SVG animation element, dispatched at the animation element.+ Time,+}++/// An event of the pending animation event queue, as the host creates it as it dispatches it, the fields of its kind+/// set.+#[repr(C)]+#[derive(Clone, Copy, Debug)]+pub struct FfiPendingAnimationEvent {+ pub kind: PendingAnimationEventKind,+ /// For `Css`.+ pub css_event_type: FfiCssEventType,+ /// For `Playback`.+ pub playback_event_type: PlaybackEventType,+ /// For `Time`.+ pub time_event_type: TimeEventType,+ /// For `Time`, the iteration a repeat event is of.+ pub detail: i32,+ /// For `Css`, in seconds.+ pub elapsed_time: f64,+ /// For `Playback`.+ pub current_time: OptionalTimeValue,+ pub timeline_time: OptionalTimeValue,+ /// https://www.w3.org/TR/web-animations-1/#scheduled-event-time+ pub scheduled_event_time: OptionalNumber,+ /// The time the event was queued at, which is its time stamp.+ pub time_stamp: f64,+}++/// An event of the queue and the animation it is of, which the queue holds.+pub(crate) struct PendingAnimationEvent {+ pub(crate) animation: AnimationHandle,+ pub(crate) event: FfiPendingAnimationEvent,+}++/// The pending animation event queue of a document, and the events queued while style and layout feedback is+/// provisional, which join it only as the outermost style stabilization epoch commits.+#[derive(Default)]+pub(crate) struct PendingAnimationEvents {+ pending: Vec<PendingAnimationEvent>,+ provisional: Vec<PendingAnimationEvent>,+}++impl PendingAnimationEvents {+ /// Appends an event to the pending animation event queue, or, where `provisional`, to the provisional events.+ pub(crate) fn append(&mut self, event: PendingAnimationEvent, provisional: bool) {+ if provisional {+ self.provisional.push(event);+ } else {+ self.pending.push(event);+ }+ }++ pub(crate) fn has_provisional_events(&self) -> bool {+ !self.provisional.is_empty()+ }++ /// Appends the provisional events to the pending animation event queue but those `drops` says to drop, answering how+ /// many it appended.+ pub(crate) fn commit_provisional_events(&mut self, mut drops: impl FnMut(&AnimationCell) -> bool) -> usize {+ let before = self.pending.len();+ for event in std::mem::take(&mut self.provisional) {+ if !drops(&event.animation) {+ self.pending.push(event);+ }+ }+ self.pending.len() - before+ }++ /// Takes the events of the pending animation event queue in the order to dispatch them in.+ /// https://www.w3.org/TR/web-animations-1/#update-animations-and-send-events+ pub(crate) fn take_events_to_dispatch(&mut self, tree_order: &mut impl TreeOrder) -> Vec<PendingAnimationEvent> {+ // 4. Let events to dispatch be a copy of doc’s pending animation event queue.+ // 5. Clear doc’s pending animation event queue.+ let mut events_to_dispatch = std::mem::take(&mut self.pending);++ // 6. Perform a stable sort of the animation events in events to dispatch as follows:+ // Sort the events by their scheduled event time such that events that were scheduled to occur earlier, sort+ // before events scheduled to occur later and events whose scheduled event time is unresolved sort before+ // events with a resolved scheduled event time.+ // Within events with equal scheduled event times, sort by their composite order.+ // NB: An event of an animation without an associated effect sorts before those of animations with one.+ events_to_dispatch.sort_by(|a, b| {+ let (a_time, b_time) = (a.event.scheduled_event_time, b.event.scheduled_event_time);+ match (a_time.has_value, b_time.has_value) {+ (false, true) => return Ordering::Less,+ (true, false) => return Ordering::Greater,+ (true, true) => {+ // NB: A total order keeps the sort well defined should a time be NaN, and adding zero makes+ // -0 and +0 equal times, as they compare.+ let ordering = (a_time.value + 0.0).total_cmp(&(b_time.value + 0.0));+ if ordering != Ordering::Equal {+ return ordering;+ }+ }+ (false, false) => {}+ }+ let (a, b) = (a.animation.borrow(), b.animation.borrow());+ match (a.effect().is_some(), b.effect().is_some()) {+ (true, true) => composite_order(&a, &b, tree_order),+ (a_has_effect, b_has_effect) => a_has_effect.cmp(&b_has_effect),+ }+ });+ events_to_dispatch+ }++ /// Calls `visit` with each GC cell of the host that keeps alive the elements the records of the queued events+ /// name.+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>, HostCellKind)) {+ for event in self.pending.iter().chain(&self.provisional) {+ event.animation.for_each_host_cell(&mut visit);+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/procedures.rs b/Libraries/LibWeb/Rust/src/animations/procedures.rsnew file mode 100644index 00000000000..13b54cf6ee5--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/procedures.rs@@ -0,0 +1,2594 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The procedures of the Web Animations timing model that run on an animation.+//! https://www.w3.org/TR/web-animations-1/#animations+//!+//! A procedure changes the records it runs on and records what it asks the host to do as `HostEffects`, in the order+//! its steps ask for them, which the host performs once it has returned.++use super::animation::{AnimationHandle, AnimationKind, CSS_TRANSITION_PHASE_IDLE, CssAnimationFlag};+use super::composite_order::{TreeOrder, composite_order};+use super::effect::{EffectFlag, EffectHandle};+use super::host_effects::{HostEffectKind, HostEffects, PlaybackEventType};+use super::timeline::{TimelineCell, TimelineHandle};+use super::timeline_state::{TimelineState, zero_time};+use super::timing::{+ self, AnimationEffectPhase, AnimationEffectTiming, AnimationPlayState, AnimationPlayback, AnimationReplaceState,+ FillMode, TimeValue, TimeValueType, time_value,+};+use std::collections::HashSet;+use std::ffi::c_void;+use std::ptr::NonNull;++/// An exception a procedure throws, as the host throws it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum AnimationError {+ /// An "InvalidStateError" DOMException.+ InvalidState(&'static str),+ TypeError(&'static str),+}++/// Whether a procedure updates the finished state of an animation after seeking it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum DidSeek {+ No,+ Yes,+}++/// Whether the finish notification steps of an animation run right away rather than in a task.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum SynchronouslyNotify {+ No,+ Yes,+}++/// Whether a procedure invalidates the style its animation's effect produces.+/// NB: Script always wants this. The style computation does not, as it runs a procedure before it computes the effect+/// stack it would invalidate.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Invalidate {+ No,+ Yes,+}++/// https://www.w3.org/TR/web-animations-1/#playing-an-animation-section+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum AutoRewind {+ No,+ Yes,+}++/// Runs `procedure` on `animation` and hands back what it asks the host to do.+pub(crate) fn run<T>(+ animation: &AnimationHandle,+ procedure: impl FnOnce(&mut Procedures<'_>) -> Result<T, AnimationError>,+) -> Result<(T, HostEffects), AnimationError> {+ let timeline = animation.borrow().timeline_state();+ run_on(animation, timeline, procedure)+}++/// Runs `procedure` on `animation`, whose timeline reads `timeline` now, if it has one, and hands back what it asks+/// the host to do.+fn run_on<T>(+ animation: &AnimationHandle,+ timeline: Option<TimelineState>,+ procedure: impl FnOnce(&mut Procedures<'_>) -> Result<T, AnimationError>,+) -> Result<(T, HostEffects), AnimationError> {+ let mut effects = HostEffects::default();+ let value = procedure(&mut Procedures {+ animation,+ timeline,+ effects: &mut effects,+ })?;+ Ok((value, effects))+}++/// An animation and its timeline as it is now, on which the procedures run, and what they ask the host to do so far.+pub(crate) struct Procedures<'a> {+ animation: &'a AnimationHandle,+ /// The animation's timeline as the animation reads it as the procedures begin, if it has one.+ timeline: Option<TimelineState>,+ effects: &'a mut HostEffects,+}++impl Procedures<'_> {+ /// The animation the procedures run on.+ pub(crate) fn animation(&self) -> &AnimationHandle {+ self.animation+ }++ fn emit(&mut self, kind: HostEffectKind) {+ self.effects.push(self.animation, kind);+ }++ fn playback(&self) -> AnimationPlayback {+ *self.animation.borrow().playback()+ }++ fn update_playback(&self, update: impl FnOnce(&mut AnimationPlayback)) {+ update(self.animation.borrow_mut().playback_mut());+ }++ fn start_time(&self) -> Option<TimeValue> {+ self.playback().start_time.get()+ }++ fn hold_time(&self) -> Option<TimeValue> {+ self.playback().hold_time.get()+ }++ fn playback_rate(&self) -> f64 {+ self.playback().playback_rate+ }++ fn pending_playback_rate(&self) -> Option<f64> {+ self.playback().pending_playback_rate.get()+ }++ fn pending(&self) -> bool {+ self.playback().pending()+ }++ fn set_start_time(&self, time: Option<TimeValue>) {+ self.update_playback(|playback| playback.start_time = time.into());+ }++ fn set_hold_time(&self, time: Option<TimeValue>) {+ self.update_playback(|playback| playback.hold_time = time.into());+ }++ fn set_pending_playback_rate(&self, playback_rate: Option<f64>) {+ self.update_playback(|playback| playback.pending_playback_rate = playback_rate.into());+ }++ fn set_has_pending_play_task(&self, value: bool) {+ self.update_playback(|playback| playback.has_pending_play_task = value);+ }++ fn set_has_pending_pause_task(&self, value: bool) {+ self.update_playback(|playback| playback.has_pending_pause_task = value);+ }++ fn set_auto_align_start_time(&self, value: bool) {+ self.animation.borrow_mut().set_auto_align_start_time(value);+ }++ /// The current time of the timeline, which is unresolved without one or where it is inactive.+ fn timeline_time(&self) -> Option<TimeValue> {+ self.timeline.as_ref().and_then(TimelineState::current_time)+ }++ /// Whether the animation is associated with an active timeline.+ fn has_active_timeline(&self) -> bool {+ self.timeline.as_ref().is_some_and(|timeline| !timeline.is_inactive())+ }++ /// Whether the animation has an associated timeline that is not monotonically increasing.+ fn has_finite_timeline(&self) -> bool {+ self.timeline+ .as_ref()+ .is_some_and(|timeline| !timeline.sample.is_monotonically_increasing)+ }++ /// Whether the animation is associated with a monotonically increasing timeline.+ fn has_monotonically_increasing_timeline(&self) -> bool {+ self.timeline+ .as_ref()+ .is_some_and(|timeline| timeline.sample.is_monotonically_increasing)+ }++ fn zero(&self) -> TimeValue {+ zero_time(self.timeline.as_ref())+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-current-time+ fn current_time(&self) -> Option<TimeValue> {+ timing::current_time_at(&self.playback(), self.timeline_time())+ }++ /// The current time of the animation, substituting an unresolved time value for the hold time.+ fn current_time_without_hold_time(&self) -> Option<TimeValue> {+ let playback = AnimationPlayback {+ hold_time: None.into(),+ ..self.playback()+ };+ timing::current_time_at(&playback, self.timeline_time())+ }++ /// The normalized timing of the associated effect, if any.+ fn effect_timing(&self) -> Option<AnimationEffectTiming> {+ self.animation.borrow().effect().map(|effect| effect.borrow().timing())+ }++ /// https://www.w3.org/TR/web-animations-1/#associated-effect-end+ fn associated_effect_end(&self) -> TimeValue {+ // The associated effect end of an animation is equal to the end time of the animation’s associated effect. If+ // the animation has no associated effect, the associated effect end is zero.+ match self.effect_timing() {+ Some(timing) => timing::end_time(&timing),+ None => self.zero(),+ }+ }++ /// https://www.w3.org/TR/web-animations-1/#play-states+ pub(crate) fn play_state(&self) -> AnimationPlayState {+ timing::play_state_at(&self.playback(), self.current_time(), self.associated_effect_end())+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-relevant+ fn is_relevant(&self) -> bool {+ let effect_timing = self.effect_timing();+ timing::is_relevant(+ &self.playback(),+ self.timeline.as_ref().map(|timeline| &timeline.sample),+ effect_timing.as_ref(),+ self.current_time(),+ )+ }++ /// The phase of the associated effect, if any, at its local time, the current time of the animation.+ /// https://www.w3.org/TR/web-animations-1/#animation-effect-phases-and-states+ fn effect_phase(&self) -> Option<AnimationEffectPhase> {+ let timing = self.effect_timing()?;+ let playback = self.playback();+ let resolved = timing::resolve_timing(+ &timing,+ self.current_time(),+ Some(&playback),+ self.timeline.as_ref().map(|timeline| &timeline.sample),+ );+ Some(resolved.phase)+ }++ /// The host's `DOM::Element` the associated effect targets, if any.+ fn effect_target(&self) -> Option<NonNull<c_void>> {+ self.animation+ .borrow()+ .effect()+ .and_then(|effect| effect.borrow().target_element())+ }++ /// Whether the associated effect has a target.+ fn effect_has_target(&self) -> bool {+ self.effect_target().is_some()+ }++ fn invalidate_effect(&mut self) {+ if self.animation.borrow().effect().is_some() {+ self.emit(HostEffectKind::InvalidateEffect { changes_plan: true });+ }+ }++ /// https://www.w3.org/TR/web-animations-1/#apply-any-pending-playback-rate+ fn apply_any_pending_playback_rate(&self) {+ self.update_playback(|playback| {+ // 1. If animation does not have a pending playback rate, abort these steps.+ let Some(pending_playback_rate) = playback.pending_playback_rate.get() else {+ return;+ };++ // 2. Set animation’s playback rate to its pending playback rate.+ playback.playback_rate = pending_playback_rate;++ // 3. Clear animation’s pending playback rate.+ playback.pending_playback_rate = None.into();+ });+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-silently-set-the-current-time+ /// NB: The host validates seek time as a CSSNumberish time before it runs this procedure.+ fn silently_set_current_time(&self, valid_seek_time: Option<TimeValue>) -> Result<(), AnimationError> {+ // 1. If seek time is an unresolved time value, then perform the following steps.+ let Some(valid_seek_time) = valid_seek_time else {+ // 1. If the current time is resolved, then throw a TypeError.+ if self.current_time().is_some() {+ return Err(AnimationError::TypeError(+ "Cannot change an animation's current time from a resolve value to an unresolved value",+ ));+ }++ // 2. Abort these steps.+ return Ok(());+ };++ // 2. Let valid seek time be the result of running the validate a CSSNumberish time procedure with seek time as+ // the input.+ // 3. If valid seek time is false, abort this procedure.+ // AD-HOC: The host has already validated seek time.++ // 4. Set auto align start time to false.+ self.set_auto_align_start_time(false);++ // 5. Update either animation’s hold time or start time as follows:+ let playback = self.playback();++ // -> If any of the following conditions are true:+ // - animation’s hold time is resolved, or+ // - animation’s start time is unresolved, or+ // - animation has no associated timeline or the associated timeline is inactive, or+ // - animation’s playback rate is 0,+ match self.timeline_time() {+ Some(timeline_time)+ if playback.hold_time.get().is_none()+ && playback.start_time.get().is_some()+ && playback.playback_rate != 0.0 =>+ {+ // -> Otherwise,+ // Set animation’s start time to the result of evaluating timeline time - (seek time / playback+ // rate) where timeline time is the current time value of timeline associated with animation.+ self.set_start_time(Some(timeline_time - (valid_seek_time / playback.playback_rate)));+ }+ _ => {+ // Set animation’s hold time to seek time.+ self.set_hold_time(Some(valid_seek_time));+ }+ }++ // 6. If animation has no associated timeline or the associated timeline is inactive, make animation’s start+ // time unresolved.+ if !self.has_active_timeline() {+ self.set_start_time(None);+ }++ // 7. Make animation’s previous current time unresolved.+ self.animation.borrow_mut().set_previous_current_time(None);++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time+ /// NB: The host validates seek time as a CSSNumberish time before it runs this procedure.+ fn set_current_time(&mut self, seek_time: Option<TimeValue>) -> Result<(), AnimationError> {+ // 1. Run the steps to silently set the current time of animation to seek time.+ self.silently_set_current_time(seek_time)?;++ // 2. If animation has a pending pause task, synchronously complete the pause operation by performing the+ // following steps:+ if self.playback().has_pending_pause_task {+ // 1. Set animation’s hold time to seek time.+ self.set_hold_time(seek_time);++ // 2. Apply any pending playback rate to animation.+ self.apply_any_pending_playback_rate();++ // 3. Make animation’s start time unresolved.+ self.set_start_time(None);++ // 4. Cancel the pending pause task.+ self.set_has_pending_pause_task(false);++ // 5 Resolve animation’s current ready promise with animation.+ self.emit(HostEffectKind::ResolveReadyPromise);+ }++ // 3. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // true, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::Yes, SynchronouslyNotify::No, Invalidate::Yes, None);++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#set-the-start-time+ /// NB: The host validates new start time as a CSSNumberish time before it runs this procedure.+ fn set_the_start_time(&mut self, new_start_time: Option<TimeValue>) {+ // 1. Let valid start time be the result of running the validate a CSSNumberish time procedure with new start+ // time as the input.+ // 2. If valid start time is false, abort this procedure.+ // AD-HOC: The host has already validated new start time.++ // 3. Set auto align start time to false.+ self.set_auto_align_start_time(false);++ // 4. Let timeline time be the current time value of the timeline that animation is associated with. If there+ // is no timeline associated with animation or the associated timeline is inactive, let the timeline time be+ // unresolved.+ let timeline_time = self.timeline_time();++ // 5. If timeline time is unresolved and new start time is resolved, make animation’s hold time unresolved.+ if timeline_time.is_none() && new_start_time.is_some() {+ self.set_hold_time(None);+ }++ // 6. Let previous current time be animation’s current time.+ let previous_current_time = self.current_time();++ // 7. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 8. Set animation’s start time to new start time.+ self.set_start_time(new_start_time);++ // 9. Update animation’s hold time based on the first matching condition from the following,++ // -> If new start time is resolved,+ if new_start_time.is_some() {+ // If animation’s playback rate is not zero, make animation’s hold time unresolved.+ if self.playback_rate() != 0.0 {+ self.set_hold_time(None);+ }+ }+ // -> Otherwise (new start time is unresolved),+ else {+ // Set animation’s hold time to previous current time even if previous current time is unresolved.+ self.set_hold_time(previous_current_time);+ }++ // 10. If animation has a pending play task or a pending pause task, cancel that task and resolve animation’s+ // current ready promise with animation.+ if self.pending() {+ self.set_has_pending_play_task(false);+ self.set_has_pending_pause_task(false);+ self.emit(HostEffectKind::ResolveReadyPromise);+ }++ // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // true, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::Yes, SynchronouslyNotify::No, Invalidate::Yes, None);+ }++ /// https://www.w3.org/TR/web-animations-1/#set-the-playback-rate+ pub(crate) fn set_playback_rate(&mut self, new_playback_rate: f64) -> Result<(), AnimationError> {+ // 1. Clear any pending playback rate on animation.+ self.set_pending_playback_rate(None);++ // 2. Let previous time be the value of the current time of animation before changing the playback rate.+ let previous_time = self.current_time();++ // 3. Let previous playback rate be the current effective playback rate of animation.+ let previous_playback_rate = self.playback_rate();++ // 4. Set the playback rate to new playback rate.+ self.update_playback(|playback| playback.playback_rate = new_playback_rate);++ // 5. Perform the steps corresponding to the first matching condition from the following, if any:++ // -> If animation is associated with a monotonically increasing timeline and the previous time is resolved,+ if self.has_monotonically_increasing_timeline()+ && let Some(previous_time) = previous_time+ {+ // set the current time of animation to previous time.+ self.as_script_changing_the_play_state(|procedures| procedures.set_current_time(Some(previous_time)))?;+ }+ // -> If animation is associated with a non-null timeline that is not monotonically increasing, the start time+ // of animation is resolved, associated effect end is not infinity, and either:+ // - the previous playback rate < 0 and the new playback rate ≥ 0, or+ // - the previous playback rate ≥ 0 and the new playback rate < 0,+ else if self.has_finite_timeline()+ && let Some(start_time) = self.start_time()+ && !self.associated_effect_end().value.is_infinite()+ && ((previous_playback_rate < 0.0 && new_playback_rate >= 0.0)+ || (previous_playback_rate >= 0.0 && new_playback_rate < 0.0))+ {+ // Set animation’s start time to the result of evaluating associated effect end - start time for animation.+ self.set_start_time(Some(self.associated_effect_end() - start_time));+ }++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state+ /// `observed_current_time`, where given, is the unconstrained current time.+ pub(crate) fn update_finished_state(+ &mut self,+ did_seek: DidSeek,+ synchronously_notify: SynchronouslyNotify,+ invalidate: Invalidate,+ observed_current_time: Option<TimeValue>,+ ) {+ // 1. Let the unconstrained current time be the result of calculating the current time substituting an+ // unresolved time value for the hold time if did seek is false. If did seek is true, the unconstrained+ // current time is equal to the current time.+ //+ // Note: This is required to accommodate timelines that may change direction. Without this definition, a once-+ // finished animation would remain finished even when its timeline progresses in the opposite direction.+ let unconstrained_current_time = observed_current_time.or_else(|| match did_seek {+ DidSeek::No => self.current_time_without_hold_time(),+ DidSeek::Yes => self.current_time(),+ });++ // 2. If all three of the following conditions are true,+ // - the unconstrained current time is resolved, and+ // - animation’s start time is resolved, and+ // - animation does not have a pending play task or a pending pause task,+ if let Some(unconstrained_current_time) = unconstrained_current_time+ && self.start_time().is_some()+ && !self.pending()+ {+ // then update animation’s hold time based on the first matching condition for animation from below, if any:+ self.update_hold_time_for_finished_state(did_seek, unconstrained_current_time);+ }++ // 3. Set the previous current time of animation be the result of calculating its current time.+ let current_time = self.current_time();+ self.animation.borrow_mut().set_previous_current_time(current_time);++ // 4. Let current finished state be true if the play state of animation is finished. Otherwise, let it be false.+ let current_finished_state = self.play_state() == AnimationPlayState::Finished;++ // 5. If current finished state is true and the current finished promise is not yet resolved, perform the+ // following steps:+ if current_finished_state && !self.playback().is_finished {+ // 1. Let finish notification steps refer to the following procedure:+ // NB: See finish_notification_steps().++ // 2. If synchronously notify is true, cancel any queued microtask to run the finish notification steps for+ // this animation, and run the finish notification steps immediately.+ if synchronously_notify == SynchronouslyNotify::Yes {+ self.emit(HostEffectKind::CancelFinishNotificationTask);+ self.finish_notification_steps();+ }+ // Otherwise, if synchronously notify is false, queue a microtask to run finish notification steps for+ // animation unless there is already a microtask queued to run those steps for animation.+ else {+ self.emit(HostEffectKind::QueueFinishNotificationTask);+ }+ }++ // 6. If current finished state is false and animation’s current finished promise is already resolved, set+ // animation’s current finished promise to a new promise in the relevant Realm of animation.+ if !current_finished_state && self.playback().is_finished {+ self.emit(HostEffectKind::ReplaceFinishedPromise);+ self.update_playback(|playback| playback.is_finished = false);+ }++ // AD-HOC: An animation disassociated from its target while inert can only be revived through here.+ if let Some(play_state_when_disassociated) = self.animation.borrow().play_state_when_disassociated_from_target()+ && (self.pending() || self.is_relevant() || self.play_state() != play_state_when_disassociated)+ && let Some(element) = self.effect_target()+ {+ self.emit(HostEffectKind::AssociateWithTarget { element });+ }++ // AD-HOC: An animation that has finished without filling produces nothing more, so it leaves its target's list.+ if current_finished_state && !self.pending() && !self.is_relevant() {+ self.animation.borrow_mut().set_disassociation_from_target_pending(true);+ }++ if invalidate == Invalidate::Yes {+ self.invalidate_effect();+ }+ }++ /// Step 2 of https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state+ fn update_hold_time_for_finished_state(&self, did_seek: DidSeek, unconstrained_current_time: TimeValue) {+ let playback_rate = self.playback_rate();+ let previous_current_time = self.animation.borrow().previous_current_time();++ // -> If playback rate > 0 and unconstrained current time is greater than or equal to associated effect end,+ let associated_effect_end = self.associated_effect_end();+ if playback_rate > 0.0 && unconstrained_current_time >= associated_effect_end {+ // If did seek is true, let the hold time be the value of unconstrained current time.+ if did_seek == DidSeek::Yes {+ self.set_hold_time(Some(unconstrained_current_time));+ }+ // If did seek is false, let the hold time be the maximum value of previous current time and associated+ // effect end. If the previous current time is unresolved, let the hold time be associated effect end.+ else if let Some(previous_current_time) = previous_current_time {+ self.set_hold_time(Some(time_value::max(previous_current_time, associated_effect_end)));+ } else {+ self.set_hold_time(Some(associated_effect_end));+ }+ }+ // -> If playback rate < 0 and unconstrained current time is less than or equal to 0,+ else if playback_rate < 0.0 && unconstrained_current_time.value <= 0.0 {+ // If did seek is true, let the hold time be the value of unconstrained current time.+ if did_seek == DidSeek::Yes {+ self.set_hold_time(Some(unconstrained_current_time));+ }+ // If did seek is false, let the hold time be the minimum value of previous current time and zero. If the+ // previous current time is unresolved, let the hold time be zero.+ else if let Some(previous_current_time) = previous_current_time {+ self.set_hold_time(Some(time_value::min(previous_current_time, self.zero())));+ } else {+ self.set_hold_time(Some(self.zero()));+ }+ }+ // -> If playback rate ≠ 0, and animation is associated with an active timeline,+ else if playback_rate != 0.0+ && let Some(timeline_time) = self.timeline_time()+ {+ // Perform the following steps:++ // 1. If did seek is true and the hold time is resolved, let animation’s start time be equal to the result+ // of evaluating timeline time - (hold time / playback rate) where timeline time is the current time+ // value of timeline associated with animation.+ if did_seek == DidSeek::Yes+ && let Some(hold_time) = self.hold_time()+ {+ self.set_start_time(Some(timeline_time - (hold_time / playback_rate)));+ }++ // 2. Let the hold time be unresolved.+ self.set_hold_time(None);+ }+ }++ /// The finish notification steps of step 5 of+ /// https://www.w3.org/TR/web-animations-1/#update-an-animations-finished-state+ pub(crate) fn finish_notification_steps(&mut self) {+ // 1. If animation’s play state is not equal to finished, abort these steps.+ if self.play_state() != AnimationPlayState::Finished {+ return;+ }++ // 2. Resolve animation’s current finished promise object with animation.+ self.emit(HostEffectKind::ResolveFinishedPromise);+ self.update_playback(|playback| playback.is_finished = true);++ // 3. Create an AnimationPlaybackEvent, finishEvent.+ // 4. Set finishEvent’s type attribute to finish.+ // 5. Set finishEvent’s currentTime attribute to the current time of animation.+ // 6. Set finishEvent’s timelineTime attribute to the current time of the timeline with which animation is+ // associated. If animation is not associated with a timeline, or the timeline is inactive, let timelineTime+ // be null.+ // 7. If animation has a document for timing, then append finishEvent to its document for timing's pending+ // animation event queue along with its target, animation. For the scheduled event time, use the result of+ // converting animation’s associated effect end to an origin-relative time.+ // Otherwise, queue a task to dispatch finishEvent at animation. The task source for this task is the DOM+ // manipulation task source.+ // NB: The host creates and queues the event. The conversion of the associated effect end to an origin-relative+ // time starts here, from the animation as it is now, by converting it to a timeline time.+ let current_time = self.current_time();+ let timeline_time = self.timeline_time();+ let scheduled_timeline_time =+ self.convert_an_animation_time_to_timeline_time(Some(self.associated_effect_end()));+ self.emit(HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Finish,+ current_time,+ timeline_time,+ scheduled_timeline_time,+ });+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-time-to-timeline-time+ fn convert_an_animation_time_to_timeline_time(&self, time: Option<TimeValue>) -> Option<TimeValue> {+ // 1. If time is unresolved, return time.+ let time = time?;++ // 2. If time is infinity, return an unresolved time value.+ if time.value.is_infinite() {+ return None;+ }++ // 3. If animation’s playback rate is zero, return an unresolved time value.+ let playback_rate = self.playback_rate();+ if playback_rate == 0.0 {+ return None;+ }++ // 4. If animation’s start time is unresolved, return an unresolved time value.+ let start_time = self.start_time()?;++ // 5. Return the result of calculating: time × (1 / playback rate) + start time (where playback rate and start+ // time are the playback rate and start time of animation, respectively).+ Some((time * (1.0 / playback_rate)) + start_time)+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-reset-an-animations-pending-tasks+ fn reset_an_animations_pending_tasks(&mut self) {+ // 1. If animation does not have a pending play task or a pending pause task, abort this procedure.+ if !self.pending() {+ return;+ }++ // 2. If animation has a pending play task, cancel that task.+ self.set_has_pending_play_task(false);++ // 3. If animation has a pending pause task, cancel that task.+ self.set_has_pending_pause_task(false);++ // 4. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 5. Reject animation’s current ready promise with a DOMException named "AbortError".+ // 6. Set the [[PromiseIsHandled]] internal slot of animation’s current ready promise to true.+ // 7. Let animation’s current ready promise be the result of creating a new resolved Promise object with value+ // animation in the relevant Realm of animation.+ self.emit(HostEffectKind::RejectReadyPromise);+ }++ /// https://www.w3.org/TR/web-animations-1/#cancel-an-animation+ fn cancel_an_animation(&mut self, invalidate: Invalidate) {+ // 1. If animation’s play state is not idle, perform the following steps:+ if self.play_state() != AnimationPlayState::Idle {+ // 1. Run the procedure to reset an animation’s pending tasks on animation.+ self.reset_an_animations_pending_tasks();++ // 2. Reject the current finished promise with a DOMException named "AbortError".+ // 3. Set the [[PromiseIsHandled]] internal slot of the current finished promise to true.+ // 4. Let current finished promise be a new promise in the relevant Realm of animation.+ self.emit(HostEffectKind::RejectFinishedPromise);+ self.update_playback(|playback| playback.is_finished = false);++ // 5. Create an AnimationPlaybackEvent, cancelEvent.+ // 6. Set cancelEvent’s type attribute to cancel.+ // 7. Set cancelEvent’s currentTime to null.+ // 8. Let timeline time be the current time of the timeline with which animation is associated. If+ // animation is not associated with an active timeline, let timeline time be an unresolved time value.+ // 9. Set cancelEvent’s timelineTime to timeline time. If timeline time is unresolved, set it to null.+ // 10. If animation has a document for timing, then append cancelEvent to its document for timing's pending+ // animation event queue along with its target, animation. If animation is associated with an active+ // timeline that defines a procedure to convert timeline times to origin-relative time, let the+ // scheduled event time be the result of applying that procedure to timeline time. Otherwise, the+ // scheduled event time is an unresolved time value.+ // Otherwise, queue a task to dispatch cancelEvent at animation. The task source for this task is the+ // DOM manipulation task source.+ // NB: The host creates and queues the event.+ let timeline_time = self.timeline_time();+ self.emit(HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Cancel,+ current_time: None,+ timeline_time,+ scheduled_timeline_time: timeline_time,+ });+ }++ // 2. Make animation’s hold time unresolved.+ self.set_hold_time(None);++ // 3. Make animation’s start time unresolved.+ self.set_start_time(None);++ // This time is needed for dispatching the animationcancel DOM event+ if let Some(timing) = self.effect_timing() {+ let timing = AnimationEffectTiming {+ fill_mode: FillMode::Both,+ ..timing+ };+ let playback = self.playback();+ let active_time = timing::resolve_timing(+ &timing,+ self.current_time(),+ Some(&playback),+ self.timeline.as_ref().map(|timeline| &timeline.sample),+ )+ .active_time;+ self.animation.borrow_mut().set_saved_cancel_time(active_time);+ }++ // AD-HOC: The target's animation list is our own cache of the animations whose effect targets it, and holding a+ // cancelled animation there keeps it alive and walked every frame. It is reassociated if revived.+ self.animation.borrow_mut().set_disassociation_from_target_pending(true);++ if invalidate == Invalidate::Yes {+ self.invalidate_effect();+ }+ }++ /// https://www.w3.org/TR/web-animations-1/#finish-an-animation+ pub(crate) fn finish_an_animation(&mut self) -> Result<(), AnimationError> {+ // 1. If animation’s effective playback rate is zero, or if animation’s effective playback rate > 0 and+ // associated effect end is infinity, throw an "InvalidStateError" DOMException and abort these steps.+ let effective_playback_rate = self.playback().effective_playback_rate();+ if effective_playback_rate == 0.0 {+ return Err(AnimationError::InvalidState(+ "Animation with a playback rate of 0 cannot be finished",+ ));+ }+ if effective_playback_rate > 0.0 && self.associated_effect_end().value.is_infinite() {+ return Err(AnimationError::InvalidState("Animation with no end cannot be finished"));+ }++ // 2. Apply any pending playback rate to animation.+ self.apply_any_pending_playback_rate();++ // 3. Set limit as follows:+ // -> If playback rate > 0,+ // Let limit be associated effect end.+ // -> Otherwise,+ // Let limit be zero.+ let playback_rate = self.playback_rate();+ let limit = if playback_rate > 0.0 {+ self.associated_effect_end()+ } else {+ self.zero()+ };++ // 4. Silently set the current time to limit.+ self.silently_set_current_time(Some(limit))?;++ // 5. If animation’s start time is unresolved and animation has an associated active timeline, let the start+ // time be the result of evaluating timeline time - (limit / playback rate) where timeline time is the+ // current time value of the associated timeline.+ if self.start_time().is_none()+ && let Some(timeline_time) = self.timeline_time()+ {+ self.set_start_time(Some(timeline_time - (limit / playback_rate)));+ }++ // 6. If there is a pending pause task and start time is resolved,+ let mut should_resolve_ready_promise = false;+ if self.playback().has_pending_pause_task && self.start_time().is_some() {+ // 1. Let the hold time be unresolved.+ // Note: Typically the hold time will already be unresolved except in the case when the animation was+ // previously idle.+ self.set_hold_time(None);++ // 2. Cancel the pending pause task.+ self.set_has_pending_pause_task(false);++ // 3. Resolve the current ready promise of animation with animation.+ should_resolve_ready_promise = true;+ }++ // 7. If there is a pending play task and start time is resolved, cancel that task and resolve the current ready+ // promise of animation with animation.+ if self.playback().has_pending_play_task && self.start_time().is_some() {+ self.set_has_pending_play_task(false);+ should_resolve_ready_promise = true;+ }++ if should_resolve_ready_promise {+ self.emit(HostEffectKind::ResolveReadyPromise);+ }++ // 8. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // true, and the synchronously notify flag set to true.+ self.update_finished_state(DidSeek::Yes, SynchronouslyNotify::Yes, Invalidate::Yes, None);++ Ok(())+ }++ /// https://drafts.csswg.org/web-animations-1/#playing-an-animation-section+ /// https://drafts.csswg.org/web-animations-2/#play-an-animation+ pub(crate) fn play_an_animation(+ &mut self,+ auto_rewind: AutoRewind,+ invalidate: Invalidate,+ ) -> Result<(), AnimationError> {+ // 1. Let aborted pause be a boolean flag that is true if animation has a pending pause task, and false+ // otherwise.+ let aborted_pause = self.playback().has_pending_pause_task;++ // 2. Let has pending ready promise be a boolean flag that is initially false.+ let mut has_pending_ready_promise = false;++ // 3. Let has finite timeline be true if animation has an associated timeline that is not monotonically+ // increasing.+ let has_finite_timeline = self.has_finite_timeline();++ // 4. Let previous current time be the animation’s current time+ let previous_current_time = self.current_time();++ // 5. Let enable seek be true if the auto-rewind flag is true and has finite timeline is false. Otherwise,+ // initialize to false.+ let enable_seek = auto_rewind == AutoRewind::Yes && !has_finite_timeline;++ // 6. Perform the steps corresponding to the first matching condition from the following, if any:+ let effective_playback_rate = self.playback().effective_playback_rate();+ let associated_effect_end = self.associated_effect_end();++ // -> If animation’s effective playback rate > 0, enable seek is true and either animation’s:+ // - previous current time is unresolved, or+ // - previous current time < zero, or+ // - previous current time ≥ associated effect end,+ if effective_playback_rate > 0.0+ && enable_seek+ && previous_current_time.is_none_or(|previous| previous.value < 0.0 || previous >= associated_effect_end)+ {+ // Set the animation’s hold time to zero.+ self.set_hold_time(Some(self.zero()));+ }+ // -> If animation’s effective playback rate < 0, enable seek is true and either animation’s:+ // - previous current time is unresolved, or+ // - previous current time ≤ zero, or+ // - previous current time > associated effect end,+ else if effective_playback_rate < 0.0+ && enable_seek+ && previous_current_time.is_none_or(|previous| previous.value <= 0.0 || previous > associated_effect_end)+ {+ // -> If associated effect end is positive infinity,+ if associated_effect_end.value == f64::INFINITY {+ // throw an "InvalidStateError" DOMException and abort these steps.+ return Err(AnimationError::InvalidState(+ "Cannot rewind an animation with an infinite effect end",+ ));+ }++ // -> Otherwise,+ // Set the animation’s hold time to the animation’s associated effect end.+ self.set_hold_time(Some(associated_effect_end));+ }+ // -> If animation’s effective playback rate = 0 and animation’s current time is unresolved,+ else if effective_playback_rate == 0.0 && previous_current_time.is_none() {+ // Set the animation’s hold time to zero.+ self.set_hold_time(Some(self.zero()));+ }++ // 7. If has finite timeline and previous current time is unresolved:+ if has_finite_timeline && previous_current_time.is_none() {+ // Set the flag auto align start time to true.+ self.set_auto_align_start_time(true);+ }++ // 8. If animation’s hold time is resolved, let its start time be unresolved.+ if self.hold_time().is_some() {+ self.set_start_time(None);+ }++ // 9. If animation has a pending play task or a pending pause task,+ if self.pending() {+ // 1. Cancel that task.+ self.set_has_pending_play_task(false);+ self.set_has_pending_pause_task(false);++ // 2. Set has pending ready promise to true.+ has_pending_ready_promise = true;+ }++ // 10. If the following three conditions are all satisfied:+ // - animation’s hold time is unresolved, and+ // - aborted pause is false, and+ // - animation does not have a pending playback rate,+ // AD-HOC: We also don't abort if we have a pending auto-alignment of the start time, see+ // https://github.com/w3c/csswg-drafts/issues/13236+ let pending_auto_aligned_start_time =+ self.animation.borrow().auto_align_start_time() && self.start_time().is_none();+ if self.hold_time().is_none()+ && !aborted_pause+ && self.pending_playback_rate().is_none()+ && !pending_auto_aligned_start_time+ {+ // abort this procedure.+ return Ok(());+ }++ // 11. If has pending ready promise is false, let animation’s current ready promise be a new promise in the+ // relevant Realm of animation.+ if !has_pending_ready_promise {+ self.emit(HostEffectKind::ReplaceReadyPromise);+ }++ // 12. Schedule a task to run as soon as animation is ready. The task shall perform the following steps:+ //+ // Note: Steps omitted, see run_pending_play_task()+ //+ // So long as the above task is scheduled but has yet to run, animation is described as having a pending+ // play task. While the task is running, however, animation does not have a pending play task.+ //+ // If a user agent determines that animation is immediately ready, it may schedule the above task as a+ // microtask such that it runs at the next microtask checkpoint, but it must not perform the task+ // synchronously.+ self.set_has_pending_play_task(true);++ // 13. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, invalidate, None);++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#pause-an-animation+ fn pause_an_animation(&mut self) -> Result<(), AnimationError> {+ // 1. If animation has a pending pause task, abort these steps.+ if self.playback().has_pending_pause_task {+ return Ok(());+ }++ // 2. If the play state of animation is paused, abort these steps.+ if self.play_state() == AnimationPlayState::Paused {+ return Ok(());+ }++ // 3. Let seek time be a time value that is initially unresolved.+ let mut seek_time = None;++ // 4. Let has finite timeline be true if animation has an associated timeline that is not monotonically+ // increasing.+ let has_finite_timeline = self.has_finite_timeline();++ // 5. If the animation’s current time is unresolved, perform the steps according to the first matching+ // condition from below:+ if self.current_time().is_none() {+ // -> If animation’s playback rate is ≥ 0,+ if self.playback_rate() >= 0.0 {+ // Set seek time to zero.+ seek_time = Some(self.zero());+ }+ // -> Otherwise+ else {+ // If associated effect end for animation is positive infinity,+ let associated_effect_end = self.associated_effect_end();+ if associated_effect_end.value == f64::INFINITY {+ // throw an "InvalidStateError" DOMException and abort these steps.+ return Err(AnimationError::InvalidState(+ "Cannot pause an animation with an infinite effect end",+ ));+ }++ // Otherwise,+ // Set seek time to animation’s associated effect end.+ seek_time = Some(associated_effect_end);+ }+ }++ // 6. If seek time is resolved,+ if let Some(seek_time) = seek_time {+ // If has finite timeline is true,+ if has_finite_timeline {+ // Set animation’s start time to seek time.+ self.set_start_time(Some(seek_time));+ }+ // Otherwise,+ else {+ // Set animation’s hold time to seek time.+ self.set_hold_time(Some(seek_time));+ }+ }++ // 7. Let has pending ready promise be a boolean flag that is initially false.+ let mut has_pending_ready_promise = false;++ // 8. If animation has a pending play task, cancel that task and let has pending ready promise be true.+ if self.playback().has_pending_play_task {+ self.set_has_pending_play_task(false);+ has_pending_ready_promise = true;+ }++ // 9. If has pending ready promise is false, set animation’s current ready promise to a new promise in the+ // relevant Realm of animation.+ if !has_pending_ready_promise {+ self.emit(HostEffectKind::ReplaceReadyPromise);+ }++ // 10. Schedule a task to be executed at the first possible moment where both of the following conditions are+ // true:+ // NB: Criteria has been listed out in is_ready_to_run_pending_pause_task()+ // NB: This is run_pending_pause_task()+ self.set_has_pending_pause_task(true);++ // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#seamlessly-update-the-playback-rate+ pub(crate) fn update_playback_rate(&mut self, new_playback_rate: f64) -> Result<(), AnimationError> {+ // 1. Let previous play state be animation’s play state.+ // Note: It is necessary to record the play state before updating animation’s effective playback rate since,+ // in the following logic, we want to immediately apply the pending playback rate of animation if it is+ // currently finished regardless of whether or not it will still be finished after we apply the pending+ // playback rate.+ let previous_play_state = self.play_state();++ // 2. Let animation’s pending playback rate be new playback rate.+ self.set_pending_playback_rate(Some(new_playback_rate));++ // 3. Perform the steps corresponding to the first matching condition from below:++ // -> If animation has a pending play task or a pending pause task,+ if self.pending() {+ // Abort these steps.+ // Note: The different types of pending tasks will apply the pending playback rate when they run so there+ // is no further action required in this case.+ return Ok(());+ }++ // -> If previous play state is idle or paused, or animation’s current time is unresolved,+ if matches!(+ previous_play_state,+ AnimationPlayState::Idle | AnimationPlayState::Paused+ ) || self.current_time().is_none()+ {+ // Apply any pending playback rate on animation.+ // Note: the second condition above is required so that if we have a running animation with an unresolved+ // current time and no pending play task, we do not attempt to play it below.+ self.apply_any_pending_playback_rate();+ }+ // -> If previous play state is finished,+ else if previous_play_state == AnimationPlayState::Finished {+ // 1. Let the unconstrained current time be the result of calculating the current time of animation+ // substituting an unresolved time value for the hold time.+ let unconstrained_current_time = self.current_time_without_hold_time();++ // 2. Let animation’s start time be the result of evaluating the following expression:+ // timeline time - (unconstrained current time / pending playback rate)+ // Where timeline time is the current time value of the timeline associated with animation.+ // If pending playback rate is zero, let animation’s start time be timeline time.+ let timeline_time = self.timeline_time();+ if new_playback_rate == 0.0 {+ self.set_start_time(timeline_time);+ }+ // INTEROP: The timeline time is unresolved where the timeline became inactive after the animation+ // finished, as a scroll timeline whose scroller stopped overflowing, while the hold time keeps+ // the current time resolved. Like other browsers, leave the start time as it is then.+ else if let Some(timeline_time) = timeline_time {+ let unconstrained_current_time = unconstrained_current_time+ .expect("a finished animation on an active timeline has a resolved unconstrained current time");+ self.set_start_time(Some(timeline_time - (unconstrained_current_time / new_playback_rate)));+ }++ // 3. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 4. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);+ }+ // -> Otherwise,+ else {+ // Run the procedure to play an animation for animation with the auto-rewind flag set to false.+ self.play_an_animation(AutoRewind::No, Invalidate::Yes)?;+ }++ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#reverse-an-animation+ fn reverse_an_animation(&mut self) -> Result<(), AnimationError> {+ // 1. If there is no timeline associated with animation, or the associated timeline is inactive throw an+ // "InvalidStateError" DOMException and abort these steps.+ if !self.has_active_timeline() {+ return Err(AnimationError::InvalidState(+ "Cannot reverse an animation with an inactive timeline",+ ));+ }++ // 2. Let original pending playback rate be animation’s pending playback rate.+ let original_pending_playback_rate = self.pending_playback_rate();++ // 3. Let animation’s pending playback rate be the additive inverse of its effective playback rate (i.e.+ // -effective playback rate).+ self.set_pending_playback_rate(Some(-self.playback().effective_playback_rate()));++ // 4. Run the steps to play an animation for animation with the auto-rewind flag set to true.+ // If the steps to play an animation throw an exception, set animation’s pending playback rate to original+ // pending playback rate and propagate the exception.+ if let Err(error) = self.play_an_animation(AutoRewind::Yes, Invalidate::Yes) {+ self.set_pending_playback_rate(original_pending_playback_rate);+ return Err(error);+ }++ Ok(())+ }++ /// https://drafts.csswg.org/web-animations-2/#ready+ fn is_ready(&self) -> bool {+ // An animation is ready at the first moment where all of the following conditions are true:++ // FIXME: - the user agent has completed any setup required to begin the playback of each inclusive descendant+ // of the animation’s associated effect including rendering the first frame of any keyframe effect or+ // executing any custom effects associated with an animation effect++ // - the animation is associated with a timeline that is not inactive.+ if !self.has_active_timeline() {+ return false;+ }++ // - the animation’s hold time or start time is resolved.+ self.hold_time().is_some() || self.start_time().is_some()+ }++ /// Runs the pending play task of the animation if it has one and is ready.+ pub(crate) fn run_pending_play_task_if_ready(&mut self) {+ if !self.playback().has_pending_play_task || !self.is_ready() {+ return;+ }+ self.set_has_pending_play_task(false);+ self.run_pending_play_task();+ }++ /// The time a new CSS transition became ready at, if it runs on the compositor from the time of its style change+ /// event.+ fn compositor_transition_ready_time(&self) -> Option<TimeValue> {+ let animation = self.animation.borrow();+ let AnimationKind::CssTransition(transition) = animation.kind() else {+ return None;+ };+ let may_run_on_the_compositor = animation.effect()?.borrow().may_run_on_the_compositor();+ if !may_run_on_the_compositor || transition.previous_phase != CSS_TRANSITION_PHASE_IDLE {+ return None;+ }+ Some(TimeValue::milliseconds(+ animation.css_transition_style_change_event_time(),+ ))+ }++ /// Whether the animation is a CSS transition a compositor animation runs.+ fn is_compositor_driven_transition(&self) -> bool {+ let animation = self.animation.borrow();+ matches!(animation.kind(), AnimationKind::CssTransition(_))+ && animation+ .effect()+ .is_some_and(|effect| effect.borrow().has_flag(EffectFlag::CompositorDriven))+ }++ /// Step 12 of https://www.w3.org/TR/web-animations-1/#playing-an-animation-section+ fn run_pending_play_task(&mut self) {+ // 1. Assert that at least one of animation’s start time or hold time is resolved.+ assert!(self.start_time().is_some() || self.hold_time().is_some());++ // 2. Let ready time be the time value of the timeline associated with animation at the moment when animation+ // became ready.+ // FIXME: We can get a more accurate time here if we record the actual instant we became ready rather than+ // waiting to try and run this task+ // AD-HOC: A new CSS transition of properties the compositor may run stays pending past the rendering update of+ // its style change event, which already rendered it, on the compositor or here. It became ready at the+ // time of its style change event, from which the compositor runs it, so that a style change a frame+ // later starts the next transition from the value on the screen rather than from this transition's+ // start value.+ let ready_time = self.compositor_transition_ready_time().unwrap_or_else(|| {+ self.timeline_time()+ .expect("an animation is ready only on an active timeline")+ });++ // 3. Perform the steps corresponding to the first matching condition below, if any:++ // -> If animation’s hold time is resolved,+ if let Some(hold_time) = self.hold_time() {+ // 1. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 2. Let new start time be the result of evaluating ready time - hold time / playback rate for animation.+ // If the playback rate is zero, let new start time be simply ready time.+ let playback_rate = self.playback_rate();+ let new_start_time = if playback_rate != 0.0 {+ ready_time - (hold_time / playback_rate)+ } else {+ ready_time+ };++ // 3. Set the start time of animation to new start time.+ self.set_start_time(Some(new_start_time));++ // 4. If animation’s playback rate is not 0, make animation’s hold time unresolved.+ if playback_rate != 0.0 {+ self.set_hold_time(None);+ }+ }+ // -> If animation’s start time is resolved and animation has a pending playback rate,+ else if let Some(start_time) = self.start_time()+ && self.pending_playback_rate().is_some()+ {+ // 1. Let current time to match be the result of evaluating (ready time - start time) × playback rate for+ // animation.+ let current_time_to_match = (ready_time - start_time) * self.playback_rate();++ // 2. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 3. If animation’s playback rate is zero, let animation’s hold time be current time to match.+ let playback_rate = self.playback_rate();+ if playback_rate == 0.0 {+ self.set_hold_time(Some(current_time_to_match));+ }++ // 4. Let new start time be the result of evaluating ready time - current time to match / playback rate for+ // animation. If the playback rate is zero, let new start time be simply ready time.+ let new_start_time = if playback_rate != 0.0 {+ ready_time - (current_time_to_match / playback_rate)+ } else {+ ready_time+ };++ // 5. Set the start time of animation to new start time.+ self.set_start_time(Some(new_start_time));+ }++ // 4. Resolve animation’s current ready promise with animation.+ self.emit(HostEffectKind::ResolveReadyPromise);++ // 5. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ // OPTIMIZATION: A new CSS transition can already have a provisional compositor descriptor anchored to its style+ // change event time. Keep that descriptor so resolving this task does not restart its visual+ // time.+ let invalidate = if self.is_compositor_driven_transition() {+ Invalidate::No+ } else {+ Invalidate::Yes+ };+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, invalidate, None);++ // AD-HOC: A pending animation is not handed to the compositor, and the frame that hands it over once it is no+ // longer pending is recorded only if something needs a repaint. Its output may not change, so ask for+ // one.+ if self.effect_has_target() {+ self.emit(HostEffectKind::RequestRepaint);+ }+ }++ /// Whether the conditions hold at which step 10 of https://www.w3.org/TR/web-animations-1/#pause-an-animation+ /// schedules the pending pause task to run.+ fn is_ready_to_run_pending_pause_task(&self) -> bool {+ // https://www.w3.org/TR/web-animations-1/#pause-an-animation+ // https://drafts.csswg.org/web-animations-2/#pausing-an-animation-section+ // FIXME: - the user agent has performed any processing necessary to suspend the playback of animation’s+ // associated effect, if any.++ // - the animation is associated with a timeline that is not inactive.+ if !self.has_active_timeline() {+ return false;+ }++ // - the animation has a resolved hold time or start time.+ self.hold_time().is_some() || self.start_time().is_some()+ }++ /// Step 10 of https://www.w3.org/TR/web-animations-1/#pause-an-animation+ fn run_pending_pause_task(&mut self) {+ // 1. Let ready time be the time value of the timeline associated with animation at the moment when the user+ // agent completed processing necessary to suspend playback of animation’s associated effect.+ // FIXME: We can get a more accurate time here if we record the actual instant the above is true rather than+ // waiting for this task to run+ let ready_time = self+ .timeline_time()+ .expect("a pending pause task runs only on an active timeline");++ // 2. If animation’s start time is resolved and its hold time is not resolved, let animation’s hold time be the+ // result of evaluating (ready time - start time) × playback rate.+ // Note: The hold time might be already set if the animation is finished, or if the animation has a pending+ // play task. In either case we want to preserve the hold time as we enter the paused state.+ if let Some(start_time) = self.start_time()+ && self.hold_time().is_none()+ {+ self.set_hold_time(Some((ready_time - start_time) * self.playback_rate()));+ }++ // 3. Apply any pending playback rate on animation.+ self.apply_any_pending_playback_rate();++ // 4. Make animation’s start time unresolved.+ self.set_start_time(None);++ // 5. Resolve animation’s current ready promise with animation.+ self.emit(HostEffectKind::ResolveReadyPromise);++ // 6. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);+ }++ /// Normalizes the timing of the associated effect against the attachment interval where it moved.+ /// https://drafts.csswg.org/web-animations-2/#auto-aligning-start-time+ /// NB: The effect's timing is normalized against the attachment interval, which moves with the timeline's scroll+ /// container and subject. That holds whether or not the start time is auto-aligned, e.g. for a paused+ /// animation.+ fn normalize_timing_against_attachment_interval(&mut self) {+ let Some(interval) = self.timeline.as_ref().and_then(TimelineState::attachment_interval) else {+ return;+ };+ if self.animation.borrow().normalized_attachment_interval() == Some(interval) {+ return;+ }+ self.normalize_effect_timing();+ self.invalidate_effect();+ }++ /// Notes the attachment interval of the timeline and normalizes the specified timing of the associated effect+ /// against it.+ fn normalize_effect_timing(&self) {+ let interval = self.timeline.as_ref().and_then(TimelineState::attachment_interval);+ let mut animation = self.animation.borrow_mut();+ animation.set_normalized_attachment_interval(interval);+ if let Some(effect) = animation.effect() {+ effect.borrow_mut().normalize_specified_timing(self.timeline.as_ref());+ }+ }++ /// https://drafts.csswg.org/web-animations-2/#auto-aligning-start-time+ fn calculate_auto_aligned_start_time(&mut self) {+ assert!(+ self.timeline+ .as_ref()+ .is_some_and(|timeline| timeline.is_progress_based)+ );++ // 1. If the auto-align start time flag is false, abort this procedure.+ if !self.animation.borrow().auto_align_start_time() {+ return;+ }++ // 2. If the timeline is inactive, abort this procedure.+ if !self.has_active_timeline() {+ return;+ }++ // 3. If play state is idle, abort this procedure.+ let play_state = self.play_state();+ if play_state == AnimationPlayState::Idle {+ return;+ }++ // 4. If play state is paused, and hold time is resolved, abort this procedure.+ if play_state == AnimationPlayState::Paused && self.hold_time().is_some() {+ return;+ }++ self.normalize_timing_against_attachment_interval();+ let interval = self+ .timeline+ .as_ref()+ .and_then(TimelineState::attachment_interval)+ .expect("a progress-based timeline has an attachment interval");++ // 5. Let start offset be the resolved timeline time corresponding to the start of the animation attachment+ // range. In the case of view timelines, it requires a calculation based on the proportion of the cover+ // range.+ let start_offset = interval.start;++ // 6. Let end offset be the resolved timeline time corresponding to the end of the animation attachment range.+ // In the case of view timelines, it requires a calculation based on the proportion of the cover range.+ let end_offset = interval.end;++ // 7. Set start time to start offset if effective playback rate ≥ 0, and end offset otherwise.+ if self.playback().effective_playback_rate() >= 0.0 {+ self.set_start_time(Some(start_offset));+ } else {+ self.set_start_time(Some(end_offset));+ }++ // 8. Clear hold time.+ self.set_hold_time(None);+ }++ /// Takes in a change of the attachment range of the animation on its progress-based timeline.+ /// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range+ pub(crate) fn attachment_range_changed(&mut self) {+ if !self+ .timeline+ .as_ref()+ .is_some_and(|timeline| timeline.is_progress_based)+ {+ return;+ }+ self.normalize_effect_timing();+ self.calculate_auto_aligned_start_time();+ self.invalidate_effect();+ }++ /// Updates the animation as its timeline's current time was updated.+ /// https://drafts.csswg.org/web-animations-1/#animation-frame-loop+ pub(crate) fn update(&mut self) {+ let timeline = self.timeline.expect("an animation updates as its timeline does");++ // https://drafts.csswg.org/scroll-animations-1/#event-loop+ // When updating timeline current time, the start time of any attached animation is conditionally updated. For+ // each attached animation, run the procedure for calculating an auto-aligned start time.+ if timeline.is_progress_based {+ self.normalize_timing_against_attachment_interval();+ self.calculate_auto_aligned_start_time();+ }++ let is_monotonically_increasing = timeline.sample.is_monotonically_increasing;++ // Prevent unnecessary work if the animation is already finished and can't exit the finished state due to+ // timeline changes+ let was_finished = self.playback().is_finished;+ if !was_finished || !is_monotonically_increasing {+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::Yes, Invalidate::No, None);+ if self.play_state() == AnimationPlayState::Running && self.animation.borrow().effect().is_some() {+ let output_is_constant_before_active_start = !self.pending()+ && self.effect_phase() == Some(AnimationEffectPhase::Before)+ && is_monotonically_increasing+ && self.playback_rate() > 0.0;+ let invalidate = !self.pending() && !output_is_constant_before_active_start;+ self.emit(HostEffectKind::InvalidateUnlessThrottled { invalidate });+ } else if self.playback().is_finished != was_finished && self.animation.borrow().effect().is_some() {+ self.emit(HostEffectKind::InvalidateEffect { changes_plan: false });+ }+ }++ // Act on the pending play or pause task+ self.run_pending_play_task_if_ready();++ if self.playback().has_pending_pause_task && self.is_ready_to_run_pending_pause_task() {+ self.set_has_pending_pause_task(false);+ self.run_pending_pause_task();+ }++ if self.play_state() == AnimationPlayState::Running+ && !self.pending()+ && self.effect_phase() == Some(AnimationEffectPhase::Before)+ && is_monotonically_increasing+ && self.playback_rate() > 0.0+ && let Some(timing) = self.effect_timing()+ && timing.start_delay.r#type == TimeValueType::Milliseconds+ && let Some(current_time) = self.current_time()+ && current_time.r#type == TimeValueType::Milliseconds+ {+ let delay = (timing.start_delay.value - current_time.value) / self.playback_rate();+ if delay > 0.0 && self.effect_has_target() {+ self.emit(HostEffectKind::ScheduleWakeup { delay });+ }+ }+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-set-the-timeline-of-an-animation+ /// https://drafts.csswg.org/web-animations-2/#setting-the-timeline+ pub(crate) fn set_timeline(&mut self, new_timeline: Option<TimelineHandle>) {+ // 1. Let old timeline be the current timeline of animation, if any.+ let old_timeline = self.animation.borrow().timeline().cloned();++ // 2. If new timeline is the same object as old timeline, abort this procedure.+ let same = match (&new_timeline, &old_timeline) {+ (Some(new_timeline), Some(old_timeline)) => new_timeline.ptr_eq(old_timeline),+ (None, None) => true,+ _ => false,+ };+ if same {+ return;+ }++ // NB: The procedures below read the old timeline through `old` and the new one through `self`.+ let mut no_effects = HostEffects::default();+ let old = Procedures {+ animation: self.animation,+ timeline: self.timeline,+ effects: &mut no_effects,+ };+ let range = self.animation.borrow().range();+ self.timeline = new_timeline.as_ref().map(|timeline| timeline.state_for(&range));++ // 3. Let previous play state be animation’s play state.+ let previous_play_state = old.play_state();++ // 4. Let previous current time be the animation’s current time.+ let previous_current_time = old.current_time();++ // 5. Set previous progress based in the first condition that applies:+ // AD-HOC: The spec doesn't say what to do if we have no effect so we just assume an end time of 0+ let end_time = old.associated_effect_end();+ let previous_progress = previous_current_time.map(|previous_current_time| {+ // If previous current time is unresolved:+ // Set previous progress to unresolved.++ // If end time is zero:+ // Set previous progress to zero.+ if end_time.value == 0.0 {+ return 0.0;+ }++ // Otherwise+ // Set previous progress = previous current time / end time+ previous_current_time / end_time+ });++ // 6. Let from finite timeline be true if old timeline is not null and not monotonically increasing.+ let from_finite_timeline = old.has_finite_timeline();++ // 7. Let to finite timeline be true if timeline is not null and not monotonically increasing.+ let to_finite_timeline = self.has_finite_timeline();++ // 8. Let the timeline of animation be new timeline.+ if let Some(old_timeline) = &old_timeline {+ old_timeline.associated_animations().borrow_mut().remove(self.animation);+ }+ if let Some(new_timeline) = &new_timeline {+ new_timeline.associated_animations().borrow_mut().insert(self.animation);+ }+ self.animation.borrow_mut().replace_timeline(new_timeline);+ let new_timeline = self.timeline;++ // AD-HOC: The normalization of the specified timing of the associated effect depends on the associated+ // timeline. This must be done before setting the current time below to ensure consistent units.+ self.normalize_effect_timing();++ let previous_progress_multiplied_by_end_time = |procedures: &Self, previous_progress: f64| {+ // AD-HOC: The spec doesn't say what to do if we have no effect so we just assume an end time of 0+ match procedures.effect_timing() {+ None => zero_time(new_timeline.as_ref()),+ Some(timing) => TimeValue::new(+ super::timeline_state::time_unit(new_timeline.as_ref()),+ timing::end_time(&timing).value * previous_progress,+ ),+ }+ };++ // 9. Perform the steps corresponding to the first matching condition from the following, if any:+ // If to finite timeline,+ if to_finite_timeline {+ // 1. Apply any pending playback rate on animation+ self.apply_any_pending_playback_rate();++ // 2. set auto align start time to true.+ self.set_auto_align_start_time(true);++ // 3. Set start time to unresolved.+ self.set_start_time(None);++ // 4. Set hold time to unresolved.+ self.set_hold_time(None);++ // 5. If previous play state is "finished" or "running"+ if matches!(+ previous_play_state,+ AnimationPlayState::Finished | AnimationPlayState::Running+ ) {+ // 1. Schedule a pending play task+ self.set_has_pending_play_task(true);+ }++ // 6. If previous play state is "paused" and previous progress is resolved:+ if previous_play_state == AnimationPlayState::Paused+ && let Some(previous_progress) = previous_progress+ {+ // 1. Set hold time to previous progress * end time.+ self.set_hold_time(Some(previous_progress_multiplied_by_end_time(self, previous_progress)));+ }+ // NOTE: This step ensures that previous progress is preserved even in the case of a pause-pending+ // animation with a resolved start time.+ }+ // If from finite timeline and previous progress is resolved,+ else if from_finite_timeline && let Some(previous_progress) = previous_progress {+ // Run the procedure to set the current time to previous progress * end time.+ // NB: The time is valid, so setting it cannot throw. This is the procedure itself, not script setting the+ // current time of a CSS animation. Until it is done, the start time is still in the units of the old+ // timeline.+ let time = previous_progress_multiplied_by_end_time(self, previous_progress);+ self.set_current_time(Some(time))+ .expect("setting the current time to a resolved time does not throw");+ }++ // 10. If the start time of animation is resolved, make animation’s hold time unresolved.+ if let Some(start_time) = self.start_time() {+ // AD-HOC: A finished animation holds a time beside its start time, and setting its current time as it+ // leaves a finite timeline sets the hold time alone, which leaves the start time in the units of+ // the old timeline. See https://github.com/w3c/csswg-drafts/issues/11761. Like WebKit, the start+ // time takes the hold time.+ if let Some(hold_time) = self.hold_time()+ && hold_time.r#type != start_time.r#type+ {+ self.set_start_time(Some(hold_time));+ }+ // AD-HOC: Nor does anything convert a start time left from the old timeline, as one script set while the+ // old timeline was inactive and the previous progress was unresolved. A time in units the new+ // timeline does not have means nothing on it, so the start time becomes unresolved.+ else if start_time.r#type != super::timeline_state::time_unit(new_timeline.as_ref()) {+ self.set_start_time(None);+ }+ self.set_hold_time(None);+ }++ // 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, Invalidate::Yes, None);+ }++ /// https://www.w3.org/TR/web-animations-1/#setting-the-associated-effect+ pub(crate) fn set_the_associated_effect(&mut self, new_effect: Option<&EffectHandle>, invalidate: Invalidate) {+ // 1. Let old effect be the current associated effect of animation, if any.+ let old_effect = self.animation.borrow().effect().cloned();++ // 2. If new effect is the same object as old effect, abort this procedure.+ if new_effect == old_effect.as_ref() {+ return;+ }++ // 3. If animation has a pending pause task, reschedule that task to run as soon as animation is ready.+ // 4. If animation has a pending play task, reschedule that task to run as soon as animation is ready to play+ // new effect.+ // NB: There is no real difference between "pending" and "as soon as possible", so these steps are no-ops.++ // 5. If new effect is not null and if new effect is the associated effect of another animation, previous+ // animation, run the procedure to set the associated effect of an animation (this procedure) on previous+ // animation passing null as new effect.+ let previous_animation = new_effect.and_then(|effect| effect.borrow().associated_animation());+ if let Some(previous_animation) = previous_animation+ && !previous_animation.ptr_eq(self.animation)+ {+ let timeline = previous_animation.borrow().timeline_state();+ Procedures {+ animation: &previous_animation,+ timeline,+ effects: &mut *self.effects,+ }+ .set_the_associated_effect(None, Invalidate::Yes);+ }++ // 6. Let the associated effect of animation be new effect.+ let old_target = self.effect_target();+ let new_target = new_effect.and_then(|effect| effect.borrow().target_element());+ if old_target != new_target {+ if let (Some(element), Some(effect)) = (old_target, &old_effect) {+ self.emit(HostEffectKind::DisassociateFromTarget {+ element,+ effect: effect.clone(),+ });+ }+ if let Some(element) = new_target {+ self.emit(HostEffectKind::AssociateWithTarget { element });+ }+ }+ self.link_associated_effect(new_effect);++ // NB: Once the animated properties of old effect no longer apply, the style of its target is recomputed without+ // them.+ if let Some(old_effect) = old_effect {+ self.emit(HostEffectKind::RecomputeEffectStyle { effect: old_effect });+ }++ // 7. Run the procedure to update an animation’s finished state for animation with the did seek flag set to+ // false, and the synchronously notify flag set to false.+ self.update_finished_state(DidSeek::No, SynchronouslyNotify::No, invalidate, None);+ }++ /// Lets the associated effect of the animation be `new_effect`, which is associated with no other animation, and+ /// associates the old effect with none.+ fn link_associated_effect(&self, new_effect: Option<&EffectHandle>) {+ if let Some(new_effect) = new_effect {+ new_effect+ .borrow_mut()+ .set_associated_animation(Some(self.animation), self.timeline.as_ref());+ }+ if let Some(old_effect) = self.animation.borrow().effect() {+ old_effect.borrow_mut().set_associated_animation(None, None);+ }+ self.animation.borrow_mut().set_effect(new_effect.cloned());+ }++ /// Lets the associated effect of the animation, which has none, be `effect`, without associating the animation+ /// with the target of the effect, which must not observe it until a surrounding style stabilization epoch commits+ /// it.+ pub(crate) fn set_provisional_effect(&self, effect: &EffectHandle) {+ assert!(+ self.animation.borrow().effect().is_none(),+ "the animation has no associated effect"+ );+ assert!(+ effect.borrow().associated_animation().is_none(),+ "the effect is associated with no animation"+ );+ self.link_associated_effect(Some(effect));+ }++ /// Lets the animation, whose associated effect was set provisionally, have no associated effect again.+ pub(crate) fn discard_provisional_effect(&self) {+ let animation = self+ .animation+ .borrow()+ .effect()+ .and_then(|effect| effect.borrow().associated_animation());+ assert!(+ animation.is_some_and(|animation| animation.ptr_eq(self.animation)),+ "the animation has a provisional effect"+ );+ self.link_associated_effect(None);+ }++ /// Keeps the animation of an SVG animation element at the time of its time container: where the container is+ /// paused at `paused_time`, in milliseconds, the animation holds that time, and otherwise it starts at+ /// `zero_time`, the time of the document timeline at which the container's timeline began.+ /// https://drafts.csswg.org/web-animations-1/#setting-the-start-time-of-an-animation+ /// https://drafts.csswg.org/web-animations-1/#setting-the-current-time-of-an-animation+ /// NB: Both procedures take effect synchronously, and update the finished state of the animation as a seek does. A+ /// backward seek therefore applies to an animation that already finished, too.+ pub(crate) fn synchronize_with_smil_time_container(&mut self, zero_time: f64, paused_time: Option<f64>) {+ let Some(paused_time) = paused_time else {+ self.set_the_start_time(Some(TimeValue::milliseconds(zero_time)));+ return;+ };+ // NB: Making the start time unresolved holds the animation at its current time, which setting the current time+ // then moves to the time the timeline is paused at.+ self.set_the_start_time(None);+ self.set_current_time(Some(TimeValue::milliseconds(paused_time)))+ .expect("setting the current time to a resolved time does not throw");+ }++ /// Disassociates the animation from the target of its associated effect where it is inert, which a procedure+ /// scheduled.+ /// AD-HOC: The target's animation list is our own cache of the animations whose effect targets it, which an+ /// animation that produces nothing leaves until it is revived.+ pub(crate) fn disassociate_from_target_if_inert(&mut self) {+ self.animation+ .borrow_mut()+ .set_disassociation_from_target_pending(false);+ // NB: Script may have revived the animation since the disassociation was scheduled.+ let Some(effect) = self.animation.borrow().effect().cloned() else {+ return;+ };+ let Some(element) = effect.borrow().target_element() else {+ return;+ };+ if self.pending() || self.is_relevant() {+ return;+ }+ self.emit(HostEffectKind::DisassociateFromTarget {+ element,+ effect: effect.clone(),+ });+ let play_state = self.play_state();+ self.animation+ .borrow_mut()+ .set_play_state_when_disassociated_from_target(Some(play_state));+ // NB: The target's animated style keeps the effect's values until they are recomputed without it.+ self.emit(HostEffectKind::RecomputeEffectStyle { effect });+ }++ /// https://www.w3.org/TR/web-animations-1/#animation-replace-state+ /// NB: An animation whose replace state is removed is associated with neither the target of its associated effect+ /// nor its timeline, until it is persisted.+ pub(crate) fn set_replace_state(&mut self, replace_state: AnimationReplaceState) {+ let previous_replace_state = self.playback().replace_state;+ let associated = match replace_state {+ AnimationReplaceState::Removed => Some(false),+ AnimationReplaceState::Persisted if previous_replace_state == AnimationReplaceState::Removed => Some(true),+ _ => None,+ };+ if let Some(associated) = associated {+ let effect = self.animation.borrow().effect().cloned();+ if let Some(effect) = effect+ && let Some(element) = effect.borrow().target_element()+ {+ self.emit(if associated {+ HostEffectKind::AssociateWithTarget { element }+ } else {+ HostEffectKind::DisassociateFromTarget {+ element,+ effect: effect.clone(),+ }+ });+ }+ let timeline = self.animation.borrow().timeline().cloned();+ if let Some(timeline) = timeline {+ let mut associated_animations = timeline.associated_animations().borrow_mut();+ if associated {+ associated_animations.insert(self.animation);+ } else {+ associated_animations.remove(self.animation);+ }+ }+ }+ self.update_playback(|playback| playback.replace_state = replace_state);+ }++ /// https://www.w3.org/TR/web-animations-1/#replaceable-animation+ fn is_replaceable(&self) -> bool {+ // An animation is replaceable if all of the following conditions are true:++ // - The existence of the animation is not prescribed by markup. That is, it is not a CSS animation with an+ // owning element, nor a CSS transition with an owning element.+ {+ let animation = self.animation.borrow();+ if matches!(+ animation.kind(),+ AnimationKind::CssAnimation(_) | AnimationKind::CssTransition(_)+ ) && animation.owning_element().is_some()+ {+ return false;+ }+ }++ // - The animation's play state is finished.+ if self.play_state() != AnimationPlayState::Finished {+ return false;+ }++ // - The animation's replace state is not removed.+ if self.playback().replace_state == AnimationReplaceState::Removed {+ return false;+ }++ // - The animation is associated with a monotonically increasing timeline.+ if !self.has_monotonically_increasing_timeline() {+ return false;+ }++ // - The animation has an associated effect.+ let Some(timing) = self.effect_timing() else {+ return false;+ };++ // - The animation's associated effect is in effect.+ // NB: The local time of the associated effect is the current time of the animation.+ let playback = self.playback();+ let resolved = timing::resolve_timing(+ &timing,+ self.current_time(),+ Some(&playback),+ self.timeline.as_ref().map(|timeline| &timeline.sample),+ );+ if !timing::is_in_effect(&resolved) {+ return false;+ }++ // - The animation's associated effect has an effect target.+ self.effect_has_target()+ }++ /// The steps the remove replaced animations procedure performs for an animation it removes.+ /// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations+ fn remove_as_replaced(&mut self) {+ // - Set animation’s replace state to removed.+ self.set_replace_state(AnimationReplaceState::Removed);++ // - Create an AnimationPlaybackEvent, removeEvent.+ // - Set removeEvent’s type attribute to remove.+ // - Set removeEvent’s currentTime attribute to the current time of animation.+ // - Set removeEvent’s timelineTime attribute to the current time of the timeline with which animation is+ // associated.+ // - If animation has a document for timing, then append removeEvent to its document for timing's pending+ // animation event queue along with its target, animation. For the scheduled event time, use the result of+ // applying the procedure to convert timeline time to origin-relative time to the current time of the+ // timeline with which animation is associated.+ // Otherwise, queue a task to dispatch removeEvent at animation. The task source for this task is the DOM+ // manipulation task source.+ // NB: The host creates and queues the event.+ let timeline_time = self.timeline_time();+ self.emit(HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Remove,+ current_time: self.current_time(),+ timeline_time,+ scheduled_timeline_time: timeline_time,+ });+ }++ // NB: The procedures below run as script asks for them through the Animation interface. Script that changes the+ // play state of a CSS animation overrides its animation-play-state from then on, which the procedures the+ // style computation runs for animation-play-state do not.++ /// Notes that script changed the play state of the animation, where it is a CSS animation.+ fn note_script_play_state_override(&self) {+ let mut animation = self.animation.borrow_mut();+ if let AnimationKind::CssAnimation(_) = animation.kind() {+ animation.css_animation_mut().flags |= CssAnimationFlag::ScriptOverrodePlayState as u8;+ }+ }++ /// Runs `procedure`, noting that script changed the play state where it changes it.+ fn as_script_changing_the_play_state(+ &mut self,+ procedure: impl FnOnce(&mut Self) -> Result<(), AnimationError>,+ ) -> Result<(), AnimationError> {+ let previous_play_state = self.play_state();+ procedure(self)?;+ if self.play_state() != previous_play_state {+ self.note_script_play_state_override();+ }+ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-play+ pub(crate) fn play(&mut self, invalidate: Invalidate) -> Result<(), AnimationError> {+ // Begins or resumes playback of the animation by running the procedure to play an animation passing true as+ // the value of the auto-rewind flag.+ self.as_script_changing_the_play_state(|procedures| procedures.play_an_animation(AutoRewind::Yes, invalidate))+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-pause+ pub(crate) fn pause(&mut self) -> Result<(), AnimationError> {+ self.pause_an_animation()?;+ self.note_script_play_state_override();+ Ok(())+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-reverse+ pub(crate) fn reverse(&mut self) -> Result<(), AnimationError> {+ self.as_script_changing_the_play_state(Self::reverse_an_animation)+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-cancel+ pub(crate) fn cancel(&mut self, invalidate: Invalidate) {+ self.note_script_play_state_override();+ self.cancel_an_animation(invalidate);+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-starttime+ pub(crate) fn set_start_time_for_bindings(&mut self, new_start_time: Option<TimeValue>) {+ // Setting this attribute updates the start time using the procedure to set the start time of this object to+ // the new value.+ self.as_script_changing_the_play_state(|procedures| {+ procedures.set_the_start_time(new_start_time);+ Ok(())+ })+ .expect("setting the start time does not throw");+ }++ /// https://www.w3.org/TR/web-animations-1/#dom-animation-currenttime+ pub(crate) fn set_current_time_for_bindings(&mut self, seek_time: Option<TimeValue>) -> Result<(), AnimationError> {+ // Setting this attribute follows the procedure to set the current time of this object to the new value.+ self.as_script_changing_the_play_state(|procedures| procedures.set_current_time(seek_time))+ }++ /// Plays a CSS animation as its animation-play-state asks.+ /// https://drafts.csswg.org/css-animations-1/#animation-play-state+ pub(crate) fn play_from_css(&mut self) -> Result<(), AnimationError> {+ self.play_an_animation(AutoRewind::Yes, Invalidate::Yes)+ }++ /// Pauses a CSS animation as its animation-play-state asks.+ /// https://drafts.csswg.org/css-animations-1/#animation-play-state+ pub(crate) fn pause_from_css(&mut self) -> Result<(), AnimationError> {+ self.pause_an_animation()+ }+}++/// Sets the target element of `effect` to `element`, the host's `DOM::Element`, or to none, and hands back what that asks+/// the host to do: its associated animation, if any, is associated with the new target rather than the old.+/// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-target+pub(crate) fn set_effect_target(effect: &EffectHandle, element: Option<NonNull<c_void>>) -> HostEffects {+ let mut effects = HostEffects::default();+ let animation = effect.borrow().associated_animation();+ if let Some(animation) = animation {+ let old_target = effect.borrow().target_element();+ if let Some(old_target) = old_target {+ effects.push(+ &animation,+ HostEffectKind::DisassociateFromTarget {+ element: old_target,+ effect: effect.clone(),+ },+ );+ }+ if let Some(element) = element {+ effects.push(&animation, HostEffectKind::AssociateWithTarget { element });+ }+ }+ effect.borrow_mut().set_target_element(element);+ effects+}++/// https://www.w3.org/TR/web-animations-1/#remove-replaced-animations+/// For the document whose associated timelines are `timelines`, where `is_descendant_of_document` answers whether the+/// host's `DOM::Element` is a descendant of it, and `tree_order` compares elements in tree order. Hands back what that+/// asks the host to do.+pub(crate) fn remove_replaced_animations<'a>(+ timelines: impl IntoIterator<Item = &'a TimelineCell>,+ is_descendant_of_document: impl Fn(NonNull<c_void>) -> bool,+ tree_order: &mut impl TreeOrder,+) -> HostEffects {+ // When asked to remove replaced animations for a Document, doc, then for every animation, animation, that:+ // - has an associated animation effect whose effect target is a descendant of doc, and+ // - is replaceable, and+ // - has a replace state of active, and+ // - for which there exists for each target property of every animation effect associated with animation, an+ // animation effect associated with a replaceable animation with a higher composite order than animation that+ // includes the same target property+ let mut replaceable_animations: Vec<AnimationHandle> = Vec::new();+ for timeline in timelines {+ let mut associated_animations = timeline.associated_animations().borrow_mut();+ associated_animations.prune();+ for index in 0..associated_animations.entry_count() {+ let Some(animation) = associated_animations.get(index) else {+ continue;+ };+ // AD-HOC: Like a CSS animation with an owning element, an SVG animation element prescribes its animation in+ // markup, so it is not replaceable.+ if matches!(animation.borrow().kind(), AnimationKind::Smil { .. }) {+ continue;+ }+ let target = animation+ .borrow()+ .effect()+ .and_then(|effect| effect.borrow().target_element());+ if !target.is_some_and(&is_descendant_of_document) {+ continue;+ }+ let Ok((true, _)) = run(&animation, |procedures| {+ Ok(procedures.is_replaceable() && procedures.playback().replace_state == AnimationReplaceState::Active)+ }) else {+ continue;+ };+ // NB: Every animation effect is a keyframe effect, whose composite order is defined.+ replaceable_animations.push(animation);+ }+ }++ replaceable_animations.sort_by(|a, b| composite_order(&a.borrow(), &b.borrow(), tree_order));++ let mut effects = HostEffects::default();+ let mut properties_with_a_higher_animation = HashSet::new();+ for animation in replaceable_animations.iter().rev() {+ let mut has_any_highest_priority_property = false;+ if let Some(keyframes) = animation+ .borrow()+ .effect()+ .and_then(|effect| effect.borrow().keyframes().cloned())+ {+ let properties = keyframes+ .target_properties()+ .iter()+ .map(|property| TargetProperty::Longhand(*property))+ .chain(+ keyframes+ .target_custom_properties()+ .iter()+ .map(|name| TargetProperty::Custom(name.raw())),+ );+ for property in properties {+ has_any_highest_priority_property |= properties_with_a_higher_animation.insert(property);+ }+ }++ if !has_any_highest_priority_property {+ // perform the following steps:+ let ((), removal_effects) = run(animation, |procedures| {+ procedures.remove_as_replaced();+ Ok(())+ })+ .expect("removing an animation does not throw");+ effects.extend(removal_effects);+ }+ }+ effects+}++/// A target property of a keyframe effect: the host's `PropertyID` of a longhand, or the raw fly string of a custom+/// property's name.+/// https://www.w3.org/TR/web-animations-1/#target-property+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+enum TargetProperty {+ Longhand(u16),+ Custom(usize),+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::animations::animation::CssAnimationState;+ use crate::animations::easing::{CompactEasing, keyword_cubic_bezier};+ use crate::animations::effect::EffectHandle;+ use crate::animations::timeline::TimelineKind;+ use crate::css::retained_fly_string::RetainedUtf16FlyString;+ use timing::{OptionalTimeValue, SpecifiedEffectTiming, SpecifiedIterationDuration, TimelineSample};++ fn document_timeline_at(milliseconds: f64) -> TimelineState {+ TimelineState {+ sample: TimelineSample {+ current_time: Some(TimeValue::milliseconds(milliseconds)).into(),+ minimum_timeline_time: OptionalTimeValue::UNRESOLVED,+ maximum_timeline_time: OptionalTimeValue::UNRESOLVED,+ is_monotonically_increasing: true,+ },+ duration: None,+ attachment_interval: None,+ is_progress_based: false,+ }+ }++ /// An animation of `kind` with a one second effect, on `timeline`.+ fn one_second_animation(kind: AnimationKind, timeline: &TimelineState) -> AnimationHandle {+ let effect = EffectHandle::new();+ effect.borrow_mut().set_specified_timing(SpecifiedEffectTiming {+ iteration_duration: SpecifiedIterationDuration {+ is_auto: false,+ milliseconds: 1000.0,+ },+ ..SpecifiedEffectTiming::default()+ });+ effect.borrow_mut().normalize_specified_timing(Some(timeline));+ let animation = AnimationHandle::new(kind);+ animation.borrow_mut().set_effect(Some(effect));+ animation+ }++ fn css_animation() -> AnimationKind {+ AnimationKind::CssAnimation(CssAnimationState {+ name: RetainedUtf16FlyString::none(),+ default_easing: CompactEasing::of(keyword_cubic_bezier(0)),+ applied_definition: None,+ named_timeline: RetainedUtf16FlyString::none(),+ name_index: 0,+ last_css_play_state: None,+ flags: 0,+ })+ }++ fn kinds_of<T>(+ animation: &AnimationHandle,+ timeline: &TimelineState,+ procedure: impl FnOnce(&mut Procedures<'_>) -> Result<T, AnimationError>,+ ) -> Vec<HostEffectKind> {+ run_on(animation, Some(*timeline), procedure)+ .expect("the procedure does not throw")+ .1+ .kinds()+ }++ fn play_state(animation: &AnimationHandle, timeline: &TimelineState) -> AnimationPlayState {+ run_on(animation, Some(*timeline), |procedures| Ok(procedures.play_state()))+ .unwrap()+ .0+ }++ #[test]+ fn playing_waits_for_the_pending_play_task_to_start() {+ let timeline = document_timeline_at(100.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);++ let kinds = kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));+ assert!(kinds.contains(&HostEffectKind::ReplaceReadyPromise));+ assert!(animation.borrow().playback().has_pending_play_task);+ assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Running);++ let timeline = document_timeline_at(250.0);+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.run_pending_play_task_if_ready();+ Ok(())+ });+ assert!(kinds.contains(&HostEffectKind::ResolveReadyPromise));+ let playback = *animation.borrow().playback();+ assert!(!playback.has_pending_play_task);+ assert_eq!(playback.start_time.get(), Some(TimeValue::milliseconds(250.0)));+ assert_eq!(playback.hold_time.get(), None);+ }++ #[test]+ fn finishing_notifies_synchronously() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));++ let kinds = kinds_of(&animation, &timeline, |procedures| procedures.finish_an_animation());+ let resolve = kinds+ .iter()+ .position(|kind| *kind == HostEffectKind::ResolveFinishedPromise)+ .expect("finishing resolves the finished promise");+ assert!(matches!(+ kinds[resolve + 1],+ HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Finish,+ current_time: Some(time),+ ..+ } if time == TimeValue::milliseconds(1000.0)+ ));+ assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Finished);+ }++ #[test]+ fn finishing_an_animation_at_rate_zero_throws() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ animation.borrow_mut().playback_mut().playback_rate = 0.0;+ let result = run_on(&animation, Some(timeline), |procedures| {+ procedures.finish_an_animation()+ });+ assert!(matches!(result, Err(AnimationError::InvalidState(_))));+ }++ #[test]+ fn pausing_while_play_pending_keeps_the_ready_promise() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));++ let kinds = kinds_of(&animation, &timeline, |procedures| procedures.pause());+ assert!(!kinds.contains(&HostEffectKind::ReplaceReadyPromise));+ let playback = *animation.borrow().playback();+ assert!(!playback.has_pending_play_task);+ assert!(playback.has_pending_pause_task);+ assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Paused);+ }++ #[test]+ fn cancelling_rejects_ready_then_finished_promise_then_queues_cancel() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));++ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.cancel(Invalidate::No);+ Ok(())+ });+ assert_eq!(+ kinds,+ [+ HostEffectKind::RejectReadyPromise,+ HostEffectKind::RejectFinishedPromise,+ HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Cancel,+ current_time: None,+ timeline_time: Some(TimeValue::milliseconds(0.0)),+ scheduled_timeline_time: Some(TimeValue::milliseconds(0.0)),+ },+ ]+ );+ assert_eq!(play_state(&animation, &timeline), AnimationPlayState::Idle);++ // Cancelling an idle animation does nothing observable.+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.cancel(Invalidate::No);+ Ok(())+ });+ assert!(kinds.is_empty());+ }++ #[test]+ fn reversing_without_an_active_timeline_throws() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ let result = run_on(&animation, None, |procedures| procedures.reverse());+ assert!(matches!(result, Err(AnimationError::InvalidState(_))));+ }++ fn script_overrode_play_state(animation: &AnimationHandle) -> bool {+ let mut animation = animation.borrow_mut();+ animation.css_animation_mut().flags & CssAnimationFlag::ScriptOverrodePlayState as u8 != 0+ }++ // https://drafts.csswg.org/css-animations-2/#animations+ #[test]+ fn script_changing_the_play_state_overrides_animation_play_state() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(css_animation(), &timeline);++ kinds_of(&animation, &timeline, |procedures| procedures.play_from_css());+ kinds_of(&animation, &timeline, |procedures| procedures.pause_from_css());+ assert!(!script_overrode_play_state(&animation));++ // Playing a paused animation changes its play state.+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));+ assert!(script_overrode_play_state(&animation));+ }++ #[test]+ fn script_playing_a_running_css_animation_does_not_override_animation_play_state() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(css_animation(), &timeline);++ kinds_of(&animation, &timeline, |procedures| procedures.play_from_css());+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));+ assert!(!script_overrode_play_state(&animation));++ kinds_of(&animation, &timeline, |procedures| procedures.pause());+ assert!(script_overrode_play_state(&animation));+ }++ // https://www.w3.org/TR/web-animations-1/#setting-the-associated-effect+ #[test]+ fn setting_the_effect_of_another_animation_takes_it_from_that_one() {+ let timeline = document_timeline_at(0.0);+ let previous_animation = one_second_animation(AnimationKind::Script, &timeline);+ let effect = previous_animation.borrow().effect().cloned().unwrap();+ // NB: The test helper links the effect to the animation as the record alone; link it as the procedure does.+ effect+ .borrow_mut()+ .set_associated_animation(Some(&previous_animation), Some(&timeline));+ let animation = AnimationHandle::new(AnimationKind::Script);++ run_on(&animation, Some(timeline), |procedures| {+ procedures.set_the_associated_effect(Some(&effect), Invalidate::No);+ Ok(())+ })+ .unwrap();+ assert!(previous_animation.borrow().effect().is_none());+ assert!(animation.borrow().effect().is_some_and(|linked| linked.ptr_eq(&effect)));+ assert!(+ effect+ .borrow()+ .associated_animation()+ .is_some_and(|associated| associated.ptr_eq(&animation))+ );++ // Setting the same effect again does nothing.+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.set_the_associated_effect(Some(&effect), Invalidate::Yes);+ Ok(())+ });+ assert!(kinds.is_empty());+ }++ #[test]+ fn unsetting_the_effect_recomputes_the_style_it_applied() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ let effect = animation.borrow().effect().cloned().unwrap();+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.set_the_associated_effect(None, Invalidate::No);+ Ok(())+ });+ assert_eq!(kinds, [HostEffectKind::RecomputeEffectStyle { effect }]);+ assert!(animation.borrow().effect().is_none());+ }++ #[test]+ fn removing_an_animation_disassociates_it_from_its_timeline_until_persisted() {+ let dangling = NonNull::<u8>::dangling().cast::<c_void>();+ let timeline = TimelineHandle::new(+ dangling,+ TimelineKind::Internal {+ time_for_observation: None,+ },+ );+ let animation = one_second_animation(AnimationKind::Script, &document_timeline_at(0.0));+ // NB: A set of animations holds only the animations whose host `Animation` is alive.+ animation.set_facade(Some(dangling));+ let associated = || timeline.associated_animations().borrow().contains(&animation);+ run(&animation, |procedures| {+ procedures.set_timeline(Some(timeline.clone()));+ Ok(())+ })+ .unwrap();+ assert!(associated());++ for (replace_state, is_associated) in [+ (AnimationReplaceState::Removed, false),+ (AnimationReplaceState::Persisted, true),+ // Persisting an animation that was not removed changes no association.+ (AnimationReplaceState::Persisted, true),+ ] {+ let kinds = run(&animation, |procedures| {+ procedures.set_replace_state(replace_state);+ Ok(())+ })+ .unwrap()+ .1+ .kinds();+ assert!(kinds.is_empty());+ assert_eq!(associated(), is_associated);+ }+ }++ #[test]+ fn an_inert_animation_leaves_its_target_until_it_is_associated_again() {+ let timeline = document_timeline_at(0.0);+ let animation = one_second_animation(AnimationKind::Script, &timeline);+ let effect = animation.borrow().effect().cloned().unwrap();+ let element = NonNull::<u8>::dangling().cast::<c_void>();+ effect.borrow_mut().set_target_element(Some(element));++ // An idle animation is not relevant.+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.disassociate_from_target_if_inert();+ Ok(())+ });+ assert_eq!(+ kinds,+ [+ HostEffectKind::DisassociateFromTarget {+ element,+ effect: effect.clone()+ },+ HostEffectKind::RecomputeEffectStyle { effect }+ ]+ );+ assert_eq!(+ animation.borrow().play_state_when_disassociated_from_target(),+ Some(AnimationPlayState::Idle)+ );++ animation.borrow_mut().did_associate_with_target();+ assert_eq!(animation.borrow().play_state_when_disassociated_from_target(), None);+ assert!(animation.borrow().disassociation_from_target_pending());++ // A playing animation is relevant, so it stays.+ kinds_of(&animation, &timeline, |procedures| procedures.play(Invalidate::No));+ let kinds = kinds_of(&animation, &timeline, |procedures| {+ procedures.disassociate_from_target_if_inert();+ Ok(())+ });+ assert!(kinds.is_empty());+ assert!(!animation.borrow().disassociation_from_target_pending());+ }++ /// A finished script animation on `timeline`, which runs from time zero, whose one second effect targets `target`,+ /// fills forwards and animates `properties`.+ fn finished_animation(timeline: &TimelineHandle, target: NonNull<c_void>, properties: &[u16]) -> AnimationHandle {+ use crate::animations::keyframes::{+ CompositeOperationOrAuto, KeyframeProperty, KeyframeSet, ProcessedKeyframe,+ };+ use crate::css::css_enums::keyword;+ use crate::css::style_value::{RetainedStyleValueData, StyleValueData};+ use std::sync::Arc;++ let animation = one_second_animation(AnimationKind::Script, &document_timeline_at(0.0));+ let effect = animation.borrow().effect().cloned().unwrap();+ let specified = SpecifiedEffectTiming {+ fill_mode: FillMode::Forwards,+ ..*effect.borrow().specified_timing()+ };+ effect.borrow_mut().set_specified_timing(specified);+ effect+ .borrow_mut()+ .normalize_specified_timing(Some(&document_timeline_at(0.0)));+ effect.borrow_mut().set_target_element(Some(target));+ let keyframe = |key| ProcessedKeyframe {+ key,+ composite: CompositeOperationOrAuto::Auto,+ easing: None,+ declarations: properties+ .iter()+ .map(|property| {+ (+ KeyframeProperty::Id(*property),+ RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: keyword::AUTO }),+ )+ })+ .collect(),+ };+ effect+ .borrow_mut()+ .set_keyframes(Some(Arc::new(KeyframeSet::from_processed_keyframes(+ vec![keyframe(0), keyframe(crate::animations::keyframes::FINAL_KEY)],+ None,+ ))));+ // NB: A set of animations holds only the animations whose host `Animation` is alive.+ animation.set_facade(Some(NonNull::<u8>::dangling().cast()));+ animation.borrow_mut().playback_mut().start_time = Some(TimeValue::milliseconds(0.0)).into();+ run(&animation, |procedures| {+ procedures.set_timeline(Some(timeline.clone()));+ Ok(())+ })+ .unwrap();+ animation+ }++ fn removed_animations(effects: HostEffects) -> Vec<AnimationHandle> {+ effects+ .into_iter()+ .filter_map(|(animation, kind)| {+ matches!(+ kind,+ HostEffectKind::QueuePlaybackEvent {+ r#type: PlaybackEventType::Remove,+ ..+ }+ )+ .then_some(animation)+ })+ .collect()+ }++ #[test]+ fn an_animation_whose_properties_later_animations_replace_is_removed() {+ use crate::css::property_metadata::property_id;+ let dangling = NonNull::<u8>::dangling().cast::<c_void>();+ let timeline = TimelineHandle::new(+ dangling,+ TimelineKind::Internal {+ time_for_observation: None,+ },+ );+ timeline.set_internal_time(Some(2000.0), false, 0, || {});+ let target = dangling;+ let in_document = |_| true;+ let replaced = finished_animation(&timeline, target, &[property_id::OPACITY]);+ let partly_replaced = finished_animation(&timeline, target, &[property_id::OPACITY, property_id::COLOR]);+ let replacing = finished_animation(&timeline, target, &[property_id::OPACITY]);++ let effects = remove_replaced_animations([&*timeline], in_document, &mut |_, _| std::cmp::Ordering::Equal);+ let removed = removed_animations(effects);+ assert_eq!(removed.len(), 1);+ assert!(removed[0].ptr_eq(&replaced));+ assert_eq!(+ replaced.borrow().playback().replace_state,+ AnimationReplaceState::Removed+ );+ assert!(!timeline.associated_animations().borrow().contains(&replaced));+ for animation in [&partly_replaced, &replacing] {+ assert_eq!(+ animation.borrow().playback().replace_state,+ AnimationReplaceState::Active+ );+ }++ // A removed animation is no longer replaceable, and the others replace nothing more.+ let effects = remove_replaced_animations([&*timeline], in_document, &mut |_, _| std::cmp::Ordering::Equal);+ assert!(removed_animations(effects).is_empty());+ }++ #[test]+ fn only_finished_animations_of_the_document_are_replaced() {+ use crate::css::property_metadata::property_id;+ let dangling = NonNull::<u8>::dangling().cast::<c_void>();+ let timeline = TimelineHandle::new(+ dangling,+ TimelineKind::Internal {+ time_for_observation: None,+ },+ );+ timeline.set_internal_time(Some(500.0), false, 0, || {});+ let running = finished_animation(&timeline, dangling, &[property_id::OPACITY]);+ let _replacing = finished_animation(&timeline, dangling, &[property_id::OPACITY]);++ // An animation that has not finished is not replaceable.+ let effects = remove_replaced_animations([&*timeline], |_| true, &mut |_, _| std::cmp::Ordering::Equal);+ assert!(removed_animations(effects).is_empty());++ // Nor is one whose target is not a descendant of the document.+ timeline.set_internal_time(Some(2000.0), false, 0, || {});+ let effects = remove_replaced_animations([&*timeline], |_| false, &mut |_, _| std::cmp::Ordering::Equal);+ assert!(removed_animations(effects).is_empty());++ let effects = remove_replaced_animations([&*timeline], |_| true, &mut |_, _| std::cmp::Ordering::Equal);+ let removed = removed_animations(effects);+ assert_eq!(removed.len(), 1);+ assert!(removed[0].ptr_eq(&running));+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/snapshot.rs b/Libraries/LibWeb/Rust/src/animations/snapshot.rsindex b6069bb526a..769047796b6 100644--- a/Libraries/LibWeb/Rust/src/animations/snapshot.rs+++ b/Libraries/LibWeb/Rust/src/animations/snapshot.rs@@ -7,19 +7,13 @@//! 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::timeline::AnimationTimelineId;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 {@@ -41,13 +35,13 @@ pub struct TimelineClock {/// The origin time of a document timeline.pub origin_time: f64,/// The identity of a scroll timeline.- pub scroll_timeline: ScrollTimelineId,+ pub scroll_timeline: AnimationTimelineId,}/// The progress, in percent, of a scroll timeline, which is its time.#[derive(Clone, Copy, Debug, PartialEq)]pub struct ScrollProgress {- pub timeline: ScrollTimelineId,+ pub timeline: AnimationTimelineId,pub progress: f64,}@@ -233,12 +227,12 @@ impl CompactEffectTiming {TimelineClockSource::Document => TimelineClock {source: TimelineClockSource::Document,origin_time: f64::from_bits(self.clock_reference),- scroll_timeline: ScrollTimelineId::default(),+ scroll_timeline: AnimationTimelineId::default(),},TimelineClockSource::Scroll => TimelineClock {source: TimelineClockSource::Scroll,origin_time: 0.0,- scroll_timeline: ScrollTimelineId(self.clock_reference),+ scroll_timeline: AnimationTimelineId(self.clock_reference),},}}@@ -406,7 +400,7 @@ mod tests {clock: TimelineClock {source: TimelineClockSource::Document,origin_time: 16.75,- scroll_timeline: ScrollTimelineId::default(),+ scroll_timeline: AnimationTimelineId::default(),},});}@@ -437,7 +431,7 @@ mod tests {clock: TimelineClock {source: TimelineClockSource::Scroll,origin_time: 0.0,- scroll_timeline: ScrollTimelineId(u64::MAX - 3),+ scroll_timeline: AnimationTimelineId(u64::MAX - 3),},});}diff --git a/Libraries/LibWeb/Rust/src/animations/timeline.rs b/Libraries/LibWeb/Rust/src/animations/timeline.rsnew file mode 100644index 00000000000..327d14769fc--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/timeline.rs@@ -0,0 +1,1602 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Timelines.+//! https://www.w3.org/TR/web-animations-1/#timelines++use super::animation::{AttachmentInterval, AttachmentRangeEdge, AttachmentRangeEdgeOffset, WeakAnimationSet};+use super::snapshot::{TimelineClock, TimelineClockSource};+use super::timeline_state::TimelineState;+use super::timing::{TimeValue, TimelineSample};+use crate::css::css_enums::{direction, writing_mode};+use crate::css::css_pixels::{CssPixelRect, CssPixels};+use crate::css::style::tree::StyleNodeID;+use crate::css::style_value::{RetainedStyleValueData, optional_style_values_equal};+use crate::layout::LayoutNodeArena;+use crate::layout::node_data::NodeSlotId;+use crate::painting::paint_read::{GeometryRead, PaintRow};+use crate::painting::paintable_geometry::{+ first_fragment_border_box_rect, first_fragment_padding_box_rect, has_scrollable_overflow, scrollable_overflow_rect,+ unbroken_content_size,+};+use std::cell::{Cell, Ref, RefCell, RefMut};+use std::ffi::c_void;+use std::ptr::NonNull;+use std::rc::Rc;+use std::sync::atomic::{AtomicU64, Ordering};++/// The identity of a timeline, by which a clock tick finds the progress of the scroller a scroll timeline follows.+#[repr(transparent)]+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]+pub struct AnimationTimelineId(pub u64);++impl AnimationTimelineId {+ fn mint() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(1);+ Self(NEXT.fetch_add(1, Ordering::Relaxed))+ }+}++/// The host's `TimelineRangeName`.+/// https://drafts.csswg.org/scroll-animations-1/#named-ranges+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum TimelineRangeName {+ /// NB: An edge given without a range name is measured along the entire timeline.+ None,+ Cover,+ Contain,+ Entry,+ Exit,+ EntryCrossing,+ ExitCrossing,+ Scroll,+}++impl TimelineRangeName {+ fn from_host(name: u8) -> Self {+ match name {+ 0 => Self::None,+ 1 => Self::Cover,+ 2 => Self::Contain,+ 3 => Self::Entry,+ 4 => Self::Exit,+ 5 => Self::EntryCrossing,+ 6 => Self::ExitCrossing,+ 7 => Self::Scroll,+ _ => unreachable!("the host names a timeline range it knows"),+ }+ }+}++/// A length plus a percentage of what it resolves against, or a calculation only that resolves.+fn length_percentage_px(calculated: &RetainedStyleValueData, px: f64, percentage: f64, basis: f64) -> f64 {+ match calculated.optional_data() {+ Some(calculated) => crate::css::style_compute::length_percentage_px(calculated, basis),+ None => px + percentage / 100.0 * basis,+ }+}++impl AttachmentRangeEdgeOffset {+ /// The offset, in pixels, along a range of the given size.+ fn offset_along(&self, range_size: f64) -> f64 {+ length_percentage_px(&self.calculated, self.px, self.percentage, range_size)+ }+}++/// One side of the view progress visibility range: auto takes the scroll container's scroll padding, otherwise a+/// length plus a percentage of the scrollport.+/// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset+#[derive(Clone)]+pub(crate) struct ViewTimelineInsetEdge {+ pub(crate) is_auto: bool,+ pub(crate) px: f64,+ pub(crate) percentage: f64,+ /// NB: An inset only a calculation can describe, such as min(50%, 10px), resolves against the scrollport size.+ pub(crate) calculated: RetainedStyleValueData,+}++/// One side of the view progress visibility range that is auto, or a length plus a percentage of the scrollport, as a+/// clock tick resolves it.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct LinearInsetEdge {+ is_auto: bool,+ px: f64,+ percentage: f64,+}++impl LinearInsetEdge {+ /// The inset, in pixels, in a scrollport of the given size, where auto takes `scroll_padding`.+ fn resolve(&self, scrollport_size: f64, scroll_padding: f64) -> f64 {+ if self.is_auto {+ return scroll_padding;+ }+ self.px + self.percentage / 100.0 * scrollport_size+ }+}++impl ViewTimelineInsetEdge {+ /// The inset, in pixels, in a scrollport of the given size, where auto takes `scroll_padding`.+ fn resolve(&self, scrollport_size: f64, scroll_padding: f64) -> f64 {+ if !self.is_auto+ && let Some(calculated) = self.calculated.optional_data()+ {+ return crate::css::style_compute::length_percentage_px(calculated, scrollport_size);+ }+ self.as_length_plus_percentage()+ .resolve(scrollport_size, scroll_padding)+ }++ fn as_length_plus_percentage(&self) -> LinearInsetEdge {+ LinearInsetEdge {+ is_auto: self.is_auto,+ px: self.px,+ percentage: self.percentage,+ }+ }++ /// The inset as a clock tick resolves it, where it is auto or a length plus a percentage, which not every+ /// calculation is.+ fn as_linear(&self) -> Option<LinearInsetEdge> {+ self.calculated+ .optional_data()+ .is_none_or(crate::css::style_compute::length_percentage_is_linear)+ .then(|| self.as_length_plus_percentage())+ }++ fn equals(&self, other: &Self) -> bool {+ self.is_auto == other.is_auto+ && self.px == other.px+ && self.percentage == other.percentage+ && optional_style_values_equal(self.calculated.optional_data(), other.calculated.optional_data())+ }+}++/// The start and the end inset of a view progress visibility range.+#[derive(Clone)]+pub(crate) struct ViewTimelineInset {+ pub(crate) start: ViewTimelineInsetEdge,+ pub(crate) end: ViewTimelineInsetEdge,+}++impl ViewTimelineInset {+ pub(crate) fn equals(&self, other: &Self) -> bool {+ self.start.equals(&other.start) && self.end.equals(&other.end)+ }+}++/// The scroll node of the host's `AsyncScrollNodeStableID`.+#[repr(C)]+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ScrollNodeStableId {+ pub node_id: i64,+ pub kind: u8,+ pub pseudo_element_type: u8,+}++/// The scroll node the timeline followed at its last update, the style node of the element whose box scrolls, or 0+/// for the viewport, and the scroll offset there and at 100% progress, in CSS pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct FollowedScroller {+ pub(crate) scroll_node: ScrollNodeStableId,+ pub(crate) scroller_style_node: u32,+ pub(crate) vertical: bool,+ pub(crate) scroll_offset: f64,+ pub(crate) max_scroll_offset: f64,+}++/// The scroll container a scroll timeline follows, along the timeline's axis, in CSS pixels, as the host laid it out.+#[derive(Clone, Copy, Debug)]+pub(crate) struct ScrollerMetrics {+ pub(crate) scroll_node: Option<ScrollNodeStableId>,+ pub(crate) scroller_style_node: u32,+ pub(crate) is_vertical: bool,+ pub(crate) scroll_offset: f64,+ pub(crate) max_scroll_offset: f64,+ /// Where the scrollport starts in the coordinates the boxes inside it are laid out in, and its size.+ pub(crate) scrollport_start: f64,+ pub(crate) scrollport_size: f64,+ /// The scroll padding at the start and at the end of the scrollport.+ pub(crate) scroll_padding_start: f64,+ pub(crate) scroll_padding_end: f64,+}++/// The length along the vertical axis, where `vertical`, and along the horizontal one otherwise, of what `vertical` and+/// `horizontal` measure.+fn along(vertical: bool, vertical_length: CssPixels, horizontal_length: CssPixels) -> f64 {+ if vertical {+ vertical_length.to_double()+ } else {+ horizontal_length.to_double()+ }+}++impl ScrollerMetrics {+ /// The scroll container whose box `arena` lays out in `scroller`, along the vertical axis where `vertical`, and+ /// along the horizontal one otherwise, where its box has scrollable overflow. Its scroll padding is measured only+ /// where `with_scroll_padding`. `scroll_node` and `scroller_style_node` name it as `FollowedScroller` does.+ pub(crate) fn measure(+ arena: &LayoutNodeArena,+ scroller: NodeSlotId,+ scroll_node: Option<ScrollNodeStableId>,+ scroller_style_node: u32,+ vertical: bool,+ with_scroll_padding: bool,+ ) -> Option<Self> {+ if !has_scrollable_overflow(arena, scroller) {+ return None;+ }+ let scrollable_overflow_rect = scrollable_overflow_rect(arena, scroller)?;+ let content_size = unbroken_content_size(arena, scroller);+ let scrollport = first_fragment_padding_box_rect(arena, scroller);+ // NB: Only a view progress timeline measures its subject against the scroll padding, so a scroll progress+ // timeline does not resolve it on every update.+ let snapport = if with_scroll_padding {+ crate::painting::scroll_snap::scroll_snapport_rect(arena, scroller, scrollport)+ } else {+ scrollport+ };++ // FIXME: Scroll offset is currently incorrect as it is always relative to the top left of the scrollable+ // overflow rect when it should instead be relative to the scroll origin.++ // FIXME: Support the case where the computed scroll axis is reversed++ let scroll_offset = arena.row_scroll_offset(scroller);+ let bottom = |rect: CssPixelRect| rect.y + rect.height;+ let right = |rect: CssPixelRect| rect.x + rect.width;+ Some(Self {+ scroll_node,+ scroller_style_node,+ is_vertical: vertical,+ scroll_offset: along(vertical, scroll_offset.y, scroll_offset.x),+ max_scroll_offset: if vertical {+ scrollable_overflow_rect.height.to_double() - content_size.height.to_double()+ } else {+ scrollable_overflow_rect.width.to_double() - content_size.width.to_double()+ },+ scrollport_start: along(vertical, scrollport.y, scrollport.x),+ scrollport_size: along(vertical, scrollport.height, scrollport.width),+ scroll_padding_start: along(vertical, snapport.y - scrollport.y, snapport.x - scrollport.x),+ scroll_padding_end: along(+ vertical,+ bottom(scrollport) - bottom(snapport),+ right(scrollport) - right(snapport),+ ),+ })+ }++ fn followed_scroller(&self) -> Option<FollowedScroller> {+ Some(FollowedScroller {+ scroll_node: self.scroll_node?,+ scroller_style_node: self.scroller_style_node,+ vertical: self.is_vertical,+ scroll_offset: self.scroll_offset,+ max_scroll_offset: self.max_scroll_offset,+ })+ }+}++/// Where the subject of a view timeline is, along the timeline's axis, as the host laid it out: where its border box+/// starts, in the coordinates the boxes inside the scrollport are laid out in, and its size, in CSS pixels.+#[derive(Clone, Copy, Debug)]+pub(crate) struct SubjectMetrics {+ pub(crate) start: f64,+ pub(crate) size: f64,+}++impl SubjectMetrics {+ /// The subject whose box `arena` lays out in `subject`, along the vertical axis where `vertical`, and along the+ /// horizontal one otherwise, where it has a box.+ pub(crate) fn measure(arena: &LayoutNodeArena, subject: NodeSlotId, vertical: bool) -> Option<Self> {+ if !arena.paintable_row_is_populated(subject) {+ return None;+ }+ // NB: The border box is laid out where the scroll container's scrolled content is at its scroll origin, with+ // transforms ignored and relative positioning accounted for, as the view progress timeline ranges ask.+ let border_box = first_fragment_border_box_rect(arena, subject);+ Some(Self {+ start: along(vertical, border_box.y, border_box.x),+ size: along(vertical, border_box.height, border_box.width),+ })+ }+}++/// Whether the scroll axis `axis`, the host's `ScrollAxis`, of a scroll container whose computed `writing-mode` and+/// `direction` are `writing_mode` and `direction` is vertical, and whether it is reversed.+fn computed_scroll_axis(axis: u8, writing_mode: u8, direction: u8) -> (bool, bool) {+ // NB: This is based on the table specified here: https://drafts.csswg.org/css-writing-modes-4/#logical-to-physical++ // FIXME: Note: The used direction depends on the computed writing-mode and text-orientation: in vertical writing+ // modes, a text-orientation value of upright forces the used direction to ltr.+ let used_direction = direction;++ match axis {+ SCROLL_AXIS_BLOCK => match writing_mode {+ writing_mode::HORIZONTAL_TB => (true, false),+ writing_mode::VERTICAL_RL | writing_mode::SIDEWAYS_RL => (false, true),+ writing_mode::VERTICAL_LR | writing_mode::SIDEWAYS_LR => (false, false),+ _ => unreachable!("a writing mode the style engine computes"),+ },+ SCROLL_AXIS_INLINE => match writing_mode {+ writing_mode::HORIZONTAL_TB => (false, used_direction == direction::RTL),+ writing_mode::VERTICAL_RL | writing_mode::SIDEWAYS_RL | writing_mode::VERTICAL_LR => {+ (true, used_direction == direction::RTL)+ }+ writing_mode::SIDEWAYS_LR => (true, used_direction == direction::LTR),+ _ => unreachable!("a writing mode the style engine computes"),+ },+ SCROLL_AXIS_X => (false, false),+ SCROLL_AXIS_Y => (true, false),+ _ => unreachable!("the host names a scroll axis it knows"),+ }+}++/// The host's `ScrollAxis`.+/// https://drafts.csswg.org/scroll-animations-1/#enumdef-scrollaxis+const SCROLL_AXIS_BLOCK: u8 = 0;+const SCROLL_AXIS_INLINE: u8 = 1;+const SCROLL_AXIS_X: u8 = 2;+const SCROLL_AXIS_Y: u8 = 3;++/// The boxes a scroll timeline follows, as the host found them from its source, and from its subject for a view+/// timeline.+pub(crate) struct ScrollTimelineBoxes {+ /// The box of the scroll container, if any: the viewport's where the source is the root element.+ pub(crate) scroller: NodeSlotId,+ pub(crate) scroll_node: Option<ScrollNodeStableId>,+ /// The style node of the element whose box scrolls, or 0 for the viewport.+ pub(crate) scroller_style_node: u32,+ /// The box of a view timeline's subject, if any.+ pub(crate) subject: NodeSlotId,+}++/// What decides the progress of a view timeline, along its axis, in CSS pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct ViewTimelineMetrics {+ pub(crate) followed_scroller: Option<FollowedScroller>,+ pub(crate) scroll_offset: f64,+ pub(crate) max_scroll_offset: f64,+ pub(crate) scrollport_size: f64,+ /// The insets of the view progress visibility range, at the start and at the end of the scrollport.+ pub(crate) inset_start: f64,+ pub(crate) inset_end: f64,+ /// Where the subject's border box starts, from the start of the scrollport, and its size.+ pub(crate) subject_offset: f64,+ pub(crate) subject_size: f64,+}++/// The scroll offsets at the start and at the end of a named timeline range, in CSS pixels.+struct ScrollOffsetInterval {+ start: f64,+ end: f64,+}++/// https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress+/// The progress of a scroll progress timeline whose scroller is at the scroll offset `position`, of which+/// `max_scroll_offset` is at 100% progress, where those positions do not coincide.+pub(crate) fn scroll_progress_at(position: f64, max_scroll_offset: f64) -> Option<TimeValue> {+ // If the 0% position and 100% position coincide (i.e. the denominator in the current time formula is zero), the+ // timeline is inactive.+ if max_scroll_offset == 0.0 {+ return None;+ }++ // Progress (the current time) for a scroll progress timeline is calculated as:+ // scroll offset ÷ (scrollable overflow size − scroll container size)+ let progress = position / max_scroll_offset;+ Some(TimeValue::percentage(progress * 100.0))+}++impl ViewTimelineMetrics {+ /// What decides the progress of a view timeline whose scroller is `scroller` and whose subject is `subject`, with+ /// the insets of its view progress visibility range resolved to `inset_start` and `inset_end`.+ fn new(scroller: &ScrollerMetrics, subject: &SubjectMetrics, inset_start: f64, inset_end: f64) -> Self {+ // https://drafts.csswg.org/scroll-animations-1/#valdef-animation-timeline-range-cover+ // 0% progress represents the latest position at which the start border edge of the element’s principal box+ // coincides with the end edge of its view progress visibility range.+ // 100% progress represents the earliest position at which the end border edge of the element’s principal box+ // coincides with the start edge of its view progress visibility range.+ Self {+ followed_scroller: scroller.followed_scroller(),+ scroll_offset: scroller.scroll_offset,+ max_scroll_offset: scroller.max_scroll_offset,+ scrollport_size: scroller.scrollport_size,+ inset_start,+ inset_end,+ subject_offset: subject.start - scroller.scrollport_start,+ subject_size: subject.size,+ }+ }++ /// The start of the cover range.+ pub(crate) fn cover_start(&self) -> f64 {+ self.subject_offset - (self.scrollport_size - self.inset_end)+ }++ /// The end of the cover range.+ pub(crate) fn cover_end(&self) -> f64 {+ self.subject_offset + self.subject_size - self.inset_start+ }++ /// https://drafts.csswg.org/scroll-animations-1/#view-timelines-ranges+ fn interval_for_range_name(&self, name: TimelineRangeName) -> ScrollOffsetInterval {+ let sorted = |start: f64, end: f64| {+ if end < start {+ return ScrollOffsetInterval { start: end, end: start };+ }+ ScrollOffsetInterval { start, end }+ };+ match name {+ TimelineRangeName::None | TimelineRangeName::Cover => {+ // Represents the full range of the view progress timeline.+ ScrollOffsetInterval {+ start: self.cover_start(),+ end: self.cover_end(),+ }+ }+ TimelineRangeName::Contain => {+ // Represents the range during which the principal box is either fully contained by, or fully covers,+ // its view progress visibility range within the scrollport.+ sorted(+ self.cover_start() + self.subject_size,+ self.cover_end() - self.subject_size,+ )+ }+ TimelineRangeName::Entry => {+ // 0% is equivalent to 0% of the cover range.+ // 100% is equivalent to 0% of the contain range.+ let contain = self.interval_for_range_name(TimelineRangeName::Contain);+ sorted(self.cover_start(), contain.start)+ }+ TimelineRangeName::Exit => {+ // 0% is equivalent to 100% of the contain range.+ // 100% is equivalent to 100% of the cover range.+ let contain = self.interval_for_range_name(TimelineRangeName::Contain);+ sorted(contain.end, self.cover_end())+ }+ TimelineRangeName::EntryCrossing => {+ // Represents the range during which the principal box crosses the end border edge.+ sorted(self.cover_start(), self.cover_start() + self.subject_size)+ }+ TimelineRangeName::ExitCrossing => {+ // Represents the range during which the principal box crosses the start border edge.+ sorted(self.cover_end() - self.subject_size, self.cover_end())+ }+ TimelineRangeName::Scroll => {+ // Represents the full range of the scroll container on which the view progress timeline is defined.+ ScrollOffsetInterval {+ start: 0.0,+ end: self.max_scroll_offset,+ }+ }+ }+ }++ /// The timeline time at the scroll offset `position`, as a proportion of the cover range, which spans the entire+ /// timeline, where the cover range is not empty.+ fn time_at(&self, position: f64) -> Option<TimeValue> {+ let cover_length = self.cover_end() - self.cover_start();+ if cover_length == 0.0 {+ return None;+ }+ Some(TimeValue::percentage(+ (position - self.cover_start()) / cover_length * 100.0,+ ))+ }+}++/// The source of a scroll timeline.+/// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source+#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum ScrollTimelineSource {+ /// The host's `DOM::Element` script or a named timeline gave, if any.+ Element(Option<NonNull<c_void>>),+ /// The scroller, the host's `CSS::Scroller`, that an anonymous timeline finds from `target`, the host's+ /// `DOM::Element`, or its pseudo-element, the host's `PseudoElement`.+ /// https://drafts.csswg.org/scroll-animations-1/#scroll-notation+ Anonymous {+ scroller: u8,+ target: NonNull<c_void>,+ pseudo_element: Option<u8>,+ },+}++/// What a view timeline adds to the scroll timeline it is.+/// https://drafts.csswg.org/scroll-animations-1/#viewtimeline+pub(crate) struct ViewTimelineState {+ /// https://drafts.csswg.org/scroll-animations-1/#view-timeline-inset+ pub(crate) inset: ViewTimelineInset,+ /// What the timeline's progress was last calculated from: none while it was inactive.+ pub(crate) last_metrics: Option<ViewTimelineMetrics>,+ /// The style node by which a clock tick finds the subject's box, as of the timeline's last update, unless the+ /// subject is a pseudo-element.+ pub(crate) subject_style_node: Option<StyleNodeID>,+}++/// The state of a scroll timeline, and of a view timeline, which is one.+/// https://drafts.csswg.org/scroll-animations-1/#scrolltimeline+pub(crate) struct ScrollTimelineState {+ /// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-source+ pub(crate) source: ScrollTimelineSource,+ /// https://drafts.csswg.org/scroll-animations-1/#dom-scrolltimeline-axis+ /// The host's `ScrollAxis`.+ pub(crate) axis: u8,+ /// The maximum scroll offset at the last update of a scroll progress timeline, while it was active.+ pub(crate) last_max_scroll_offset: Option<f64>,+ /// The scroller the timeline followed at its last update, while it was active.+ pub(crate) followed_scroller: Option<FollowedScroller>,+ /// What a view timeline adds.+ pub(crate) view: Option<ViewTimelineState>,+}++impl ScrollTimelineState {+ /// What decides the progress of the view timeline this is, where it is not inactive, from where the host laid out+ /// its scroller and its subject.+ fn view_metrics(+ &self,+ scroller: Option<&ScrollerMetrics>,+ subject: Option<&SubjectMetrics>,+ ) -> Option<ViewTimelineMetrics> {+ let view = self.view.as_ref().expect("a view timeline has a subject");+ // If the source or subject of a ViewTimeline is an element whose principal box does not exist, or if its+ // nearest ancestor scroll container has no scrollable overflow or is not scrollable in the specified axis (or+ // if there is no such ancestor, e.g. in print media), then the ViewTimeline is inactive.+ let (scroller, subject) = (scroller?, subject?);+ Some(ViewTimelineMetrics::new(+ scroller,+ subject,+ view.inset+ .start+ .resolve(scroller.scrollport_size, scroller.scroll_padding_start),+ view.inset+ .end+ .resolve(scroller.scrollport_size, scroller.scroll_padding_end),+ ))+ }++ /// Where `arena` lays out the scroller of the timeline in `boxes`, if its box is a scroll container with scrollable+ /// overflow, and, for a view timeline, its subject, if it has a box.+ pub(crate) fn measure(+ &self,+ arena: &LayoutNodeArena,+ boxes: &ScrollTimelineBoxes,+ ) -> (Option<ScrollerMetrics>, Option<SubjectMetrics>) {+ let Some(style) = arena+ .node(boxes.scroller)+ .filter(|_| crate::painting::style_queries::is_scroll_container(arena, boxes.scroller))+ .and_then(|row| row.style())+ else {+ return (None, None);+ };+ let (vertical, _reversed) = computed_scroll_axis(self.axis, style.writing_mode(), style.direction());+ let Some(scroller) = ScrollerMetrics::measure(+ arena,+ boxes.scroller,+ boxes.scroll_node,+ boxes.scroller_style_node,+ vertical,+ self.view.is_some(),+ ) else {+ return (None, None);+ };+ let subject = self+ .view+ .as_ref()+ .and_then(|_| SubjectMetrics::measure(arena, boxes.subject, vertical));+ (Some(scroller), subject)+ }++ /// The timeline times of the start and the end of the attachment range `range`.+ /// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range+ fn interval_for_attachment_range(&self, range: &[AttachmentRangeEdge; 2]) -> AttachmentInterval {+ if let Some(metrics) = self.view.as_ref().and_then(|view| view.last_metrics)+ && metrics.time_at(0.0).is_some()+ {+ // Each edge is measured from the start of its named timeline range, along that range, and is then placed+ // as a proportion of the cover range, which spans the entire timeline.+ let time_of = |edge: &AttachmentRangeEdge| {+ let named_range = metrics.interval_for_range_name(TimelineRangeName::from_host(edge.name));+ let position = named_range.start + edge.offset.offset_along(named_range.end - named_range.start);+ metrics.time_at(position).expect("the cover range is not empty")+ };+ return AttachmentInterval {+ start: time_of(&range[0]),+ end: time_of(&range[1]),+ };+ }++ // NB: A scroll progress timeline has no named timeline ranges, so each edge is measured along the entire+ // timeline, whose length is the maximum scroll offset. This matches WebKit.+ let max_scroll_offset = self.last_max_scroll_offset.unwrap_or(0.0);+ let time_of = |edge: &AttachmentRangeEdge| {+ if max_scroll_offset == 0.0 {+ return TimeValue::percentage(edge.offset.percentage);+ }+ TimeValue::percentage(edge.offset.offset_along(max_scroll_offset) / max_scroll_offset * 100.0)+ };+ AttachmentInterval {+ start: time_of(&range[0]),+ end: time_of(&range[1]),+ }+ }+}++/// A scroll timeline as a rendering update seals it into the render clock's plan, whose ticks sample its animations+/// where the compositor has scrolled its scroller to, and follow the layout the ticks' frames make of it.+#[derive(Clone, Copy, Debug)]+pub(crate) struct ScrollTimelineSnapshot {+ pub(crate) timeline: AnimationTimelineId,+ /// The scroller the timeline followed as the plan was sealed, with its scroll offset at 100% progress in the+ /// layout the ticks' frames last made of it.+ pub(crate) scroller: FollowedScroller,+ view: Option<ViewTimelineSnapshot>,+}++/// What a view timeline adds to the scroll timeline it is, as the render clock's plan seals it.+#[derive(Clone, Copy, Debug)]+struct ViewTimelineSnapshot {+ subject: StyleNodeID,+ inset_start: LinearInsetEdge,+ inset_end: LinearInsetEdge,+ /// What decides the timeline's progress, in the layout the ticks' frames last made of it.+ metrics: ViewTimelineMetrics,+}++impl ScrollTimelineSnapshot {+ /// The progress, in percent, of the timeline at the scroll offset `position`.+ /// NB: The 0% and 100% positions never coincide: the plan seals no such timeline, and `follow_layout` leaves one+ /// where they would.+ pub(crate) fn progress_at(&self, position: f64) -> f64 {+ let progress = match &self.view {+ None => scroll_progress_at(position, self.scroller.max_scroll_offset),+ Some(view) => view.metrics.time_at(position),+ };+ progress.expect("the 0% and 100% positions do not coincide").value+ }++ /// Has the timeline follow the layout `arena` holds, as a host's layout decides its next rendering update's+ /// samples. What makes the timeline inactive there leaves it where it was: the host decides that.+ pub(crate) fn follow_layout(&mut self, arena: &LayoutNodeArena) {+ let scroller = StyleNodeID::from_raw(self.scroller.scroller_style_node)+ .map_or_else(|| arena.layout_root(), |element| arena.bound_row(element));+ let Some(scroller) = ScrollerMetrics::measure(+ arena,+ scroller,+ Some(self.scroller.scroll_node),+ self.scroller.scroller_style_node,+ self.scroller.vertical,+ self.view.is_some(),+ ) else {+ return;+ };+ if scroll_progress_at(0.0, scroller.max_scroll_offset).is_none() {+ return;+ }+ self.scroller.max_scroll_offset = scroller.max_scroll_offset;+ let Some(view) = &mut self.view else {+ return;+ };+ let Some(subject) = SubjectMetrics::measure(arena, arena.bound_row(view.subject), self.scroller.vertical)+ else {+ return;+ };+ let metrics = ViewTimelineMetrics::new(+ &scroller,+ &subject,+ view.inset_start+ .resolve(scroller.scrollport_size, scroller.scroll_padding_start),+ view.inset_end+ .resolve(scroller.scrollport_size, scroller.scroll_padding_end),+ );+ if metrics.time_at(0.0).is_some() {+ view.metrics = metrics;+ }+ }+}++/// What kind of timeline a timeline is, with the state of its kind.+pub(crate) enum TimelineKind {+ /// https://www.w3.org/TR/web-animations-1/#document-timelines+ Document {+ /// https://www.w3.org/TR/web-animations-1/#origin-time+ origin_time: f64,+ },+ /// A scroll progress timeline, or a view progress timeline where it has view state.+ Scroll(Box<ScrollTimelineState>),+ /// The timeline of the Internals interface, whose time tests set.+ Internal {+ /// The time a read of the timeline observes, where one is set.+ time_for_observation: Option<TimeValue>,+ },+}++/// What script observed of a timeline in a task.+#[derive(Clone, Copy, Default)]+struct TimelineObservation {+ /// The task generation of the event loop in which the timeline was last updated or observed.+ task_generation: Option<u64>,+ current_time: Option<TimeValue>,+}++/// The state of a timeline.+/// https://www.w3.org/TR/web-animations-1/#the-animationtimeline-interface+pub(crate) struct TimelineRecord {+ id: AnimationTimelineId,+ /// https://www.w3.org/TR/web-animations-1/#timeline-associated-with-a-document+ /// The host's `DOM::Document`, which the host's timeline keeps alive.+ document: NonNull<c_void>,+ /// https://www.w3.org/TR/web-animations-1/#dom-animationtimeline-currenttime+ current_time: Option<TimeValue>,+ /// https://drafts.csswg.org/web-animations-1/#monotonically-increasing-timeline+ is_monotonically_increasing: bool,+ observation: TimelineObservation,+ /// The current time a style sampling reads instead of the current time, where it is set.+ style_sampling_override: Option<Option<TimeValue>>,+ pub(crate) kind: TimelineKind,+}++impl TimelineRecord {+ #[must_use]+ pub(crate) fn id(&self) -> AnimationTimelineId {+ self.id+ }++ #[must_use]+ pub(crate) fn scroll(&self) -> Option<&ScrollTimelineState> {+ match &self.kind {+ TimelineKind::Scroll(scroll) => Some(scroll),+ TimelineKind::Document { .. } | TimelineKind::Internal { .. } => None,+ }+ }++ fn scroll_mut(&mut self) -> &mut ScrollTimelineState {+ match &mut self.kind {+ TimelineKind::Scroll(scroll) => scroll,+ TimelineKind::Document { .. } | TimelineKind::Internal { .. } => {+ unreachable!("the timeline is a scroll timeline")+ }+ }+ }++ /// The current time a style sampling reads instead of the current time, where it is set.+ #[must_use]+ pub(crate) fn style_sampling_override(&self) -> Option<Option<TimeValue>> {+ self.style_sampling_override+ }++ pub(crate) fn set_style_sampling_override(&mut self, current_time: Option<Option<TimeValue>>) {+ self.style_sampling_override = current_time;+ }++ fn effective_current_time(&self) -> Option<TimeValue> {+ match self.style_sampling_override {+ Some(current_time) => current_time,+ None => self.current_time,+ }+ }++ /// https://drafts.csswg.org/web-animations-2/#progress-based-timeline+ #[must_use]+ pub(crate) fn is_progress_based(&self) -> bool {+ matches!(self.kind, TimelineKind::Scroll(_))+ }++ /// https://drafts.csswg.org/web-animations-2/#timeline-duration+ #[must_use]+ pub(crate) fn duration(&self) -> Option<TimeValue> {+ // The duration of a timeline gives the maximum value a timeline may generate for its current time. This value+ // is used to calculate the intrinsic iteration duration for the target effect of an animation that is+ // associated with the timeline when the effect’s iteration duration is "auto". The value is computed such that+ // the effect fills the available time. For a monotonic timeline, there is no upper bound on current time, and+ // timeline duration is unresolved. For a non-monotonic (e.g. scroll) timeline, the duration has a fixed upper+ // bound. In this case, the timeline is a progress-based timeline, and its timeline duration is 100%.+ self.is_progress_based().then_some(TimeValue::percentage(100.0))+ }++ /// https://drafts.csswg.org/web-animations-2/#minimum-timeline-time+ /// NB: None for a monotonically increasing timeline, whose minimum timeline time is -infinity.+ fn minimum_timeline_time(&self) -> Option<TimeValue> {+ let scroll = self.scroll()?;+ match &scroll.view {+ // NB: The timeline times at the minimum and the maximum scroll offsets, which need not be 0% and 100%.+ Some(view) => view.last_metrics.and_then(|metrics| metrics.time_at(0.0)),+ // NB: The minimum and the maximum scroll offsets.+ None => Some(TimeValue::percentage(0.0)),+ }+ }++ /// https://drafts.csswg.org/web-animations-2/#maximum-timeline-time+ /// NB: None for a monotonically increasing timeline, whose maximum timeline time is +infinity.+ fn maximum_timeline_time(&self) -> Option<TimeValue> {+ let scroll = self.scroll()?;+ match &scroll.view {+ Some(view) => view+ .last_metrics+ .and_then(|metrics| metrics.time_at(metrics.max_scroll_offset)),+ None => Some(TimeValue::percentage(100.0)),+ }+ }++ /// The current time at `timestamp` of a timeline that can sample it there, and its current time otherwise.+ fn current_time_at_timestamp(&self, timestamp: f64, is_inactive: bool) -> Option<TimeValue> {+ match &self.kind {+ TimelineKind::Document { origin_time } => {+ (!is_inactive).then(|| TimeValue::milliseconds(timestamp - origin_time))+ }+ TimelineKind::Internal { time_for_observation } => *time_for_observation,+ TimelineKind::Scroll(_) => (!is_inactive).then_some(self.effective_current_time()).flatten(),+ }+ }++ /// Whether a read of the timeline can sample its current time at a timestamp of its own.+ #[must_use]+ pub(crate) fn can_sample_current_time_at_timestamp(&self) -> bool {+ match &self.kind {+ TimelineKind::Document { .. } => true,+ TimelineKind::Internal { time_for_observation } => time_for_observation.is_some(),+ TimelineKind::Scroll(_) => false,+ }+ }++ /// The task generation in which script observed the timeline at a time ahead of its current time, if any.+ #[must_use]+ pub(crate) fn observed_ahead_in_task_generation(&self) -> Option<u64> {+ if self.observation.current_time == self.current_time {+ return None;+ }+ self.observation.task_generation+ }++ /// The task generation of the event loop in which the timeline was last updated or observed, if any, and its+ /// current time then.+ #[must_use]+ pub(crate) fn observed_in_task_generation(&self) -> (Option<u64>, Option<TimeValue>) {+ (self.observation.task_generation, self.observation.current_time)+ }++ /// Sets the current time of the timeline in the task of `task_generation`, answering whether it took it: a+ /// monotonically increasing timeline only moves forward.+ fn set_current_time(&mut self, value: Option<TimeValue>, task_generation: u64) -> bool {+ if self.is_monotonically_increasing+ && let Some(current_time) = self.current_time+ && value.is_none_or(|value| value < current_time)+ {+ return false;+ }+ self.current_time = value;+ self.observation = TimelineObservation {+ task_generation: Some(task_generation),+ current_time: value,+ };+ true+ }+}++/// A timeline's record, which every handle to the timeline shares, the animations associated with it, and the host's+/// timeline of it.+pub struct TimelineCell {+ record: RefCell<TimelineRecord>,+ /// NB: The animations associated with the timeline, none of which it keeps alive.+ associated_animations: RefCell<WeakAnimationSet>,+ /// The host's `AnimationTimeline`, which holds a reference to the record until it is finalized and clears this as+ /// it does. It keeps the document and the elements the record names alive, so the record does not reach them+ /// without it.+ facade: Cell<Option<NonNull<c_void>>>,+}++/// How a timeline came to have its current time.+pub(crate) enum TimelineUpdate<'a> {+ /// A document timeline's at the now timestamp of the update animations and send events procedure.+ Timestamp(f64),+ /// A scroll timeline's from where the host laid out its scroller, if it has a box that is a scroll container with+ /// scrollable overflow, and, for a view timeline, its subject, if it has a box, which a clock tick finds by+ /// `subject_style_node`.+ Layout {+ scroller: Option<&'a ScrollerMetrics>,+ subject: Option<&'a SubjectMetrics>,+ subject_style_node: Option<StyleNodeID>,+ },+}++impl TimelineCell {+ pub(crate) fn borrow(&self) -> Ref<'_, TimelineRecord> {+ self.record.borrow()+ }++ pub(crate) fn borrow_mut(&self) -> RefMut<'_, TimelineRecord> {+ self.record.borrow_mut()+ }++ /// The host's `AnimationTimeline` of the timeline, while it is alive.+ pub(crate) fn facade(&self) -> Option<NonNull<c_void>> {+ self.facade.get()+ }++ /// Calls `visit` with each GC cell of the host the record names: the document the timeline is associated with, and+ /// the element a scroll timeline finds its scroller from, if any, which a holder of the record the GC traces+ /// visits.+ pub(crate) fn for_each_host_cell(&self, mut visit: impl FnMut(NonNull<c_void>)) {+ let record = self.borrow();+ visit(record.document);+ match record.scroll().map(|scroll| scroll.source) {+ Some(ScrollTimelineSource::Element(Some(element))) => visit(element),+ Some(ScrollTimelineSource::Anonymous { target, .. }) => visit(target),+ Some(ScrollTimelineSource::Element(None)) | None => {}+ }+ }++ /// The host's `DOM::Document` the timeline is associated with.+ pub(crate) fn document(&self) -> NonNull<c_void> {+ self.borrow().document+ }++ pub(crate) fn associated_animations(&self) -> &RefCell<WeakAnimationSet> {+ &self.associated_animations+ }++ /// https://drafts.csswg.org/web-animations-1/#timeline+ #[must_use]+ pub(crate) fn is_inactive(&self) -> bool {+ let record = self.borrow();+ // A timeline is considered to be inactive when its time value is unresolved, and active otherwise.+ if record.effective_current_time().is_none() {+ return true;+ }+ if let TimelineKind::Document { .. } = record.kind {+ // https://www.w3.org/TR/web-animations-1/#document-timelines+ // A document timeline that is associated with a Document which is not an active document is also+ // considered to be inactive.+ // NB: A timeline whose host timeline was finalized reaches no document.+ return self.facade().is_none() || !super::ffi::document_is_active(record.document);+ }+ false+ }++ /// https://drafts.csswg.org/web-animations-1/#dom-animationtimeline-currenttime+ #[must_use]+ pub(crate) fn current_time(&self) -> Option<TimeValue> {+ // Returns the current time for this timeline or null if this timeline is inactive.+ if self.is_inactive() {+ return None;+ }+ self.borrow().effective_current_time()+ }++ /// What the timing model reads of the timeline now.+ #[must_use]+ pub(crate) fn sample(&self) -> TimelineSample {+ let current_time = self.current_time();+ let record = self.borrow();+ TimelineSample {+ current_time: current_time.into(),+ minimum_timeline_time: record.minimum_timeline_time().into(),+ maximum_timeline_time: record.maximum_timeline_time().into(),+ is_monotonically_increasing: record.is_monotonically_increasing,+ }+ }++ /// What moves the timeline as a clock tick samples it.+ #[must_use]+ pub(crate) fn clock(&self) -> TimelineClock {+ // A document timeline's time is a timestamp less its origin time, which is what lets a clock tick sample it.+ if let Some(origin_time) =+ self.convert_a_timeline_time_to_an_origin_relative_time(Some(TimeValue::milliseconds(0.0)))+ {+ return TimelineClock {+ source: TimelineClockSource::Document,+ origin_time,+ scroll_timeline: AnimationTimelineId::default(),+ };+ }+ let record = self.borrow();+ match &record.kind {+ // 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.+ TimelineKind::Scroll(scroll) if scroll.followed_scroller.is_some() => TimelineClock {+ source: TimelineClockSource::Scroll,+ origin_time: 0.0,+ scroll_timeline: record.id,+ },+ TimelineKind::Document { .. } | TimelineKind::Scroll(_) | TimelineKind::Internal { .. } => {+ TimelineClock::default()+ }+ }+ }++ /// The timeline as the render clock's plan seals it, where a clock tick can follow it: a scroll timeline that+ /// follows a scroller, and of a view timeline, one whose subject a tick finds and whose insets it resolves.+ #[must_use]+ pub(crate) fn clock_snapshot(&self) -> Option<ScrollTimelineSnapshot> {+ let current_time = self.current_time()?;+ if current_time.r#type != super::timing::TimeValueType::Percentage {+ return None;+ }+ let record = self.borrow();+ let scroll = record.scroll()?;+ let scroller = scroll.followed_scroller?;+ let view = match &scroll.view {+ None => None,+ Some(view) => Some(ViewTimelineSnapshot {+ // NB: A tick finds the subject of a view timeline by its box, which a pseudo-element does not name.+ subject: view.subject_style_node?,+ // NB: A tick resolves the insets of a view timeline as a length plus a percentage, which not every+ // calculation is.+ inset_start: view.inset.start.as_linear()?,+ inset_end: view.inset.end.as_linear()?,+ metrics: view.last_metrics?,+ }),+ };+ Some(ScrollTimelineSnapshot {+ timeline: record.id,+ scroller,+ view,+ })+ }++ /// The timeline as an animation attached to `range` of it reads it now.+ #[must_use]+ pub(crate) fn state_for(&self, range: &[AttachmentRangeEdge; 2]) -> TimelineState {+ let sample = self.sample();+ let record = self.borrow();+ TimelineState {+ sample,+ duration: record.duration(),+ attachment_interval: record+ .scroll()+ .map(|scroll| scroll.interval_for_attachment_range(range)),+ is_progress_based: record.is_progress_based(),+ }+ }++ /// https://www.w3.org/TR/web-animations-1/#timeline-time-to-origin-relative-time+ #[must_use]+ pub(crate) fn convert_a_timeline_time_to_an_origin_relative_time(+ &self,+ timeline_time: Option<TimeValue>,+ ) -> Option<f64> {+ let TimelineKind::Document { origin_time } = self.borrow().kind else {+ return None;+ };+ self.convert_a_timeline_time_to_an_origin_relative_time_from(timeline_time, origin_time)+ }++ /// https://www.w3.org/TR/web-animations-1/#ref-for-timeline-time-to-origin-relative-time+ fn convert_a_timeline_time_to_an_origin_relative_time_from(+ &self,+ timeline_time: Option<TimeValue>,+ origin_time: f64,+ ) -> Option<f64> {+ // To convert a timeline time, timeline time, to an origin-relative time for a document timeline, timeline,+ // return the sum of the timeline time and timeline’s origin time. If timeline is inactive, return an+ // unresolved time value.+ if self.is_inactive() {+ return None;+ }+ let timeline_time = timeline_time?;+ // NB: We know the timeline time of a DocumentTimeline is always in milliseconds because it's only ever set+ // from update_current_time()+ assert!(timeline_time.r#type == super::timing::TimeValueType::Milliseconds);+ Some(timeline_time.value + origin_time)+ }++ /// The current time at `timestamp` of a timeline that can sample it there, and its current time otherwise. Where+ /// script observes it in the task of `observed_in_task_generation`, the timeline keeps it as what script observed+ /// in that task.+ pub(crate) fn current_time_at_timestamp(+ &self,+ timestamp: f64,+ observed_in_task_generation: Option<u64>,+ ) -> Option<TimeValue> {+ let is_inactive = self.is_inactive();+ let mut record = self.borrow_mut();+ let current_time = record.current_time_at_timestamp(timestamp, is_inactive);+ if let Some(task_generation) = observed_in_task_generation {+ record.observation = TimelineObservation {+ task_generation: Some(task_generation),+ current_time,+ };+ }+ current_time+ }++ /// Updates the current time of the timeline in the task of `task_generation`, as `update` has it, unless the+ /// update leaves it as it was where `only_if_stale`, answering whether it updated it. `update_associated_animations`+ /// updates the animations associated with the timeline as its current time changes.+ /// https://drafts.csswg.org/web-animations-1/#animation-frame-loop+ pub(crate) fn update_current_time(+ &self,+ update: TimelineUpdate<'_>,+ task_generation: u64,+ only_if_stale: bool,+ update_associated_animations: impl FnOnce(),+ ) -> bool {+ let mut record = self.borrow_mut();+ // NB: The Internals interface's timeline keeps the time its tests set, and only updates its animations.+ let current_time = match update {+ TimelineUpdate::Timestamp(timestamp) => match record.kind {+ TimelineKind::Document { origin_time } => {+ // https://drafts.csswg.org/web-animations-1/#document-timeline+ // A document timeline is a type of timeline that is associated with a document and whose current+ // time is calculated as a fixed offset from the now timestamp provided each time the update+ // animations and send events procedure is run. This fixed offset is equal to the current time of+ // the default document timeline when this timeline’s current time was zero, and is thus referred+ // to as the document timeline’s origin time.+ Some(Some(TimeValue::milliseconds(timestamp - origin_time)))+ }+ TimelineKind::Internal { .. } => None,+ TimelineKind::Scroll(_) => unreachable!("a scroll timeline updates from the layout of its scroller"),+ },+ TimelineUpdate::Layout {+ scroller,+ subject,+ subject_style_node,+ } => {+ let scroll = record.scroll_mut();+ if let Some(view) = &mut scroll.view {+ view.subject_style_node = subject_style_node;+ }+ if only_if_stale && !scroll.is_stale(scroller, subject) {+ return false;+ }+ Some(scroll.take_layout(scroller, subject))+ }+ };+ let took_current_time =+ current_time.is_none_or(|current_time| record.set_current_time(current_time, task_generation));+ drop(record);+ if took_current_time {+ update_associated_animations();+ }++ // https://drafts.csswg.org/web-animations-1/#ref-for-active-timeline+ // After a document timeline becomes active, it is monotonically increasing.+ if matches!(self.borrow().kind, TimelineKind::Document { .. })+ && !self.borrow().is_monotonically_increasing+ && !self.is_inactive()+ {+ self.borrow_mut().is_monotonically_increasing = true;+ }+ true+ }++ /// Sets the current time of the Internals interface's timeline to `time`, in milliseconds, in the task of+ /// `task_generation`, or where `for_observation`, the time a read of the timeline observes.+ pub(crate) fn set_internal_time(+ &self,+ time: Option<f64>,+ for_observation: bool,+ task_generation: u64,+ update_associated_animations: impl FnOnce(),+ ) {+ let time = time.map(TimeValue::milliseconds);+ let mut record = self.borrow_mut();+ if for_observation {+ let TimelineKind::Internal { time_for_observation } = &mut record.kind else {+ unreachable!("the timeline is the Internals interface's");+ };+ *time_for_observation = time;+ record.observation.task_generation = None;+ return;+ }+ let took_current_time = record.set_current_time(time, task_generation);+ drop(record);+ if took_current_time {+ update_associated_animations();+ }+ }++ /// Sets the axis of a scroll timeline, and the inset of a view timeline, answering whether that changed either.+ pub(crate) fn set_axis_and_inset(&self, axis: u8, inset: Option<ViewTimelineInset>) -> bool {+ let mut record = self.borrow_mut();+ let scroll = record.scroll_mut();+ let inset_changed = match (&mut scroll.view, inset) {+ (Some(view), Some(inset)) if !view.inset.equals(&inset) => {+ view.inset = inset;+ true+ }+ _ => false,+ };+ let axis_changed = scroll.axis != axis;+ scroll.axis = axis;+ axis_changed || inset_changed+ }+}++impl ScrollTimelineState {+ /// https://drafts.csswg.org/scroll-animations-1/#stale-timelines+ /// Whether the layout of the scroller, and of the subject of a view timeline, changed the timeline since its last+ /// update.+ fn is_stale(&self, scroller: Option<&ScrollerMetrics>, subject: Option<&SubjectMetrics>) -> bool {+ // FIXME: This should probably be a spec bug++ // AD-HOC: The spec only lists two criteria for a scroll timeline to be considered stale: a) it was newly+ // created within the current frame or; b) style update and layout within the current frame changed+ // it's associated named timeline ranges. However, WPT expects us to also consider the source element+ // resizing as a cause for staleness, so we use a more broad definition of staleness and consider any+ // timeline whose max scroll offset has changed since the last call to `update_current_time` to be+ // stale. This matches the (admittedly narrow) tests in WPT and is the same behavior as is implemented+ // by WebKit.+ if let Some(view) = &self.view {+ // NB: A view progress timeline's named timeline ranges move with its subject too.+ return self.view_metrics(scroller, subject) != view.last_metrics;+ }++ // FIXME: Account for the named timeline ranges of view progress timelines once they are implemented.+ scroller.map(|scroller| scroller.max_scroll_offset) != self.last_max_scroll_offset+ }++ /// Takes in where the host laid out the scroller, and the subject of a view timeline, answering the current time+ /// that makes the timeline.+ fn take_layout(+ &mut self,+ scroller: Option<&ScrollerMetrics>,+ subject: Option<&SubjectMetrics>,+ ) -> Option<TimeValue> {+ self.followed_scroller = None;+ if self.view.is_some() {+ return self.take_view_layout(scroller, subject);+ }++ // https://drafts.csswg.org/scroll-animations-1/#ref-for-dom-animationtimeline-currenttime+ // currentTime represents the scroll progress of the scroll container as a percentage CSSUnitValue, with 0%+ // representing its startmost scroll position (in the writing mode of the scroll container). Null when the+ // timeline is inactive.+ self.last_max_scroll_offset = scroller.map(|scroller| scroller.max_scroll_offset);++ // If the source of a ScrollTimeline is an element whose principal box does not exist or is not a scroll+ // container, or if there is no scrollable overflow, then the ScrollTimeline is inactive.+ let scroller = scroller?;++ // https://drafts.csswg.org/scroll-animations-1/#scroll-timeline-progress+ let progress = scroll_progress_at(scroller.scroll_offset, scroller.max_scroll_offset)?;++ // FIXME: In paged media, scroll progress timelines that would otherwise reference the document viewport are+ // also inactive.++ self.followed_scroller = scroller.followed_scroller();+ Some(progress)+ }++ fn take_view_layout(+ &mut self,+ scroller: Option<&ScrollerMetrics>,+ subject: Option<&SubjectMetrics>,+ ) -> Option<TimeValue> {+ let metrics = self.view_metrics(scroller, subject);+ self.view.as_mut().expect("a view timeline has a subject").last_metrics = metrics;+ let metrics = metrics?;++ // https://drafts.csswg.org/scroll-animations-1/#view-timeline-progress+ // Progress (the current time) in a view progress timeline is calculated as: distance ÷ range where:+ // - distance is the current scroll offset minus the scroll offset corresponding to the start of the cover+ // range+ // - range is the scroll offset corresponding to the end of the cover range minus the scroll offset+ // corresponding to the start of the cover range+ // If the 0% position and 100% position coincide (i.e. the denominator in the current time formula is zero),+ // the timeline is inactive.+ // NB: The time at the scroll offset is that proportion of the cover range.+ let progress = metrics.time_at(metrics.scroll_offset)?;++ // FIXME: In paged media, view progress timelines that would otherwise reference the document viewport are+ // also inactive.++ self.followed_scroller = metrics.followed_scroller;+ Some(progress)+ }+}++/// A strong reference to a timeline.+#[derive(Clone)]+pub(crate) struct TimelineHandle(Rc<TimelineCell>);++impl TimelineHandle {+ /// A new timeline of `kind`, associated with the host's `DOM::Document` `document`, whose host timeline is+ /// `facade`. Its current time is unresolved, and a document timeline is not monotonically increasing until it+ /// becomes active.+ pub(crate) fn new(document: NonNull<c_void>, kind: TimelineKind) -> Self {+ // NB: The Internals interface's timeline starts at zero and only moves forward.+ let (current_time, is_monotonically_increasing) = match kind {+ TimelineKind::Internal { .. } => (Some(TimeValue::milliseconds(0.0)), true),+ TimelineKind::Document { .. } | TimelineKind::Scroll(_) => (None, false),+ };+ Self(Rc::new(TimelineCell {+ record: RefCell::new(TimelineRecord {+ id: AnimationTimelineId::mint(),+ document,+ current_time,+ is_monotonically_increasing,+ observation: TimelineObservation::default(),+ style_sampling_override: None,+ kind,+ }),+ associated_animations: RefCell::default(),+ facade: Cell::new(None),+ }))+ }++ /// A new reference to the timeline the host holds a reference to.+ ///+ /// # Safety+ /// `cell` must be a timeline the host holds a reference to.+ pub(crate) unsafe fn retained_from_host(cell: &TimelineCell) -> Self {+ let cell = std::ptr::from_ref(cell);+ // SAFETY: Guaranteed by the caller.+ unsafe {+ Rc::increment_strong_count(cell);+ Self(Rc::from_raw(cell))+ }+ }++ /// Whether `self` and `other` are the same timeline.+ #[must_use]+ pub(crate) fn ptr_eq(&self, other: &Self) -> bool {+ Rc::ptr_eq(&self.0, &other.0)+ }++ /// Notes the cell of the object script sees of the timeline, or that it was finalized.+ pub(crate) fn set_facade(&self, facade: Option<NonNull<c_void>>) {+ self.0.facade.set(facade);+ }+}++impl std::ops::Deref for TimelineHandle {+ type Target = TimelineCell;++ fn deref(&self) -> &TimelineCell {+ &self.0+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facade() -> NonNull<c_void> {+ NonNull::<u8>::dangling().cast()+ }++ fn edge(name: u8, px: f64, percentage: f64) -> AttachmentRangeEdge {+ AttachmentRangeEdge {+ name,+ offset: AttachmentRangeEdgeOffset {+ px,+ percentage,+ calculated: RetainedStyleValueData::none(),+ },+ }+ }++ fn auto_inset() -> ViewTimelineInset {+ let edge = ViewTimelineInsetEdge {+ is_auto: true,+ px: 0.0,+ percentage: 0.0,+ calculated: RetainedStyleValueData::none(),+ };+ ViewTimelineInset {+ start: edge.clone(),+ end: edge,+ }+ }++ fn scroll_timeline(view: Option<ViewTimelineInset>) -> TimelineHandle {+ TimelineHandle::new(+ facade(),+ TimelineKind::Scroll(Box::new(ScrollTimelineState {+ source: ScrollTimelineSource::Element(None),+ axis: 0,+ last_max_scroll_offset: None,+ followed_scroller: None,+ view: view.map(|inset| ViewTimelineState {+ inset,+ last_metrics: None,+ subject_style_node: None,+ }),+ })),+ )+ }++ fn scroller(scroll_offset: f64, max_scroll_offset: f64) -> ScrollerMetrics {+ ScrollerMetrics {+ scroll_node: Some(ScrollNodeStableId {+ node_id: 1,+ kind: 1,+ pseudo_element_type: 0,+ }),+ scroller_style_node: 2,+ is_vertical: true,+ scroll_offset,+ max_scroll_offset,+ scrollport_start: 0.0,+ scrollport_size: 100.0,+ scroll_padding_start: 0.0,+ scroll_padding_end: 0.0,+ }+ }++ fn update(timeline: &TimelineHandle, scroller: Option<&ScrollerMetrics>, subject: Option<&SubjectMetrics>) {+ assert!(timeline.update_current_time(+ TimelineUpdate::Layout {+ scroller,+ subject,+ subject_style_node: None,+ },+ 1,+ false,+ || {}+ ));+ }++ #[test]+ fn scroll_progress_is_the_scroll_offset_over_the_maximum() {+ let timeline = scroll_timeline(None);+ update(&timeline, Some(&scroller(50.0, 200.0)), None);+ assert_eq!(timeline.current_time(), Some(TimeValue::percentage(25.0)));+ assert_eq!(timeline.clock().source, TimelineClockSource::Scroll);++ // Without scrollable overflow the timeline is inactive, and nothing moves it.+ update(&timeline, Some(&scroller(0.0, 0.0)), None);+ assert_eq!(timeline.current_time(), None);+ assert_eq!(timeline.clock().source, TimelineClockSource::Unticked);+ }++ #[test]+ fn a_scroll_timeline_is_stale_where_its_maximum_scroll_offset_moved() {+ let timeline = scroll_timeline(None);+ update(&timeline, Some(&scroller(50.0, 200.0)), None);+ let mut updated = false;+ timeline.update_current_time(+ TimelineUpdate::Layout {+ scroller: Some(&scroller(80.0, 200.0)),+ subject: None,+ subject_style_node: None,+ },+ 1,+ true,+ || updated = true,+ );+ assert!(!updated);+ timeline.update_current_time(+ TimelineUpdate::Layout {+ scroller: Some(&scroller(80.0, 400.0)),+ subject: None,+ subject_style_node: None,+ },+ 1,+ true,+ || updated = true,+ );+ assert!(updated);+ assert_eq!(timeline.current_time(), Some(TimeValue::percentage(20.0)));+ }++ #[test]+ fn an_attachment_range_on_a_scroll_timeline_spans_the_scroll_range() {+ let timeline = scroll_timeline(None);+ update(&timeline, Some(&scroller(0.0, 200.0)), None);+ let state = timeline.state_for(&[edge(0, 20.0, 0.0), edge(0, 0.0, 50.0)]);+ let interval = state.attachment_interval().unwrap();+ assert_eq!(interval.start, TimeValue::percentage(10.0));+ assert_eq!(interval.end, TimeValue::percentage(50.0));+ assert_eq!(state.duration, Some(TimeValue::percentage(100.0)));+ }++ #[test]+ fn view_progress_runs_through_the_cover_range() {+ let mut inset = auto_inset();+ inset.start = ViewTimelineInsetEdge {+ is_auto: false,+ px: 10.0,+ percentage: 0.0,+ calculated: RetainedStyleValueData::none(),+ };+ let timeline = scroll_timeline(Some(inset));+ // A scrollport of 100px with 20px of scroll padding at its end, and a subject of 50px at 300px.+ let mut metrics = scroller(250.0, 1000.0);+ metrics.scroll_padding_end = 20.0;+ let subject = SubjectMetrics {+ start: 300.0,+ size: 50.0,+ };+ update(&timeline, Some(&metrics), Some(&subject));+ // The cover range runs from 300 - (100 - 20) = 220 to 300 + 50 - 10 = 340.+ let progress = (250.0 - 220.0) / 120.0 * 100.0;+ assert_eq!(timeline.current_time(), Some(TimeValue::percentage(progress)));+ let sample = timeline.sample();+ assert_eq!(+ sample.minimum_timeline_time.get(),+ Some(TimeValue::percentage((0.0 - 220.0) / 120.0 * 100.0))+ );+ assert_eq!(+ sample.maximum_timeline_time.get(),+ Some(TimeValue::percentage((1000.0 - 220.0) / 120.0 * 100.0))+ );++ // The contain range runs from 270 to 290, and the entry range from 220 to 270.+ let interval = timeline+ .state_for(&[edge(2, 0.0, 0.0), edge(3, 0.0, 50.0)])+ .attachment_interval()+ .unwrap();+ assert_eq!(interval.start, TimeValue::percentage((270.0 - 220.0) / 120.0 * 100.0));+ assert_eq!(interval.end, TimeValue::percentage((245.0 - 220.0) / 120.0 * 100.0));++ // Without a box for the subject the timeline is inactive.+ update(&timeline, Some(&metrics), None);+ assert_eq!(timeline.current_time(), None);+ }++ #[test]+ fn a_clock_tick_finds_the_progress_the_record_has() {+ let timeline = scroll_timeline(None);+ update(&timeline, Some(&scroller(50.0, 200.0)), None);+ let snapshot = timeline.clock_snapshot().unwrap();+ assert_eq!(+ Some(TimeValue::percentage(snapshot.progress_at(50.0))),+ timeline.current_time()+ );++ // A tick does not follow a view timeline whose subject it cannot find.+ let timeline = scroll_timeline(Some(auto_inset()));+ let subject = SubjectMetrics {+ start: 300.0,+ size: 50.0,+ };+ update(&timeline, Some(&scroller(250.0, 1000.0)), Some(&subject));+ assert!(timeline.current_time().is_some());+ assert!(timeline.clock_snapshot().is_none());+ assert!(timeline.update_current_time(+ TimelineUpdate::Layout {+ scroller: Some(&scroller(250.0, 1000.0)),+ subject: Some(&subject),+ subject_style_node: StyleNodeID::from_raw(3),+ },+ 1,+ false,+ || {}+ ));+ let snapshot = timeline.clock_snapshot().unwrap();+ assert_eq!(+ Some(TimeValue::percentage(snapshot.progress_at(250.0))),+ timeline.current_time()+ );+ }++ #[test]+ fn the_block_axis_of_a_vertical_writing_mode_is_horizontal() {+ assert_eq!(+ computed_scroll_axis(SCROLL_AXIS_BLOCK, writing_mode::HORIZONTAL_TB, direction::LTR),+ (true, false)+ );+ assert_eq!(+ computed_scroll_axis(SCROLL_AXIS_BLOCK, writing_mode::VERTICAL_RL, direction::LTR),+ (false, true)+ );+ assert_eq!(+ computed_scroll_axis(SCROLL_AXIS_INLINE, writing_mode::HORIZONTAL_TB, direction::RTL),+ (false, true)+ );+ assert_eq!(+ computed_scroll_axis(SCROLL_AXIS_Y, writing_mode::VERTICAL_LR, direction::RTL),+ (true, false)+ );+ }++ #[test]+ fn a_monotonically_increasing_timeline_only_moves_forward() {+ let timeline = TimelineHandle::new(+ facade(),+ TimelineKind::Internal {+ time_for_observation: None,+ },+ );+ let mut updates = 0;+ timeline.set_internal_time(Some(10.0), false, 1, || updates += 1);+ timeline.set_internal_time(Some(5.0), false, 1, || updates += 1);+ timeline.set_internal_time(None, false, 1, || updates += 1);+ assert_eq!(updates, 1);+ assert_eq!(timeline.current_time(), Some(TimeValue::milliseconds(10.0)));+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/timeline_state.rs b/Libraries/LibWeb/Rust/src/animations/timeline_state.rsnew file mode 100644index 00000000000..b1404c8db5c--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/timeline_state.rs@@ -0,0 +1,74 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the procedures of an animation read of its timeline.++use super::animation::AttachmentInterval;+use super::timing::time_value::max;+use super::timing::{TimeValue, TimeValueType, TimelineSample};++/// An animation's timeline as the animation sees it at one moment.+/// https://www.w3.org/TR/web-animations-1/#timelines+#[derive(Clone, Copy, Debug)]+pub(crate) struct TimelineState {+ /// What the timing calculations read of the timeline. Its current time is unresolved where the timeline is+ /// inactive.+ pub(crate) sample: TimelineSample,+ /// https://drafts.csswg.org/web-animations-2/#timeline-duration+ pub(crate) duration: Option<TimeValue>,+ /// The timeline times of the start and the end of the animation's attachment range, on a progress-based timeline.+ /// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-range+ pub(crate) attachment_interval: Option<AttachmentInterval>,+ /// https://drafts.csswg.org/web-animations-2/#progress-based-timeline+ pub(crate) is_progress_based: bool,+}++impl TimelineState {+ /// https://www.w3.org/TR/web-animations-1/#timeline-current-time+ #[must_use]+ pub(crate) fn current_time(&self) -> Option<TimeValue> {+ self.sample.current_time.get()+ }++ /// https://www.w3.org/TR/web-animations-1/#inactive-timeline+ #[must_use]+ pub(crate) fn is_inactive(&self) -> bool {+ // A timeline is considered to be inactive when its time value is unresolved, and active otherwise.+ self.current_time().is_none()+ }++ #[must_use]+ pub(crate) fn attachment_interval(&self) -> Option<AttachmentInterval> {+ self.attachment_interval+ }++ /// The duration of the timeline as an animation attached to its attachment range sees it.+ #[must_use]+ pub(crate) fn duration_for_attachment_range(&self) -> Option<TimeValue> {+ // AD-HOC: The duration of a progress-based timeline, as an animation attached to a range of it sees it, is the+ // length of its attachment range. This matches WebKit.+ // An attachment range whose end comes before its start is empty.+ if let Some(interval) = self.attachment_interval() {+ return Some(max(interval.end - interval.start, TimeValue::percentage(0.0)));+ }+ self.duration+ }+}++/// The unit of the times of `timeline`, which is milliseconds without one.+#[must_use]+pub(crate) fn time_unit(timeline: Option<&TimelineState>) -> TimeValueType {+ if timeline.is_some_and(|timeline| timeline.is_progress_based) {+ return TimeValueType::Percentage;+ }+ TimeValueType::Milliseconds+}++/// A zero time in the unit of the times of `timeline`.+#[must_use]+pub(crate) fn zero_time(timeline: Option<&TimelineState>) -> TimeValue {+ TimeValue::zero(time_unit(timeline))+}diff --git a/Libraries/LibWeb/Rust/src/animations/transitions.rs b/Libraries/LibWeb/Rust/src/animations/transitions.rsnew file mode 100644index 00000000000..9f403eb5012--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/transitions.rs@@ -0,0 +1,241 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! CSS transitions: what becomes of a transition from its provisional start until its element holds it, and how the+//! host takes in the transitions the hover of a clock lane left running.+//! https://drafts.csswg.org/css-transitions/#starting++use super::animation::{AnimationHandle, AnimationRecord};+use super::easing::CompactEasing;+use super::effect::{AnimationEffectId, EffectHandle};+use super::element_animations::{AnimationOwnerSlot, ElementAnimations};+use super::host_effects::{HostEffectKind, HostEffects};+use super::procedures::{Invalidate, Procedures};+use super::timing::{AnimationPlayState, FillMode, SpecifiedIterationDuration};+use crate::css::retained_fly_string::RetainedUtf16FlyString;+use crate::css::transition::{FfiExistingTransition, FfiLaneTransition};++/// Who started a transition the element comes to hold.+#[expect(dead_code, reason = "C++ constructs the variants")]+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum TransitionOrigin {+ /// A style change event of the host's.+ StyleChange,+ /// The hover of a clock lane, which the host took in.+ Lane,+}++/// What becomes of a running transition of the host's as it takes in what the hover of a clock lane left the element+/// running.+#[repr(u8)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LaneAdoption {+ /// The transition stands: the lane runs it as the host does, or the lane's steps saw it without ending it.+ Stands,+ /// The transition ends: the lane's steps ended it as they ran, or the lane started it, the host took it in, and the+ /// lane no longer runs it.+ Ends,+ /// The host started the transition since the lane forked, so the lane decided nothing over it, and the host decides+ /// what becomes of it and of its property in its turn.+ HostDecides,+}++impl AnimationRecord {+ /// The identity of the effect of the transition, if it has one.+ fn transition_effect_id(&self) -> Option<AnimationEffectId> {+ self.effect().map(|effect| effect.borrow().id())+ }++ /// Whether `lane_transition` is the lane's run of the transition: the host's transition the lane took in by its+ /// effect, or, for one the lane started itself, one the host took in from the lane, started at the same time.+ fn is_run_by_lane_as(&self, lane_transition: &FfiLaneTransition) -> bool {+ let state = self.css_transition();+ if lane_transition.property_id != state.property_id {+ return false;+ }+ if lane_transition.host_identity != AnimationEffectId::default() {+ return self.transition_effect_id() == Some(lane_transition.host_identity);+ }+ state.adopted_from_lane && state.start_time == lane_transition.start_time + lane_transition.delay+ }++ /// Whether the transition already runs from when the lane started it, as one of `lane_transitions` does.+ pub(crate) fn runs_as_lane_does(&self, lane_transitions: &[FfiLaneTransition]) -> bool {+ lane_transitions+ .iter()+ .any(|lane_transition| self.is_run_by_lane_as(lane_transition))+ }++ /// Whether `lane_transition` is the lane's run of this transition of the host's, which the lane took to start.+ pub(crate) fn is_host_transition_of(&self, lane_transition: &FfiLaneTransition) -> bool {+ lane_transition.host_identity != AnimationEffectId::default()+ && self.transition_effect_id() == Some(lane_transition.host_identity)+ }++ /// What becomes of the transition, which runs, as the host takes in `lane_transitions`, the transitions the lane+ /// leaves its element running, where the lane's steps ended those of the host's transitions whose effects+ /// `cancelled` names, and saw those `seen` names.+ pub(crate) fn lane_adoption(+ &self,+ lane_transitions: &[FfiLaneTransition],+ cancelled: &[AnimationEffectId],+ seen: &[AnimationEffectId],+ ) -> LaneAdoption {+ if self.runs_as_lane_does(lane_transitions) {+ return LaneAdoption::Stands;+ }+ let identity = self.transition_effect_id();+ let is_named_by = |identities: &[AnimationEffectId]| identity.is_some_and(|id| identities.contains(&id));+ if is_named_by(cancelled) {+ LaneAdoption::Ends+ } else if is_named_by(seen) {+ LaneAdoption::Stands+ } else if self.css_transition().adopted_from_lane {+ LaneAdoption::Ends+ } else {+ LaneAdoption::HostDecides+ }+ }++ /// What a style change event that decides the transitions of the transition's target reads of the transition, at+ /// time `t` of the document timeline, in milliseconds. The host gives the current value of a running transition of+ /// a custom property.+ pub(crate) fn existing_transition(&self, t: f64) -> FfiExistingTransition {+ let state = self.css_transition();+ let running = !self.playback().is_finished && self.timing_state(None).play_state != AnimationPlayState::Idle;+ FfiExistingTransition {+ property_id: state.property_id,+ custom_name: state.custom_property_name.raw(),+ custom_current_value: std::ptr::null(),+ running,+ end_value: state.end_value.pointer(),+ reversing_adjusted_start_value: state.reversing_adjusted_start_value.pointer(),+ timing_function_output: if running {+ self.timing_function_output_at_time(t)+ } else {+ 0.0+ },+ reversing_shortening_factor: state.reversing_shortening_factor,+ }+ }++ /// The output of the timing function of the effect the transition was started with at time `t` of the document+ /// timeline, in milliseconds, through the transition's interval.+ fn timing_function_output_at_time(&self, t: f64) -> f64 {+ let state = self.css_transition();+ let effect = state+ .effect_started_with+ .as_ref()+ .expect("a transition is started with an effect")+ .borrow();+ // AD-HOC: If the transition has an empty duration then we get NaN here,+ // setting progress to 1 because an instant transition may be considered "finished".+ let mut progress = 1.0;+ if state.start_time < state.end_time {+ progress = (t - state.start_time) / (state.end_time - state.start_time);+ }++ // FIXME: Is this before_flag value correct?+ let before_flag = t < state.start_time;+ effect.timing_function().as_easing().evaluate_at(progress, before_flag)+ }+}++/// The timing a transition starts with: its delay and duration, in milliseconds, and its timing function, with the+/// serialization of the value it was made from.+pub(crate) struct ProvisionalTransitionTiming {+ pub(crate) delay: f64,+ pub(crate) duration: f64,+ pub(crate) timing_function: CompactEasing,+ pub(crate) timing_function_serialization: RetainedUtf16FlyString,+}++impl Procedures<'_> {+ /// Starts the transition, whose timeline is set already, provisionally, with `effect`, which targets its owning+ /// element and runs its keyframes, as its associated effect: the transition plays, but its target does not observe+ /// it until the stabilization epoch that started it commits it.+ /// https://drafts.csswg.org/css-transitions/#starting+ pub(crate) fn start_a_provisional_transition(+ &mut self,+ effect: &EffectHandle,+ timing: ProvisionalTransitionTiming,+ ) {+ {+ let mut effect = effect.borrow_mut();+ let mut specified = *effect.specified_timing();+ specified.start_delay = timing.delay;+ specified.iteration_duration = SpecifiedIterationDuration {+ is_auto: false,+ milliseconds: timing.duration,+ };+ // AD-HOC: CSS Transitions require the start value to apply during transition-delay. A default+ // KeyframeEffect does not fill in the before phase, so use backwards fill to keep the transition+ // value in the cascade until the active interval starts.+ specified.fill_mode = FillMode::Backwards;+ effect.set_specified_timing(specified);+ effect.set_timing_function(timing.timing_function, timing.timing_function_serialization);+ }+ // NB: Setting the effect normalizes its specified timing against the timeline.+ self.animation().borrow_mut().css_transition_mut().effect_started_with = Some(effect.clone());+ self.set_provisional_effect(effect);+ // NB: The current style computation collects the effect before publishing its result, so invalidating it here+ // would evaluate the same transition twice.+ self.play(Invalidate::No)+ .expect("playing a transition on a monotonically increasing timeline does not throw");+ }++ /// Discards the transition, which was started provisionally and has no timeline any more: a later pass of the+ /// stabilization epoch that started it decided otherwise.+ pub(crate) fn discard_provisional_transition(&mut self) {+ self.discard_provisional_effect();+ let mut record = self.animation().borrow_mut();+ let state = record.css_transition_mut();+ assert!(state.provisional, "the transition is provisional");+ state.provisional = false;+ }+}++/// Commits `transition`, which was started provisionally, as the running transition of its property the owner at+/// `slot` of `animations` holds, where it is one that can hold one, which `origin` started, and hands back what that+/// asks the host to do: associate the transition with its target.+pub(crate) fn commit_provisional_transition(+ animations: Option<(&mut ElementAnimations, AnimationOwnerSlot)>,+ transition: AnimationHandle,+ origin: TransitionOrigin,+) -> HostEffects {+ let mut effects = HostEffects::default();+ let target = transition+ .borrow()+ .effect()+ .and_then(|effect| effect.borrow().target_element())+ .expect("a transition targets its owning element");+ effects.push(&transition, HostEffectKind::AssociateWithTarget { element: target });+ if let Some((animations, slot)) = animations {+ animations.commit_provisional_transition(slot, transition, origin);+ }+ effects+}++impl ElementAnimations {+ /// Commits `transition`, which was started provisionally and whose target is now associated with it, as the running+ /// transition of its property the owner at `slot` holds, which `origin` started.+ pub(crate) fn commit_provisional_transition(+ &mut self,+ slot: AnimationOwnerSlot,+ transition: AnimationHandle,+ origin: TransitionOrigin,+ ) {+ {+ let mut record = transition.borrow_mut();+ let state = record.css_transition_mut();+ assert!(state.provisional, "the transition is provisional");+ state.provisional = false;+ state.adopted_from_lane = origin == TransitionOrigin::Lane;+ }+ self.add_transition(slot, transition);+ }+}diff --git a/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rsnew file mode 100644index 00000000000..94329150402--- /dev/null+++ b/Libraries/LibWeb/Rust/src/animations/weak_record_set.rs@@ -0,0 +1,230 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Sets of animation records that do not keep them alive.++use std::hash::BuildHasher;+use std::rc::{Rc, Weak};++use hashbrown::HashTable;++/// A set of records, by identity, that keeps none of them alive.+///+/// A record is alive to the set while something keeps it alive and the set's liveness test accepts it. A record that+/// dies stays in the set as a dead entry, which no lookup or enumeration yields, until the set is next+/// pruned. Dropping a record therefore never reaches into a set that holds it. A dead entry still holds its record's+/// allocation, so the address of a record identifies it for as long as the set has an entry for it.+///+/// The entries are kept in insertion order, except that removing one moves the last entry into its place.+pub(crate) struct WeakRecordSet<T> {+ entries: Vec<Weak<T>>,+ /// The index of each entry in `entries`, by the hash of its record's address.+ indices: HashTable<u32>,+ is_alive: fn(&T) -> bool,+}++fn hash_of<T>(record: *const T) -> u64 {+ foldhash::fast::FixedState::default().hash_one(record as usize)+}++impl<T> WeakRecordSet<T> {+ /// A new empty set, to which a record that something keeps alive is alive while `is_alive` accepts it.+ pub(crate) fn new(is_alive: fn(&T) -> bool) -> Self {+ Self {+ entries: Vec::new(),+ indices: HashTable::new(),+ is_alive,+ }+ }++ fn live_record(&self, entry: &Weak<T>) -> Option<Rc<T>> {+ entry.upgrade().filter(|record| (self.is_alive)(record))+ }++ fn find(&self, record: *const T) -> Option<u32> {+ let entries = &self.entries;+ self.indices+ .find(hash_of(record), |&index| entries[index as usize].as_ptr() == record)+ .copied()+ }++ /// Whether the set holds `record`.+ pub(crate) fn contains(&self, record: *const T) -> bool {+ self.find(record).is_some()+ }++ /// Adds `record` to the set, answering whether the set did not hold it yet.+ pub(crate) fn insert(&mut self, record: &Rc<T>) -> bool {+ let pointer = Rc::as_ptr(record);+ if self.contains(pointer) {+ return false;+ }+ if self.entries.len() == self.entries.capacity() {+ self.prune();+ }+ let index = u32::try_from(self.entries.len()).expect("a set of records holds fewer than 2^32 entries");+ self.entries.push(Rc::downgrade(record));+ let entries = &self.entries;+ self.indices.insert_unique(hash_of(pointer), index, |&index| {+ hash_of(entries[index as usize].as_ptr())+ });+ true+ }++ /// Removes `record` from the set, answering whether the set held it.+ pub(crate) fn remove(&mut self, record: *const T) -> bool {+ let entries = &self.entries;+ let Ok(slot) = self+ .indices+ .find_entry(hash_of(record), |&index| entries[index as usize].as_ptr() == record)+ else {+ return false;+ };+ let (index, _) = slot.remove();+ let last = u32::try_from(self.entries.len() - 1).expect("a set of records holds fewer than 2^32 entries");+ if index != last {+ let moved = self.entries[last as usize].as_ptr();+ let entries = &self.entries;+ let slot = self+ .indices+ .find_mut(hash_of(moved), |&candidate| {+ candidate == last && entries[candidate as usize].as_ptr() == moved+ })+ .expect("every entry of a set of records has an index");+ *slot = index;+ }+ self.entries.swap_remove(index as usize);+ true+ }++ /// Drops the entries of records that are no longer alive to the set.+ pub(crate) fn prune(&mut self) {+ let is_alive = self.is_alive;+ let entry_is_alive = |entry: &Weak<T>| entry.upgrade().is_some_and(|record| is_alive(&record));+ if self.entries.iter().all(entry_is_alive) {+ return;+ }+ self.entries.retain(entry_is_alive);+ self.indices.clear();+ for (index, entry) in self.entries.iter().enumerate() {+ let index = u32::try_from(index).expect("a set of records holds fewer than 2^32 entries");+ let entries = &self.entries;+ self.indices.insert_unique(hash_of(entry.as_ptr()), index, |&index| {+ hash_of(entries[index as usize].as_ptr())+ });+ }+ }++ /// The number of entries, live or dead, which enumeration runs over.+ pub(crate) fn entry_count(&self) -> usize {+ self.entries.len()+ }++ /// The record of the entry at `index`, where it is alive to the set.+ pub(crate) fn get(&self, index: usize) -> Option<Rc<T>> {+ self.live_record(&self.entries[index])+ }++ /// Empties the set, calling `callback` with each record alive to it, in insertion order.+ pub(crate) fn take_each(&mut self, mut callback: impl FnMut(Rc<T>)) {+ for entry in &self.entries {+ if let Some(record) = self.live_record(entry) {+ callback(record);+ }+ }+ self.clear();+ }++ /// Removes every entry.+ pub(crate) fn clear(&mut self) {+ self.entries.clear();+ self.indices.clear();+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn live(set: &WeakRecordSet<u32>) -> Vec<u32> {+ (0..set.entry_count())+ .filter_map(|index| set.get(index))+ .map(|record| *record)+ .collect()+ }++ #[test]+ fn insert_and_remove_track_membership_by_identity() {+ let mut set = WeakRecordSet::new(|_| true);+ let first = Rc::new(1);+ let second = Rc::new(1);+ assert!(set.insert(&first));+ assert!(!set.insert(&first));+ assert!(set.insert(&second));+ assert!(set.contains(Rc::as_ptr(&first)));+ assert!(set.remove(Rc::as_ptr(&first)));+ assert!(!set.remove(Rc::as_ptr(&first)));+ assert!(!set.contains(Rc::as_ptr(&first)));+ assert!(set.contains(Rc::as_ptr(&second)));+ }++ #[test]+ fn removing_an_entry_keeps_the_others_findable() {+ let mut set = WeakRecordSet::new(|_| true);+ let records: Vec<_> = (0..5).map(Rc::new).collect();+ for record in &records {+ set.insert(record);+ }+ set.remove(Rc::as_ptr(&records[1]));+ assert_eq!(live(&set), [0, 4, 2, 3]);+ for record in [&records[0], &records[2], &records[3], &records[4]] {+ assert!(set.contains(Rc::as_ptr(record)));+ assert!(set.remove(Rc::as_ptr(record)));+ }+ assert_eq!(set.entry_count(), 0);+ }++ #[test]+ fn taking_each_record_yields_the_live_ones_and_empties_the_set() {+ let mut set = WeakRecordSet::new(|&record| record != 2);+ let records: Vec<_> = (0..4).map(Rc::new).collect();+ for record in &records {+ set.insert(record);+ }+ let mut taken = Vec::new();+ set.take_each(|record| taken.push(*record));+ assert_eq!(taken, [0, 1, 3]);+ assert_eq!(set.entry_count(), 0);+ }++ #[test]+ fn a_dead_record_is_not_yielded_and_is_pruned() {+ let mut set = WeakRecordSet::new(|_| true);+ let kept = Rc::new(1);+ let dropped = Rc::new(2);+ set.insert(&kept);+ set.insert(&dropped);+ drop(dropped);+ assert_eq!(live(&set), [1]);+ assert_eq!(set.entry_count(), 2);+ set.prune();+ assert_eq!(set.entry_count(), 1);+ assert!(set.contains(Rc::as_ptr(&kept)));+ }++ #[test]+ fn a_record_the_set_does_not_consider_alive_is_not_yielded_and_is_pruned() {+ let mut set = WeakRecordSet::new(|&record| record != 2);+ let kept = Rc::new(1);+ let retired = Rc::new(2);+ set.insert(&kept);+ set.insert(&retired);+ assert_eq!(set.get(1), None);+ set.prune();+ assert_eq!(live(&set), [1]);+ assert!(!set.contains(Rc::as_ptr(&retired)));+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/animation.rs b/Libraries/LibWeb/Rust/src/css/animation.rsindex 771b607f668..a90dec2b5c1 100644--- a/Libraries/LibWeb/Rust/src/css/animation.rs+++ b/Libraries/LibWeb/Rust/src/css/animation.rs@@ -20,10 +20,11 @@ use ak::math;use std::collections::{BTreeMap, HashSet};use std::sync::Arc;+use crate::animations::keyframes::KeyframeValue;use crate::css::custom_properties::CustomPropertyValueToFinalize;-use crate::css::easing::{Easing, FfiEasingDescriptor, FfiLinearEasingPoint, evaluate_easing_descriptor};+use crate::css::easing::{Easing, FfiEasingDescriptor, FfiLinearEasingPoint};use crate::css::property_metadata::{property_animation_type, property_numeric_ranges};-use crate::css::style::effect_descriptions::{PublishedEffect, PublishedValue};+use crate::css::style::effect_descriptions::PublishedEffect;use crate::css::style_value::{BasicShapeData, ColorBase, CssString, CssStringList, FILTER_KIND_BLUR, FILTER_KIND_COLOR, FILTER_KIND_DROP_SHADOW,FILTER_KIND_HUE_ROTATE, GridTrackEntryKind, OwnedBasicShapeData, RetainedGridTrackEntry,@@ -199,20 +200,6 @@ pub(crate) unsafe fn style_value_from_easing(descriptor: &FfiEasingDescriptor) -))))}-/// Evaluate a resolved easing descriptor without consulting C++.-///-/// # Safety-/// `descriptor` must point to a live descriptor. Its linear point range must be live when the-/// descriptor kind is linear.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_evaluate_easing(- descriptor: &FfiEasingDescriptor,- input_progress: f64,- before_flag: bool,-) -> f64 {- evaluate_easing_descriptor(descriptor, input_progress, before_flag)-}-/// Describes the easing a computed timing function value names, appending a linear easing's/// control points through `append_point`. Returns false for a value that names none.///@@ -332,21 +319,12 @@ struct AnimationValueInput<'a> {keyframe_plans: &'a [AnimationKeyframePlan],}-/// The version of an effect a preparation was made from.-#[derive(Clone, Copy, PartialEq, Eq)]-#[repr(C)]-pub struct FfiAnimationPreparationEffect {- pub identity: u64,- pub generation: u64,-}--/// One effect a sample composes, in composite order: the version a preparation is keyed by, and-/// where the effect is.-#[derive(Clone, Copy)]-#[repr(C)]-pub struct FfiSampledAnimationEffect {- pub effect: FfiAnimationPreparationEffect,- pub current_key: f64,+/// One effect a sample composes, in composite order: its description, which a preparation is keyed by, and where the+/// effect is.+#[derive(Clone)]+pub(crate) struct SampledAnimationEffect {+ pub(crate) description: std::sync::Arc<crate::css::style::effect_descriptions::EffectDescription>,+ pub(crate) current_key: f64,}/// The declarations an element's effects resolved to, and the computed value of each, which a@@ -361,7 +339,7 @@ pub(crate) struct ComputedAnimationBatch<'a> {pub(crate) context: FfiAnimationContext<'a>,/// The device pixel ratio that animated border widths are snapped to.pub(crate) device_pixels_per_css_pixel: f64,- pub(crate) sampled_effects: &'a [FfiSampledAnimationEffect],+ pub(crate) sampled_effects: &'a [SampledAnimationEffect],/// The identities of the custom-property environments of the element and of the one it/// inherits from, which a preparation that substituted keyframe values against the element was/// made under.@@ -8814,6 +8792,11 @@ pub unsafe extern "C" fn rust_substitute_compositor_keyframe_value(})}+/// The key of `keyframe` on the scale keyframes are interpolated on.+fn keyframe_key(keyframe: &crate::animations::keyframes::Keyframe) -> i64 {+ i64::try_from(keyframe.key).expect("a keyframe's offset is at most 100%")+}+#[derive(Clone, Copy)]struct CustomPropertyKeyframeLookup {keyframe_index: usize,@@ -8851,12 +8834,12 @@ fn select_custom_property_interval_span(current_key: f64,) -> [CustomPropertyKeyframeLookup; 2] {let first_lookup = keyframe_lookups[0];- let first_composite = effect.keyframes()[first_lookup.keyframe_index].composite;+ let first_composite = effect.composite_of(&effect.keyframes()[first_lookup.keyframe_index]);let first_value = &effect.custom_declaration_at(first_lookup.declaration_index).value;- let can_use_constant_interpolation = !matches!(first_value, PublishedValue::ElementValue)+ let can_use_constant_interpolation = !matches!(first_value, KeyframeValue::ElementValue)&& keyframe_lookups.iter().all(|lookup| {- let composite = effect.keyframes()[lookup.keyframe_index].composite;+ let composite = effect.composite_of(&effect.keyframes()[lookup.keyframe_index]);let value = &effect.custom_declaration_at(lookup.declaration_index).value;composite == first_composite && value == first_value});@@ -8867,7 +8850,7 @@ fn select_custom_property_interval_span((0, keyframe_lookups.len() - 1)} else {keyframe_interval(keyframe_lookups.len(), current_key, |index| {- effect.keyframes()[keyframe_lookups[index].keyframe_index].key+ keyframe_key(&effect.keyframes()[keyframe_lookups[index].keyframe_index])})};@@ -8888,7 +8871,7 @@ fn select_contributing_custom_property_intervals(let effect = selection.effect;let mut intervals = Vec::new();for (name_id, keyframe_lookups) in build_custom_property_keyframe_lookups(effect, custom_properties) {- if keyframe_lookups.len() < 2 || custom_properties.is_important(name_id) && !effect.is_transition {+ if keyframe_lookups.len() < 2 || custom_properties.is_important(name_id) && !effect.is_transition() {continue;}if replaced_names.contains(&name_id) {@@ -8898,10 +8881,11 @@ fn select_contributing_custom_property_intervals(let interpolable = registry.name_has_interpolable_syntax(custom_properties.units(name_id));let replaces_underlying = interval_span.iter().all(|lookup| {let composite_replaces = !interpolable- || effect.keyframes()[lookup.keyframe_index].composite == FfiCompositeOperation::Replace;+ || effect.composite_of(&effect.keyframes()[lookup.keyframe_index])+ == FfiCompositeOperation::Replace;let has_declared_value = matches!(effect.custom_declaration_at(lookup.declaration_index).value,- PublishedValue::Declared(_)+ KeyframeValue::Declared(_));composite_replaces && has_declared_value});@@ -8917,7 +8901,7 @@ fn select_contributing_custom_property_intervals(name: custom_properties.name(name_id).clone(),declared_values: interval_span.map(|lookup| {match &effect.custom_declaration_at(lookup.declaration_index).value {- PublishedValue::Declared(value) => value.clone(),+ KeyframeValue::Declared(value) => value.clone(),_ => RetainedStyleValueData::none(),}}),@@ -8947,7 +8931,8 @@ pub(crate) fn resolve_published_animation_declarations(important_property_bitmap: &[u8],conversions: &std::cell::RefCell<KeyframeConversionCache>,) -> PublishedAnimationDeclarations {- use crate::css::style::effect_descriptions::{PublishedValue, easing_from_computed_timing_function};+ use crate::animations::keyframes::KeyframeEasing;+ use crate::css::style::effect_descriptions::easing_from_computed_timing_function;let registry = engine.custom_property_registry();let mut custom_properties = AnimatedCustomProperties {stores,@@ -8982,7 +8967,7 @@ pub(crate) fn resolve_published_animation_declarations(let intervals_by_effect = select_contributing_custom_property_intervals(selected, &mut custom_properties, registry);for (selection, intervals) in selected.iter().zip(intervals_by_effect) {let effect = selection.effect;- let is_transition = effect.is_transition;+ let is_transition = effect.is_transition();let style_sheet_resource_context = match effect.resource_context() {None => FfiAnimationStyleSheetResourceContext {base_url: std::ptr::null(),@@ -9003,10 +8988,14 @@ pub(crate) fn resolve_published_animation_declarations(let first_keyframe_index = keyframes.len();for keyframe in effect.keyframes() {let keyframe_index = keyframes.len();- keyframes.push((keyframe.key, keyframe.composite));+ keyframes.push((keyframe_key(keyframe), effect.composite_of(keyframe)));// A keyframe's own easing written as a value substitutes against the element; one that- // resolves to no easing runs its animation's.- let substituted_easing = keyframe.easing_value.as_ref().and_then(|written| {+ // resolves to no easing runs its animation's, as does one that declares none.+ let written_easing = match &keyframe.easing {+ KeyframeEasing::Value(written) => Some(written),+ KeyframeEasing::None | KeyframeEasing::Easing(_) => None,+ };+ let substituted_easing = written_easing.and_then(|written| {let substituted;let mut value = written.data();if matches!(value, StyleValueData::Unresolved { .. }) {@@ -9022,20 +9011,24 @@ pub(crate) fn resolve_published_animation_declarations(}easing_from_computed_timing_function(value)});- easings.push(substituted_easing.unwrap_or_else(|| keyframe.easing.clone()));+ easings.push(match (&keyframe.easing, substituted_easing) {+ (KeyframeEasing::Easing(easing), _) => easing.clone(),+ (_, Some(substituted_easing)) => substituted_easing,+ (_, None) => effect.default_easing(),+ });let keyframe_declarations = effect.declarations_of(keyframe);// The values of the shorthands written with arbitrary substitution functions that this keyframe's// longhands pend the substitution of, each already standing for its longhands.let mut substituted_shorthand_values: Vec<*const StyleValueData> = Vec::new();- for declaration in keyframe_declarations {+ for declaration in keyframe_declarations.clone() {let (value, use_initial) = match &declaration.value {- PublishedValue::ElementValue => {+ KeyframeValue::ElementValue => {let Some(value) = longhands.handle(declaration.property_id) else {continue;};(value.clone_retained(), true)}- PublishedValue::Declared(value) => match value.data() {+ KeyframeValue::Declared(value) => match value.data() {// https://drafts.csswg.org/css-values-5/#pending-substitution-value// The longhands of a shorthand written with an arbitrary substitution function take their// parts of its value once it substitutes, so the shorthand stands for them.@@ -9058,9 +9051,9 @@ pub(crate) fn resolve_published_animation_declarations(}substituted_shorthand_values.push(original);let pending_longhands = keyframe_declarations- .iter()+ .clone().filter(|candidate| {- matches!(&candidate.value, PublishedValue::Declared(written)+ matches!(&candidate.value, KeyframeValue::Declared(written)if matches!(written.data(), StyleValueData::PendingSubstitution { .. })&& written_shorthand_value(written).pointer() == original)})@@ -9143,13 +9136,13 @@ pub(crate) fn resolve_published_animation_declarations(interval.interval_span.map(|lookup| {let declaration = effect.custom_declaration_at(lookup.declaration_index);match &declaration.value {- PublishedValue::ElementValue => custom_properties.underlying_value(registry, name_id),+ KeyframeValue::ElementValue => custom_properties.underlying_value(registry, name_id),// A custom property's value is a token stream; only the substitution functions// in it resolve against the element.- PublishedValue::Declared(value) if holds_arbitrary_substitution(value.data()) => {+ KeyframeValue::Declared(value) if holds_arbitrary_substitution(value.data()) => {substitute(crate::css::property_metadata::property_id::CUSTOM, name, value)}- PublishedValue::Declared(value) => value.clone_retained(),+ KeyframeValue::Declared(value) => value.clone_retained(),}})}@@ -9172,7 +9165,7 @@ pub(crate) fn resolve_published_animation_declarations(custom_is_important: important,value,style_sheet_resource_context,- use_initial: matches!(declaration.value, PublishedValue::ElementValue),+ use_initial: matches!(declaration.value, KeyframeValue::ElementValue),is_transition,});}@@ -9221,20 +9214,22 @@ fn holds_arbitrary_substitution(value: &StyleValueData) -> bool {}struct AnimationPreparationKey {- effects: Box<[FfiAnimationPreparationEffect]>,+ /// The descriptions of the effects the preparation was made from, which it holds, so that no other description+ /// can take the place of one.+ effects: Box<[std::sync::Arc<crate::css::style::effect_descriptions::EffectDescription>]>,/// The custom-property environments a preparation that substituted keyframe values against the/// element was made under, which it holds for only as long as they stand.custom_property_environments: Option<[u64; 2]>,}impl AnimationPreparationKey {- fn matches(&self, sampled: &[FfiSampledAnimationEffect], custom_property_environments: [u64; 2]) -> bool {+ fn matches(&self, sampled: &[SampledAnimationEffect], custom_property_environments: [u64; 2]) -> bool {self.effects.len() == sampled.len()&& self.effects.iter().zip(sampled)- .all(|(effect, sampled)| *effect == sampled.effect)+ .all(|(effect, sampled)| std::sync::Arc::ptr_eq(effect, &sampled.description))&& self.custom_property_environments.is_none_or(|environments| environments == custom_property_environments)@@ -9306,7 +9301,7 @@ unsafe impl Sync for PreparedAnimationBatch {}/// under the custom-property environments a sample reads.pub(crate) fn animation_preparation_matches(overlay: Option<&crate::css::animated_overlay::AnimatedOverlay>,- sampled: &[FfiSampledAnimationEffect],+ sampled: &[SampledAnimationEffect],custom_property_environments: [u64; 2],) -> bool {overlay@@ -9400,7 +9395,7 @@ pub(crate) fn prepare_animations(batch: &mut ComputedAnimationBatch<'_>) -> Arc<.collect();std::sync::Arc::new(PreparedAnimationBatch {key: AnimationPreparationKey {- effects: sampled.iter().map(|sampled| sampled.effect).collect(),+ effects: sampled.iter().map(|sampled| sampled.description.clone()).collect(),custom_property_environments: preparation_reads_custom_property_environments.then_some(*custom_property_environments),},@@ -9526,64 +9521,38 @@ mod tests {#[test]fn preserves_lower_custom_property_effects_for_single_endpoint_intervals() {- use crate::css::retained_fly_string::RetainedUtf16FlyString;- use crate::css::style::bridge::{- FfiPublishedAnimationCustomDeclaration, FfiPublishedAnimationEffect, FfiPublishedAnimationKeyframe,- FfiPublishedEasingKind,+ use crate::animations::easing::CompactEasing;+ use crate::animations::effect::AnimationEffectId;+ use crate::animations::keyframes::{+ CompositeOperationOrAuto, FINAL_KEY, KeyframeEasing, KeyframeProperty, KeyframeSet,};- use crate::css::style::effect_descriptions::PublishedEffectBuffers;+ use crate::css::retained_fly_string::RetainedUtf16FlyString;+ use crate::css::style::effect_descriptions::{EffectAnimation, EffectDescription};let name = RetainedUtf16FlyString::from_utf16(&"--value".encode_utf16().collect::<Vec<_>>());let values = [1.0, 1.0, 2.0, 3.0, 4.0, 5.0].map(|value| RetainedStyleValueData::from_arc(StyleValueArc::new(StyleValueData::Number { value })));- let declarations = values.each_ref().map(|value| FfiPublishedAnimationCustomDeclaration {- name: name.raw(),- value: value.pointer().cast(),- });- let keyframes =- [(0, 0), (100, 1), (0, 2), (0, 3), (100, 4), (100, 5)].map(|(key, first_custom_declaration)| {- FfiPublishedAnimationKeyframe {- key,- easing_kind: FfiPublishedEasingKind::Linear,- step_position: 0,- interval_count: 0,- x1: 0.0,- y1: 0.0,- x2: 0.0,- y2: 0.0,- first_linear_point: 0,- linear_point_count: 0,- easing_value: std::ptr::null(),- composite: FfiCompositeOperation::Replace,- first_declaration: 0,- declaration_count: 0,- first_custom_declaration,- custom_declaration_count: 1,- }- });- let effects = [(0, 2), (2, 4)].map(|(first_keyframe, keyframe_count)| FfiPublishedAnimationEffect {- identity: u64::from(first_keyframe),- generation: 0,- is_transition: false,- has_resource_context: false,- resource_context_is_origin_clean: false,- first_keyframe,- keyframe_count,- base_url_offset: 0,- base_url_length: 0,- reversing_adjusted_start_value: std::ptr::null(),- reversing_shortening_factor: 1.0,+ let keys = [0, FINAL_KEY, 0, 0, FINAL_KEY, FINAL_KEY];+ let effects = [(0, 2), (2, 4)].map(|(first_keyframe, keyframe_count)| {+ let keyframes = (first_keyframe..first_keyframe + keyframe_count)+ .map(|index| {+ (+ keys[index],+ CompositeOperationOrAuto::Replace,+ KeyframeEasing::None,+ vec![(+ KeyframeProperty::Custom(name.clone()),+ KeyframeValue::Declared(values[index].clone()),+ )],+ )+ })+ .collect();+ PublishedEffect::new(Arc::new(EffectDescription {+ keyframe_set: Some(Arc::new(KeyframeSet::from_keyframes_as_given(keyframes))),+ animation: EffectAnimation::Animation(CompactEasing::Linear),+ ..EffectDescription::new(AnimationEffectId(u64::try_from(first_keyframe).unwrap()))+ }))});- let buffers = PublishedEffectBuffers {- effects: &effects,- keyframes: &keyframes,- declarations: &[],- custom_declarations: &declarations,- linear_points: &[],- base_url_bytes: &[],- };- // SAFETY: The name and values remain live while the descriptions retain them.- let effects = unsafe { buffers.effects() };let registry = Registry::shared_empty();let mut custom_properties = AnimatedCustomProperties {stores: KeyframeStores {@@ -9599,7 +9568,11 @@ mod tests {has_uncached_interval_values: false,};- for (current_key, expected_span, lower_count) in [(50.0, [1, 2], 0), (100.0, [3, 3], 1), (-1.0, [0, 0], 1)] {+ #[expect(clippy::cast_precision_loss)]+ let final_key = FINAL_KEY as f64;+ for (current_key, expected_span, lower_count) in+ [(final_key / 2.0, [1, 2], 0), (final_key, [3, 3], 1), (-1.0, [0, 0], 1)]+ {let selected = effects.iter().map(|effect| SelectedEffect { effect, current_key })diff --git a/Libraries/LibWeb/Rust/src/css/mod.rs b/Libraries/LibWeb/Rust/src/css/mod.rsindex c7af99ba2a5..9ed984fc962 100644--- a/Libraries/LibWeb/Rust/src/css/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/mod.rs@@ -57,7 +57,7 @@ pub(crate) mod selector;mod selector_arena;mod selector_operations;pub(crate) mod selector_parser;-mod selector_serialization;+pub(crate) mod selector_serialization;pub(crate) mod selector_tree;pub(crate) mod serialize;pub mod style;diff --git a/Libraries/LibWeb/Rust/src/css/property_metadata.rs b/Libraries/LibWeb/Rust/src/css/property_metadata.rsindex 90f0f7c4511..8b9f3b41bff 100644--- a/Libraries/LibWeb/Rust/src/css/property_metadata.rs+++ b/Libraries/LibWeb/Rust/src/css/property_metadata.rs@@ -352,6 +352,11 @@ fn property_index(property_id: u16) -> usize {(property_id - FIRST_SHORTHAND_PROPERTY_ID) as usize}+/// The IDL attribute name of the property, https://drafts.csswg.org/cssom/#css-property-to-idl-attribute+pub(crate) fn property_idl_name(property_id: u16) -> &'static str {+ PROPERTY_IDL_NAMES[property_index(property_id)]+}+pub(crate) fn property_is_logical_alias_including_shorthands(property_id: u16) -> bool {PROPERTY_IS_LOGICAL_ALIAS[property_index(property_id)]}diff --git a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs b/Libraries/LibWeb/Rust/src/css/rule/compilation.rsindex d7079c5da9e..a9d2c89e3d5 100644--- a/Libraries/LibWeb/Rust/src/css/rule/compilation.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/compilation.rs@@ -1414,9 +1414,7 @@ mod tests {assert_eq!(compiled.get(), 1);use crate::css::rule::FfiRuleTraversalOrder;use crate::css::rule::function::{CompiledFunction, rust_rule_view_compile_function};- use crate::css::rule::read::{- NativeRuleView, rust_rule_view_keyframes, rust_rule_view_property, rust_rule_view_type,- };+ use crate::css::rule::read::{NativeRuleView, rust_rule_view_property, rust_rule_view_type};use std::sync::Arc;#[derive(Default)]struct Definitions {@@ -1426,16 +1424,6 @@ mod tests {descriptors: std::cell::Cell<usize>,font_features: std::cell::Cell<usize>,}- unsafe extern "C" fn frame(- context: *const c_void,- _: *const f64,- count: usize,- _: *const crate::css::declaration_block::DeclarationBlockHeader,- ) {- assert_eq!(count, 1);- let definitions = unsafe { &*context.cast::<Definitions>() };- definitions.keyframes.set(definitions.keyframes.get() + 1);- }unsafe extern "C" fn definition(context: *const c_void, rule: &NativeRuleView<'_>, _: FfiUtf16View) {let definitions = unsafe { &*context.cast::<Definitions>() };match rust_rule_view_type(rule) {@@ -1443,9 +1431,10 @@ mod tests {.functions.borrow_mut().push(unsafe { Arc::from_raw(rust_rule_view_compile_function(rule)) }),- NativeRuleType::Keyframes => unsafe {- rust_rule_view_keyframes(rule, context, frame);- },+ NativeRuleType::Keyframes => rule.for_each_keyframe(|keys, _| {+ assert_eq!(keys.len(), 1);+ definitions.keyframes.set(definitions.keyframes.get() + 1);+ }),NativeRuleType::Property => {assert!(!rust_rule_view_property(rule).is_null());definitions.properties.set(definitions.properties.get() + 1);diff --git a/Libraries/LibWeb/Rust/src/css/rule/read.rs b/Libraries/LibWeb/Rust/src/css/rule/read.rsindex fecb95f3b19..77ed5b7f0b1 100644--- a/Libraries/LibWeb/Rust/src/css/rule/read.rs+++ b/Libraries/LibWeb/Rust/src/css/rule/read.rs@@ -229,27 +229,16 @@ pub extern "C" fn rust_rule_view_position_try_declarations()}-/// # Safety-/// The callback must not mutate the graph. Keys and declarations are borrowed for the callback.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn rust_rule_view_keyframes(- view: &NativeRuleView<'_>,- context: *const std::ffi::c_void,- visit: unsafe extern "C" fn(- *const std::ffi::c_void,- *const f64,- usize,- *const crate::css::declaration_block::DeclarationBlockHeader,- ),-) {- assert!(view.rule.rule_type() == NativeRuleType::Keyframes);- let _ = view.rule.visit_children(&mut |frame| {- let (keys, declarations) = frame.keyframe();- unsafe {- visit(context, keys.as_ptr(), keys.len(), declarations.as_ptr());- }- ControlFlow::Continue(())- });+impl NativeRuleView<'_> {+ /// Each keyframe block of the `@keyframes` rule this views: its keys and its declarations.+ pub(crate) fn for_each_keyframe(&self, mut visit: impl FnMut(&[f64], SharedDeclarationBlock)) {+ assert!(self.rule.rule_type() == NativeRuleType::Keyframes);+ let _ = self.rule.visit_children(&mut |frame| {+ let (keys, declarations) = frame.keyframe();+ visit(keys, declarations);+ ControlFlow::Continue(())+ });+ }}impl<'a> RuleRef<'a> {diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rsindex d09b58e5e47..b6447553442 100644--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs@@ -1486,6 +1486,11 @@ fn parse_pseudo_element_selector(Ok((selector, pseudo_element_type))}+/// The pseudo-element selector the text parses as, for the target pseudo-selector of an animation effect.+pub(crate) fn parse_pseudo_element_selector_from_utf16(input: &[u16]) -> Result<(SelectorRef, PseudoElementType), ()> {+ parse_pseudo_element_selector(input.into(), false)+}+/// A parsed selector list, in the arena it is packed into.#[derive(Clone, Debug, PartialEq)]pub struct RustParsedSelectorList {diff --git a/Libraries/LibWeb/Rust/src/css/selector_serialization.rs b/Libraries/LibWeb/Rust/src/css/selector_serialization.rsindex a1f6ceed127..fea73a02754 100644--- a/Libraries/LibWeb/Rust/src/css/selector_serialization.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_serialization.rs@@ -339,6 +339,20 @@ pub unsafe extern "C" fn rust_selector_serialize(}}+/// The serialization of a selector that names no namespaces, as a style sheet that declares none serializes it.+pub(crate) fn serialize_selector_ref(selector: &super::selector::SelectorRef) -> ak::Utf16String {+ let mut sink = TextSink::new();+ serialize_selector(+ &mut sink,+ selector.view(),+ &NamespaceContext {+ has_default_namespace: false,+ prefixes_mapping_to_default: &[],+ },+ );+ ak::Utf16String::from_utf16(&sink.into_utf16())+}+#[cfg(test)]pub(super) fn serialize_selector_without_namespaces(selector: &RustSelector) -> Vec<u16> {let mut sink = TextSink::new();diff --git a/Libraries/LibWeb/Rust/src/css/style/animations.rs b/Libraries/LibWeb/Rust/src/css/style/animations.rsindex f78fcf85a59..4ecc4fe6131 100644--- a/Libraries/LibWeb/Rust/src/css/style/animations.rs+++ b/Libraries/LibWeb/Rust/src/css/style/animations.rs@@ -19,15 +19,17 @@//! Which `@keyframes` a definition runs is decided here too, from the keyframes each style scope//! publishes, so the computation never reaches into a scope's rule cache.-use super::bridge::{FfiAppliedAnimationDefinition, FfiAppliedAnimationValues};use super::tree::{StyleNodeID, TreeScopeID};+use crate::animations::keyframes::KeyframeSet;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_value::{RetainedStyleValueData, StyleValueData, retain_style_value};use std::collections::HashMap;+use std::sync::Arc;/// Which of an element's animation lists a row belongs to, in the host's own numbering: zero for/// the element itself, and the pseudo-element's value plus one for each pseudo-element.@@ -36,89 +38,111 @@ pub(crate) type AnimationSlot = u8;/// The definition that claimed no existing animation and asks for a new one.pub(crate) const NO_MATCHED_ANIMATION: i32 = -1;-impl FfiAppliedAnimationDefinition {- /// What the host publishes back for a definition once it has applied it: the definition's own- /// values, field for field.+/// What an applied animation definition holds by value, its numbers before its bytes, which pack behind them.+#[derive(Clone, Copy, PartialEq)]+struct AppliedAnimationValues {+ duration: f64,+ iteration_count: f64,+ delay: f64,+ range_start_px: f64,+ range_start_percentage: f64,+ range_end_px: f64,+ range_end_percentage: f64,+ duration_is_auto: bool,+ direction: u8,+ play_state: u8,+ fill_mode: u8,+ composition: u8,+ /// An `FfiAnimationTimelineKind`.+ timeline_kind: u8,+ scroll_scroller: u8,+ scroll_axis: u8,+ range_start_name: u8,+ range_end_name: u8,+}++const _: () = assert!(size_of::<AppliedAnimationValues>() == 72);++impl AppliedAnimationValues {+ /// The values of the definition `animation`, field for field.#[must_use]fn of(animation: &crate::css::style_compute::FfiComputedAnimation) -> Self {Self {- values: FfiAppliedAnimationValues {- duration_is_auto: animation.duration_is_auto,- duration: animation.duration,- iteration_count: animation.iteration_count,- direction: animation.direction,- play_state: animation.play_state,- delay: animation.delay,- fill_mode: animation.fill_mode,- composition: animation.composition,- timeline_kind: animation.timeline_kind as u8,- scroll_scroller: animation.scroll_scroller,- scroll_axis: animation.scroll_axis,- range_start_name: animation.range_start_name,- range_start_px: animation.range_start_px,- range_start_percentage: animation.range_start_percentage,- range_end_name: animation.range_end_name,- range_end_px: animation.range_end_px,- range_end_percentage: animation.range_end_percentage,- },- keyframe_set: animation.keyframe_set,- timing_function: animation.timing_function,- range_start_calculated: animation.range_start_calculated,- range_end_calculated: animation.range_end_calculated,+ duration_is_auto: animation.duration_is_auto,+ duration: animation.duration,+ iteration_count: animation.iteration_count,+ direction: animation.direction,+ play_state: animation.play_state,+ delay: animation.delay,+ fill_mode: animation.fill_mode,+ composition: animation.composition,+ timeline_kind: animation.timeline_kind as u8,+ scroll_scroller: animation.scroll_scroller,+ scroll_axis: animation.scroll_axis,+ range_start_name: animation.range_start_name,+ range_start_px: animation.range_start_px,+ range_start_percentage: animation.range_start_percentage,+ range_end_name: animation.range_end_name,+ range_end_px: animation.range_end_px,+ range_end_percentage: animation.range_end_percentage,}}+}- /// Whether applying `self` to an animation that last had `published` applied would leave it- /// exactly as it is. A scroll, view or named timeline is found from the element's surroundings- /// every time it is applied, so a definition that names one is never called unchanged, and an animation no- /// plan has described yet publishes a null timing function, which no computed definition has.- /// The timing function and range calculations are compared by value: a recomputed style builds a fresh allocation for- /// a declaration that has not changed.- #[must_use]- fn would_change_nothing(&self, published: &Self) -> bool {- use crate::css::style_compute::FfiAnimationTimelineKind;- ![- FfiAnimationTimelineKind::Scroll as u8,- FfiAnimationTimelineKind::View as u8,- FfiAnimationTimelineKind::Named as u8,+/// Whether applying `definition` to an animation that last had `applied` applied would leave it exactly as it is. A+/// scroll, view or named timeline is found from the element's surroundings every time it is applied, so a definition+/// that names one is never called unchanged. The timing function and range calculations are compared by value: a+/// recomputed style builds a fresh allocation for a declaration that has not changed.+#[must_use]+fn would_change_nothing(+ definition: &crate::css::style_compute::FfiComputedAnimation,+ applied: &AppliedAnimationDefinition,+) -> bool {+ use crate::css::style_compute::FfiAnimationTimelineKind;+ let keyframe_set = applied+ .keyframes+ .as_ref()+ .map_or(std::ptr::null(), |set| Arc::as_ptr(set).cast());+ !matches!(+ definition.timeline_kind,+ FfiAnimationTimelineKind::Scroll | FfiAnimationTimelineKind::View | FfiAnimationTimelineKind::Named+ ) && !applied.timing_function.pointer().is_null()+ && AppliedAnimationValues::of(definition) == applied.values+ && definition.keyframe_set == keyframe_set+ && [+ (definition.timing_function, &applied.timing_function),+ (definition.range_start_calculated, &applied.range_start_calculated),+ (definition.range_end_calculated, &applied.range_end_calculated),]- .contains(&self.values.timeline_kind)- && !published.timing_function.is_null()- && self.values == published.values- && self.keyframe_set == published.keyframe_set- && [- (self.timing_function, published.timing_function),- (self.range_start_calculated, published.range_start_calculated),- (self.range_end_calculated, published.range_end_calculated),- ]- .into_iter()- .all(|(value, published_value)| {- use crate::css::style_value::StyleValueData;- // SAFETY: Each is null or a value the host holds live.- let (value, published_value) = unsafe {- (- value.cast::<StyleValueData>().as_ref(),- published_value.cast::<StyleValueData>().as_ref(),- )- };- crate::css::style_value::optional_style_values_equal(value, published_value)- })- }+ .into_iter()+ .all(|(value, applied_value)| {+ // SAFETY: Each is null or a value the plan holds live.+ let value = unsafe { value.cast::<crate::css::style_value::StyleValueData>().as_ref() };+ crate::css::style_value::optional_style_values_equal(value, applied_value.optional_data())+ })}-/// A definition the host published as applied, holding the values it names, so that it can read them whenever the-/// animation it describes has moved on.-#[derive(Clone)]-pub(crate) struct HeldAppliedAnimationDefinition {- definition: FfiAppliedAnimationDefinition,- _values: [crate::css::style_value::RetainedStyleValueData; 3],+/// The definition the style computation last applied to a CSS animation, which the animation holds, and the style+/// engine beside the animation's name, so that a plan whose every definition equals what its animation last had+/// applied changes nothing, and the engine does not hand it over.+pub(crate) struct AppliedAnimationDefinition {+ values: AppliedAnimationValues,+ /// The keyframe set the plan gave the animation's effect.+ keyframes: Option<Arc<KeyframeSet>>,+ /// The computed `animation-timing-function`.+ timing_function: RetainedStyleValueData,+ /// The calculations the edges of the attachment range resolve, or none.+ range_start_calculated: RetainedStyleValueData,+ range_end_calculated: RetainedStyleValueData,}-impl HeldAppliedAnimationDefinition {+impl AppliedAnimationDefinition {+ /// The definition a style computation applies as it hands `definition` over, holding what it names.+ ////// # Safety- /// The values `definition` names must be null or live style values.- pub(crate) unsafe fn retained(definition: FfiAppliedAnimationDefinition) -> Self {- use crate::css::style_value::{RetainedStyleValueData, StyleValueData, retain_style_value};+ /// The values `definition` names must be null or live style values, and its keyframe set null or one the plan+ /// holds a reference to.+ pub(crate) unsafe fn retained(definition: &crate::css::style_compute::FfiComputedAnimation) -> Self {let hold = |value: *const std::ffi::c_void| {if value.is_null() {return RetainedStyleValueData::none();@@ -126,23 +150,59 @@ impl HeldAppliedAnimationDefinition {// SAFETY: Guaranteed by the caller; the handle takes the reference this retains.unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(value.cast::<StyleValueData>())) }};+ let keyframe_set = definition.keyframe_set.cast::<KeyframeSet>();Self {- definition,- _values: [- hold(definition.timing_function),- hold(definition.range_start_calculated),- hold(definition.range_end_calculated),- ],+ values: AppliedAnimationValues::of(definition),+ // SAFETY: Guaranteed by the caller.+ keyframes: (!keyframe_set.is_null()).then(|| unsafe { KeyframeSet::retained_from_host(keyframe_set) }),+ timing_function: hold(definition.timing_function),+ range_start_calculated: hold(definition.range_start_calculated),+ range_end_calculated: hold(definition.range_end_calculated),}}++ /// The computed `animation-timing-function`.+ #[must_use]+ pub(crate) fn timing_function(&self) -> &RetainedStyleValueData {+ &self.timing_function+ }++ /// Whether applying `self` to an animation sets the same properties as applying `other` does, whatever keyframes+ /// each gives its effect.+ #[must_use]+ pub(crate) fn applies_the_same_properties(&self, other: &Self) -> bool {+ self.values == other.values+ && [+ (&self.timing_function, &other.timing_function),+ (&self.range_start_calculated, &other.range_start_calculated),+ (&self.range_end_calculated, &other.range_end_calculated),+ ]+ .into_iter()+ .all(|(value, other_value)| {+ crate::css::style_value::optional_style_values_equal(value.optional_data(), other_value.optional_data())+ })+ }}/// One of the CSS animations the host holds: its name, and the definition the last plan applied-/// to it.+/// to it, which it shares with the animation, or none where no plan has described it yet.#[derive(Clone)]pub(crate) struct CssDefinedAnimation {pub(crate) name: CssString,- applied_definition: HeldAppliedAnimationDefinition,+ pub(crate) applied_definition: Option<Arc<AppliedAnimationDefinition>>,+}++impl CssDefinedAnimation {+ /// The name of the CSS animation `animation` and the definition last applied to it.+ pub(crate) fn of(animation: &crate::animations::animation::AnimationCell) -> Self {+ let animation = animation.borrow();+ let state = animation.css_animation();+ Self {+ // SAFETY: The animation holds its name.+ name: unsafe { CssString::from_borrowed_raw(state.name.raw()) },+ applied_definition: state.applied_definition.clone(),+ }+ }}/// The CSS animations the host holds in one of an element's lists, in its order.@@ -175,28 +235,9 @@ impl CssDefinedAnimations {bytes}- /// Replace one list from the names and applied definitions the host publishes, a definition per- /// animation. An empty list drops it, so an element that stops animating stops costing anything.- pub(crate) fn set(- &mut self,- node: StyleNodeID,- slot: AnimationSlot,- names: Box<[CssString]>,- definitions: Box<[HeldAppliedAnimationDefinition]>,- ) {- debug_assert_eq!(- definitions.len(),- names.len(),- "every published animation name comes with its applied definition"- );- let animations: Box<[CssDefinedAnimation]> = names- .into_iter()- .zip(definitions)- .map(|(name, applied_definition)| CssDefinedAnimation {- name,- applied_definition,- })- .collect();+ /// Replace one list with the animations the host publishes. An empty list drops it, so an element that stops+ /// animating stops costing anything.+ pub(crate) fn set(&mut self, node: StyleNodeID, slot: AnimationSlot, animations: Box<[CssDefinedAnimation]>) {let lists = self.rows.entry(node).or_default();let existing = lists.iter().position(|(list_slot, _)| *list_slot == slot);match (existing, animations.is_empty()) {@@ -286,8 +327,10 @@ pub(crate) fn plan_changes_nothing(.enumerate().all(|(index, (definition, animation))| {usize::try_from(definition.matched_existing_index) == Ok(index)- && FfiAppliedAnimationDefinition::of(definition)- .would_change_nothing(&animation.applied_definition.definition)+ && animation+ .applied_definition+ .as_ref()+ .is_some_and(|applied| would_change_nothing(definition, applied))})}@@ -302,18 +345,15 @@ pub(crate) enum DeclarationScope {Shadow(TreeScopeID),}-/// One style scope's `@keyframes`: the host's keyframe set for each name the scope defines.-pub(crate) type KeyframesRow = HashMap<Box<[u16]>, usize>;+/// One style scope's `@keyframes`: the keyframe set for each name the scope defines.+pub(crate) type KeyframesRow = HashMap<Box<[u16]>, Arc<KeyframeSet>>;/// The `@keyframes` every style scope of the document defines, as each scope's rule cache resolved-/// them, with the host's keyframe set for each name.+/// them, with the keyframe set for each name.////// A scope publishes its row whenever its rule cache is built, and the host builds every scope's/// cache before a style update, so resolving an animation's keyframes is a lookup here rather-/// than building a rule cache in the middle of a style computation. A keyframe set is the host's-/// refcounted object, borrowed: the scope keeps a reference to every set its row names until it-/// publishes the row again or gives it up, which the engine takes in ahead of anything that-/// resolves keyframes.+/// than building a rule cache in the middle of a style computation.#[derive(Clone, Default)]pub(crate) struct AnimationKeyframes {scopes: crate::cow_map::CowMap<TreeScopeID, KeyframesRow>,@@ -322,13 +362,13 @@ pub(crate) struct AnimationKeyframes {impl AnimationKeyframes {/// The row of the names, packed into one buffer of code units with a length each, the way an/// element's animation names arrive, and the host's keyframe set for each.- pub(crate) fn row(name_lengths: &[u32], name_units: &[u16], keyframe_sets: &[usize]) -> KeyframesRow {+ pub(crate) fn row(name_lengths: &[u32], name_units: &[u16], keyframe_sets: Vec<Arc<KeyframeSet>>) -> KeyframesRow {debug_assert_eq!(name_lengths.len(), keyframe_sets.len());let mut offset = 0;name_lengths.iter().zip(keyframe_sets)- .map(|(&length, &set)| {+ .map(|(&length, set)| {let units = &name_units[offset..offset + length as usize];offset += length as usize;(Box::from(units), set)@@ -345,7 +385,7 @@ impl AnimationKeyframes {self.scopes.insert(tree_scope, row);}- /// The host's keyframe set an animation of this name runs, or `None` where no scope in its chain+ /// The keyframe set an animation of this name runs, or `None` where no scope in its chain/// defines the name.////// The chain is the tree scope of the winning `animation-name` declaration first, because that@@ -358,11 +398,11 @@ impl AnimationKeyframes {declaration_scope: DeclarationScope,element_tree_scope: TreeScopeID,name: &[u16],- ) -> Option<usize> {+ ) -> Option<&Arc<KeyframeSet>> {if self.scopes.is_empty() {return None;}- let in_scope = |scope: TreeScopeID| self.scopes.get(&scope)?.get(name).copied();+ let in_scope = |scope: TreeScopeID| self.scopes.get(&scope)?.get(name);let declared = match declaration_scope {DeclarationScope::Shadow(scope) => in_scope(scope),DeclarationScope::Unscoped => None,@@ -409,15 +449,38 @@ impl<'a> AnimationTimelineSamples<'a> {}/// The timing the host sampled each of an element's effects with, by the effect's identity.-pub(crate) type SampledEffectTimings = Box<[(u64, EffectTiming)]>;+pub(crate) type SampledEffectTimings = Box<[(crate::animations::effect::AnimationEffectId, CompactEffectTiming)]>;-/// One animation effect's timing and easing, as the host last sampled the effect.+/// One animation effect's timing and easing, as a hover's lane runs a transition of its own.#[derive(Clone, Debug, PartialEq)]pub(crate) struct EffectTiming {pub(crate) timing: CompactEffectTiming,pub(crate) easing: crate::css::easing::Easing,}+impl std::ops::Deref for EffectTiming {+ type Target = CompactEffectTiming;++ fn deref(&self) -> &CompactEffectTiming {+ &self.timing+ }+}++impl std::ops::DerefMut for EffectTiming {+ fn deref_mut(&mut self) -> &mut CompactEffectTiming {+ &mut self.timing+ }+}++impl EffectTiming {+ /// The key the effect's keyframes are sampled at with its timeline at `samples` (see+ /// [`CompactEffectTiming::key_at`]).+ #[must_use]+ pub(crate) fn key_at(&self, samples: AnimationTimelineSamples<'_>) -> Option<Option<f64>> {+ self.timing.key_at(&self.easing, samples)+ }+}+/// 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)]@@ -428,62 +491,49 @@ struct SampledEffect {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 none for an unresolved progress, which samples nothing.+impl CompactEffectTiming {+ /// The key the effect samples its keyframes at as the host samples it, eased by `easing`: the one its timing gives+ /// at the time the host sampled its timeline, or none for an unresolved progress, which samples nothing.#[must_use]- pub(crate) fn key(&self) -> Option<f64> {- self.key_at(AnimationTimelineSamples::default())+ pub(crate) fn key(&self, easing: &crate::css::easing::Easing) -> Option<f64> {+ self.key_at(easing, AnimationTimelineSamples::default()).expect("the host's samples move every timeline")}- /// 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 timeline_time = samples.timeline_time(&self.timing)?;- timing::current_time_at(&self.timing.playback(), timeline_time).map(|time| time.value)+ let timeline_time = samples.timeline_time(self)?;+ timing::current_time_at(&self.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+ let playback = self.playback();+ let current_time = timing::current_time_at(&playback, self.timeline_time());+ timing::play_state_at(&playback, current_time, timing::end_time(&self.effect())) == AnimationPlayState::Paused}/// 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)));+ self.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();+ let playback = self.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;- let timeline_time = samples.timeline_time(timing)?;- let effect = timing.effect();- let playback = timing.playback();+ let timeline_time = samples.timeline_time(self)?;+ let effect = self.effect();+ let playback = self.playback();// https://www.w3.org/TR/web-animations-1/#animation-current-timelet unconstrained_time = timing::current_time_at(@@ -509,7 +559,7 @@ impl EffectTiming {Some(hold_time) if !finish_released => Some(hold_time),_ => unconstrained_time,};- let timeline = timing.timeline().map(|timeline| TimelineSample {+ let timeline = self.timeline().map(|timeline| TimelineSample {current_time: timeline_time.into(),..timeline});@@ -523,6 +573,7 @@ impl EffectTiming {/// 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.+ /// The phase is determined with the endpoint-inclusive active interval flag `endpoint_inclusive`.fn resolve_at(&self,samples: AnimationTimelineSamples<'_>,@@ -540,21 +591,40 @@ impl EffectTiming {Some((sampled.effect, resolved))}- /// The key the effect's keyframes are sampled at with its timeline at `samples`, which is+ /// The key the effect's keyframes are sampled at with its timeline at `samples`, eased by `easing`, which is/// `AnimationEffect::transformed_progress()` scaled the way the host scales it. The outer `None` is/// 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>> {- self.key_with(samples, timing::EndpointInclusiveActiveInterval::No)+ pub(crate) fn key_at(+ &self,+ easing: &crate::css::easing::Easing,+ samples: AnimationTimelineSamples<'_>,+ ) -> Option<Option<f64>> {+ self.key_with(easing, samples, timing::EndpointInclusiveActiveInterval::No)+ }++ /// https://drafts.csswg.org/web-animations-1/#commit-computed-styles+ /// The key the effect's keyframes are sampled at as the host sampled it, eased by `easing`, with the+ /// endpoint-inclusive active interval flag set when determining its phase, as committing computed styles samples+ /// it. None is an unresolved progress, which samples nothing.+ #[must_use]+ pub(crate) fn endpoint_inclusive_key(&self, easing: &crate::css::easing::Easing) -> Option<f64> {+ self.key_with(+ easing,+ AnimationTimelineSamples::default(),+ timing::EndpointInclusiveActiveInterval::Yes,+ )+ .expect("the host's samples move every timeline")}fn key_with(&self,+ easing: &crate::css::easing::Easing,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 {+ let Some(output_progress) = timing::transformed_progress(&effect, &resolved, easing) else {return Some(None);};@@ -594,41 +664,18 @@ mod tests {.collect()}- /// Publish a list of animations of the given names, each with an applied definition no plan- /// has described.+ /// Publish a list of animations of the given names, none of which a plan has described.fn set(animations: &mut CssDefinedAnimations, node: StyleNodeID, slot: AnimationSlot, names: &[&str]) {- let undescribed = FfiAppliedAnimationDefinition {- values: FfiAppliedAnimationValues {- duration_is_auto: false,- duration: 0.0,- iteration_count: 0.0,- direction: 0,- play_state: 0,- delay: 0.0,- fill_mode: 0,- composition: 0,- timeline_kind: 0,- scroll_scroller: 0,- scroll_axis: 0,- range_start_name: 0,- range_start_px: 0.0,- range_start_percentage: 0.0,- range_end_name: 0,- range_end_px: 0.0,- range_end_percentage: 0.0,- },- keyframe_set: std::ptr::null(),- timing_function: std::ptr::null(),- range_start_calculated: std::ptr::null(),- range_end_calculated: std::ptr::null(),- };- // SAFETY: The definition names no values.- let undescribed = unsafe { HeldAppliedAnimationDefinition::retained(undescribed) };animations.set(node,slot,- self::names(names),- vec![undescribed; names.len()].into_boxed_slice(),+ self::names(names)+ .into_iter()+ .map(|name| CssDefinedAnimation {+ name,+ applied_definition: None,+ })+ .collect(),);}@@ -640,7 +687,8 @@ mod tests {.collect()}- use crate::animations::snapshot::{EffectTimingSnapshot, ScrollTimelineId, TimelineClock, TimelineClockSource};+ use crate::animations::snapshot::{EffectTimingSnapshot, TimelineClock, TimelineClockSource};+ use crate::animations::timeline::AnimationTimelineId;use crate::animations::timing::{AnimationEffectTiming, AnimationReplaceState, FillMode, PlaybackDirection};impl EffectTiming {@@ -714,7 +762,7 @@ mod tests {clock: TimelineClock {source: TimelineClockSource::Scroll,origin_time: 0.0,- scroll_timeline: ScrollTimelineId(7),+ scroll_timeline: AnimationTimelineId(7),},}),easing: crate::css::easing::Easing::default(),@@ -829,7 +877,8 @@ mod tests {#[test]fn a_key_is_where_the_host_sampled_the_timeline() {- assert_eq!(timing_at(500.0).key(), Some(50_000.0));+ let timing = timing_at(500.0);+ assert_eq!(timing.timing.key(&timing.easing), 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");@@ -840,7 +889,7 @@ mod tests {let on_scroll_timeline = scroll_timing_at(25.0);let scrolled = |timeline| {[ScrollProgress {- timeline: ScrollTimelineId(timeline),+ timeline: AnimationTimelineId(timeline),progress: 60.0,}]};@@ -962,50 +1011,67 @@ mod tests {assert!(animations.rows.is_empty());}- fn publish(keyframes: &mut AnimationKeyframes, scope: u32, rows: &[(&str, usize)]) {+ fn publish(keyframes: &mut AnimationKeyframes, scope: u32, rows: &[(&str, &Arc<KeyframeSet>)]) {let lengths: Vec<u32> = rows.iter().map(|(name, _)| name.encode_utf16().count() as u32).collect();let units: Vec<u16> = rows.iter().flat_map(|(name, _)| name.encode_utf16()).collect();- let sets: Vec<usize> = rows.iter().map(|&(_, set)| set).collect();- keyframes.set(TreeScopeID(scope), AnimationKeyframes::row(&lengths, &units, &sets));+ let sets = rows.iter().map(|&(_, set)| set.clone()).collect();+ keyframes.set(TreeScopeID(scope), AnimationKeyframes::row(&lengths, &units, sets));}- fn resolve(keyframes: &AnimationKeyframes, declaration: Option<u32>, scope: u32, name: &str) -> Option<usize> {+ fn resolve(+ keyframes: &AnimationKeyframes,+ declaration: Option<u32>,+ scope: u32,+ name: &str,+ ) -> Option<*const KeyframeSet> {let declaration_scope = declaration.map_or(DeclarationScope::Unscoped, |scope| {DeclarationScope::Shadow(TreeScopeID(scope))});- keyframes.resolve(- declaration_scope,- TreeScopeID(scope),- &name.encode_utf16().collect::<Vec<_>>(),- )+ keyframes+ .resolve(+ declaration_scope,+ TreeScopeID(scope),+ &name.encode_utf16().collect::<Vec<_>>(),+ )+ .map(Arc::as_ptr)+ }++ fn keyframe_sets<const N: usize>() -> [Arc<KeyframeSet>; N] {+ std::array::from_fn(|_| Arc::new(KeyframeSet::from_processed_keyframes(Vec::new(), None)))+ }++ fn address(set: &Arc<KeyframeSet>) -> Option<*const KeyframeSet> {+ Some(Arc::as_ptr(set))}#[test]fn keyframes_resolve_in_the_declaration_scope_then_the_element_scope_then_the_document() {+ let [one, two, three, four, five] = keyframe_sets();let mut keyframes = AnimationKeyframes::default();- publish(&mut keyframes, 0, &[("a", 1), ("b", 2)]);- publish(&mut keyframes, 1, &[("a", 3)]);- publish(&mut keyframes, 2, &[("a", 4), ("b", 5)]);+ publish(&mut keyframes, 0, &[("a", &one), ("b", &two)]);+ publish(&mut keyframes, 1, &[("a", &three)]);+ publish(&mut keyframes, 2, &[("a", &four), ("b", &five)]);- assert_eq!(resolve(&keyframes, None, 0, "a"), Some(1));- assert_eq!(resolve(&keyframes, None, 1, "a"), Some(3));- assert_eq!(resolve(&keyframes, None, 1, "b"), Some(2));+ assert_eq!(resolve(&keyframes, None, 0, "a"), address(&one));+ assert_eq!(resolve(&keyframes, None, 1, "a"), address(&three));+ assert_eq!(resolve(&keyframes, None, 1, "b"), address(&two));// A `:host` rule of scope 2 styling an element of scope 1.- assert_eq!(resolve(&keyframes, Some(2), 1, "a"), Some(4));+ assert_eq!(resolve(&keyframes, Some(2), 1, "a"), address(&four));assert_eq!(resolve(&keyframes, Some(2), 1, "c"), None);}#[test]fn a_departed_scope_gives_up_its_row() {+ let [three, four] = keyframe_sets();let mut keyframes = AnimationKeyframes::default();- publish(&mut keyframes, 1, &[("a", 3)]);- publish(&mut keyframes, 2, &[("a", 4)]);+ publish(&mut keyframes, 1, &[("a", &three)]);+ publish(&mut keyframes, 2, &[("a", &four)]);publish(&mut keyframes, 1, &[]);assert_eq!(keyframes.scopes.len(), 1);- assert_eq!(resolve(&keyframes, Some(2), 0, "a"), Some(4));+ assert_eq!(resolve(&keyframes, Some(2), 0, "a"), address(&four));publish(&mut keyframes, 2, &[]);assert!(keyframes.scopes.is_empty());diff --git a/Libraries/LibWeb/Rust/src/css/style/boundary.rs b/Libraries/LibWeb/Rust/src/css/style/boundary.rsindex c47c39b8457..b921db1a669 100644--- a/Libraries/LibWeb/Rust/src/css/style/boundary.rs+++ b/Libraries/LibWeb/Rust/src/css/style/boundary.rs@@ -14,8 +14,7 @@use super::ReplacedContentInput;use super::StyleEngine;-use super::animations::HeldAppliedAnimationDefinition;-use super::bridge::{ElementBoxKind, FfiAppliedAnimationDefinition, borrow};+use super::bridge::{ElementBoxKind, borrow};use super::bridge::{FfiFrameSetBorder, FfiFrameSetDimension};use super::engine_calls::EngineWrite;use super::engine_calls::with_engine;@@ -98,9 +97,6 @@ carried! {|span| unsafe { borrow(span.data, span.size) }.iter().copied().map(StyleAtomID).collect();Box<[StyleNodeID]>: FfiSpan<u32> as "ReadonlySpan<StyleNodeID>" =|span| unsafe { borrow(span.data, span.size) }.iter().copied().filter_map(StyleNodeID::from_raw).collect();- Box<[HeldAppliedAnimationDefinition]>: FfiSpan<FfiAppliedAnimationDefinition>- as "ReadonlySpan<FfiAppliedAnimationDefinition>" =- |span| unsafe { borrow(span.data, span.size) }.iter().map(|&definition| unsafe { HeldAppliedAnimationDefinition::retained(definition) }).collect();FfiSpan<u16>: FfiSpan<u16> as "ReadonlySpan<u16>" = |span| span;FfiSpan<u32>: FfiSpan<u32> as "ReadonlySpan<StyleNodeID>" = |span| span;}@@ -431,9 +427,6 @@ style_boundary! {engine.set_held_pseudo_style_record(node, target, style_record);drop(released);};- set_element_css_defined_animations => SetElementCssDefinedAnimations {- node: StyleNodeID, slot: u8, names: Box<[CssString]>, definitions: Box<[HeldAppliedAnimationDefinition]>- } => engine.set_element_css_defined_animations(node, slot, names, definitions);set_sheet_conditions_hold => SetSheetConditionsHold { sheet: SheetID, conditions_hold: bool };}diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge.rs b/Libraries/LibWeb/Rust/src/css/style/bridge.rsindex c181815c0e8..5ed6a816b00 100644--- a/Libraries/LibWeb/Rust/src/css/style/bridge.rs+++ b/Libraries/LibWeb/Rust/src/css/style/bridge.rs@@ -1172,67 +1172,18 @@ impl StyleEngine {}}-/// The definition a plan last applied to one of the host's CSS animations, published beside the-/// animation's name: what the style computation handed the host for it, field for field, so that a-/// definition just computed and one published back compare directly. A plan whose every definition-/// equals what its animation last had applied changes nothing, and the engine does not hand it-/// over.-#[repr(C)]-#[derive(Clone, Copy)]-pub struct FfiAppliedAnimationDefinition {- pub values: FfiAppliedAnimationValues,- /// The keyframe set the plan gave the animation's effect, which the animation retains.- pub keyframe_set: *const c_void,- /// The computed `animation-timing-function`, which the animation retains, or null where no plan- /// has described the animation yet.- pub timing_function: *const c_void,- /// The calculations the edges of the attachment range resolve, which the animation retains, or null.- pub range_start_calculated: *const c_void,- pub range_end_calculated: *const c_void,-}--/// What an applied animation definition holds by value, its numbers before its bytes, which pack-/// behind them.-#[repr(C)]-#[derive(Clone, Copy, PartialEq)]-pub struct FfiAppliedAnimationValues {- pub duration: f64,- pub iteration_count: f64,- pub delay: f64,- pub range_start_px: f64,- pub range_start_percentage: f64,- pub range_end_px: f64,- pub range_end_percentage: f64,- pub duration_is_auto: bool,- pub direction: u8,- pub play_state: u8,- pub fill_mode: u8,- pub composition: u8,- /// An `FfiAnimationTimelineKind`.- pub timeline_kind: u8,- pub scroll_scroller: u8,- pub scroll_axis: u8,- pub range_start_name: u8,- pub range_end_name: u8,-}--const _: () = assert!(size_of::<FfiAppliedAnimationValues>() == 72);--// SAFETY: the keyframe set is only compared by address, and the timing function is immutable style-// value data the animation retains for as long as the definition is published, read only to-// compare it.-unsafe impl Send for FfiAppliedAnimationDefinition {}-unsafe impl Sync for FfiAppliedAnimationDefinition {}-/// Replaces the `@keyframes` row of one style scope: each name the scope defines, packed into one-/// buffer of code units with a length each, with the host's keyframe set for it. An empty row gives-/// the scope's row up; a shadow root's scope is named by the root's pointer identity as well.+/// buffer of code units with a length each, with the keyframe set for it, by the address of a set+/// the host holds a reference to. The row takes references of its own. An empty row gives the+/// scope's row up; a shadow root's scope is named by the root's pointer identity as well.+///+/// The host publishes a scope whenever its rule cache is built. The row is written as the host's+/// other writes are, ahead of the next job, which is the first that resolves keyframes from it.///-/// The host publishes a scope whenever its rule cache is built, and keeps a reference to every set-/// the row names until it replaces or gives the row up. The row is written as the host's other-/// writes are, ahead of the next job, which is the first that resolves keyframes from it.+/// # Safety+/// Every set must be a keyframe set the host holds a reference to.#[unsafe(no_mangle)]-pub extern "C" fn style_engine_set_tree_scope_animation_keyframes(+pub unsafe extern "C" fn style_engine_set_tree_scope_animation_keyframes(host: &DocumentHost,tree_scope: u32,name_lengths: ak::Span<'_, u32>,@@ -1244,11 +1195,19 @@ pub extern "C" fn style_engine_set_tree_scope_animation_keyframes(keyframe_sets.as_slice().len(),"each keyframes name has a set");- let row = super::animations::AnimationKeyframes::row(- name_lengths.as_slice(),- name_units.as_slice(),- keyframe_sets.as_slice(),- );+ let keyframe_sets: Vec<_> = keyframe_sets+ .as_slice()+ .iter()+ .map(|&set| {+ let set = set as *const crate::animations::keyframes::KeyframeSet;+ // SAFETY: Guaranteed by the caller; the row takes a reference of its own.+ unsafe {+ std::sync::Arc::increment_strong_count(set);+ std::sync::Arc::from_raw(set)+ }+ })+ .collect();+ let row = super::animations::AnimationKeyframes::row(name_lengths.as_slice(), name_units.as_slice(), keyframe_sets);let write = super::engine_calls::EngineWrite::AnimationKeyframes {tree_scope: TreeScopeID(tree_scope),row,diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs b/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rsindex 57f7adf9173..1f852c7dab6 100644--- a/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs+++ b/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs@@ -6,190 +6,6 @@use super::*;-/// How one animation effect's description travels across the boundary: the ranges of the flat-/// buffers that belong to it.-#[repr(C)]-pub struct FfiPublishedAnimationEffect {- pub identity: u64,- pub generation: u64,- /// The effect belongs to a CSS transition, which the interpolation treats differently.- pub is_transition: bool,- /// The effect's keyframes come from a style sheet, which their URLs resolve against: its base- /// URL is the range of the base URL buffer below.- pub has_resource_context: bool,- pub resource_context_is_origin_clean: bool,- pub first_keyframe: u32,- pub keyframe_count: u32,- pub base_url_offset: u32,- pub base_url_length: u32,- /// A transition's reversing-adjusted start value, or null for any other effect.- pub reversing_adjusted_start_value: *const c_void,- /// A transition's reversing shortening factor.- pub reversing_shortening_factor: f64,-}--/// The easing function a published keyframe spells out.-#[repr(u8)]-#[derive(Clone, Copy)]-#[expect(dead_code, reason = "C++ constructs the variants")]-pub enum FfiPublishedEasingKind {- Linear,- CubicBezier,- Steps,-}--/// One keyframe of a published effect: its offset on the scale the host keys keyframes by, its-/// easing spelled out, its composite operation and the ranges of what it declares.-#[repr(C)]-pub struct FfiPublishedAnimationKeyframe {- pub key: i64,- pub easing_kind: FfiPublishedEasingKind,- pub step_position: u8,- pub interval_count: i32,- pub x1: f64,- pub y1: f64,- pub x2: f64,- pub y2: f64,- pub first_linear_point: u32,- pub linear_point_count: u32,- /// The keyframe's own easing where it still has to be substituted against the element being- /// sampled, or null.- pub easing_value: *const c_void,- /// The keyframe's composite operation, with `auto` already the effect's own.- pub composite: crate::css::animation::FfiCompositeOperation,- pub first_declaration: u32,- pub declaration_count: u32,- pub first_custom_declaration: u32,- pub custom_declaration_count: u32,-}--/// One control point of a published `linear()` easing.-#[repr(C)]-pub struct FfiPublishedLinearEasingPoint {- pub input: f64,- pub output: f64,-}--/// Borrowed buffers describing an effect list for publication or a temporary sample.-#[repr(C)]-pub struct FfiAnimationEffectDescriptions {- pub effects: *const FfiPublishedAnimationEffect,- pub effect_count: usize,- pub keyframes: *const FfiPublishedAnimationKeyframe,- pub keyframe_count: usize,- pub declarations: *const FfiPublishedAnimationDeclaration,- pub declaration_count: usize,- pub custom_declarations: *const FfiPublishedAnimationCustomDeclaration,- pub custom_declaration_count: usize,- pub linear_points: *const FfiPublishedLinearEasingPoint,- pub linear_point_count: usize,- pub base_url_bytes: *const u8,- pub base_url_byte_count: usize,-}--impl FfiAnimationEffectDescriptions {- /// # Safety- /// Every buffer and the values it names must remain live for the call.- pub(crate) unsafe fn effects(&self) -> Box<[crate::css::style::effect_descriptions::PublishedEffect]> {- // SAFETY: Guaranteed by the caller.- unsafe {- crate::css::style::effect_descriptions::PublishedEffectBuffers {- effects: ak::slice_from_raw_parts(self.effects, self.effect_count),- keyframes: ak::slice_from_raw_parts(self.keyframes, self.keyframe_count),- declarations: ak::slice_from_raw_parts(self.declarations, self.declaration_count),- custom_declarations: ak::slice_from_raw_parts(self.custom_declarations, self.custom_declaration_count),- linear_points: ak::slice_from_raw_parts(self.linear_points, self.linear_point_count),- base_url_bytes: ak::slice_from_raw_parts(self.base_url_bytes, self.base_url_byte_count),- }- .effects()- }- }-}--/// One longhand a published keyframe declares. A null value stands for the element's own value,-/// which a keyframe the host synthesized holds and which is not known until the element is-/// sampled.-#[repr(C)]-pub struct FfiPublishedAnimationDeclaration {- pub property_id: u16,- pub value: *const c_void,-}--/// One custom property a published keyframe declares, by the raw representation of its name. A-/// null value stands for the element's own value of it.-#[repr(C)]-pub struct FfiPublishedAnimationCustomDeclaration {- pub name: usize,- pub value: *const c_void,-}--/// The version of one animation effect the host is about to sample.-#[repr(C)]-pub struct FfiAnimationEffectVersion {- pub identity: u64,- pub generation: u64,-}--/// Describe the effects one of an element's animation lists holds, in composite order, for the-/// style engine to sample them from. The host retains every value the effects name and streams-/// the description to the engine.-///-/// # Safety-/// `host` must be a live document host, on its document's thread, every buffer must hold the count-/// it is given, and every value and custom-property name the buffers name must be live for the-/// duration of the call.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn style_engine_set_element_animation_effect_descriptions(- host: &DocumentHost,- node: u32,- slot: u32,- descriptions: &FfiAnimationEffectDescriptions,-) {- // NB: The slot of an element's own animations is u8::MAX, whose upper bits a u8 parameter could not promise.- let slot = slot as u8;- let Some(node) = StyleNodeID::from_raw(node) else {- return;- };- // SAFETY: Guaranteed by the caller.- let effects = unsafe { descriptions.effects() };- host.engine_memo().described.borrow_mut().follow(node, slot, &effects);- host.queue_change(crate::render_state::ArenaChange::Engine(- crate::css::style::engine_calls::EngineWrite::AnimationEffectDescriptions { node, slot, effects },- ));-}--/// Notes what the `attr()`s of the value `value`, which an animation effect's keyframes hold, can read, answering-/// whether they can read a name none could before.-///-/// # Safety-/// `value` must be a live style value.-#[unsafe(no_mangle)]-pub unsafe extern "C" fn style_engine_note_attr_names_read_by_value(host: &DocumentHost, value: *const c_void) -> bool {- // SAFETY: Guaranteed by the caller.- let value = unsafe { &*value.cast::<crate::css::style_value::StyleValueData>() };- let before = crate::css::style::host_atoms::attr_names_read_generation(host);- crate::css::style::host_atoms::note_attr_names_read_by(host, std::iter::once(value));- crate::css::style::host_atoms::attr_names_read_generation(host) != before-}--/// Whether the engine describes one of an element's animation lists as holding exactly these-/// versions of its effects, in this order, so that the host need not describe them again. Only-/// the host describes them, so it knows without asking.-#[unsafe(no_mangle)]-pub extern "C" fn style_engine_describes_animation_effects(- host: &DocumentHost,- node: u32,- slot: u32,- versions: ak::Span<'_, FfiAnimationEffectVersion>,-) -> bool {- StyleNodeID::from_raw(node).is_some_and(|node| {- host.engine_memo()- .described- .borrow()- .describe(node, slot as u8, versions.as_slice())- })-}-/// Publish already bound immutable selector inputs, after all host interning has finished.pub(crate) fn publish_style_rule(engine: &mut StyleEngine,diff --git a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rsindex 79e8f19b469..0d8b7094901 100644--- a/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs+++ b/Libraries/LibWeb/Rust/src/css/style/effect_descriptions.rs@@ -6,135 +6,35 @@//! The animation effects an element holds, described for the style engine.//!-//! Sampling an element's animations interpolates what its effects' keyframes declare. Everything a-//! keyframe declares that does not depend on the element being sampled - its offset, its easing,-//! its composite operation and the values it declares - is settled when the host describes the-//! effect, which it does again whenever the effect changes in a way that moves any of it. What does-//! depend on the element, a value or an easing still to be substituted against it, travels as-//! written.+//! Sampling an element's animations interpolates what its effects' keyframes declare. A description+//! holds the keyframe set its effect runs, which it shares with everything else that runs it, beside+//! what depends on the effect: the composite operation and the easing a keyframe whose own is `auto`+//! or missing runs instead, which a sample resolves per keyframe. What depends on the element, a+//! value or an easing still to be substituted against it, travels as written in the set.use super::animations::{AnimationSlot, EffectTiming};-use super::bridge::{- FfiAnimationEffectVersion, FfiPublishedAnimationCustomDeclaration, FfiPublishedAnimationDeclaration,- FfiPublishedAnimationEffect, FfiPublishedAnimationKeyframe, FfiPublishedEasingKind, FfiPublishedLinearEasingPoint,-};use super::tree::StyleNodeID;-use super::weak_pool::WeakPool;+use crate::animations::easing::{CompactEasing, KEYWORD_CUBIC_BEZIERS, keyword_cubic_bezier};+use crate::animations::effect::AnimationEffectId;+use crate::animations::keyframes::{+ CompositeOperationOrAuto, Keyframe, KeyframeCustomDeclaration, KeyframeDeclaration, KeyframeSet, KeyframeValue,+ ResourceContext,+};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::easing::{Easing, FfiLinearEasingPoint};use crate::css::style_value::EasingPayload;use crate::css::style_value::{RetainedStyleValueData, StyleValueData};use std::collections::HashMap;-use std::ffi::c_void;-use std::ops::Range;use std::sync::{Arc, Mutex};-/// What a published keyframe declares for a property.-#[derive(Clone, PartialEq)]-pub(crate) enum PublishedValue {- /// The element's own value, held by a keyframe the host synthesized, and not known until the- /// element is sampled.- ElementValue,- Declared(RetainedStyleValueData),-}--impl PublishedValue {- /// The value's identity: zero for the element's own value.- fn identity(&self) -> usize {- match self {- Self::ElementValue => 0,- Self::Declared(value) => value.pointer() as usize,- }- }-- /// Retains the value a host pointer names, or stands for the element's own value where it is- /// null.- ///- /// # Safety- /// `value` must be null or a live style value.- unsafe fn from_host(value: *const c_void) -> Self {- match value.is_null() {- true => Self::ElementValue,- false => Self::Declared(unsafe { retained(value) }),- }- }-}--impl PublishedEffect {- pub(crate) fn for_keyframe_computation(- frames: Vec<Vec<PublishedDeclaration>>,- resource_context: Option<PublishedResourceContext>,- ) -> Self {- let mut declarations = Vec::new();- let keyframes = frames- .into_iter()- .enumerate()- .map(|(index, frame)| {- let first = declarations.len();- declarations.extend(frame);- PublishedKeyframe {- key: i64::try_from(index).expect("keyframe index fits in i64"),- easing: Easing::default(),- easing_value: None,- composite: FfiCompositeOperation::Replace,- declarations: first..declarations.len(),- custom_declarations: 0..0,- }- })- .collect();- Self {- identity: 0,- generation: 0,- is_transition: false,- keyframes: Arc::new(PublishedKeyframes {- resource_context,- target_properties: target_properties(declarations.iter().map(|declaration| declaration.property_id)),- keyframes,- declarations: declarations.into_boxed_slice(),- custom_declarations: Box::new([]),- }),- custom_property_interval_values: None,- timing: None,- reversing: None,- }- }-+impl EffectDescription {/// The values the effect's keyframes declare, and those they run their easing by.pub(crate) fn declared_values(&self) -> impl Iterator<Item = &StyleValueData> {- let keyframes = &self.keyframes;- let declared = keyframes- .declarations- .iter()- .map(|declaration| &declaration.value)- .chain(- keyframes- .custom_declarations- .iter()- .map(|declaration| &declaration.value),- )- .filter_map(|value| match value {- PublishedValue::ElementValue => None,- PublishedValue::Declared(value) => value.optional_data(),- });- let easings = keyframes- .keyframes- .iter()- .filter_map(|keyframe| keyframe.easing_value.as_ref())- .filter_map(RetainedStyleValueData::optional_data);- declared.chain(easings)- }-}--/// # Safety-/// `value` must be a live style value.-unsafe fn retained(value: *const c_void) -> RetainedStyleValueData {- unsafe {- RetainedStyleValueData::from_retained_pointer(crate::css::style_value::retain_style_value(- value.cast::<StyleValueData>(),- ))+ self.sampled_keyframes()+ .into_iter()+ .flat_map(|keyframes| keyframes.declared_values())}}@@ -147,14 +47,13 @@ pub(crate) fn easing_from_computed_timing_function(value: &StyleValueData) -> Oplet StyleValueData::Keyword { keyword } = value else {return None;};- return match *keyword {- keyword::LINEAR => Some(Easing::default()),- keyword::EASE => Some(cubic_bezier(0.25, 0.1, 0.25, 1.0)),- keyword::EASE_IN => Some(cubic_bezier(0.42, 0.0, 1.0, 1.0)),- keyword::EASE_OUT => Some(cubic_bezier(0.0, 0.0, 0.58, 1.0)),- keyword::EASE_IN_OUT => Some(cubic_bezier(0.42, 0.0, 0.58, 1.0)),- _ => None,- };+ if *keyword == keyword::LINEAR {+ return Some(Easing::default());+ }+ return KEYWORD_CUBIC_BEZIERS+ .iter()+ .position(|&(cubic_bezier_keyword, _)| cubic_bezier_keyword == *keyword)+ .map(keyword_cubic_bezier);};let EasingPayload {kind,@@ -210,158 +109,63 @@ pub(crate) fn easing_from_computed_timing_function(value: &StyleValueData) -> Op}}-#[derive(Clone)]--pub(crate) struct PublishedDeclaration {- pub(crate) property_id: u16,- pub(crate) value: PublishedValue,-}+/// Maps an interval's declaration indices to its substituted values.+type CustomPropertyIntervalValues = HashMap<[usize; 2], [RetainedStyleValueData; 2]>;-/// A custom property a keyframe declares. The name is retained: a description outlives the call-/// that published it, and a fly string's raw representation is only an identity while the string-/// is alive.+/// What an effect's animation is, as far as sampling the effect goes.#[derive(Clone)]-pub(crate) struct PublishedCustomDeclaration {- pub(crate) name: RetainedUtf16FlyString,- pub(crate) value: PublishedValue,+pub(crate) enum EffectAnimation {+ /// No animation: the effect is associated with none, and samples nothing.+ Unassociated,+ /// Any animation but a CSS transition, with the easing a keyframe that declares none runs: a CSS animation's+ /// `animation-timing-function`, and `linear` for any other.+ Animation(CompactEasing),+ /// A CSS transition the host runs, with what a transition that reverses it starts from.+ Transition(TransitionReversing),+ /// A CSS transition a hover's lane starts or runs on itself, whose run holds what reverses it.+ LaneTransition,}-#[derive(Clone, PartialEq)]-pub(crate) struct PublishedKeyframe {- pub(crate) key: i64,- /// The easing the keyframe runs, which is the one its animation runs where the keyframe has- /// none of its own, and what it runs where `easing_value` substitutes to nothing.- pub(crate) easing: Easing,- pub(crate) easing_value: Option<RetainedStyleValueData>,- /// The composite operation, with a keyframe's `auto` already the effect's own.+/// One animation effect, described for the style engine to sample it from: the keyframes it runs, its timing function+/// and composite operation, and what its animation is. The host's record of the effect keeps these in its description,+/// which every list of the engine's that holds the effect shares. A description never changes once anything but the+/// record holds it: a change describes the effect anew, so that two descriptions of the effect differ by identity.+#[derive(Clone)]+pub(crate) struct EffectDescription {+ pub(crate) identity: AnimationEffectId,+ /// https://www.w3.org/TR/web-animations-1/#keyframe+ /// Shared with everything else that runs the keyframes, or none for an effect with no keyframes.+ pub(crate) keyframe_set: Option<Arc<KeyframeSet>>,+ /// https://www.w3.org/TR/web-animations-1/#time-transformations+ pub(crate) timing_function: CompactEasing,+ pub(crate) animation: EffectAnimation,+ /// https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-composite+ /// The effect's composite operation, which a keyframe whose own is `auto` runs.pub(crate) composite: FfiCompositeOperation,- declarations: Range<usize>,- custom_declarations: Range<usize>,}-/// The style sheet an effect's keyframes come from, which their URLs resolve against.+/// One of an element's animation effects as a list of the style engine's holds it: its description, beside what the+/// engine keeps of it between samples.#[derive(Clone)]-pub(crate) struct PublishedResourceContext {- /// Shared with every resolution of the effect's declarations that points into it.- pub(crate) base_url: Arc<[u8]>,- pub(crate) origin_clean: bool,-}--/// Maps an interval's declaration indices to its substituted values.-type CustomPropertyIntervalValues = HashMap<[usize; 2], [RetainedStyleValueData; 2]>;--/// What an effect's keyframes declare, which effects describing equal keyframes share: the elements running one-/// `@keyframes` rule hold one of these between them.-pub(crate) struct PublishedKeyframes {- /// The style sheet the keyframes come from, which their URLs resolve against.- resource_context: Option<PublishedResourceContext>,- target_properties: Box<[u16]>,- keyframes: Box<[PublishedKeyframe]>,- declarations: Box<[PublishedDeclaration]>,- custom_declarations: Box<[PublishedCustomDeclaration]>,+pub(crate) struct PublishedEffect {+ description: Arc<EffectDescription>,+ /// Substituted interval values retained for this description of the effect, for an effect whose keyframes declare+ /// custom properties.+ custom_property_interval_values: Option<Arc<Mutex<CustomPropertyIntervalValues>>>,+ /// The timing the host last sampled the effect with, which moves without the description.+ pub(crate) timing: Option<CompactEffectTiming>,}-impl PublishedKeyframes {- /// The hash the document's pool finds equal keyframes under: what each declares, values by identity.- fn pool_hash(&self) -> u64 {- use std::hash::{Hash, Hasher};- let mut hasher = super::fast_hash::fast_hasher();- self.resource_context- .as_ref()- .map(|context| (&context.base_url, context.origin_clean))- .hash(&mut hasher);- self.target_properties.hash(&mut hasher);- for keyframe in &self.keyframes {- keyframe.key.hash(&mut hasher);- (keyframe.composite as u8).hash(&mut hasher);- }- for declaration in &self.declarations {- declaration.property_id.hash(&mut hasher);- declaration.value.identity().hash(&mut hasher);- }- for declaration in &self.custom_declarations {- declaration.name.raw().hash(&mut hasher);- declaration.value.identity().hash(&mut hasher);- }- hasher.finish()- }+const _: () = assert!(size_of::<PublishedEffect>() == 128);- /// Whether the two declare the same, values by identity.- fn declares_the_same_as(&self, other: &Self) -> bool {- self.resource_context- .as_ref()- .map(|context| (&context.base_url, context.origin_clean))- == other- .resource_context- .as_ref()- .map(|context| (&context.base_url, context.origin_clean))- && self.target_properties == other.target_properties- && self.keyframes.len() == other.keyframes.len()- && self.keyframes.iter().zip(&other.keyframes).all(|(first, second)| {- first.key == second.key- && first.easing == second.easing- && first.easing_value.as_ref().map(RetainedStyleValueData::pointer)- == second.easing_value.as_ref().map(RetainedStyleValueData::pointer)- && first.composite == second.composite- && first.declarations == second.declarations- && first.custom_declarations == second.custom_declarations- })- && self.declarations.len() == other.declarations.len()- && self- .declarations- .iter()- .zip(&other.declarations)- .all(|(first, second)| {- first.property_id == second.property_id && first.value.identity() == second.value.identity()- })- && self.custom_declarations.len() == other.custom_declarations.len()- && self- .custom_declarations- .iter()- .zip(&other.custom_declarations)- .all(|(first, second)| {- first.name.raw() == second.name.raw() && first.value.identity() == second.value.identity()- })- }+impl std::ops::Deref for PublishedEffect {+ type Target = EffectDescription;- fn heap_size(&self) -> usize {- self.resource_context- .as_ref()- .map_or(0, |context| crate::heap_size::ARC_HEADER_BYTES + context.base_url.len())- + size_of_val::<[u16]>(&self.target_properties)- + size_of_val::<[PublishedKeyframe]>(&self.keyframes)- + self- .keyframes- .iter()- .map(|keyframe| match &keyframe.easing {- Easing::Linear(points) => crate::heap_size::vec_bytes(points),- _ => 0,- })- .sum::<usize>()- + size_of_val::<[PublishedDeclaration]>(&self.declarations)- + size_of_val::<[PublishedCustomDeclaration]>(&self.custom_declarations)+ fn deref(&self) -> &EffectDescription {+ &self.description}}-/// One of an element's animation effects, described for the style engine.-#[derive(Clone)]-pub(crate) struct PublishedEffect {- pub(crate) identity: u64,- pub(crate) generation: u64,- /// The effect belongs to a CSS transition, which the interpolation treats differently.- pub(crate) is_transition: bool,- keyframes: Arc<PublishedKeyframes>,- /// Substituted interval values retained for this effect version, for an effect whose keyframes declare custom- /// properties.- custom_property_interval_values: Option<Arc<Mutex<CustomPropertyIntervalValues>>>,- /// The timing the host last sampled the effect with, which moves without the description.- pub(crate) timing: Option<EffectTiming>,- /// What a transition reverses to, and how much shorter a reversing transition runs, where the effect is one.- pub(crate) reversing: Option<TransitionReversing>,-}--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#[derive(Clone)]@@ -370,92 +174,67 @@ pub(crate) struct TransitionReversing {pub(crate) shortening_factor: f64,}-fn target_properties(properties: impl IntoIterator<Item = u16>) -> Box<[u16]> {- use crate::css::property_metadata::{longhands_for_shorthand, property_animation_type, property_is_shorthand};-- let mut pending: Vec<_> = properties.into_iter().collect();- let mut longhands = Vec::new();- while let Some(property) = pending.pop() {- if property_is_shorthand(property) {- pending.extend_from_slice(longhands_for_shorthand(property));- } else if property_animation_type(property) != crate::css::animation::ANIMATION_TYPE_NONE {- longhands.push(property);+impl PublishedEffect {+ /// The effect `description` describes, as a list of the engine's first holds it.+ pub(crate) fn new(description: Arc<EffectDescription>) -> Self {+ Self {+ custom_property_interval_values: description+ .sampled_keyframes()+ .is_some_and(|keyframes| !keyframes.custom_declarations().is_empty())+ .then(Default::default),+ description,+ timing: None,}}- longhands.sort_unstable();- longhands.dedup();- longhands.into_boxed_slice()-}-impl PublishedEffect {- /// The effect of a CSS transition of `property_id` from `start` to `end`, as the host describes one:- /// two keyframes, each running the linear easing, that replace the value beneath them.- pub(crate) fn transition(- identity: u64,+ /// The effect of a CSS transition of `property_id` from `start` to `end` a hover's lane starts or runs on: two+ /// keyframes, each running the linear easing, that replace the value beneath them, with `timing`.+ pub(crate) fn lane_transition(+ identity: AnimationEffectId,property_id: u16,start: RetainedStyleValueData,end: RetainedStyleValueData,- timing: Option<EffectTiming>,+ timing: EffectTiming,) -> Self {- let keyframe = |key, index| PublishedKeyframe {- key,- easing: Easing::default(),- easing_value: None,- composite: FfiCompositeOperation::Replace,- declarations: index..index + 1,- custom_declarations: 0..0,- };+ let EffectTiming { timing, easing } = timing;Self {- identity,- generation: 0,- is_transition: true,- keyframes: Arc::new(PublishedKeyframes {- resource_context: None,- target_properties: target_properties([property_id]),- // `KeyframeEffect::AnimationKeyFrameKeyScaleFactor` keys the end at 100%.- keyframes: Box::new([keyframe(0, 0), keyframe(100 * 1000, 1)]),- declarations: Box::new([start, end].map(|value| PublishedDeclaration {- property_id,- value: PublishedValue::Declared(value),- })),- custom_declarations: Box::new([]),+ description: Arc::new(EffectDescription {+ identity,+ keyframe_set: Some(Arc::new(KeyframeSet::for_transition(+ crate::animations::keyframes::KeyframeProperty::Id(property_id),+ start,+ end,+ 1.0,+ ))),+ timing_function: CompactEasing::of(easing),+ animation: EffectAnimation::LaneTransition,+ composite: FfiCompositeOperation::Replace,}),custom_property_interval_values: None,- timing,- reversing: None,+ timing: Some(timing),}}- /// The style sheet the effect's keyframes come from, which their URLs resolve against.- #[must_use]- pub(crate) fn resource_context(&self) -> Option<&PublishedResourceContext> {- self.keyframes.resource_context.as_ref()- }-- /// The longhands the effect's keyframes animate, sorted.- #[must_use]- pub(crate) fn target_properties(&self) -> &[u16] {- &self.keyframes.target_properties- }-- #[must_use]- pub(crate) fn keyframes(&self) -> &[PublishedKeyframe] {- &self.keyframes.keyframes- }-+ /// The description of the effect, which the host's record of it shares.#[must_use]- pub(crate) fn declarations_of(&self, keyframe: &PublishedKeyframe) -> &[PublishedDeclaration] {- &self.keyframes.declarations[keyframe.declarations.clone()]+ pub(crate) fn description(&self) -> &Arc<EffectDescription> {+ &self.description}+ /// The key the effect samples its keyframes at as the host last sampled it, or none where the host has not sampled+ /// it or its progress is unresolved.#[must_use]- pub(crate) fn custom_declarations_of(&self, keyframe: &PublishedKeyframe) -> &[PublishedCustomDeclaration] {- &self.keyframes.custom_declarations[keyframe.custom_declarations.clone()]+ pub(crate) fn key(&self) -> Option<f64> {+ self.timing.as_ref()?.key(self.timing_function.as_easing())}+ /// The timing and easing the host last sampled the effect with, where it sampled it.#[must_use]- pub(crate) fn custom_declaration_at(&self, index: usize) -> &PublishedCustomDeclaration {- &self.keyframes.custom_declarations[index]+ pub(crate) fn effect_timing(&self) -> Option<EffectTiming> {+ Some(EffectTiming {+ timing: self.timing?,+ easing: self.timing_function.easing(),+ })}/// Look up retained interval values, also reporting whether the interval retains its values across samples.@@ -466,7 +245,7 @@ impl PublishedEffect {) -> (Option<[RetainedStyleValueData; 2]>, bool) {let has_neutral_endpoint = declaration_indices.iter()- .any(|&index| matches!(self.custom_declaration_at(index).value, PublishedValue::ElementValue));+ .any(|&index| matches!(self.custom_declaration_at(index).value, KeyframeValue::ElementValue));if has_interpolable_syntax || has_neutral_endpoint {return (None, false);@@ -532,115 +311,148 @@ impl PublishedEffect {}}-/// The flat buffers one animation list's descriptions travel in.-#[derive(Clone, Copy)]-pub(crate) struct PublishedEffectBuffers<'a> {- pub(crate) effects: &'a [FfiPublishedAnimationEffect],- pub(crate) keyframes: &'a [FfiPublishedAnimationKeyframe],- pub(crate) declarations: &'a [FfiPublishedAnimationDeclaration],- pub(crate) custom_declarations: &'a [FfiPublishedAnimationCustomDeclaration],- pub(crate) linear_points: &'a [FfiPublishedLinearEasingPoint],- pub(crate) base_url_bytes: &'a [u8],-}+impl EffectDescription {+ /// The description of the effect `identity` names with the default timing function, no keyframes and no+ /// animation.+ pub(crate) fn new(identity: AnimationEffectId) -> Self {+ Self {+ identity,+ keyframe_set: None,+ timing_function: CompactEasing::Linear,+ animation: EffectAnimation::Unassociated,+ composite: FfiCompositeOperation::Replace,+ }+ }-fn range(first: u32, count: u32) -> Range<usize> {- first as usize..first as usize + count as usize-}+ /// The keyframes a sample of the effect interpolates: none for an effect with no animation, which samples nothing.+ fn sampled_keyframes(&self) -> Option<&Arc<KeyframeSet>> {+ match self.animation {+ EffectAnimation::Unassociated => None,+ EffectAnimation::Animation(_) | EffectAnimation::Transition(_) | EffectAnimation::LaneTransition => {+ self.keyframe_set.as_ref()+ }+ }+ }-impl PublishedEffectBuffers<'_> {- /// The effects the buffers describe, each value they name retained.- ///- /// # Safety- /// Every value and custom-property name the buffers name must be live.- pub(crate) unsafe fn effects(self) -> Box<[PublishedEffect]> {- self.effects- .iter()- .map(|effect| {- let mut declarations = Vec::new();- let mut custom_declarations = Vec::new();- let keyframes = self.keyframes[range(effect.first_keyframe, effect.keyframe_count)]- .iter()- .map(|keyframe| {- let first_declaration = declarations.len();- declarations.extend(- self.declarations[range(keyframe.first_declaration, keyframe.declaration_count)]- .iter()- .map(|declaration| PublishedDeclaration {- property_id: declaration.property_id,- value: unsafe { PublishedValue::from_host(declaration.value) },- }),- );- let first_custom_declaration = custom_declarations.len();- custom_declarations.extend(- self.custom_declarations- [range(keyframe.first_custom_declaration, keyframe.custom_declaration_count)]- .iter()- .map(|declaration| PublishedCustomDeclaration {- name: unsafe { RetainedUtf16FlyString::from_borrowed_raw(declaration.name) },- value: unsafe { PublishedValue::from_host(declaration.value) },- }),- );- PublishedKeyframe {- key: keyframe.key,- easing: self.easing(keyframe),- easing_value: (!keyframe.easing_value.is_null())- .then(|| unsafe { retained(keyframe.easing_value) }),- composite: keyframe.composite,- declarations: first_declaration..declarations.len(),- custom_declarations: first_custom_declaration..custom_declarations.len(),- }- })- .collect();- PublishedEffect {- identity: effect.identity,- generation: effect.generation,- is_transition: effect.is_transition,- custom_property_interval_values: (!custom_declarations.is_empty()).then(Default::default),- keyframes: Arc::new(PublishedKeyframes {- resource_context: effect.has_resource_context.then(|| PublishedResourceContext {- base_url: self.base_url_bytes[range(effect.base_url_offset, effect.base_url_length)].into(),- origin_clean: effect.resource_context_is_origin_clean,- }),- target_properties: target_properties(- declarations.iter().map(|declaration| declaration.property_id),- ),- keyframes,- declarations: declarations.into(),- custom_declarations: custom_declarations.into(),- }),- timing: None,- reversing: (!effect.reversing_adjusted_start_value.is_null()).then(|| TransitionReversing {- adjusted_start_value: unsafe { retained(effect.reversing_adjusted_start_value) },- shortening_factor: effect.reversing_shortening_factor,- }),+ /// Whether the effect belongs to a CSS transition, which the interpolation treats differently.+ #[must_use]+ pub(crate) fn is_transition(&self) -> bool {+ matches!(+ self.animation,+ EffectAnimation::Transition(_) | EffectAnimation::LaneTransition+ )+ }++ /// What a transition that reverses the one the effect belongs to starts from, where the host runs it.+ #[must_use]+ pub(crate) fn reversing(&self) -> Option<&TransitionReversing> {+ match &self.animation {+ EffectAnimation::Transition(reversing) => Some(reversing),+ EffectAnimation::Unassociated | EffectAnimation::Animation(_) | EffectAnimation::LaneTransition => None,+ }+ }++ /// The style sheet the effect's keyframes come from, which their URLs resolve against.+ #[must_use]+ pub(crate) fn resource_context(&self) -> Option<&ResourceContext> {+ self.sampled_keyframes()?.resource_context()+ }++ /// Calls `callback` with each longhand the effect's keyframes animate that can be animated, which may repeat: the+ /// longhands of a shorthand whose value is still to be substituted stand for it.+ pub(crate) fn for_each_animated_longhand(&self, mut callback: impl FnMut(u16)) {+ use crate::css::property_metadata::{longhands_for_shorthand, property_animation_type, property_is_shorthand};+ fn visit(property: u16, callback: &mut impl FnMut(u16)) {+ if property_is_shorthand(property) {+ for &longhand in longhands_for_shorthand(property) {+ visit(longhand, callback);}+ } else if property_animation_type(property) != crate::css::animation::ANIMATION_TYPE_NONE {+ callback(property);+ }+ }+ for &property in self+ .sampled_keyframes()+ .into_iter()+ .flat_map(|keyframes| keyframes.target_properties())+ {+ visit(property, &mut callback);+ }+ }++ #[must_use]+ pub(crate) fn keyframes(&self) -> &[Keyframe] {+ self.sampled_keyframes().map_or(&[], |keyframes| keyframes.keyframes())+ }++ /// The custom properties the effect's keyframes interpolate.+ pub(crate) fn target_custom_properties(&self) -> &[crate::css::retained_fly_string::RetainedUtf16FlyString] {+ self.sampled_keyframes()+ .map_or(&[], |keyframes| keyframes.target_custom_properties())+ }++ /// What `keyframe`, one of the effect's, declares that samples. A keyframe generated to hold the element's own+ /// value of a shorthand stands for its longhands', which have keyframes of their own. A value that is invalid at+ /// computed-value time animates nothing. A longhand pending the substitution of its shorthand's value is+ /// substituted with it when the effect is sampled.+ /// https://drafts.csswg.org/css-values-5/#invalid-at-computed-value-time+ pub(crate) fn declarations_of(&self, keyframe: &Keyframe) -> impl Iterator<Item = &KeyframeDeclaration> + Clone {+ use crate::css::property_metadata::property_is_shorthand;+ self.sampled_keyframes()+ .into_iter()+ .flat_map(|keyframes| keyframes.declarations_of(keyframe))+ .filter(|declaration| match &declaration.value {+ KeyframeValue::ElementValue => !property_is_shorthand(declaration.property_id),+ KeyframeValue::Declared(value) => !matches!(value.data(), StyleValueData::GuaranteedInvalid),})- .collect()}- fn easing(self, keyframe: &FfiPublishedAnimationKeyframe) -> Easing {- match keyframe.easing_kind {- FfiPublishedEasingKind::Linear => Easing::Linear(- self.linear_points[range(keyframe.first_linear_point, keyframe.linear_point_count)]- .iter()- .map(|point| FfiLinearEasingPoint {- input: point.input,- output: point.output,- })- .collect(),- ),- FfiPublishedEasingKind::CubicBezier => Easing::CubicBezier {- x1: keyframe.x1,- y1: keyframe.y1,- x2: keyframe.x2,- y2: keyframe.y2,- },- FfiPublishedEasingKind::Steps => Easing::Steps {- interval_count: keyframe.interval_count,- position: keyframe.step_position,- },+ #[must_use]+ pub(crate) fn custom_declarations_of(&self, keyframe: &Keyframe) -> &[KeyframeCustomDeclaration] {+ self.sampled_keyframes()+ .map_or(&[], |keyframes| keyframes.custom_declarations_of(keyframe))+ }++ /// The custom property the effect's keyframes declare at `index`, counting over all of them in order.+ #[must_use]+ pub(crate) fn custom_declaration_at(&self, index: usize) -> &KeyframeCustomDeclaration {+ &self+ .sampled_keyframes()+ .expect("an effect that declares custom properties runs keyframes")+ .custom_declarations()[index]+ }++ /// The composite operation `keyframe`, one of the effect's, runs: its own, or the effect's where its own is `auto`.+ #[must_use]+ pub(crate) fn composite_of(&self, keyframe: &Keyframe) -> FfiCompositeOperation {+ match keyframe.composite {+ CompositeOperationOrAuto::Replace => FfiCompositeOperation::Replace,+ CompositeOperationOrAuto::Add => FfiCompositeOperation::Add,+ CompositeOperationOrAuto::Accumulate => FfiCompositeOperation::Accumulate,+ CompositeOperationOrAuto::Auto => self.composite,}}++ /// The easing a keyframe of the effect runs where it declares none, or where the one it declares still to be+ /// substituted substitutes to none: the animation's.+ #[must_use]+ pub(crate) fn default_easing(&self) -> Easing {+ match &self.animation {+ EffectAnimation::Animation(default_easing) => default_easing.easing(),+ EffectAnimation::Unassociated | EffectAnimation::Transition(_) | EffectAnimation::LaneTransition => {+ Easing::default()+ }+ }+ }++ /// The bytes the description holds beyond itself, without the keyframe set, which others share.+ fn heap_size(&self) -> usize {+ let default_easing = match &self.animation {+ EffectAnimation::Animation(default_easing) => default_easing.heap_size(),+ EffectAnimation::Unassociated | EffectAnimation::Transition(_) | EffectAnimation::LaneTransition => 0,+ };+ self.timing_function.heap_size() + default_easing+ }}/// The effects one of an element's animation lists holds, in composite order.@@ -653,20 +465,19 @@ pub(crate) struct AnimationEffectDescriptions {/// Holding an animation is rare, so only the elements that do have a row, and a row holds only/// the lists that are not empty.rows: crate::cow_map::CowMap<StyleNodeID, Vec<AnimationEffectList>>,- /// The keyframes the effects describe, by content, which an effect describing equal ones shares.- keyframes: WeakPool<PublishedKeyframes>,}impl AnimationEffectDescriptions {- /// The bytes of the descriptions: the rows, the effects, and the keyframes and interval caches they hold, each- /// shared one once. The values the keyframes declare are their rules'.+ /// The bytes of the descriptions: the rows, the effects, the descriptions they share with the host's records of+ /// the effects, and the easings and interval caches those hold, each shared one once. The keyframe sets the effects+ /// run are the host's effects', and the values the keyframes declare their rules'.pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {use crate::heap_size::{map_bytes, vec_bytes};let effect_bytes =|effect: &PublishedEffect, sizer: &mut crate::heap_size::HeapSizer| {- let keyframes = match sizer.arc_shallow(&effect.keyframes) {+ let description = match sizer.arc_shallow(effect.description()) {0 => 0,- bytes => bytes + effect.keyframes.heap_size(),+ bytes => bytes + effect.description().heap_size(),};let interval_values = effect.custom_property_interval_values.as_ref().map_or(0, |values| {match sizer.arc_shallow(values) {@@ -674,7 +485,7 @@ impl AnimationEffectDescriptions {bytes => bytes + map_bytes(&values.lock().unwrap()),}});- keyframes + interval_values+ description + interval_values};let mut bytes = self.rows.heap_size();for lists in self.rows.values() {@@ -719,26 +530,17 @@ impl AnimationEffectDescriptions {self.rows.get(&node).is_some_and(|lists| {lists.iter().flat_map(|(_, effects)| effects.iter()).any(|effect| {effect- .keyframes- .custom_declarations+ .target_custom_properties().iter()- .any(|declaration| moved(&declaration.name.to_utf16()))+ .any(|name| moved(&name.to_utf16()))})})}- /// Replace one list. An empty list drops it.+ /// Replace one list. An empty list drops it. An effect the list held already, by the identity of its description,+ /// keeps the interval values the engine retained for it, and the timing the host last sampled it with where the+ /// list gives it none: a description that changed in any way is another description.pub(crate) fn set(&mut self, node: StyleNodeID, slot: AnimationSlot, mut effects: Box<[PublishedEffect]>) {- for effect in &mut effects {- let hash = effect.keyframes.pool_hash();- match self- .keyframes- .find(hash, |pooled| pooled.declares_the_same_as(&effect.keyframes))- {- Some(pooled) => effect.keyframes = pooled,- None => self.keyframes.insert(hash, &effect.keyframes),- }- }let lists = self.rows.entry(node).or_default();let existing = lists.iter().position(|(list_slot, _)| *list_slot == slot);if let Some(index) = existing {@@ -746,9 +548,10 @@ impl AnimationEffectDescriptions {for effect in &mut effects {if let Some(previous_effect) = previous_effects.iter()- .find(|previous| previous.identity == effect.identity && previous.generation == effect.generation)+ .find(|previous| Arc::ptr_eq(previous.description(), effect.description())){effect.custom_property_interval_values = previous_effect.custom_property_interval_values.clone();+ effect.timing = effect.timing.or(previous_effect.timing);}}}@@ -774,84 +577,62 @@ impl AnimationEffectDescriptions {.map_or(&[], |(_, effects)| effects)}- /// Whether one of an element's lists describes exactly these versions of the effects, in this- /// order. Every change that moves what a description says moves its effect's generation.- #[cfg(test)]- #[must_use]- pub(crate) fn describe(- &self,+ /// One of an element's effects in one of its lists, by its description.+ fn effect_mut(+ &mut self,node: StyleNodeID,slot: AnimationSlot,- versions: &[FfiAnimationEffectVersion],- ) -> bool {- let effects = self.effects(node, slot);- effects.len() == versions.len()- && effects- .iter()- .zip(versions)- .all(|(effect, version)| effect.identity == version.identity && effect.generation == version.generation)+ mut matches: impl FnMut(&EffectDescription) -> bool,+ ) -> Option<&mut PublishedEffect> {+ self.rows+ .get_mut(&node)+ .and_then(|lists| lists.iter_mut().find(|(list_slot, _)| *list_slot == slot))+ .and_then(|(_, effects)| effects.iter_mut().find(|effect| matches(effect)))}- /// 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 none for an unresolved progress, which samples nothing. An effect the list does not- /// describe keeps nothing, and samples nothing either.- ///- /// # Safety- /// The linear points `easing` names must be live.- pub(crate) unsafe fn time_effect(+ /// Keeps `timing`, 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 none for an unresolved progress, which samples nothing. An effect the list does not describe+ /// keeps nothing, and samples nothing either.+ pub(crate) fn time_effect(&mut self,node: StyleNodeID,slot: AnimationSlot,- identity: u64,- timing: &EffectTimingSnapshot,- easing: &FfiEasingDescriptor,+ description: &Arc<EffectDescription>,+ timing: CompactEffectTiming,) -> Option<f64> {- let effect = self- .rows- .get_mut(&node)- .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) });- if !unchanged {- effect.timing = Some(EffectTiming {- timing,- easing: unsafe { Easing::from_descriptor(easing) },- });- }- effect.timing.as_ref().expect("the timing was kept above").key()+ let effect = self.effect_mut(node, slot, |effect| std::ptr::eq(effect, &raw const **description))?;+ effect.timing = Some(timing);+ effect.key()}/// Keeps `timing`, what the host sampled one of an element's described effects with where it sampled/// without asking the engine. An effect the list does not describe keeps nothing.- pub(crate) fn keep_timing(&mut self, node: StyleNodeID, slot: AnimationSlot, identity: u64, timing: EffectTiming) {- if let Some(effect) = self- .rows- .get_mut(&node)- .and_then(|lists| lists.iter_mut().find(|(list_slot, _)| *list_slot == slot))- .and_then(|(_, effects)| effects.iter_mut().find(|effect| effect.identity == identity))- {+ pub(crate) fn keep_timing(+ &mut self,+ node: StyleNodeID,+ slot: AnimationSlot,+ identity: AnimationEffectId,+ timing: CompactEffectTiming,+ ) {+ if let Some(effect) = self.effect_mut(node, slot, |effect| effect.identity == identity) {effect.timing = Some(timing);}}- /// 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: &EffectTimingSnapshot) {+ /// Has one of an element's described effects that the host sampled before take `timing`: 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: AnimationEffectId,+ timing: &EffectTimingSnapshot,+ ) {if let Some(kept) = self- .rows- .get_mut(&node)- .and_then(|lists| lists.iter_mut().find(|(list_slot, _)| *list_slot == 0))- .and_then(|(_, effects)| effects.iter_mut().find(|effect| effect.identity == identity))+ .effect_mut(node, 0, |effect| effect.identity == identity).and_then(|effect| effect.timing.as_mut()){- kept.timing = CompactEffectTiming::from(timing);+ *kept = CompactEffectTiming::from(timing);}}@@ -862,206 +643,48 @@ impl AnimationEffectDescriptions {}}-/// The versions of the effects each of an element's lists holds as the host described them to the engine, which the-/// host follows over every description it writes and every identity a transaction releases, as the engine retires the-/// node's lists then, so it knows without asking whether the engine describes a list already.-#[derive(Default)]-pub(crate) struct DescribedVersions {- rows: HashMap<StyleNodeID, Vec<DescribedList>>,-}--/// The identity and generation of each effect one of an element's lists holds, in composite order.-type DescribedList = (AnimationSlot, Box<[(u64, u64)]>);--impl DescribedVersions {- /// The bytes the versions hold on the heap.- pub(crate) fn heap_size(&self) -> usize {- use crate::heap_size::{map_bytes, vec_bytes};- map_bytes(&self.rows)- + self- .rows- .values()- .map(|lists| {- vec_bytes(lists)- + lists- .iter()- .map(|(_, versions)| size_of_val::<[(u64, u64)]>(versions))- .sum::<usize>()- })- .sum::<usize>()- }-- /// Follows the host describing `effects` as one of `node`'s lists.- pub(crate) fn follow(&mut self, node: StyleNodeID, slot: AnimationSlot, effects: &[PublishedEffect]) {- let lists = self.rows.entry(node).or_default();- lists.retain(|(list_slot, _)| *list_slot != slot);- if !effects.is_empty() {- lists.push((- slot,- effects- .iter()- .map(|effect| (effect.identity, effect.generation))- .collect(),- ));- }- if lists.is_empty() {- self.rows.remove(&node);- }- }-- /// Whether the engine describes one of `node`'s lists as exactly these versions: every change that moves what a- /// description says moves its effect's generation.- pub(crate) fn describe(- &self,- node: StyleNodeID,- slot: AnimationSlot,- versions: &[FfiAnimationEffectVersion],- ) -> bool {- let described = self- .rows- .get(&node)- .and_then(|lists| lists.iter().find(|(list_slot, _)| *list_slot == slot))- .map_or(&[][..], |(_, described)| described);- described.len() == versions.len()- && described- .iter()- .zip(versions)- .all(|(&(identity, generation), version)| {- identity == version.identity && generation == version.generation- })- }-- /// Forgets the lists of the nodes a transaction retired, whose identities it `released`.- pub(crate) fn forget(&mut self, released: &[u32]) {- if self.rows.is_empty() {- return;- }- for node in released.iter().filter_map(|&node| StyleNodeID::from_raw(node)) {- self.rows.remove(&node);- }- }-}--/// Whether `easing` is the function `descriptor` describes.-///-/// # Safety-/// The linear points `descriptor` names must be live.-unsafe fn easing_is(easing: &Easing, descriptor: &FfiEasingDescriptor) -> bool {- match (easing, descriptor.kind) {- (Easing::Linear(points), FfiEasingKind::Linear) => {- points.len() == descriptor.linear_point_count- && (points.is_empty()- || points.as_slice() == unsafe { ak::slice_from_raw_parts(descriptor.linear_points, points.len()) })- }- (Easing::CubicBezier { x1, y1, x2, y2 }, FfiEasingKind::CubicBezier) => {- [*x1, *y1, *x2, *y2] == [descriptor.x1, descriptor.y1, descriptor.x2, descriptor.y2]- }- (- Easing::Steps {- interval_count,- position,- },- FfiEasingKind::Steps,- ) => *interval_count == descriptor.interval_count && *position == descriptor.step_position,- _ => false,- }-}-#[cfg(test)]mod tests {use super::*;- fn effect(identity: u64, generation: u64) -> FfiPublishedAnimationEffect {- FfiPublishedAnimationEffect {- identity,- generation,- is_transition: false,- has_resource_context: false,- resource_context_is_origin_clean: false,- first_keyframe: 0,- keyframe_count: 0,- base_url_offset: 0,- base_url_length: 0,- reversing_adjusted_start_value: std::ptr::null(),- reversing_shortening_factor: 1.0,- }- }-- /// The engine's descriptions, and the host's record of what it described, which must answer alike.- #[derive(Default)]- struct Described {- rows: AnimationEffectDescriptions,- host: DescribedVersions,- }-- impl Described {- fn describe(&self, node: StyleNodeID, slot: AnimationSlot, versions: &[FfiAnimationEffectVersion]) -> bool {- let described = self.rows.describe(node, slot, versions);- assert_eq!(described, self.host.describe(node, slot, versions));- described- }-- fn effects(&self, node: StyleNodeID, slot: AnimationSlot) -> &[PublishedEffect] {- self.rows.effects(node, slot)- }-- fn retire(&mut self, node: StyleNodeID) {- self.rows.retire(node);- self.host.forget(&[node.raw()]);- }+ fn effect(identity: u64) -> PublishedEffect {+ PublishedEffect::new(Arc::new(EffectDescription::new(AnimationEffectId(identity))))}- fn set(- descriptions: &mut Described,- node: StyleNodeID,- slot: AnimationSlot,- effects: &[FfiPublishedAnimationEffect],- ) {- let buffers = PublishedEffectBuffers {- effects,- keyframes: &[],- declarations: &[],- custom_declarations: &[],- linear_points: &[],- base_url_bytes: &[],- };- let effects = unsafe { buffers.effects() };- descriptions.host.follow(node, slot, &effects);- descriptions.rows.set(node, slot, effects);- }-- fn version(identity: u64, generation: u64) -> FfiAnimationEffectVersion {- FfiAnimationEffectVersion { identity, generation }+ #[test]+ fn an_empty_list_drops_the_row() {+ let node = StyleNodeID::from_raw(1).unwrap();+ let mut descriptions = AnimationEffectDescriptions::default();+ descriptions.set(node, 0, Box::new([effect(7), effect(9)]));+ assert_eq!(descriptions.effects(node, 0).len(), 2);+ assert!(descriptions.effects(node, 2).is_empty());+ descriptions.set(node, 0, Box::new([]));+ assert!(descriptions.rows.is_empty());}#[test]- fn a_list_describes_the_versions_it_was_published_for() {+ fn an_effect_the_list_held_already_keeps_its_timing() {let node = StyleNodeID::from_raw(1).unwrap();- let mut descriptions = Described::default();- set(&mut descriptions, node, 0, &[effect(7, 1), effect(9, 3)]);- assert!(descriptions.describe(node, 0, &[version(7, 1), version(9, 3)]));- assert!(!descriptions.describe(node, 0, &[version(7, 2), version(9, 3)]));- assert!(!descriptions.describe(node, 0, &[version(9, 3), version(7, 1)]));- assert!(!descriptions.describe(node, 0, &[version(7, 1)]));- assert!(!descriptions.describe(node, 2, &[version(7, 1), version(9, 3)]));- assert!(descriptions.describe(node, 2, &[]));-- set(&mut descriptions, node, 0, &[]);- assert!(descriptions.rows.rows.is_empty());- assert!(descriptions.host.rows.is_empty());+ let mut descriptions = AnimationEffectDescriptions::default();+ let kept = effect(7);+ let kept_description = kept.description().clone();+ descriptions.set(node, 0, Box::new([kept]));+ let timing = CompactEffectTiming::from(&crate::animations::snapshot::EffectTimingSnapshot::default());+ descriptions.keep_timing(node, 0, AnimationEffectId(7), timing);+ descriptions.set(node, 0, Box::new([PublishedEffect::new(kept_description), effect(9)]));+ assert_eq!(descriptions.effects(node, 0)[0].timing, Some(timing));+ assert_eq!(descriptions.effects(node, 0)[1].timing, None);}#[test]fn a_retired_identity_holds_no_descriptions_when_reissued() {let node = StyleNodeID::from_raw(1).unwrap();- let mut descriptions = Described::default();- set(&mut descriptions, node, 0, &[effect(7, 1)]);- set(&mut descriptions, node, 3, &[effect(8, 1)]);+ let mut descriptions = AnimationEffectDescriptions::default();+ descriptions.set(node, 0, Box::new([effect(7)]));+ descriptions.set(node, 3, Box::new([effect(8)]));descriptions.retire(node);assert!(descriptions.effects(node, 0).is_empty());assert!(descriptions.effects(node, 3).is_empty());- assert!(descriptions.rows.rows.is_empty());- assert!(descriptions.host.rows.is_empty());- assert!(descriptions.describe(node, 0, &[]));+ assert!(descriptions.rows.is_empty());}}diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rsindex c3bea75ef9c..6fca05c3d5e 100644--- a/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs+++ b/Libraries/LibWeb/Rust/src/css/style/engine_calls.rs@@ -125,6 +125,12 @@ pub(crate) enum EngineWrite {slot: super::animations::AnimationSlot,effects: Box<[super::effect_descriptions::PublishedEffect]>,},+ /// The CSS animations one of an element's animation lists holds, in its order.+ CssDefinedAnimations {+ node: StyleNodeID,+ slot: super::animations::AnimationSlot,+ animations: Box<[super::animations::CssDefinedAnimation]>,+ },/// The timing the host sampled each of an element's own effects with, by identity, where it sampled without asking.AnimationEffectTimings {node: StyleNodeID,@@ -262,6 +268,9 @@ impl EngineWrite {Self::AnimationEffectDescriptions { node, slot, effects } => {engine.animation_effect_descriptions.set(node, slot, effects);}+ Self::CssDefinedAnimations { node, slot, animations } => {+ engine.set_element_css_defined_animations(node, slot, animations);+ }Self::AnimationEffectTimings { node, timings } => {for (identity, timing) in timings {engine@@ -897,8 +906,6 @@ pub(crate) struct EngineMemo {pub(crate) held: std::cell::RefCell<HeldEnvironments>,/// The element style inputs the engine defers.pub(crate) deferred: std::cell::RefCell<DeferredInputs>,- /// The versions of the animation effects the host described to the engine.- pub(crate) described: std::cell::RefCell<super::effect_descriptions::DescribedVersions>,/// The transition baselines the host recorded in the engine.pub(crate) baselines: std::cell::RefCell<super::TransitionBaselines>,/// The atoms the host interned for the engine.@@ -934,7 +941,6 @@ impl EngineMemo {let bytes = size_of::<Memo<*const c_void>>()+ self.held.borrow().heap_size()+ self.deferred.borrow().heap_size()- + self.described.borrow().heap_size()+ self.baselines.borrow().heap_size()+ self.atoms.borrow().heap_size()+ vec_bytes(&unpublished.backing_elements)@@ -977,7 +983,6 @@ impl EngineMemo {return;}self.held.borrow_mut().forget(released);- self.described.borrow_mut().forget(released);self.baselines.borrow_mut().forget(released);self.identities.borrow_mut().release(released);}@@ -1012,7 +1017,6 @@ impl Default for EngineMemo {views: Memo::new(std::ptr::null()),held: Default::default(),deferred: Default::default(),- described: Default::default(),baselines: Default::default(),atoms: Default::default(),identities: Default::default(),diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rsindex ce6cdabe0db..c72f9fd897a 100644--- a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs+++ b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs@@ -388,13 +388,13 @@ impl super::StyleEngine {.iter().flat_map(|keyframe| effect.declarations_of(keyframe)).map(|declaration| declaration.property_id);- match timing.key_at(samples).ok_or(NeedsHost)? {+ match timing+ .key_at(effect.timing_function.as_easing(), samples)+ .ok_or(NeedsHost)?+ {Some(current_key) => {- composed.push(anim::FfiSampledAnimationEffect {- effect: anim::FfiAnimationPreparationEffect {- identity: effect.identity,- generation: effect.generation,- },+ composed.push(anim::SampledAnimationEffect {+ description: effect.description().clone(),current_key,});composed_properties.extend(properties);@@ -606,7 +606,7 @@ impl super::StyleEngine {record_dependencies: true,style_node: node.raw(),pseudo_kind: crate::css::cascaded_properties::NO_PSEUDO_ELEMENT,- effects: HostSampledEffects::none(),+ effects: HostSampledEffects::new(),longhands,has_animated_overlay: true,current_color: working_set_current_color(longhands, Some(overlay)),diff --git a/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs b/Libraries/LibWeb/Rust/src/css/style/host_atoms.rsindex a4571cb4156..8732de4249e 100644--- a/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs+++ b/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs@@ -477,6 +477,7 @@ pub(crate) fn note_attr_names_read_by_change(host: &DocumentHost, change: &Arena| Engine::UnparkRandomBaseValues { .. }| Engine::NoteCustomPropertyEnvironment { .. }| Engine::AnimationKeyframes { .. }+ | Engine::CssDefinedAnimations { .. }| Engine::AnimationEffectTimings { .. } => {}},_ => {}diff --git a/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs b/Libraries/LibWeb/Rust/src/css/style/hover_lane.rsindex 54183fe975b..511ab1935ae 100644--- a/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs+++ b/Libraries/LibWeb/Rust/src/css/style/hover_lane.rs@@ -921,9 +921,9 @@ pub unsafe extern "C" fn style_engine_adopt_lane_transitions(adopt: unsafe extern "C" fn(context: *mut std::ffi::c_void,node: u32,- cancelled: *const u64,+ cancelled: *const crate::animations::effect::AnimationEffectId,cancelled_count: usize,- seen: *const u64,+ seen: *const crate::animations::effect::AnimationEffectId,seen_count: usize,transitions: *const crate::css::transition::FfiLaneTransition,transition_count: usize,diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rsindex 80e8971c623..d83b1b3bd69 100644--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs@@ -1470,14 +1470,13 @@ impl RetainedState {/// Record the CSS animations the host holds for one of an element's animation lists, in the/// order it holds them: each one's name, and the definition the last plan applied to it.- pub fn set_element_css_defined_animations(+ pub(crate) fn set_element_css_defined_animations(&mut self,node: StyleNodeID,slot: animations::AnimationSlot,- names: Box<[crate::css::css_string::CssString]>,- definitions: Box<[animations::HeldAppliedAnimationDefinition]>,+ animations: Box<[animations::CssDefinedAnimation]>,) {- self.css_defined_animations.set(node, slot, names, definitions);+ self.css_defined_animations.set(node, slot, animations);}/// The CSS animations the host holds for one of an element's animation lists.@@ -1530,7 +1529,7 @@ impl RetainedState {pub(crate) fn refresh_element_animation_effect_timing(&mut self,node: StyleNodeID,- identity: u64,+ identity: crate::animations::effect::AnimationEffectId,timing: &crate::animations::snapshot::EffectTimingSnapshot,) {self.animation_effect_descriptions@@ -1540,21 +1539,15 @@ impl RetainedState {/// Keeps the timing the host samples one of an element's described effects with, and answers the/// key the effect samples its keyframes at (see/// [`super::effect_descriptions::AnimationEffectDescriptions::time_effect`]).- ///- /// # Safety- /// The linear points `easing` names must be live.- pub(crate) unsafe fn time_element_animation_effect(+ pub(crate) fn time_element_animation_effect(&mut self,node: StyleNodeID,slot: animations::AnimationSlot,- identity: u64,- timing: &crate::animations::snapshot::EffectTimingSnapshot,- easing: &crate::css::easing::FfiEasingDescriptor,+ description: &std::sync::Arc<super::effect_descriptions::EffectDescription>,+ timing: crate::animations::snapshot::CompactEffectTiming,) -> Option<f64> {- unsafe {- self.animation_effect_descriptions- .time_effect(node, slot, identity, timing, easing)- }+ self.animation_effect_descriptions+ .time_effect(node, slot, description, timing)}pub fn set_tree_scope_root(&mut self, tree_scope: TreeScopeID, root: StyleNodeID) {diff --git a/Libraries/LibWeb/Rust/src/css/style/publication.rs b/Libraries/LibWeb/Rust/src/css/style/publication.rsindex 75cf84f496b..1975511c4fd 100644--- a/Libraries/LibWeb/Rust/src/css/style/publication.rs+++ b/Libraries/LibWeb/Rust/src/css/style/publication.rs@@ -149,19 +149,20 @@ impl RetainedState {/// The animation plan `record` decides for an element, or for its pseudo-element `pseudo_kind`,/// where applying it would change the animations they run: none where it would not, or where- /// the record installs no `animation-name`. The definitions borrow the record's values.+ /// the record installs no `animation-name`. The definitions borrow the record's values, and the+ /// keyframe sets the plan holds.pub(crate) fn animation_plan_of_record(&self,node: StyleNodeID,pseudo_kind: u8,record: &std::sync::Arc<super::pipeline::Record>,- ) -> Option<smallvec::SmallVec<[crate::css::style_compute::FfiComputedAnimation; 1]>> {+ ) -> Option<crate::css::style_compute::AnimationPlan> {let longhands = StyleRecordView::of_host_record(record).longhands();let declaration_scope = self.animation_name_declaration_scope_of(node, pseudo_kind, record)?;let existing_animations =self.element_css_defined_animations(node, crate::css::style_compute::animation_slot(pseudo_kind));let element_tree_scope = self.element_tree_scope(node);- let mut definitions = smallvec::SmallVec::new();+ let mut plan = crate::css::style_compute::AnimationPlan::default();crate::css::style_compute::build_computed_animation_list(longhands,existing_animations,@@ -169,9 +170,9 @@ impl RetainedState {self.animation_keyframes().resolve(declaration_scope, element_tree_scope, name)},- &mut definitions,+ &mut plan,);- (!animations::plan_changes_nothing(&definitions, existing_animations)).then_some(definitions)+ (!animations::plan_changes_nothing(&plan.definitions, existing_animations)).then_some(plan)}/// Whether installing the `new` record the engine derived for an element, in place of the@@ -450,10 +451,8 @@ impl RetainedState {.iter().any(|effect| {effect.keyframes().iter().any(|keyframe| {- keyframe- .easing_value- .as_ref()- .is_some_and(|value| matches!(value.data(), StyleValueData::Unresolved { .. }))+ matches!(&keyframe.easing, crate::animations::keyframes::KeyframeEasing::Value(value)+ if matches!(value.data(), StyleValueData::Unresolved { .. }))})});diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 7decf2fb937..2eb123f606c 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -2273,8 +2273,8 @@ pub struct FfiComputedAnimation {/// The index, in the list of CSS animations the host already holds for this element or/// pseudo-element, of the animation this definition claims, or -1 where it asks for a new one.pub matched_existing_index: i32,- /// The host's keyframe set for this definition's name, from the `@keyframes` the scopes in the- /// name's chain published, or null where none of them defines it.+ /// The `KeyframeSet` for this definition's name, from the `@keyframes` the scopes in the name's+ /// chain published, which the plan holds, or null where none of them defines it.pub keyframe_set: *const c_void,}@@ -5405,8 +5405,7 @@ fn calculated_offset(value: &StyleValueData) -> *const c_void {}/// The pixels of a computed length-percentage, resolving its percentages against `basis`.-#[unsafe(no_mangle)]-pub extern "C" fn rust_length_percentage_px(value: &StyleValueData, basis: f64) -> f64 {+pub(crate) fn length_percentage_px(value: &StyleValueData, basis: f64) -> f64 {crate::css::computed_value_views::LengthPercentageRef::over(value).to_px(CssPixels::nearest_value_for(basis)).to_double()@@ -5414,8 +5413,7 @@ pub extern "C" fn rust_length_percentage_px(value: &StyleValueData, basis: f64)/// Whether a computed length-percentage is a length plus a percentage of what it resolves against, which only a/// calculation may not be.-#[unsafe(no_mangle)]-pub extern "C" fn rust_length_percentage_is_linear(value: &StyleValueData) -> bool {+pub(crate) fn length_percentage_is_linear(value: &StyleValueData) -> bool {match value {StyleValueData::Calculated(calculated) => calculated.rust_calculation.node().is_linear_in_percentages(),_ => true,@@ -5464,9 +5462,8 @@ fn view_timeline_inset(value: Option<&StyleValueData>) -> FfiViewTimelineInset {}}-/// The insets a computed `view-timeline-inset` item describes, for a timeline the host builds from script.-#[unsafe(no_mangle)]-pub extern "C" fn rust_view_timeline_inset(value: &StyleValueData) -> FfiViewTimelineInset {+/// The insets a computed `view-timeline-inset` item describes, for a timeline script builds.+pub(crate) fn script_view_timeline_inset(value: &StyleValueData) -> FfiViewTimelineInset {let value = match value {StyleValueData::ValueList { values, separator, .. } if *separator == 1 => values.as_slice()[0].data(),value => value,@@ -5626,8 +5623,7 @@ pub extern "C" fn rust_animation_values_declare_timelines(}/// Whether a parsed `view-timeline-inset` value has a length in a unit that is not absolute.-#[unsafe(no_mangle)]-pub extern "C" fn rust_view_timeline_inset_has_relative_length(value: &StyleValueData) -> bool {+pub(crate) fn view_timeline_inset_has_relative_length(value: &StyleValueData) -> bool {let is_absolute = |unit: u8| {matches!(length_unit_kinds().get(unit as usize),@@ -5775,12 +5771,7 @@ pub struct FfiAnimationRangeEdge {/// The edge a computed `animation-range-start` or `animation-range-end` value with a single item describes, for a range/// script sets. Answers false where the value has more than one item.-#[unsafe(no_mangle)]-pub extern "C" fn rust_animation_range_edge(- value: &StyleValueData,- is_end: bool,- out: &mut FfiAnimationRangeEdge,-) -> bool {+pub(crate) fn rust_animation_range_edge(value: &StyleValueData, is_end: bool, out: &mut FfiAnimationRangeEdge) -> bool {let item = match value {StyleValueData::ValueList { values, separator, .. } if *separator == 1 => match values.as_slice() {[item] => item.data(),@@ -5850,12 +5841,12 @@ fn settled_animation_plan(node: crate::css::style::tree::StyleNodeID,pseudo_kind: u8,record: &std::sync::Arc<crate::css::style::pipeline::Record>,-) -> Option<(smallvec::SmallVec<[FfiComputedAnimation; 1]>, bool)> {- let definitions = style_engine.animation_plan_of_record(node, pseudo_kind, record)?;+) -> Option<(AnimationPlan, bool)> {+ let plan = style_engine.animation_plan_of_record(node, pseudo_kind, record)?;let longhands = crate::css::style::StyleRecordView::of_host_record(record).longhands();let in_display_none_subtree =- in_display_none_subtree_for_animations(style_engine, node, pseudo_kind, longhands, &definitions);- Some((definitions, in_display_none_subtree))+ in_display_none_subtree_for_animations(style_engine, node, pseudo_kind, longhands, &plan.definitions);+ Some((plan, in_display_none_subtree))}/// Hands `apply` the animation plan of an element, or of its pseudo-element `pseudo_kind`, whose@@ -5896,19 +5887,18 @@ pub unsafe extern "C" fn rust_settled_animation_plan(return;}// Applying the plan publishes the element's animations to the engine, so nothing of the- // engine is borrowed while the host applies it: the definitions only point into the record.- let Some((definitions, in_display_none_subtree)) =- crate::css::style::engine_calls::with_engine(read, host, |engine| {- settled_animation_plan(engine, node, pseudo_kind, &record)- })- else {+ // engine is borrowed while the host applies it: the definitions only point into the record and+ // the keyframe sets the plan holds.+ let Some((plan, in_display_none_subtree)) = crate::css::style::engine_calls::with_engine(read, host, |engine| {+ settled_animation_plan(engine, node, pseudo_kind, &record)+ }) else {return;};unsafe {apply(context,- definitions.as_ptr(),- definitions.len(),+ plan.definitions.as_ptr(),+ plan.definitions.len(),in_display_none_subtree,);}@@ -5925,14 +5915,26 @@ pub(crate) fn animation_names_declare_css_animations(names: &RetainedStyleValueD.any(|name| !matches!(name.data(), StyleValueData::Keyword { keyword } if *keyword == keyword::NONE))}+/// The animation definitions a record decides for an element or pseudo-element, with the keyframe+/// sets they name, which the plan holds while the host applies it.+#[derive(Default)]+pub(crate) struct AnimationPlan {+ pub(crate) definitions: smallvec::SmallVec<[FfiComputedAnimation; 1]>,+ keyframe_sets: smallvec::SmallVec<[std::sync::Arc<crate::animations::keyframes::KeyframeSet>; 1]>,+}+// https://drafts.csswg.org/css-values-4/#linked-properties// https://drafts.csswg.org/css-animations-1/#animations-pub(crate) fn build_computed_animation_list(+pub(crate) fn build_computed_animation_list<'k>(longhands: crate::css::style::ViewLonghands<'_>,existing_animations: &[crate::css::style::animations::CssDefinedAnimation],- resolve_keyframes: impl Fn(&[u16]) -> Option<usize>,- animations: &mut smallvec::SmallVec<[FfiComputedAnimation; 1]>,+ resolve_keyframes: impl Fn(&[u16]) -> Option<&'k std::sync::Arc<crate::animations::keyframes::KeyframeSet>>,+ plan: &mut AnimationPlan,) {+ let AnimationPlan {+ definitions: animations,+ keyframe_sets,+ } = plan;use crate::css::property_metadata::property_id as prop;let name_values = computed_value_list(longhands, prop::ANIMATION_NAME);@@ -6006,7 +6008,10 @@ pub(crate) fn build_computed_animation_list(range_end_percentage,range_end_calculated,matched_existing_index: crate::css::style::animations::NO_MATCHED_ANIMATION,- keyframe_set: resolve_keyframes(name.units()).map_or(std::ptr::null(), |set| set as *const c_void),+ keyframe_set: resolve_keyframes(name.units()).map_or(std::ptr::null(), |set| {+ keyframe_sets.push(set.clone());+ std::sync::Arc::as_ptr(set).cast()+ }),});}@@ -6433,17 +6438,6 @@ 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 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.-#[repr(C)]-pub struct FfiSampledAnimationEffect {- pub identity: u64,- pub generation: u64,- pub timing: crate::animations::snapshot::EffectTimingSnapshot,- pub easing: crate::css::easing::FfiEasingDescriptor,-}-/// The length-resolution contexts keyframe values compute in: a font's, a line height's, and every/// other longhand's.#[repr(C)]@@ -6462,8 +6456,12 @@ pub struct FfiHostAnimationSample {pub style_node: u32,/// The pseudo-element sampled, or `NO_PSEUDO_ELEMENT` for the element itself.pub pseudo_kind: u8,- pub effects: *const FfiSampledAnimationEffect,+ /// The element's effects that target what is sampled, in composite order, which the host describes to the engine+ /// and samples where they have an animation.+ pub effects: *const crate::animations::ffi::FfiSampledEffect,pub effect_count: usize,+ /// The element's animations, which follow what the host published of their effects to the engine.+ pub animations: *mut crate::animations::element_animations::ElementAnimations,/// The style record whose longhands the working set reads, which the animations compose over.pub record: *const c_void,/// The working set's overlay before this sample, or null.@@ -6585,33 +6583,23 @@ pub(crate) fn animation_length_resolution_context(}}-/// The effects a host samples, whose easings stay live for as long as the effects are borrowed.-#[derive(Clone, Copy)]-pub(crate) struct HostSampledEffects<'a>(&'a [FfiSampledAnimationEffect]);--impl<'a> HostSampledEffects<'a> {- /// # Safety- /// The linear points each effect's easing names must be live for `'a`.- pub(crate) unsafe fn new(effects: &'a [FfiSampledAnimationEffect]) -> Self {- Self(effects)- }-- pub(crate) fn none() -> Self {- Self(&[])- }-- pub(crate) fn as_slice(&self) -> &'a [FfiSampledAnimationEffect] {- self.0- }+/// One effect the host samples: its description, and the timing the host samples it with, from which the engine+/// computes how far along it is on the scale the host keys keyframes by.+pub(crate) struct HostSampledEffect {+ pub(crate) description: std::sync::Arc<crate::css::style::effect_descriptions::EffectDescription>,+ pub(crate) timing: crate::animations::snapshot::CompactEffectTiming,}+/// The effects a host samples on an element, in composite order.+pub(crate) type HostSampledEffects = smallvec::SmallVec<[HostSampledEffect; 4]>;+/// What a sample reads of the element it samples and of the working set it samples over.pub(crate) struct AnimationSampleInput<'a> {pub(crate) style_node: u32,pub(crate) record_dependencies: bool,/// The pseudo-element sampled, or `NO_PSEUDO_ELEMENT` for the element itself.pub(crate) pseudo_kind: u8,- pub(crate) effects: HostSampledEffects<'a>,+ pub(crate) effects: HostSampledEffects,/// The working set's longhands, which the animations compose over.pub(crate) longhands: crate::css::style::ViewLonghands<'a>,/// Whether the working set held an overlay before this sample.@@ -6710,18 +6698,52 @@ impl AnimationSampleHost for HostSampleCallbacks {}impl FfiHostAnimationSample {- /// What the sample reads, and the callbacks through which it asks the host.+ /// Publishes the descriptions of the effects the sample reads to `host`'s engine, where they differ from those the+ /// host last published for the element or pseudo-element it samples, and answers the effects it samples.+ ///+ /// # Safety+ /// The effects, animations and element animations the input names must be live for the call.+ unsafe fn publish_effect_descriptions(&self, host: &crate::render_state::DocumentHost) -> HostSampledEffects {+ // SAFETY: Guaranteed by the caller.+ let described = unsafe {+ crate::animations::ffi::describe_sampled_effects(ak::slice_from_raw_parts(self.effects, self.effect_count))+ };+ let Some(node) = crate::css::style::tree::StyleNodeID::from_raw(self.style_node) else {+ return described.sampled;+ };+ let slot = animation_slot(self.pseudo_kind);+ // SAFETY: Guaranteed by the caller.+ let animations = unsafe { &mut *self.animations };+ if animations.publish_effect_descriptions(+ crate::animations::element_animations::AnimationOwnerSlot(slot),+ &described.descriptions,+ ) {+ host.queue_change(crate::render_state::ArenaChange::Engine(+ crate::css::style::engine_calls::EngineWrite::AnimationEffectDescriptions {+ node,+ slot,+ effects: described+ .descriptions+ .into_iter()+ .map(crate::css::style::effect_descriptions::PublishedEffect::new)+ .collect(),+ },+ ));+ }+ described.sampled+ }++ /// What the sample reads, with `effects`, the effects it samples, and the callbacks through which it asks the host.////// # Safety/// Every pointer and callback the input names must be live for the sample, and nothing but the/// sample may write the working set's overlay while it runs.- unsafe fn adopt(&self) -> (AnimationSampleInput<'_>, HostSampleCallbacks) {+ unsafe fn adopt(&self, effects: HostSampledEffects) -> (AnimationSampleInput<'_>, HostSampleCallbacks) {// SAFETY: Guaranteed by the caller.- let (longhands, animated_overlay, effects, environment, style_record, inheritance_parent_record) = unsafe {+ let (longhands, animated_overlay, environment, style_record, inheritance_parent_record) = unsafe {(crate::css::style::ViewLonghands::of_raw_record(self.record),self.animated_overlay.cast::<AnimatedOverlay>().as_ref(),- HostSampledEffects::new(ak::slice_from_raw_parts(self.effects, self.effect_count)),&*self.environment,crate::css::style::bridge::retain_host_record(self.style_record),crate::css::style::bridge::retain_host_record(self.inheritance_parent_record),@@ -6781,17 +6803,16 @@ pub unsafe extern "C" fn rust_compute_css_keyframe_values(context: *mut c_void,emit: unsafe extern "C" fn(*mut c_void, usize, u16, *const StyleValueData),) {+ use crate::animations::keyframes::{KeyframeSet, ResourceContext};use crate::css::animation as anim;- use crate::css::style::effect_descriptions::{- PublishedDeclaration, PublishedEffect, PublishedResourceContext, PublishedValue,- };+ use crate::css::style::effect_descriptions::{EffectAnimation, EffectDescription, PublishedEffect};use crate::css::style::engine_calls::{document_host, with_engine};// SAFETY: Guaranteed by the caller.let (host, (sample, mut callbacks), properties) = unsafe {(document_host(input.host),- input.adopt(),+ input.adopt(HostSampledEffects::new()),ak::slice_from_raw_parts(properties, property_count),)};@@ -6804,18 +6825,22 @@ pub unsafe extern "C" fn rust_compute_css_keyframe_values(let value = unsafe {RetainedStyleValueData::from_retained_pointer(crate::css::style_value::retain_style_value(property.value))};- frames[property.keyframe_index].push(PublishedDeclaration {- property_id: property.property_id,- value: PublishedValue::Declared(value),- });+ frames[property.keyframe_index].push((property.property_id, value));}- let resource_context = resource_context.has_value.then(|| PublishedResourceContext {+ let resource_context = resource_context.has_value.then(|| ResourceContext {// SAFETY: The resource context's URL is live for the call.base_url: unsafe { ak::slice_from_raw_parts(resource_context.base_url, resource_context.base_url_length) }.into(),origin_clean: resource_context.origin_clean,});- let effect = PublishedEffect::for_keyframe_computation(frames, resource_context);+ // NB: The keyframes compute as those of an effect of no animation of its own, which the style engine is not told of.+ let mut description = EffectDescription::new(Default::default());+ description.keyframe_set = Some(std::sync::Arc::new(KeyframeSet::for_value_computation(+ frames,+ resource_context,+ )));+ description.animation = EffectAnimation::Animation(crate::animations::easing::CompactEasing::Linear);+ let effect = PublishedEffect::new(std::sync::Arc::new(description));let resolved = with_engine(read, host, |engine| {let (writing_mode, direction) = computed_writing_mode_and_direction(sample.longhands);let conversions = std::cell::RefCell::new(anim::KeyframeConversionCache::new(@@ -6940,7 +6965,9 @@ pub unsafe extern "C" fn rust_sample_animation_effects(use crate::css::style::engine_calls::{document_host, with_engine_and_arena};// SAFETY: Guaranteed by the caller.- let (host, (sample, mut callbacks)) = unsafe { (document_host(input.host), input.adopt()) };+ let host = unsafe { document_host(input.host) };+ // SAFETY: As above.+ let (sample, mut callbacks) = unsafe { input.adopt(input.publish_effect_descriptions(host)) };// The first sample of the transitions a step just started rides the style job that decided the step.if let Some(result) = host.answer_fresh_transition_sample(&sample, &mut callbacks) {return result;@@ -6951,48 +6978,53 @@ 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 of the timing the host samples each effect with.+/// https://drafts.csswg.org/web-animations-1/#commit-computed-styles+/// Sample the effects `input` names onto its working set's overlay as committing computed styles does: each at the key+/// its timing gives with the endpoint-inclusive active interval flag set, from descriptions the sample makes of its own,+/// publishing nothing to the style engine and recording nothing the element's style depends on.////// # Safety-/// The inputs and every value in the descriptions must remain live for the call.+/// As for [`rust_sample_animation_effects`].#[unsafe(no_mangle)]pub unsafe extern "C" fn rust_sample_animation_effects_for_commit_styles(input: &FfiHostAnimationSample,- descriptions: &crate::css::style::bridge::FfiAnimationEffectDescriptions,read: &crate::render_state::BegunRead,) -> FfiHostAnimationSampleResult {- use crate::css::animation as anim;+ use crate::css::style::effect_descriptions::PublishedEffect;use crate::css::style::engine_calls::{document_host, with_engine_and_arena};// SAFETY: Guaranteed by the caller.- let (host, (mut sample, mut callbacks), descriptions) =- unsafe { (document_host(input.host), input.adopt(), descriptions.effects()) };- sample.record_dependencies = false;- let composed = sample- .effects- .as_slice()+ let (host, described) = unsafe {+ (+ document_host(input.host),+ crate::animations::ffi::describe_sampled_effects(ak::slice_from_raw_parts(+ input.effects,+ input.effect_count,+ )),+ )+ };+ let descriptions: Vec<_> = described+ .descriptions+ .iter()+ .cloned()+ .map(PublishedEffect::new)+ .collect();+ let composed: SampledEffects = described+ .sampled.iter()+ .filter(|effect| effect.description.keyframes().len() >= 2).filter_map(|effect| {- let description = descriptions- .iter()- .find(|description| description.identity == effect.identity)?;- 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: timing.endpoint_inclusive_key()?,+ Some(crate::css::animation::SampledAnimationEffect {+ description: effect.description.clone(),+ current_key: effect+ .timing+ .endpoint_inclusive_key(effect.description.timing_function.as_easing())?,})}).collect();+ // SAFETY: Guaranteed by the caller.+ let (mut sample, mut callbacks) = unsafe { input.adopt(described.sampled) };+ sample.record_dependencies = false;let step = with_engine_and_arena(read, host, |engine, arena| {let element_box = crate::layout::node_data::NodeSlotId {index: sample.element_box_slot,@@ -7041,7 +7073,10 @@ pub unsafe extern "C" fn rust_sample_animation_effects_each(// SAFETY: As above.let host = unsafe { document_host(first.host) };// SAFETY: As above.- let mut samples: Vec<_> = inputs.iter().map(|input| unsafe { input.adopt() }).collect();+ let mut samples: Vec<_> = inputs+ .iter()+ .map(|input| unsafe { input.adopt(input.publish_effect_descriptions(host)) })+ .collect();let steps: Vec<_> = with_engine_and_arena(read, host, |engine, arena| {samples.iter_mut()@@ -7160,43 +7195,35 @@ struct ResolvedAnimationSample {composed: SampledEffects,resolved: Box<crate::css::animation::ResolvedAnimationDeclarations>,custom_properties: crate::css::animation::AnimatedCustomProperties,+ /// The effects that custom property intervals were selected from, indexed by each interval's effect index, which+ /// keep the interval values the sample retains.+ interval_effects: Vec<crate::css::style::effect_descriptions::PublishedEffect>,result: FfiHostAnimationSampleResult,}/// The effects the host samples that the sample composes, each at the key its timing gives at the time/// the host sampled its timeline, keeping each timing for a sample at another time.fn host_sampled_effects(input: &AnimationSampleInput, engine: &mut crate::css::style::StyleEngine) -> SampledEffects {- use crate::css::animation as anim;-let Some(node) = crate::css::style::tree::StyleNodeID::from_raw(input.style_node) else {return SampledEffects::new();};let slot = animation_slot(input.pseudo_kind);input.effects- .as_slice().iter().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)- };- let description = engine+ let key = engine.time_element_animation_effect(node, slot, &effect.description, effect.timing);+ let described = engine.element_animation_effects(node, slot).iter()- .find(|description| description.identity == effect.identity);- debug_assert!(description.is_some(), "the host describes every effect it samples");- description- .is_some_and(|description| {- description.generation == effect.generation && description.keyframes().len() >= 2- })- .then_some(anim::FfiSampledAnimationEffect {- effect: anim::FfiAnimationPreparationEffect {- identity: effect.identity,- generation: effect.generation,- },+ .any(|described| std::sync::Arc::ptr_eq(described.description(), &effect.description));+ debug_assert!(described, "the host describes every effect it samples");+ (described && effect.description.keyframes().len() >= 2).then_some(+ crate::css::animation::SampledAnimationEffect {+ description: effect.description.clone(),current_key: key?,- })+ },+ )}).collect()}@@ -7212,7 +7239,7 @@ fn described_effects<'a>(}/// The effects a sample composes, in composite order, each at the key it samples its keyframes at.-pub(crate) type SampledEffects = smallvec::SmallVec<[crate::css::animation::FfiSampledAnimationEffect; 4]>;+pub(crate) type SampledEffects = smallvec::SmallVec<[crate::css::animation::SampledAnimationEffect; 4]>;fn implicit_will_change_properties(descriptions: &[crate::css::style::effect_descriptions::PublishedEffect],@@ -7230,9 +7257,9 @@ fn implicit_will_change_properties(});for effect in applicable_effects {- for &property in effect.target_properties() {+ effect.for_each_animated_longhand(|property| {properties.push(map_logical_alias_to_physical(property, writing_mode, direction));- }+ });}properties.sort_unstable();@@ -7260,7 +7287,11 @@ fn begin_animation_sample(};let pseudo = input.pseudo();let (writing_mode, direction) = computed_writing_mode_and_direction(input.longhands);- let description = |identity| descriptions.iter().find(|description| description.identity == identity);+ let description = |composed: &crate::css::animation::SampledAnimationEffect| {+ descriptions+ .iter()+ .find(|description| std::sync::Arc::ptr_eq(description.description(), &composed.description))+ };let new_implicit_will_change_properties =implicit_will_change_properties(descriptions, timeline_samples, writing_mode, direction);if composed.is_empty() && new_implicit_will_change_properties.is_empty() {@@ -7306,7 +7337,7 @@ fn begin_animation_sample(.iter().filter_map(|composed| {Some(anim::SelectedEffect {- effect: description(composed.effect.identity)?,+ effect: description(composed)?,current_key: composed.current_key,})})@@ -7344,6 +7375,11 @@ fn begin_animation_sample(};declarations};+ let interval_effects = if custom_properties.intervals.is_empty() {+ Vec::new()+ } else {+ selected.iter().map(|selection| selection.effect.clone()).collect()+ };drop(selected);let mut result = FfiHostAnimationSampleResult::with_outcome(if implicit_will_change_entries_changed {Evaluated@@ -7375,6 +7411,7 @@ fn begin_animation_sample(composed,resolved,custom_properties,+ interval_effects,result,})}@@ -7396,6 +7433,7 @@ fn finish_animation_sample(composed,resolved,mut custom_properties,+ interval_effects,mut result,} = sample;let table = input.longhands;@@ -7577,16 +7615,8 @@ fn finish_animation_sample("animation sampling preserves custom property registrations");let registry = engine.custom_property_registry();- let current_effects = described_effects(input, engine);for interval in custom_properties.intervals {- let sampled_effect = composed[interval.effect_index].effect;- let effect = current_effects- .iter()- .find(|effect| {- effect.identity == sampled_effect.identity && effect.generation == sampled_effect.generation- })- .expect("a sampled effect remains published with the same generation");- effect.update_retained_custom_property_interval_values(interval, registry);+ interval_effects[interval.effect_index].update_retained_custom_property_interval_values(interval, registry);}let rows = retained.iter()@@ -7766,19 +7796,6 @@ fn property_affects_font_metrics(property_id: u16) -> bool {|| property_id == crate::css::property_metadata::property_id::LINE_HEIGHT}-#[repr(C)]-pub struct FfiExpandedProperty {- pub property_id: u16,- pub data: *const c_void,-}--#[repr(C)]-pub struct FfiShorthandExpansion {- pub properties: *const FfiExpandedProperty,- pub count: usize,- pub storage: *mut c_void,-}-pub(crate) fn value_is_css_wide_keyword(value: &StyleValueData) -> bool {match value {StyleValueData::Keyword { keyword } => matches!(@@ -7852,51 +7869,6 @@ pub(crate) fn expand_shorthands_with<Sink>(sink(property_id, data, has_style_sheet_context);}-pub struct ShorthandExpansion {- properties: Vec<FfiExpandedProperty>,- _values: Vec<RetainedStyleValueData>,-}--fn expand_shorthands(property_id: u16, data: &RetainedStyleValueData) -> ShorthandExpansion {- let mut properties = Vec::new();- let mut values = Vec::new();- expand_shorthands_with(property_id, data, false, &mut |longhand_id, longhand_data, _| {- let value = longhand_data.clone();- properties.push(FfiExpandedProperty {- property_id: longhand_id,- data: value.pointer().cast(),- });- values.push(value);- });- ShorthandExpansion {- properties,- _values: values,- }-}--/// Expands a declared property into one owned batch of longhand assignments, recursing through-/// shorthand and pending-substitution values.-#[unsafe(no_mangle)]-pub extern "C" fn rust_expand_property_shorthands(- property_id: u16,- data: crate::css::style_value_arc::StyleValueRef<'_>,-) -> FfiShorthandExpansion {- let data = RetainedStyleValueData::from_arc(data.to_arc());- let expansion = Box::new(expand_shorthands(property_id, &data));- let properties = expansion.properties.as_ptr();- let count = expansion.properties.len();- FfiShorthandExpansion {- properties,- count,- storage: Box::into_raw(expansion).cast(),- }-}--#[unsafe(no_mangle)]-pub extern "C" fn rust_shorthand_expansion_destroy(storage: OwnedBox<ShorthandExpansion>) {- drop(storage);-}-mod adjustments;pub(crate) use adjustments::*;diff --git a/Libraries/LibWeb/Rust/src/css/style_value_arc.rs b/Libraries/LibWeb/Rust/src/css/style_value_arc.rsindex 26b5a03ceb1..af8a29d15e3 100644--- a/Libraries/LibWeb/Rust/src/css/style_value_arc.rs+++ b/Libraries/LibWeb/Rust/src/css/style_value_arc.rs@@ -242,25 +242,6 @@ impl Drop for OwnedStyleValue {}}-/// A value C++ lends through the pointer `StyleValueArc::into_raw()` gave it.-#[repr(transparent)]-pub struct StyleValueRef<'a> {- pointer: *const StyleValueData,- lent: std::marker::PhantomData<&'a StyleValueData>,-}--impl StyleValueRef<'_> {- /// A reference of Rust's own to the value.- pub(crate) fn to_arc(&self) -> StyleValueArc {- assert!(!self.pointer.is_null(), "C++ lends a live value");- // SAFETY: The value is live while it is lent.- unsafe {- StyleValueArc::increment_strong_count(self.pointer);- StyleValueArc::from_raw(self.pointer)- }- }-}-#[cfg(test)]mod tests {use super::StyleValueArc;diff --git a/Libraries/LibWeb/Rust/src/css/transition.rs b/Libraries/LibWeb/Rust/src/css/transition.rsindex 696acb6657c..164df2dead5 100644--- a/Libraries/LibWeb/Rust/src/css/transition.rs+++ b/Libraries/LibWeb/Rust/src/css/transition.rs@@ -733,11 +733,10 @@ fn same_custom_properties(/// A transition an element runs, as it stands at the time a step decides at: one the host runs, as the engine's/// description of its effect says, or one a lane's hover started, as the lane runs it.struct RunningTransitionAt {- /// The identity and generation of its effect, which a sample of it composes: the host's, or the lane's own.- identity: u64,- generation: u64,+ /// The description of its effect, which a sample of it composes: the host's, or the lane's own.+ description: std::sync::Arc<crate::css::style::effect_descriptions::EffectDescription>,/// The identity of the host's effect, where the host runs it.- host_identity: Option<u64>,+ host_identity: Option<crate::animations::effect::AnimationEffectId>,property_id: u16,/// The key its keyframes are sampled at then, or none once it has ended.key: Option<f64>,@@ -775,10 +774,10 @@ fn host_transitions_at(effects.iter().filter_map(|effect| {- if !effect.is_transition {+ if !effect.is_transition() {return None;}- let Some(timing) = effect.timing.clone() else {+ let Some(timing) = effect.effect_timing() else {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.@@ -806,10 +805,7 @@ fn host_transition_at(if timing.timing.playback().playback_rate != 1.0 {return Err("a transition that runs at another rate");}- let reversing = effect- .reversing- .as_ref()- .ok_or("a transition the host has not described")?;+ let reversing = effect.reversing().ok_or("a transition the host has not described")?;let key = timing.key_at(samples).ok_or("a transition on a timeline a tick does not move")?;@@ -819,8 +815,7 @@ fn host_transition_at(let (property_id, start_value, end_value) =transition_values(effect).ok_or("a transition the host has not described")?;Ok(RunningTransitionAt {- identity: effect.identity,- generation: effect.generation,+ description: effect.description().clone(),host_identity: Some(effect.identity),property_id,key,@@ -840,16 +835,19 @@ fn host_transition_at(fn transition_values(effect: &crate::css::style::effect_descriptions::PublishedEffect,) -> Option<(u16, *const StyleValueData, *const StyleValueData)> {- use crate::css::style::effect_descriptions::PublishedValue;+ use crate::animations::keyframes::KeyframeValue;let [start, end] = effect.keyframes() else {return None;};- let value = |keyframe| match effect.declarations_of(keyframe) {- [declaration] => match &declaration.value {- PublishedValue::Declared(value) => Some((declaration.property_id, value.pointer())),- PublishedValue::ElementValue => None,- },- _ => None,+ let value = |keyframe| {+ let mut declarations = effect.declarations_of(keyframe);+ match (declarations.next(), declarations.next()) {+ (Some(declaration), None) => match &declaration.value {+ KeyframeValue::Declared(value) => Some((declaration.property_id, value.pointer())),+ KeyframeValue::ElementValue => None,+ },+ _ => None,+ }};let (property_id, start_value) = value(start)?;let (end_property_id, end_value) = value(end)?;@@ -989,15 +987,11 @@ impl RowTransitions {// record the host installed holds them.let after_overlay = match (running.is_empty(), at) {(false, Some(at)) => {- use crate::css::animation::{FfiAnimationPreparationEffect, FfiSampledAnimationEffect};let mut composed = crate::css::style_compute::SampledEffects::new();for transition in &running {if let Some(current_key) = transition.key {- composed.push(FfiSampledAnimationEffect {- effect: FfiAnimationPreparationEffect {- identity: transition.identity,- generation: transition.generation,- },+ composed.push(crate::css::animation::SampledAnimationEffect {+ description: transition.description.clone(),current_key,});}@@ -1058,10 +1052,10 @@ impl RowTransitions {#[derive(Clone, Default)]pub(crate) struct HostTransitionsSeen {/// Those a step ended as they ran, in place of which the host runs what the steps decided.- pub(crate) cancelled: smallvec::SmallVec<[u64; 2]>,+ pub(crate) cancelled: smallvec::SmallVec<[crate::animations::effect::AnimationEffectId; 2]>,/// Every one a step decided beside, whether it ran then, ended by itself, or a step ended it: one the steps neither/// ended nor left running ended by itself.- pub(crate) seen: smallvec::SmallVec<[u64; 2]>,+ pub(crate) seen: smallvec::SmallVec<[crate::animations::effect::AnimationEffectId; 2]>,}/// The transitions a lane's hover started on an element, which the lane runs in place of those the host runs on it,@@ -1157,17 +1151,12 @@ impl FreshTransitionSample {after: &std::sync::Arc<crate::css::style::pipeline::Record>,actions: &[FfiTransitionAction],) -> Option<Self> {- use crate::css::animation::{FfiAnimationPreparationEffect, FfiSampledAnimationEffect};-let fresh = started_transition_effects(actions)?;let mut composed = crate::css::style_compute::SampledEffects::new();for effect in &fresh {- composed.push(FfiSampledAnimationEffect {- effect: FfiAnimationPreparationEffect {- identity: effect.identity,- generation: 0,- },- current_key: effect.timing.as_ref()?.key()?,+ composed.push(crate::css::animation::SampledAnimationEffect {+ description: effect.description().clone(),+ current_key: effect.key()?,});}if composed.is_empty() {@@ -1215,31 +1204,23 @@ impl FreshTransitionSample {{return None;}- let effects = input.effects.as_slice();+ let effects = &input.effects;if effects.len() != self.keys.len() {return None;}- let timings: Box<[_]> = effects- .iter()- .map(|effect| {- (- effect.identity,- 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) },- },- )- })- .collect();- let samples_alike = timings.iter().zip(&self.keys).all(|((_, timing), key)| {- timing- .key()+ let samples_alike = effects.iter().zip(&self.keys).all(|(effect, key)| {+ effect+ .timing+ .key(effect.description.timing_function.as_easing()).is_some_and(|sampled_key| sampled_key.to_bits() == key.to_bits())});if !samples_alike {return None;}+ let timings = effects+ .iter()+ .map(|effect| (effect.description.identity, effect.timing))+ .collect();if self.result.outcome == crate::css::style_compute::FfiHostAnimationSampleOutcome::Evaluated {*host.overlay_for_mutation() = self.overlay;}@@ -1267,16 +1248,16 @@ fn started_transition_effects(let easing = crate::css::style::effect_descriptions::easing_from_computed_timing_function(unsafe {&*action.timing_function})?;- let identity = effects.len() as u64 + 1;+ let identity = crate::animations::effect::AnimationEffectId(effects.len() as u64 + 1);// SAFETY: The decision compared live values, which the records it decided over hold.let [start, end] = [action.start_value, action.end_value].map(|value| unsafe { RetainedStyleValueData::from_retained_pointer(retain_style_value(value)) });- effects.push(PublishedEffect::transition(+ effects.push(PublishedEffect::lane_transition(identity,action.property_id,start,end,- Some(started_transition_timing(action, easing)),+ started_transition_timing(action, easing),));}Some(effects)@@ -1323,7 +1304,7 @@ struct HoverTransitionRun {/// The timing function it eases with, where a hover started it.timing_function: Option<crate::css::style_value::RetainedStyleValueData>,/// The identity of the host's effect, where the host runs it.- host_identity: Option<u64>,+ host_identity: Option<crate::animations::effect::AnimationEffectId>,/// The time it started at, in the document timeline's milliseconds: that of the style change event that started it,/// where a hover started it.started_at: f64,@@ -1385,7 +1366,7 @@ fn hover_transition_effects(.running.iter().find(|transition| transition.property_id == action.property_id);- let identity = effects.len() as u64 + 1;+ let identity = crate::animations::effect::AnimationEffectId(effects.len() as u64 + 1);match action.kind {Kind::None => {// A running transition the step leaves runs on as it ran. So does one a hover started that has ended,@@ -1396,12 +1377,12 @@ fn hover_transition_effects(let mut timing = transition.timing.clone();let hold_time = timing.timing.playback().hold_time.value;timing.timing.set_hold_time(Some(hold_time));- effects.push(PublishedEffect::transition(+ effects.push(PublishedEffect::lane_transition(identity,action.property_id,retain(transition.start_value).ok_or("a transition without values")?,retain(transition.end_value).ok_or("a transition without values")?,- Some(timing.clone()),+ timing.clone(),));runs.push(HoverTransitionRun {timing,@@ -1425,12 +1406,12 @@ fn hover_transition_effects(}).ok_or("a timing function the engine cannot read")?;let timing = started_transition_timing(action, easing);- effects.push(PublishedEffect::transition(+ effects.push(PublishedEffect::lane_transition(identity,action.property_id,retain(action.start_value).ok_or("a transition without values")?,retain(action.end_value).ok_or("a transition without values")?,- Some(timing.clone()),+ timing.clone(),));runs.push(HoverTransitionRun {timing,@@ -1457,7 +1438,7 @@ unsafe impl Sync for HoverTransitions {}pub struct FfiLaneTransition {pub property_id: u16,/// The identity of the effect of the host's transition it is, which the host keeps, or 0 for one the lane started.- pub host_identity: u64,+ pub host_identity: crate::animations::effect::AnimationEffectId,/// The time it started at, in the document timeline's milliseconds: that of the style change event that started it,/// where the lane started it, and where the lane took one the host runs to start, which the host takes in where its/// play is still pending.@@ -1504,7 +1485,7 @@ impl HoverTransitions {if engine.element_animation_effects(node, 0).iter()- .any(|effect| !effect.is_transition)+ .any(|effect| !effect.is_transition()){return Err("transitions beside animations");}@@ -1517,7 +1498,7 @@ impl HoverTransitions {.fold(0.0, f64::max);let properties = effects.iter()- .filter_map(|effect| effect.declarations_of(effect.keyframes().first()?).first())+ .filter_map(|effect| effect.declarations_of(effect.keyframes().first()?).next()).map(|declaration| declaration.property_id).collect();// A running transition of the host's the step leaves no run of ended with the step.@@ -1567,8 +1548,7 @@ impl HoverTransitions {.key_at(Default::default()).expect("the host's samples move every timeline");Ok(RunningTransitionAt {- identity: effect.identity,- generation: 0,+ description: effect.description().clone(),host_identity: run.host_identity,property_id,key,@@ -1594,7 +1574,7 @@ impl HoverTransitions {let (property_id, start_value, end_value) = transition_values(effect)?;Some(FfiLaneTransition {property_id,- host_identity: run.host_identity.unwrap_or(0),+ host_identity: run.host_identity.unwrap_or_default(),start_time: run.started_at,delay: run.timing.timing.effect().start_delay.value,duration: run.timing.timing.effect().iteration_duration.value,@@ -1660,7 +1640,6 @@ impl HoverTransitions {),crate::css::style::engine_sample::NeedsHost,> {- use crate::css::animation::{FfiAnimationPreparationEffect, FfiSampledAnimationEffect};use crate::css::style::engine_sample::NeedsHost;let mut composed = crate::css::style_compute::SampledEffects::new();for (effect, run) in self.effects.iter().zip(&self.runs) {@@ -1672,11 +1651,8 @@ impl HoverTransitions {else {continue;};- composed.push(FfiSampledAnimationEffect {- effect: FfiAnimationPreparationEffect {- identity: effect.identity,- generation: 0,- },+ composed.push(crate::css::animation::SampledAnimationEffect {+ description: effect.description().clone(),current_key,});}@@ -1911,8 +1887,9 @@ mod tests {timing.hold_at(local_time);let running = if kind == Kind::None {vec![RunningTransitionAt {- identity: 1,- generation: 0,+ description: std::sync::Arc::new(crate::css::style::effect_descriptions::EffectDescription::new(+ crate::animations::effect::AnimationEffectId(1),+ )),host_identity: None,property_id: action.property_id,key: Some(key),@@ -1946,7 +1923,7 @@ mod tests {let (effects, runs) = hover_transition_effects(&decision).unwrap();let published_timing = effects[0].timing.as_ref().unwrap();assert!(published_timing.implies_will_change(Default::default()));- assert_eq!(published_timing.timing, timing.timing);+ assert_eq!(*published_timing, timing.timing);assert_eq!(runs[0].timing.timing, timing.timing);assert_eq!(runs[0].local_time, local_time);assert_eq!(runs[0].timing.key_at(Default::default()), Some(Some(key)));diff --git a/Libraries/LibWeb/Rust/src/css/typed_om.rs b/Libraries/LibWeb/Rust/src/css/typed_om.rsindex a57d6df1377..6b429025ff9 100644--- a/Libraries/LibWeb/Rust/src/css/typed_om.rs+++ b/Libraries/LibWeb/Rust/src/css/typed_om.rs@@ -773,7 +773,11 @@ fn percentages_resolve_as(property_id: u16) -> Option<u8> {}/// A calculation with the context of the property, https://drafts.csswg.org/css-values-4/#calc-type-checking-fn calculated_value(property_id: u16, calculation: Arc<CalcNode>, numeric_type: NumericType) -> RetainedStyleValue {+pub(crate) fn calculated_value(+ property_id: u16,+ calculation: Arc<CalcNode>,+ numeric_type: NumericType,+) -> RetainedStyleValue {let resolve_as = percentages_resolve_as(property_id);let ranges: Vec<_> = if property_id == property_id::CUSTOM {Vec::new()diff --git a/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rsindex 471ada17993..2efa768675f 100644--- a/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/layout/update_layout/main_thread_entries.rs@@ -66,13 +66,14 @@ pub unsafe extern "C" fn render_state_pay_flown_round(host: &DocumentHost, read:/// elements whose running animations a tick samples, the monotonic time in milliseconds at which the document's/// timestamps are zero, the timestamp of the next event of the animations, past which a tick samples nothing, and the/// timestamp at which the sampled animations of the document timeline have all ended, the scroll timelines a tick-/// samples where the compositor has scrolled to, and what the lane's hover reads, where its ticks follow the pointer.-/// `update` is the serial number of the rendering update. A document whose layout is not up to date gets no plan.+/// samples where the compositor has scrolled to, as they are now, and what the lane's hover reads, where its ticks+/// follow the pointer. `update` is the serial number of the rendering update. A document whose layout is not up to date+/// gets no plan.////// # Safety////// As for [`render_state_update_layout`], with no layout update running, and `elements` must hold `count` style nodes-/// and `scroll_timelines` `scroll_timeline_count` timelines. `hover` must be null or point at inputs as+/// and `scroll_timelines` `scroll_timeline_count` live timelines. `hover` must be null or point at inputs as/// `HoverPlan::from_ffi` takes them.#[unsafe(no_mangle)]#[allow(clippy::too_many_arguments)]@@ -83,7 +84,7 @@ pub unsafe extern "C" fn render_state_seal_clock_plan(count: usize,time_origin: f64,last_end: f64,- scroll_timelines: *const crate::render_state::FfiPlannedScrollTimeline,+ scroll_timelines: *const *const crate::animations::timeline::TimelineCell,scroll_timeline_count: usize,hover: *const crate::render_state::FfiHoverPlanInputs,update: u64,@@ -118,7 +119,11 @@ pub unsafe extern "C" fn render_state_seal_clock_plan(elements,time_origin,last_end,- scroll_timelines.to_vec(),+ scroll_timelines+ .iter()+ // SAFETY: Guaranteed by the caller.+ .filter_map(|&timeline| unsafe { &*timeline }.clock_snapshot())+ .collect(),round,hover,)diff --git a/Libraries/LibWeb/Rust/src/lib.rs b/Libraries/LibWeb/Rust/src/lib.rsindex 1f64a47afd7..055792fdd8f 100644--- a/Libraries/LibWeb/Rust/src/lib.rs+++ b/Libraries/LibWeb/Rust/src/lib.rs@@ -39,6 +39,8 @@ pub(crate) mod svg;pub mod web_audio;// What libweb_bindings_rust, whose interfaces are implemented in Rust, uses of this crate.+pub use animations::animation::AnimationRecordRef;+pub use animations::bindings_api as web_animations;pub use css::font_feature_values::FontFeatureValuesRuleKind;pub use css::media_list::{MediaList as NativeMediaList, MediaListDeleteResult};pub use css::rule::cssom;diff --git a/Libraries/LibWeb/Rust/src/painting/ffi.rs b/Libraries/LibWeb/Rust/src/painting/ffi.rsindex 12bc0484efa..93ad7bd37d9 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi.rs@@ -5,7 +5,7 @@*/use crate::css::css_pixels::{CssPixelRect, CssPixels};-use crate::css::ffi_support::{FfiUtf16View, OwnedBox};+use crate::css::ffi_support::FfiUtf16View;use crate::layout::LayoutNodeArena;use crate::layout::node_data::{DomPaintFact, NodeSlotId};use crate::layout::query::inline_cursor::{CaretPosition, InlineCursor, InlineLine, LineEdge};@@ -1337,16 +1337,6 @@ pub unsafe extern "C" fn render_state_background_color_animation_keyframe_colors}}-#[unsafe(no_mangle)]-pub extern "C" fn compositor_animation_effect_state_create() -> *mut CompositorAnimationEffectState {- Box::into_raw(Box::new(CompositorAnimationEffectState::default()))-}--#[unsafe(no_mangle)]-pub extern "C" fn compositor_animation_effect_state_destroy(state: OwnedBox<CompositorAnimationEffectState>) {- drop(state);-}-/// Builds the animation of the request's target kind for the effect and keeps it pending with the/// effect. The target's nodes come from the arena's main tree.///@@ -1415,11 +1405,6 @@ pub extern "C" fn compositor_animation_effect_clear_retained(state: &mut Composistate.clear_retained();}-#[unsafe(no_mangle)]-pub extern "C" fn compositor_animation_effect_reset(state: &mut CompositorAnimationEffectState) {- state.reset();-}-/// # Safety////// The request and host, with every range they address, must be live for the call.diff --git a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rsindex 2306354b6b8..da06fd94fad 100644--- a/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs+++ b/Libraries/LibWeb/Rust/src/painting/host/visual_context.rs@@ -128,35 +128,6 @@ pub(crate) struct ResolvedSvgFilter {pub svg_filter_bounds: OptionalCssPixelRect,}-/// Whether a keyframe gives a property a value of its own, takes the target's underlying style-/// for it, or leaves it out.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-#[repr(u8)]-pub enum FfiCompositorKeyframeValueState {- Absent,- UsesUnderlyingStyle,- Present,-}--/// One keyframe of an effect as the compositor animation builder reads it. The values themselves-/// are resolved through the host on demand; the keyframe only says which properties it carries.-#[derive(Clone, Copy, Debug)]-#[repr(C)]-pub struct FfiCompositorAnimationKeyframe {- pub offset: f64,- pub easing: FfiEasingDescriptor,- /// An easing the main thread could not describe keeps the effect off the compositor.- pub easing_is_supported: bool,- pub composite_is_replace: bool,- pub opacity: FfiCompositorKeyframeValueState,- pub background_color: FfiCompositorKeyframeValueState,- pub filter: FfiCompositorKeyframeValueState,- pub translate: FfiCompositorKeyframeValueState,- pub rotate: FfiCompositorKeyframeValueState,- pub scale: FfiCompositorKeyframeValueState,- pub transform: FfiCompositorKeyframeValueState,-}-/// The timing of an effect at the moment the main thread anchored it to the monotonic clock.#[derive(Clone, Copy, Debug)]#[repr(C)]@@ -187,11 +158,14 @@ pub struct FfiCompositorAnimationRequest {pub target_inherited_ui_values: *const std::ffi::c_void,pub target_inherited_text_values: *const std::ffi::c_void,pub timing: FfiCompositorAnimationTiming,- pub keyframes: *const FfiCompositorAnimationKeyframe,- pub keyframe_count: usize,- /// The identity of the effect's keyframe set and the versions of the style it resolves against;- /// the builder keeps the values it lowered while these stay the same.- pub key_frame_set_identity: u64,+ /// The `KeyframeSet` the effect runs, which the host holds a reference to, or null for an effect with none.+ pub keyframe_set: *const std::ffi::c_void,+ /// Whether the effect's composite operation, which a keyframe whose own is `auto` runs, is `replace`.+ pub effect_composite_is_replace: bool,+ /// The easing a keyframe that declares none runs: its animation's.+ pub default_easing: FfiEasingDescriptor,+ /// The versions of the style the keyframes resolve against; the builder keeps the values it lowered while these+ /// and the keyframe set stay the same.pub target_style_generation: u64,pub style_environment_version: u64,/// The box transform percentages resolve against, in CSS pixels; zero for the other kinds.@@ -209,14 +183,13 @@ pub struct FfiCompositorAnimationRequest {#[repr(C)]pub struct FfiCompositorAnimationHost {pub context: *mut std::ffi::c_void,- /// The keyframe's value of the property, resolved and absolutized for the target, as a- /// retained style value; null when it resolves to nothing usable. With- /// `uses_underlying_style` set, the target's computed value without animations instead.+ /// The value `declared_value` a keyframe declares for the property, resolved and absolutized for the target, as a+ /// retained style value; null when it resolves to nothing usable. Where `declared_value` is null, the keyframe+ /// takes the target's underlying style, and the target's computed value without animations is answered instead.pub resolved_keyframe_value: unsafe extern "C" fn(context: *mut std::ffi::c_void,- keyframe_index: usize,property_id: u16,- uses_underlying_style: bool,+ declared_value: *const std::ffi::c_void,) -> *const std::ffi::c_void,}diff --git a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rsindex 5c595af835b..b5ba6d60444 100644--- a/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs+++ b/Libraries/LibWeb/Rust/src/painting/visual_animation_builder.rs@@ -9,6 +9,9 @@//! values, the animations an effect has built and published, and the document-wide list the visual//! context tree receives.+use crate::animations::keyframes::{+ CompositeOperationOrAuto, FINAL_KEY, Keyframe, KeyframeEasing, KeyframeSet, KeyframeValue,+};use crate::css::absolutize::number_from_value;use crate::css::color_resolution::{ColorResolutionInput, FfiColorResolutionStyle, to_color};use crate::css::css_enums::keyword;@@ -29,15 +32,16 @@ use crate::css::table_group_builder::{use crate::css::value_codes::COLOR_SYNTAX_LEGACY;use crate::painting::filter_bytes::{FfiFilterFunction, FfiFilterFunctionKind};use crate::painting::host::{- FfiCompositorAnimationBuildOutcome, FfiCompositorAnimationHost, FfiCompositorAnimationKeyframe,- FfiCompositorAnimationRequest, FfiCompositorAnimationTiming, FfiCompositorKeyframeValueState,- FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind, TARGETED_TRANSFORM_PROPERTY_ROTATE,- TARGETED_TRANSFORM_PROPERTY_SCALE, TARGETED_TRANSFORM_PROPERTY_TRANSFORM, TARGETED_TRANSFORM_PROPERTY_TRANSLATE,+ FfiCompositorAnimationBuildOutcome, FfiCompositorAnimationHost, FfiCompositorAnimationRequest,+ FfiCompositorAnimationTiming, FfiVisualAnimationTargetKind, FfiVisualAnimationTransformOperationKind,+ TARGETED_TRANSFORM_PROPERTY_ROTATE, TARGETED_TRANSFORM_PROPERTY_SCALE, TARGETED_TRANSFORM_PROPERTY_TRANSFORM,+ TARGETED_TRANSFORM_PROPERTY_TRANSLATE,};use crate::painting::visual_animation::{VisualAnimation, VisualAnimationKeyframe, VisualAnimationTransformOperation, VisualAnimationValue,};use libgfx_rust::{Color, ColorFilterType};+use std::sync::Arc;const TARGET_KIND_COUNT: usize = 4;@@ -72,18 +76,6 @@ impl AnimatedProperty {}}- fn state_in(self, keyframe: &FfiCompositorAnimationKeyframe) -> FfiCompositorKeyframeValueState {- match self {- Self::Opacity => keyframe.opacity,- Self::BackgroundColor => keyframe.background_color,- Self::Filter => keyframe.filter,- Self::Translate => keyframe.translate,- Self::Rotate => keyframe.rotate,- Self::Scale => keyframe.scale,- Self::Transform => keyframe.transform,- }- }-fn targeted_transform_flag(self) -> u8 {match self {Self::Translate => TARGETED_TRANSFORM_PROPERTY_TRANSLATE,@@ -103,21 +95,20 @@ impl<'a> Host<'a> {Self(host)}+ /// The value of `property` a keyframe gives, `value`, resolved for the target.fn resolved_keyframe_value(&self,- keyframe_index: usize,property: AnimatedProperty,- uses_underlying_style: bool,+ value: KeyframeValueOf<'_>,) -> Option<RetainedStyleValueData> {- // SAFETY: The host returns a retained style value or null, synchronously.- let value = unsafe {- (self.0.resolved_keyframe_value)(- self.0.context,- keyframe_index,- property.property_id(),- uses_underlying_style,- )+ let declared_value = match value {+ KeyframeValueOf::Absent => return None,+ KeyframeValueOf::UnderlyingStyle => std::ptr::null(),+ KeyframeValueOf::Declared(value) => value.pointer().cast(),};+ // SAFETY: The host returns a retained style value or null, synchronously. The declared value is the keyframe+ // set's, which the request keeps live.+ let value = unsafe { (self.0.resolved_keyframe_value)(self.0.context, property.property_id(), declared_value) };if value.is_null() {return None;}@@ -126,10 +117,18 @@ impl<'a> Host<'a> {}}-/// A build request with its keyframes in reach.+/// What a keyframe gives a property: a value of its own, the target's underlying style, or nothing.+#[derive(Clone, Copy)]+enum KeyframeValueOf<'a> {+ Absent,+ UnderlyingStyle,+ Declared(&'a RetainedStyleValueData),+}++/// A build request with the keyframes the effect runs in reach.pub struct Request<'a> {ffi: &'a FfiCompositorAnimationRequest,- keyframes: &'a [FfiCompositorAnimationKeyframe],+ keyframe_set: Option<Arc<KeyframeSet>>,/// The translation in CSS pixels that the x and y of a <use> element apply after its transform.additional_translation: (f32, f32),}@@ -137,12 +136,13 @@ pub struct Request<'a> {impl<'a> Request<'a> {/// # Safety///- /// The request's keyframe range must be live.+ /// The request's keyframe set must be null or one the host holds a reference to.pub unsafe fn new(ffi: &'a FfiCompositorAnimationRequest) -> Self {Self {ffi,- // SAFETY: The caller guarantees the keyframe range is live.- keyframes: unsafe { ak::slice_from_raw_parts(ffi.keyframes, ffi.keyframe_count) },+ // SAFETY: Guaranteed by the caller.+ keyframe_set: (!ffi.keyframe_set.is_null())+ .then(|| unsafe { KeyframeSet::retained_from_host(ffi.keyframe_set.cast()) }),additional_translation: (0.0, 0.0),}}@@ -151,17 +151,59 @@ impl<'a> Request<'a> {self.additional_translation = (x, y);}- /// A request whose keyframe range is `keyframes`, for a unit test.+ /// A request for the keyframes of `keyframe_set`, for a unit test.#[cfg(test)]- fn with_keyframes(ffi: &'a FfiCompositorAnimationRequest, keyframes: &'a [FfiCompositorAnimationKeyframe]) -> Self {- assert!(std::ptr::eq(ffi.keyframes, keyframes.as_ptr()) && ffi.keyframe_count == keyframes.len());+ fn with_keyframe_set(ffi: &'a FfiCompositorAnimationRequest, keyframe_set: &Arc<KeyframeSet>) -> Self {Self {ffi,- keyframes,+ keyframe_set: Some(Arc::clone(keyframe_set)),additional_translation: (0.0, 0.0),}}+ /// The keyframes the effect runs, in the order they are used.+ fn keyframes(&self) -> &[Keyframe] {+ self.keyframe_set.as_deref().map_or(&[], KeyframeSet::keyframes)+ }++ /// What `keyframe`, one of the effect's, gives `property`.+ fn value_of(&self, keyframe: &Keyframe, property: AnimatedProperty) -> KeyframeValueOf<'_> {+ let Some(keyframe_set) = &self.keyframe_set else {+ return KeyframeValueOf::Absent;+ };+ let property_id = property.property_id();+ match keyframe_set+ .declarations_of(keyframe)+ .iter()+ .find(|declaration| declaration.property_id == property_id)+ .map(|declaration| &declaration.value)+ {+ None => KeyframeValueOf::Absent,+ Some(KeyframeValue::ElementValue) => KeyframeValueOf::UnderlyingStyle,+ Some(KeyframeValue::Declared(value)) => KeyframeValueOf::Declared(value),+ }+ }++ /// The easing `keyframe`, one of the effect's, runs to the next one, or none for one still to be substituted+ /// against the target, which keeps the effect off the compositor.+ fn easing_of(&self, keyframe: &Keyframe) -> Option<Easing> {+ match &keyframe.easing {+ // SAFETY: The host keeps the default easing's points live for the build.+ KeyframeEasing::None => Some(unsafe { Easing::from_descriptor(&self.ffi.default_easing) }),+ KeyframeEasing::Easing(easing) => Some(easing.clone()),+ KeyframeEasing::Value(_) => None,+ }+ }++ /// Whether `keyframe`, one of the effect's, replaces the value beneath it.+ fn replaces(&self, keyframe: &Keyframe) -> bool {+ match keyframe.composite {+ CompositeOperationOrAuto::Replace => true,+ CompositeOperationOrAuto::Add | CompositeOperationOrAuto::Accumulate => false,+ CompositeOperationOrAuto::Auto => self.ffi.effect_composite_is_replace,+ }+ }+pub fn target_kind(&self) -> FfiVisualAnimationTargetKind {self.ffi.target_kind}@@ -208,7 +250,7 @@ impl<'a> Request<'a> {fn cache_key(&self) -> KeyframeValueCacheKey {KeyframeValueCacheKey {- key_frame_set_identity: self.ffi.key_frame_set_identity,+ keyframe_set: self.keyframe_set.clone(),target_style_generation: self.ffi.target_style_generation,style_environment_version: self.ffi.style_environment_version,reference_box_width: self.ffi.reference_box_width,@@ -552,13 +594,13 @@ fn own_transform_keyframe_operations(host: &Host,) -> Option<Vec<Vec<VisualAnimationTransformOperation>>> {let mut lists = Vec::new();- for (index, keyframe) in request.keyframes.iter().enumerate() {- match AnimatedProperty::Transform.state_in(keyframe) {- FfiCompositorKeyframeValueState::Absent => continue,- FfiCompositorKeyframeValueState::UsesUnderlyingStyle => return None,- FfiCompositorKeyframeValueState::Present => {}- }- let value = host.resolved_keyframe_value(index, AnimatedProperty::Transform, false)?;+ for keyframe in request.keyframes() {+ let declared = match request.value_of(keyframe, AnimatedProperty::Transform) {+ KeyframeValueOf::Absent => continue,+ KeyframeValueOf::UnderlyingStyle => return None,+ declared @ KeyframeValueOf::Declared(_) => declared,+ };+ let value = host.resolved_keyframe_value(AnimatedProperty::Transform, declared)?;lists.push(transform_operations_from_style_value(AnimatedProperty::Transform,value.data(),@@ -600,9 +642,9 @@ pub fn effect_transform_preserves_axes(request: &Request, host: &Host) -> bool {})}-#[derive(Clone, Copy, PartialEq)]+#[derive(Clone)]struct KeyframeValueCacheKey {- key_frame_set_identity: u64,+ keyframe_set: Option<Arc<KeyframeSet>>,target_style_generation: u64,style_environment_version: u64,reference_box_width: f32,@@ -612,6 +654,24 @@ struct KeyframeValueCacheKey {additional_translation_y: f32,}+impl PartialEq for KeyframeValueCacheKey {+ fn eq(&self, other: &Self) -> bool {+ let same_keyframe_set = match (&self.keyframe_set, &other.keyframe_set) {+ (Some(keyframe_set), Some(other_keyframe_set)) => Arc::ptr_eq(keyframe_set, other_keyframe_set),+ (None, None) => true,+ _ => false,+ };+ same_keyframe_set+ && self.target_style_generation == other.target_style_generation+ && self.style_environment_version == other.style_environment_version+ && self.reference_box_width == other.reference_box_width+ && self.reference_box_height == other.reference_box_height+ && self.device_pixels_per_css_pixel == other.device_pixels_per_css_pixel+ && self.additional_translation_x == other.additional_translation_x+ && self.additional_translation_y == other.additional_translation_y+ }+}+/// The values of one target kind lowered from an effect's keyframes, kept while the keyframes and/// the style they resolve against stay the same. A keyframe without a value of the kind holds none;/// keyframes that cannot be lowered leave no values at all.@@ -627,10 +687,9 @@ type TransformIdentityShapes = [Option<Option<Vec<VisualAnimationTransformOperatfn build_keyframe_value_cache(request: &Request, host: &Host, key: KeyframeValueCacheKey) -> KeyframeValueCache {let mut identity_shapes: TransformIdentityShapes = Default::default();let values = request- .keyframes+ .keyframes().iter()- .enumerate()- .map(|(index, keyframe)| lower_keyframe(request, host, index, keyframe, &mut identity_shapes))+ .map(|keyframe| lower_keyframe(request, host, keyframe, &mut identity_shapes)).collect();KeyframeValueCache { key, values }}@@ -640,8 +699,7 @@ fn build_keyframe_value_cache(request: &Request, host: &Host, key: KeyframeValuefn lower_keyframe(request: &Request,host: &Host,- index: usize,- keyframe: &FfiCompositorAnimationKeyframe,+ keyframe: &Keyframe,identity_shapes: &mut TransformIdentityShapes,) -> Option<Option<VisualAnimationValue>> {let kind = request.target_kind();@@ -650,15 +708,14 @@ fn lower_keyframe(FfiVisualAnimationTargetKind::BackgroundColor => AnimatedProperty::BackgroundColor,FfiVisualAnimationTargetKind::Filter => AnimatedProperty::Filter,FfiVisualAnimationTargetKind::Transform => {- return lower_transform_keyframe(request, host, index, keyframe, identity_shapes);+ return lower_transform_keyframe(request, host, keyframe, identity_shapes);}};- let state = property.state_in(keyframe);- if state == FfiCompositorKeyframeValueState::Absent {+ let value = request.value_of(keyframe, property);+ if matches!(value, KeyframeValueOf::Absent) {return Some(None);}- let uses_underlying_style = state == FfiCompositorKeyframeValueState::UsesUnderlyingStyle;- let resolved = host.resolved_keyframe_value(index, property, uses_underlying_style)?;+ let resolved = host.resolved_keyframe_value(property, value)?;let value = match kind {FfiVisualAnimationTargetKind::Opacity => {VisualAnimationValue::Opacity(opacity_from_style_value(resolved.data())?)@@ -674,8 +731,7 @@ fn lower_keyframe(fn lower_transform_keyframe(request: &Request,host: &Host,- index: usize,- keyframe: &FfiCompositorAnimationKeyframe,+ keyframe: &Keyframe,identity_shapes: &mut TransformIdentityShapes,) -> Option<Option<VisualAnimationValue>> {let mut operations = Vec::new();@@ -683,14 +739,13 @@ fn lower_transform_keyframe(if !request.targets(*property) {continue;}- let state = property.state_in(keyframe);- if state == FfiCompositorKeyframeValueState::Absent {+ let value = request.value_of(keyframe, *property);+ if matches!(value, KeyframeValueOf::Absent) {// A keyframe that leaves out the only transform property is synthesized by the effect;// one that leaves out some of several cannot be lowered.return (request.targeted_transform_property_count() == 1).then_some(None);}- let uses_underlying_style = state == FfiCompositorKeyframeValueState::UsesUnderlyingStyle;- let resolved = host.resolved_keyframe_value(index, *property, uses_underlying_style)?;+ let resolved = host.resolved_keyframe_value(*property, value)?;let identity_shape = if is_none_keyword(resolved.data()) {identity_shapes[property_index].get_or_insert_with(|| resolve_transform_identity_shape(request, host, *property))@@ -726,11 +781,11 @@ fn resolve_transform_identity_shape(host: &Host,property: AnimatedProperty,) -> Option<Vec<VisualAnimationTransformOperation>> {- for (index, keyframe) in request.keyframes.iter().enumerate() {- if property.state_in(keyframe) != FfiCompositorKeyframeValueState::Present {+ for keyframe in request.keyframes() {+ let declared @ KeyframeValueOf::Declared(_) = request.value_of(keyframe, property) else {continue;- }- let Some(candidate) = host.resolved_keyframe_value(index, property, false) else {+ };+ let Some(candidate) = host.resolved_keyframe_value(property, declared) else {continue;};if is_none_keyword(candidate.data()) {@@ -777,9 +832,9 @@ impl CompositorAnimationEffectState {let mut outcome = FfiCompositorAnimationBuildOutcome::default();let kind = request.target_kind();if request- .keyframes+ .keyframes().iter()- .any(|keyframe| !keyframe.composite_is_replace || !keyframe.easing_is_supported)+ .any(|keyframe| !request.replaces(keyframe) || matches!(keyframe.easing, KeyframeEasing::Value(_))){return outcome;}@@ -787,17 +842,18 @@ impl CompositorAnimationEffectState {let Some(values) = self.resolved_values_for_target(request, host).values.as_ref() else {return outcome;};- debug_assert_eq!(values.len(), request.keyframes.len());+ debug_assert_eq!(values.len(), request.keyframes().len());let keyframes: Vec<VisualAnimationKeyframe> = request- .keyframes+ .keyframes().iter().zip(values).filter_map(|(keyframe, value)| {- value.as_ref().map(|value| VisualAnimationKeyframe {- offset: keyframe.offset,- // SAFETY: The request's easing point ranges are live for the build.- easing: unsafe { Easing::from_descriptor(&keyframe.easing) },- value: value.clone(),+ let value = value.as_ref()?.clone();+ Some(VisualAnimationKeyframe {+ #[expect(clippy::cast_precision_loss)]+ offset: keyframe.key as f64 / FINAL_KEY as f64,+ easing: request.easing_of(keyframe)?,+ value,})}).collect();@@ -996,32 +1052,25 @@ mod tests {}))}- /// A main thread whose keyframe values are given up front, counting what the builder asks for.+ /// A main thread whose keyframe values are given up front, counting what the builder asks for. Each keyframe of a+ /// test declares its index as the value of a property, which the main thread resolves to the value given for it.#[derive(Default)]struct TestHost {- values: HashMap<(usize, u16, bool), StyleValueArc>,+ values: HashMap<(usize, u16), StyleValueArc>,+ underlying_values: HashMap<u16, StyleValueArc>,resolutions: RefCell<usize>,}impl TestHost {fn with_value(mut self, keyframe_index: usize, property: AnimatedProperty, value: StyleValueData) -> Self {- self.values.insert(- (keyframe_index, property.property_id(), false),- StyleValueArc::new(value),- );+ self.values+ .insert((keyframe_index, property.property_id()), StyleValueArc::new(value));self}- fn with_underlying_value(- mut self,- keyframe_index: usize,- property: AnimatedProperty,- value: StyleValueData,- ) -> Self {- self.values.insert(- (keyframe_index, property.property_id(), true),- StyleValueArc::new(value),- );+ fn with_underlying_value(mut self, property: AnimatedProperty, value: StyleValueData) -> Self {+ self.underlying_values+ .insert(property.property_id(), StyleValueArc::new(value));self}@@ -1035,17 +1084,21 @@ mod tests {unsafe extern "C" fn test_resolved_keyframe_value(context: *mut std::ffi::c_void,- keyframe_index: usize,property_id: u16,- uses_underlying_style: bool,+ declared_value: *const std::ffi::c_void,) -> *const std::ffi::c_void {let host = unsafe { &*context.cast::<TestHost>() };*host.resolutions.borrow_mut() += 1;- host.values- .get(&(keyframe_index, property_id, uses_underlying_style))- .map_or(std::ptr::null(), |value| {- StyleValueArc::into_raw(StyleValueArc::clone(value)).cast()- })+ let value = match unsafe { declared_value.cast::<StyleValueData>().as_ref() } {+ None => host.underlying_values.get(&property_id),+ Some(&StyleValueData::Integer { value: keyframe_index }) => {+ host.values.get(&(keyframe_index as usize, property_id))+ }+ Some(_) => unreachable!("a test keyframe declares its index"),+ };+ value.map_or(std::ptr::null(), |value| {+ StyleValueArc::into_raw(StyleValueArc::clone(value)).cast()+ })}fn linear_easing() -> FfiEasingDescriptor {@@ -1072,35 +1125,59 @@ mod tests {}}- fn keyframe(+ /// What a test keyframe gives its property.+ #[derive(Clone, Copy)]+ enum ValueState {+ Absent,+ UsesUnderlyingStyle,+ Present,+ }++ /// One keyframe of a test effect, which gives one property a value.+ #[derive(Clone)]+ struct TestKeyframe {offset: f64,property: AnimatedProperty,- state: FfiCompositorKeyframeValueState,- ) -> FfiCompositorAnimationKeyframe {- let absent = FfiCompositorKeyframeValueState::Absent;- let mut keyframe = FfiCompositorAnimationKeyframe {+ state: ValueState,+ composite: CompositeOperationOrAuto,+ easing: KeyframeEasing,+ }++ fn keyframe(offset: f64, property: AnimatedProperty, state: ValueState) -> TestKeyframe {+ TestKeyframe {offset,- easing: linear_easing(),- easing_is_supported: true,- composite_is_replace: true,- opacity: absent,- background_color: absent,- filter: absent,- translate: absent,- rotate: absent,- scale: absent,- transform: absent,- };- match property {- AnimatedProperty::Opacity => keyframe.opacity = state,- AnimatedProperty::BackgroundColor => keyframe.background_color = state,- AnimatedProperty::Filter => keyframe.filter = state,- AnimatedProperty::Translate => keyframe.translate = state,- AnimatedProperty::Rotate => keyframe.rotate = state,- AnimatedProperty::Scale => keyframe.scale = state,- AnimatedProperty::Transform => keyframe.transform = state,+ property,+ state,+ composite: CompositeOperationOrAuto::Auto,+ easing: KeyframeEasing::None,}- keyframe+ }++ /// The keyframe set of `keyframes`, exactly as given, each declaring its index as the value it gives.+ fn keyframe_set(keyframes: &[TestKeyframe]) -> Arc<KeyframeSet> {+ use crate::animations::keyframes::KeyframeProperty;+ Arc::new(KeyframeSet::from_keyframes_as_given(+ keyframes+ .iter()+ .enumerate()+ .map(|(index, keyframe)| {+ let property = KeyframeProperty::Id(keyframe.property.property_id());+ let declarations = match keyframe.state {+ ValueState::Absent => Vec::new(),+ ValueState::UsesUnderlyingStyle => vec![(property, KeyframeValue::ElementValue)],+ ValueState::Present => vec![(+ property,+ KeyframeValue::Declared(retained(StyleValueData::Integer {+ value: i32::try_from(index).unwrap(),+ })),+ )],+ };+ #[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]+ let key = (keyframe.offset * FINAL_KEY as f64) as u64;+ (key, keyframe.composite, keyframe.easing.clone(), declarations)+ })+ .collect(),+ ))}fn timing() -> crate::painting::host::FfiCompositorAnimationTiming {@@ -1120,7 +1197,6 @@ mod tests {fn build_request(kind: FfiVisualAnimationTargetKind,- keyframes: &[FfiCompositorAnimationKeyframe],targeted_transform_properties: u8,) -> FfiCompositorAnimationRequest {FfiCompositorAnimationRequest {@@ -1129,9 +1205,9 @@ mod tests {target_inherited_ui_values: std::ptr::null(),target_inherited_text_values: std::ptr::null(),timing: timing(),- keyframes: keyframes.as_ptr(),- keyframe_count: keyframes.len(),- key_frame_set_identity: 7,+ keyframe_set: std::ptr::null(),+ effect_composite_is_replace: true,+ default_easing: linear_easing(),target_style_generation: 1,style_environment_version: 1,reference_box_width: 200.0,@@ -1142,8 +1218,8 @@ mod tests {}}- fn present(offset: f64, property: AnimatedProperty) -> FfiCompositorAnimationKeyframe {- keyframe(offset, property, FfiCompositorKeyframeValueState::Present)+ fn present(offset: f64, property: AnimatedProperty) -> TestKeyframe {+ keyframe(offset, property, ValueState::Present)}fn operation(kind: Kind, values: &[f32]) -> VisualAnimationTransformOperation {@@ -1169,8 +1245,9 @@ mod tests {present(0.0, AnimatedProperty::Opacity),present(1.0, AnimatedProperty::Opacity),];- let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &keyframes, 0);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let set = keyframe_set(&keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &set);let mut state = CompositorAnimationEffectState::default();let outcome = state.build(&request, &Host::new(&ffi_host), |_| vec![3]);@@ -1193,7 +1270,7 @@ mod tests {let mut changed_style = ffi_request;changed_style.target_style_generation += 1;- let request = Request::with_keyframes(&changed_style, &keyframes);+ let request = Request::with_keyframe_set(&changed_style, &set);assert!(state.build(&request, &Host::new(&ffi_host), |_| vec![3]).built);assert_eq!(*host.resolutions.borrow(), 4, "a style change lowers the values again");}@@ -1208,8 +1285,8 @@ mod tests {present(0.0, AnimatedProperty::Opacity),present(1.0, AnimatedProperty::Opacity),];- let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &keyframes, 0);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();let outcome = state.build(&request, &Host::new(&ffi_host), |_| Vec::new());@@ -1217,45 +1294,43 @@ mod tests {assert!(outcome.missing_visual_context_node);assert!(!state.has_pending());- let mut additive = keyframes;- additive[1].composite_is_replace = false;- let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &additive, 0);- let request = Request::with_keyframes(&ffi_request, &additive);+ let mut additive = keyframes.clone();+ additive[1].composite = CompositeOperationOrAuto::Add;+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&additive));assert!(!state.build(&request, &Host::new(&ffi_host), |_| vec![3]).built);- let mut unsupported_easing = keyframes;- unsupported_easing[0].easing_is_supported = false;- let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &unsupported_easing, 0);- let request = Request::with_keyframes(&ffi_request, &unsupported_easing);+ let mut unsupported_easing = keyframes.clone();+ unsupported_easing[0].easing = KeyframeEasing::Value(retained(none()));+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&unsupported_easing));assert!(!state.build(&request, &Host::new(&ffi_host), |_| vec![3]).built);- // A keyframe without the property is left out; too few remain for an animation. Another- // keyframe set has an identity of its own.+ // A keyframe without the property is left out; too few remain for an animation.let sparse = [present(0.0, AnimatedProperty::Opacity),- keyframe(1.0, AnimatedProperty::Opacity, FfiCompositorKeyframeValueState::Absent),+ keyframe(1.0, AnimatedProperty::Opacity, ValueState::Absent),];- let mut ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &sparse, 0);- ffi_request.key_frame_set_identity += 1;- let request = Request::with_keyframes(&ffi_request, &sparse);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&sparse));assert!(!state.build(&request, &Host::new(&ffi_host), |_| vec![3]).built);}#[test]fn opacity_keyframes_that_take_the_underlying_style_build_from_it() {let host = TestHost::default()- .with_underlying_value(0, AnimatedProperty::Opacity, opacity_value(0.25))+ .with_underlying_value(AnimatedProperty::Opacity, opacity_value(0.25)).with_value(1, AnimatedProperty::Opacity, opacity_value(0.5))- .with_underlying_value(2, AnimatedProperty::Opacity, opacity_value(0.25));+ .with_underlying_value(AnimatedProperty::Opacity, opacity_value(0.25));let ffi_host = host.ffi();- let underlying = FfiCompositorKeyframeValueState::UsesUnderlyingStyle;+ let underlying = ValueState::UsesUnderlyingStyle;let keyframes = [keyframe(0.0, AnimatedProperty::Opacity, underlying),present(0.5, AnimatedProperty::Opacity),keyframe(1.0, AnimatedProperty::Opacity, underlying),];- let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, &keyframes, 0);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Opacity, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();assert!(state.build(&request, &Host::new(&ffi_host), |_| vec![1]).built);@@ -1327,10 +1402,9 @@ mod tests {];let ffi_request = build_request(FfiVisualAnimationTargetKind::Transform,- &keyframes,TARGETED_TRANSFORM_PROPERTY_TRANSFORM,);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();let outcome = state.build(&request, &Host::new(&ffi_host), |_| vec![1]);@@ -1415,10 +1489,9 @@ mod tests {];let ffi_request = build_request(FfiVisualAnimationTargetKind::Transform,- &keyframes,TARGETED_TRANSFORM_PROPERTY_TRANSFORM,);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();state.build(&request, &Host::new(&ffi_host), |_| vec![1]).built};@@ -1459,7 +1532,7 @@ mod tests {transformation(transform_function::TRANSLATE_Y, vec![px(4.0)]),]),)- .with_underlying_value(0, AnimatedProperty::Scale, none())+ .with_underlying_value(AnimatedProperty::Scale, none()).with_value(1,AnimatedProperty::Scale,@@ -1473,10 +1546,9 @@ mod tests {];let ffi_request = build_request(FfiVisualAnimationTargetKind::Transform,- &keyframes,TARGETED_TRANSFORM_PROPERTY_TRANSFORM,);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();assert!(state.build(&request, &Host::new(&ffi_host), |_| vec![1]).built);let animation = pending_animation(&state, FfiVisualAnimationTargetKind::Transform);@@ -1493,19 +1565,14 @@ mod tests {// the property's own identity when no other keyframe offers a shape... except the second// keyframe does, so that shape is taken.let keyframes = [- keyframe(- 0.0,- AnimatedProperty::Scale,- FfiCompositorKeyframeValueState::UsesUnderlyingStyle,- ),+ keyframe(0.0, AnimatedProperty::Scale, ValueState::UsesUnderlyingStyle),present(1.0, AnimatedProperty::Scale),];let ffi_request = build_request(FfiVisualAnimationTargetKind::Transform,- &keyframes,TARGETED_TRANSFORM_PROPERTY_SCALE,);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();assert!(state.build(&request, &Host::new(&ffi_host), |_| vec![1]).built);let animation = pending_animation(&state, FfiVisualAnimationTargetKind::Transform);@@ -1545,10 +1612,9 @@ mod tests {];let ffi_request = build_request(FfiVisualAnimationTargetKind::Transform,- &keyframes,TARGETED_TRANSFORM_PROPERTY_TRANSFORM,);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));assert!(effect_only_translates_horizontally(&request, &Host::new(&ffi_host)));assert!(effect_transform_preserves_axes(&request, &Host::new(&ffi_host)));@@ -1560,7 +1626,7 @@ mod tests {let mut with_rotate = ffi_request;with_rotate.targeted_transform_properties |= TARGETED_TRANSFORM_PROPERTY_ROTATE;with_rotate.targets_only_transform = false;- let request = Request::with_keyframes(&with_rotate, &keyframes);+ let request = Request::with_keyframe_set(&with_rotate, &keyframe_set(&keyframes));assert!(!effect_only_translates_horizontally(&request, &Host::new(&ffi_host)));assert!(!effect_transform_preserves_axes(&request, &Host::new(&ffi_host)));@@ -1582,7 +1648,7 @@ mod tests {)]),);let vertical_host = vertical.ffi();- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));assert!(!effect_only_translates_horizontally(&request,&Host::new(&vertical_host)@@ -1613,8 +1679,8 @@ mod tests {present(0.0, AnimatedProperty::Filter),present(1.0, AnimatedProperty::Filter),];- let ffi_request = build_request(FfiVisualAnimationTargetKind::Filter, &keyframes, 0);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::Filter, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();assert!(state.build(&request, &Host::new(&ffi_host), |_| vec![2]).built);let animation = pending_animation(&state, FfiVisualAnimationTargetKind::Filter);@@ -1670,8 +1736,8 @@ mod tests {present(0.0, AnimatedProperty::BackgroundColor),present(1.0, AnimatedProperty::BackgroundColor),];- let ffi_request = build_request(FfiVisualAnimationTargetKind::BackgroundColor, &keyframes, 0);- let request = Request::with_keyframes(&ffi_request, &keyframes);+ let ffi_request = build_request(FfiVisualAnimationTargetKind::BackgroundColor, 0);+ let request = Request::with_keyframe_set(&ffi_request, &keyframe_set(&keyframes));let mut state = CompositorAnimationEffectState::default();let built = state.build(&request, &Host::new(&ffi_host), |_| vec![2]).built;built.then(|| pending_animation(&state, FfiVisualAnimationTargetKind::BackgroundColor).clone())diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rsindex b4332134e19..f50a26d1b1f 100644--- a/Libraries/LibWeb/Rust/src/render_state.rs+++ b/Libraries/LibWeb/Rust/src/render_state.rs@@ -23,7 +23,6 @@ mod owner;pub(crate) use owner::{process_style, release_unused_memory_of_style_layout_threads};mod wait;-pub use clock::FfiPlannedScrollTimeline;pub use clock::hover::FfiHoverPlanInputs;pub(crate) use clock::hover::HoverPlan;pub(crate) use clock::{ClockPlan, CommittedContent, CommittedFrame, LaneDelivery, SampledFrame};diff --git a/Libraries/LibWeb/Rust/src/render_state/clock.rs b/Libraries/LibWeb/Rust/src/render_state/clock.rsindex 6d17622f0d0..e2fc79af6b4 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock.rs@@ -28,7 +28,8 @@use super::owner::DocumentId;use super::{DocumentHost, RenderState};-use crate::animations::snapshot::{ScrollProgress, ScrollTimelineId};+use crate::animations::snapshot::ScrollProgress;+use crate::animations::timeline::ScrollTimelineSnapshot;use crate::css::css_pixels::CssPixelRect;use crate::css::ffi_support::OwnedArc;use crate::css::style::animations::AnimationTimelineSamples;@@ -41,9 +42,7 @@ use crate::layout::used_values::FfiCssPixelRect;use crate::layout::{ClockRound, ClockRoundDeclined, HostStyle, LayoutNodeArena};use crate::paint_stage::Presenting;use crate::painting::paint_passes::{ClockTickVisualContexts, VisualContextsNeedHost, prepare_for_clock_tick};-use crate::painting::paintable_geometry::{- absolute_border_box_rect, absolute_padding_box_rect, committed_content_size, scrollable_overflow_rect,-};+use crate::painting::paintable_geometry::absolute_border_box_rect;use crate::painting::presentation::Presentation;use crate::painting::record::damage::PaintDamage;use crate::painting::record::inputs::UnframedRecordingInputs;@@ -79,7 +78,7 @@ pub(crate) struct ClockPlan {/// past it shows their ends, and after it only a scroll moves anything.last_end: f64,/// The scroll timelines a tick samples where the compositor has scrolled their scrollers to.- scroll_timelines: Vec<FfiPlannedScrollTimeline>,+ scroll_timelines: Vec<ScrollTimelineSnapshot>,round: ClockRound,/// What a tick hovers the element under the pointer with, where the lane follows the pointer.hover: Option<hover::HoverPlan>,@@ -88,139 +87,18 @@ pub(crate) struct ClockPlan {pub(super) animation_changes: u64,}-/// A scroll timeline whose animations the ticks of a lane sample, as a rendering update sealed it.-#[repr(C)]-#[derive(Clone, Copy, Debug)]-pub struct FfiPlannedScrollTimeline {- /// The identity the host gave the timeline.- pub timeline: u64,- /// The unique node id of the element whose scroll node the timeline follows, or of the document for its viewport,- /// and whether along the vertical axis.- pub scroller: i64,- /// The style node of the element whose box scrolls, or 0 for the viewport.- pub scroller_element: u32,- pub vertical: bool,- /// The scroll offset the host laid out, in CSS pixels.- pub scroll_offset: f64,- /// The scroll offset at 100% progress, in CSS pixels, in the layout the host sealed the plan from, and in the- /// layout of the last frame a tick presented from then on.- pub max_scroll_offset: f64,- pub view: FfiPlannedViewTimeline,-}--/// What decides the progress of a view progress timeline, along its axis, in CSS pixels, in the layout the host sealed-/// the plan from, and where a tick's layout moved them in the layout of the last frame a tick presented from then on.-#[repr(C)]-#[derive(Clone, Copy, Debug, Default)]-pub struct FfiPlannedViewTimeline {- /// The style node of the timeline's subject, or 0 for a scroll progress timeline, which has none of this.- pub subject: u32,- pub scrollport_size: f64,- /// The insets of the view progress visibility range, at the start and at the end of the scrollport.- pub inset_start: f64,- pub inset_end: f64,- /// How much of those insets is a percentage of the scrollport's size. Scroll padding counts as none, whose pixels- /// hold until the host's next plan.- pub inset_start_percentage: f64,- pub inset_end_percentage: f64,- /// Where the subject's border box starts, from the start of the scrollport, and its size.- pub subject_offset: f64,- pub subject_size: f64,-}--impl FfiPlannedViewTimeline {- /// The scroll offsets at the start and at the end of the cover range.- fn cover_range(&self) -> (f64, f64) {- // https://drafts.csswg.org/scroll-animations-1/#valdef-animation-timeline-range-cover- // 0% progress represents the latest position at which the start border edge of the element's principal box- // coincides with the end edge of its view progress visibility range.- // 100% progress represents the earliest position at which the end border edge of the element's principal box- // coincides with the start edge of its view progress visibility range.- (- self.subject_offset - (self.scrollport_size - self.inset_end),- self.subject_offset + self.subject_size - self.inset_start,- )- }-- /// https://drafts.csswg.org/scroll-animations-1/#view-timeline-progress- /// The progress, in percent, at the scroll offset `position`.- /// NB: The 0% and 100% positions never coincide: the host plans no such timeline, and `follow_layout` leaves one- /// where they would.- fn progress_at(&self, position: f64) -> f64 {- let (cover_start, cover_end) = self.cover_range();- (position - cover_start) / (cover_end - cover_start) * 100.0- }-}--impl FfiPlannedScrollTimeline {- /// Where `scroll_offsets` scrolled the timeline's scroller to, or where the host laid it out without one for it, up- /// to the end of the scroll range: a tick's layout may have shrunk it before the compositor hears of that.- /// NB: A scroller that overflows towards its start, as with `direction: rtl`, scrolls to negative offsets.- fn position_in(&self, scroll_offsets: &[FfiScrollOffset]) -> f64 {- let position = scroll_offsets- .iter()- .find(|offset| offset.scroller == self.scroller)- .map_or(- self.scroll_offset,- |offset| {- if self.vertical { offset.y } else { offset.x }- },- );- position.min(self.max_scroll_offset)- }-- /// The progress, in percent, of the timeline at the scroll offset `position`.- fn progress_at(&self, position: f64) -> f64 {- if self.view.subject == 0 {- return position / self.max_scroll_offset * 100.0;- }- self.view.progress_at(position)- }-- /// Has the timeline follow the layout `arena` holds, as a host's layout decides its next rendering update's- /// samples.- /// What makes the timeline inactive there leaves it where it was: the host decides that.- fn follow_layout(&mut self, arena: &LayoutNodeArena) {- let rows = arena.paintable_rows();- let scroller = StyleNodeID::from_raw(self.scroller_element)- .map_or_else(|| arena.layout_root(), |element| arena.bound_row(element));- let Some(overflow) = scrollable_overflow_rect(&rows, scroller) else {- return;- };- let content = committed_content_size(&rows, scroller);- let max_scroll_offset = match self.vertical {- true => overflow.height.to_double() - content.height.to_double(),- false => overflow.width.to_double() - content.width.to_double(),- };- if max_scroll_offset <= 0.0 {- return;- }- self.max_scroll_offset = max_scroll_offset;- let Some(subject) = StyleNodeID::from_raw(self.view.subject) else {- return;- };- let subject = arena.bound_row(subject);- if !rows.paintable_row_is_populated(subject) {- return;- }- let along = |rect: CssPixelRect| match self.vertical {- true => (rect.y.to_double(), rect.height.to_double()),- false => (rect.x.to_double(), rect.width.to_double()),- };- let mut view = self.view;- let (scrollport_start, scrollport_size) = along(absolute_padding_box_rect(&rows, scroller));- let (subject_start, subject_size) = along(absolute_border_box_rect(&rows, subject));- let resized_by = scrollport_size - view.scrollport_size;- view.scrollport_size = scrollport_size;- view.inset_start += view.inset_start_percentage / 100.0 * resized_by;- view.inset_end += view.inset_end_percentage / 100.0 * resized_by;- view.subject_offset = subject_start - scrollport_start;- view.subject_size = subject_size;- let (cover_start, cover_end) = view.cover_range();- if cover_start != cover_end {- self.view = view;- }- }+/// Where `scroll_offsets` scrolled the scroller of `timeline` to, or where the host laid it out without one for it, up to+/// the end of the scroll range: a tick's layout may have shrunk it before the compositor hears of that.+/// NB: A scroller that overflows towards its start, as with `direction: rtl`, scrolls to negative offsets.+fn position_in(timeline: &ScrollTimelineSnapshot, scroll_offsets: &[FfiScrollOffset]) -> f64 {+ let scroller = &timeline.scroller;+ let position = scroll_offsets+ .iter()+ .find(|offset| offset.scroller == scroller.scroll_node.node_id)+ .map_or(scroller.scroll_offset, |offset| {+ if scroller.vertical { offset.y } else { offset.x }+ });+ position.min(scroller.max_scroll_offset)}/// Where the compositor had scrolled the scroll node of an element, or of a document's viewport, by its unique node id,@@ -238,7 +116,7 @@ impl ClockPlan {elements: Vec<StyleNodeID>,time_origin: f64,last_end: f64,- mut scroll_timelines: Vec<FfiPlannedScrollTimeline>,+ mut scroll_timelines: Vec<ScrollTimelineSnapshot>,round: ClockRound,hover: Option<hover::HoverPlan>,) -> Self {@@ -259,7 +137,7 @@ impl ClockPlan {fn scroll_positions(&self, scroll_offsets: &[FfiScrollOffset]) -> SmallVec<[f64; 2]> {self.scroll_timelines.iter()- .map(|timeline| timeline.position_in(scroll_offsets))+ .map(|timeline| position_in(timeline, scroll_offsets)).collect()}@@ -270,7 +148,7 @@ impl ClockPlan {.iter().zip(positions).map(|(timeline, &position)| ScrollProgress {- timeline: ScrollTimelineId(timeline.timeline),+ timeline: 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.rsindex 01ebe4ba48e..9b96466beed 100644--- a/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs+++ b/Libraries/LibWeb/Rust/src/render_state/clock/hover.rs@@ -42,7 +42,7 @@ pub struct FfiHoverPlanInputs {/// 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 `EffectTimingSnapshot`, by effect.pub effect_timing_nodes: *const u32,- pub effect_timing_identities: *const u64,+ pub effect_timing_identities: *const crate::animations::effect::AnimationEffectId,pub effect_timings: *const std::ffi::c_void,pub effect_timing_count: usize,/// Where a drag selecting text the lane may follow is anchored, if one runs: the style node of a text node or an@@ -238,7 +238,11 @@ 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, EffectTimingSnapshot)>,+ effect_timings: Vec<(+ StyleNodeID,+ crate::animations::effect::AnimationEffectId,+ EffectTimingSnapshot,+ )>,/// The drag selecting text the ticks show, until the button goes up.selection_drag: Option<super::selection::SelectionDrag>,}diff --git a/Libraries/LibWeb/SVG/SMILAnimation.cpp b/Libraries/LibWeb/SVG/SMILAnimation.cppdeleted file mode 100644index 71f5729188c..00000000000--- a/Libraries/LibWeb/SVG/SMILAnimation.cpp+++ /dev/null@@ -1,63 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#include <LibWeb/DOM/Document.h>-#include <LibWeb/SVG/SMILAnimation.h>-#include <LibWeb/SVG/SMILTimeContainer.h>-#include <LibWeb/SVG/SVGAnimationElement.h>--namespace Web::SVG {--GC_DEFINE_ALLOCATOR(SMILAnimation);--GC::Ref<SMILAnimation> SMILAnimation::create(SVGAnimationElement& animation_element, SMILTimeContainer& time_container, double begin_time)-{- auto& environment = animation_element.document().relevant_settings_object();- return GC::Heap::the().allocate<SMILAnimation>(environment, animation_element, time_container, begin_time);-}--SMILAnimation::SMILAnimation(HTML::EnvironmentSettingsObject& environment, SVGAnimationElement& animation_element, SMILTimeContainer& time_container, double begin_time)- : Animations::Animation(environment)- , m_animation_element(animation_element)- , m_time_container(time_container)- , m_begin_time(begin_time)-{-}--void SMILAnimation::cancel(ShouldInvalidate should_invalidate)-{- m_time_container->remove_animation(*this);- Base::cancel(should_invalidate);-}--// https://www.w3.org/TR/smil-animation/#AnimationSandwichModel-int SMILAnimation::class_specific_composite_order(GC::Ref<Animations::Animation> other) const-{- // Within an OM, animations are prioritized according to when each begins. The animation first begun has lowest- // priority and the most recently begun animation has highest priority. When two animations start at the same- // moment in time, the activation order is resolved as follows:- // ...- // If two animations share no time dependency relationship (e.g., neither is defined relative to the other, even- // indirectly) the element that appears first in the document has lower priority.- auto const& other_animation = as<SMILAnimation>(*other);- if (m_begin_time != other_animation.m_begin_time)- return m_begin_time < other_animation.m_begin_time ? -1 : 1;- // NB: Begin times only come from offsets and DOM method calls for now, so no animation is defined relative to- // another.- auto const& other_element = other_animation.animation_element();- if (m_animation_element.ptr() == &other_element)- return 0;- return m_animation_element->is_before(other_element) ? -1 : 1;-}--void SMILAnimation::visit_edges(Cell::Visitor& visitor)-{- Base::visit_edges(visitor);- visitor.visit(m_animation_element);- visitor.visit(m_time_container);-}--}diff --git a/Libraries/LibWeb/SVG/SMILAnimation.h b/Libraries/LibWeb/SVG/SMILAnimation.hdeleted file mode 100644index 52f4c681ed5..00000000000--- a/Libraries/LibWeb/SVG/SMILAnimation.h+++ /dev/null@@ -1,39 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--#pragma once--#include <LibWeb/Animations/Animation.h>-#include <LibWeb/Forward.h>--namespace Web::SVG {--class SMILAnimation final : public Animations::Animation {- WEB_NON_IDL_WRAPPABLE(SMILAnimation, Animations::Animation);- GC_DECLARE_ALLOCATOR(SMILAnimation);--public:- static GC::Ref<SMILAnimation> create(SVGAnimationElement&, SMILTimeContainer&, double begin_time);-- SVGAnimationElement& animation_element() const { return m_animation_element; }-- virtual void cancel(ShouldInvalidate = ShouldInvalidate::Yes) override;-- virtual bool is_smil_animation() const override { return true; }- virtual Animations::AnimationClass animation_class() const override { return Animations::AnimationClass::SMILAnimation; }- virtual int class_specific_composite_order(GC::Ref<Animations::Animation> other) const override;--private:- SMILAnimation(HTML::EnvironmentSettingsObject&, SVGAnimationElement&, SMILTimeContainer&, double begin_time);-- virtual void visit_edges(Cell::Visitor&) override;-- GC::Ref<SVGAnimationElement> m_animation_element;- GC::Ref<SMILTimeContainer> m_time_container;- double m_begin_time { 0 };-};--}diff --git a/Libraries/LibWeb/SVG/SMILTimeContainer.cpp b/Libraries/LibWeb/SVG/SMILTimeContainer.cppindex b787d48b8ef..6df989fceaf 100644--- a/Libraries/LibWeb/SVG/SMILTimeContainer.cpp+++ b/Libraries/LibWeb/SVG/SMILTimeContainer.cpp@@ -4,10 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-#include <LibWeb/Animations/DocumentTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>-#include <LibWeb/SVG/SMILAnimation.h>#include <LibWeb/SVG/SMILTimeContainer.h>namespace Web::SVG {@@ -35,7 +34,8 @@ void SMILTimeContainer::visit_edges(GC::Cell::Visitor& visitor){Base::visit_edges(visitor);visitor.visit(m_document);- visitor.visit(m_animations);+ for (auto const& animation : m_animations)+ animation.visit_edges(visitor);}double SMILTimeContainer::document_timeline_time() const@@ -126,15 +126,15 @@ void SMILTimeContainer::record_time_to_seek_to_once_begun_in_milliseconds(doublem_time_to_seek_to_once_begun = max(time, 0.);}-void SMILTimeContainer::add_animation(SMILAnimation& animation)+void SMILTimeContainer::add_animation(Animations::AnimationRef const& animation){m_animations.append(animation);synchronize_animation(animation);}-void SMILTimeContainer::remove_animation(SMILAnimation& animation)+void SMILTimeContainer::remove_animation(Animations::AnimationRef const& animation){- m_animations.remove_first_matching([&](auto const& entry) { return entry.ptr() == &animation; });+ m_animations.remove_first_matching([&](auto const& entry) { return entry == animation; });}void SMILTimeContainer::synchronize_animations()@@ -143,24 +143,15 @@ void SMILTimeContainer::synchronize_animations()synchronize_animation(animation);}-// https://drafts.csswg.org/web-animations-1/#setting-the-start-time-of-an-animation-// https://drafts.csswg.org/web-animations-1/#setting-the-current-time-of-an-animation-void SMILTimeContainer::synchronize_animation(SMILAnimation& animation)+void SMILTimeContainer::synchronize_animation(Animations::AnimationRef const& animation){- // NB: Both procedures take effect synchronously, and update the finished state of the animation as a seek does. A- // backward seek therefore applies to an animation that already finished, too.if (!m_has_begun)return;+ // NB: The record sets the start time or the current time of the animation. The animation has no promises to+ // settle, but the microtask checkpoint as the execution context ends stays where it was.HTML::TemporaryExecutionContext execution_context { m_document->relevant_settings_object() };- if (m_is_paused) {- // NB: Making the start time unresolved holds the animation at its current time, which setting the current time- // then moves to the time the timeline is paused at.- MUST(animation.set_start_time_for_bindings(Animations::NullableCSSNumberish { Empty {} }));- MUST(animation.set_current_time_for_bindings(Animations::NullableCSSNumberish { m_paused_time }));- return;- }- MUST(animation.set_start_time_for_bindings(Animations::NullableCSSNumberish { m_zero_time }));+ Animations::RustFFI::animations_smil_animation_synchronize(&animation.record(), m_zero_time, m_is_paused, m_paused_time, Animations::perform_host_effect);}}diff --git a/Libraries/LibWeb/SVG/SMILTimeContainer.h b/Libraries/LibWeb/SVG/SMILTimeContainer.hindex 8ff336a9ef6..3a34e157dc8 100644--- a/Libraries/LibWeb/SVG/SMILTimeContainer.h+++ b/Libraries/LibWeb/SVG/SMILTimeContainer.h@@ -11,6 +11,7 @@#include <LibGC/Cell.h>#include <LibGC/CellAllocator.h>#include <LibGC/Ptr.h>+#include <LibWeb/Animations/RecordHandles.h>#include <LibWeb/Forward.h>namespace Web::SVG {@@ -34,8 +35,8 @@ public:void seek_to_time_in_milliseconds(double);void record_time_to_seek_to_once_begun_in_milliseconds(double);- void add_animation(SMILAnimation&);- void remove_animation(SMILAnimation&);+ void add_animation(Animations::AnimationRef const&);+ void remove_animation(Animations::AnimationRef const&);private:explicit SMILTimeContainer(DOM::Document&);@@ -44,10 +45,12 @@ private:double document_timeline_time() const;void synchronize_animations();- void synchronize_animation(SMILAnimation&);+ void synchronize_animation(Animations::AnimationRef const&);GC::Ref<DOM::Document> m_document;- Vector<GC::Ref<SMILAnimation>> m_animations;+ // NB: The animations of the animation elements of the timeline, which this traces as their animation elements hold+ // them.+ Vector<Animations::AnimationRef> m_animations;bool m_has_begun { false };bool m_is_paused { false };diff --git a/Libraries/LibWeb/SVG/SVGAnimateElement.cpp b/Libraries/LibWeb/SVG/SVGAnimateElement.cppindex 4004ff5b141..70d6a0620c4 100644--- a/Libraries/LibWeb/SVG/SVGAnimateElement.cpp+++ b/Libraries/LibWeb/SVG/SVGAnimateElement.cpp@@ -122,7 +122,7 @@ static Optional<Vector<CSS::EasingFunction>> parse_key_splines(Utf16View attribu// NB: The keyTimes values are the anchor points of a segment, so its control points describe a cubic-bezier()// easing function across it.- auto easing = Animations::AnimationEffect::parse_easing_string(Utf16String::formatted("cubic-bezier({}, {}, {}, {})", control_points[0], control_points[1], control_points[2], control_points[3]));+ auto easing = CSS::EasingFunction::parse(Utf16String::formatted("cubic-bezier({}, {}, {}, {})", control_points[0], control_points[1], control_points[2], control_points[3]));if (!easing.has_value())return {};key_splines.unchecked_append(easing.release_value());@@ -131,7 +131,7 @@ static Optional<Vector<CSS::EasingFunction>> parse_key_splines(Utf16View attribu}// https://svgwg.org/specs/animations/#AnimateElement-Vector<Animations::BaseKeyframe> SVGAnimateElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const+Vector<SVGKeyframe> SVGAnimateElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const{// NB: A missing value stands for the underlying value of the attribute or property, which the keyframe effect// takes as its missing start keyframe.@@ -217,14 +217,14 @@ Vector<Animations::BaseKeyframe> SVGAnimateElement::keyframes(SVGElement const&return static_cast<double>(index) / static_cast<double>(values.size() - 1);};- Vector<Animations::BaseKeyframe> keyframes;+ Vector<SVGKeyframe> keyframes;keyframes.ensure_capacity(values.size() + 1);for (size_t i = 0; i < values.size(); ++i) {if (!values[i])continue;auto value_keyframe = keyframe(offset_of_value(i), property_id, *values[i]);if (calc_mode == CalcMode::Discrete)- value_keyframe.easing = Animations::AnimationEffect::parse_easing_string("step-end"_utf16).release_value();+ value_keyframe.easing = CSS::EasingFunction::parse("step-end"_utf16).release_value();else if (key_splines.has_value() && i < key_splines->size())value_keyframe.easing = (*key_splines)[i];elsediff --git a/Libraries/LibWeb/SVG/SVGAnimateElement.h b/Libraries/LibWeb/SVG/SVGAnimateElement.hindex c2671036cac..d12058e6895 100644--- a/Libraries/LibWeb/SVG/SVGAnimateElement.h+++ b/Libraries/LibWeb/SVG/SVGAnimateElement.h@@ -19,7 +19,7 @@ private:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;- virtual Vector<Animations::BaseKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;+ virtual Vector<SVGKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;};}diff --git a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cppindex 75189fb48ec..39a49e600dc 100644--- a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp+++ b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.cpp@@ -188,7 +188,7 @@ static MotionRotation motion_rotation(DOM::Element const& element)}// https://svgwg.org/specs/animations/#AnimateMotionElement-Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motion_path(ReadonlySpan<PathVertex> vertices, CSS::PropertyID property_id) const+Vector<SVGKeyframe> SVGAnimateMotionElement::keyframes_along_motion_path(ReadonlySpan<PathVertex> vertices, CSS::PropertyID property_id) const{// NB: Follow polylines through the motion path, with enough points along its curves to stay as close to them as the// length of the motion path is measured.@@ -206,7 +206,7 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motionMotionRotations rotations { rotation };auto length = vertices.last().distance;if (length == 0) {- Vector<Animations::BaseKeyframe> keyframes { keyframe(0, property_id, translation(vertices.first().point)), keyframe(1, property_id, translation(vertices.first().point)) };+ Vector<SVGKeyframe> keyframes { keyframe(0, property_id, translation(vertices.first().point)), keyframe(1, property_id, translation(vertices.first().point)) };if (!rotation.is_none()) {for (auto& keyframe : keyframes)set_keyframe_property(keyframe, CSS::PropertyID::Rotate, rotations.rotation_for(vertices.first().direction));@@ -220,7 +220,7 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motion// between them.// FIXME: Divide the duration between the points of the path for the other calcMode values.// NB: Where the motion path changes direction at once, its vertex appears twice, so the target turns at once.- Vector<Animations::BaseKeyframe> keyframes;+ Vector<SVGKeyframe> keyframes;keyframes.ensure_capacity(vertices.size());for (auto const& vertex : vertices) {auto vertex_keyframe = keyframe(vertex.distance / length, property_id, translation(vertex.point));@@ -232,7 +232,7 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes_along_motion}// https://svgwg.org/specs/animations/#AnimateMotionElement-Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const+Vector<SVGKeyframe> SVGAnimateMotionElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const{// Regarding the definition of the motion path, the ‘mpath’ element overrides the ‘path’ attribute, which overrides// ‘values’, which overrides ‘from’, ‘by’ and ‘to’.@@ -258,7 +258,7 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes(SVGElement c// NB: Without a from value, this is a to animation, which animates from the underlying value. The keyframe effect// takes its missing start keyframe from that value.- Vector<Animations::BaseKeyframe> keyframes;+ Vector<SVGKeyframe> keyframes;if (from_translation)keyframes.append(keyframe(0, property_id, *from_translation));keyframes.append(keyframe(1, property_id, *to_translation));@@ -276,9 +276,8 @@ Vector<Animations::BaseKeyframe> SVGAnimateMotionElement::keyframes(SVGElement cif (from_point.has_value() && to_point.has_value())direction = { to_point->x() - from_point->x(), to_point->y() - from_point->y() };if (!from_translation) {- Animations::BaseKeyframe rotation_keyframe;+ SVGKeyframe rotation_keyframe;rotation_keyframe.offset = 0;- rotation_keyframe.properties = Animations::BaseKeyframe::ParsedProperties {};keyframes.prepend(move(rotation_keyframe));}MotionRotations rotations { rotation };diff --git a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.hindex f86caa75465..cba13894324 100644--- a/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h+++ b/Libraries/LibWeb/SVG/SVGAnimateMotionElement.h@@ -25,8 +25,8 @@ private:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;virtual Optional<CSS::PropertyID> target_property() const override;- virtual Vector<Animations::BaseKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;- Vector<Animations::BaseKeyframe> keyframes_along_motion_path(ReadonlySpan<PathVertex> motion_path_vertices, CSS::PropertyID) const;+ virtual Vector<SVGKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;+ Vector<SVGKeyframe> keyframes_along_motion_path(ReadonlySpan<PathVertex> motion_path_vertices, CSS::PropertyID) const;Optional<Vector<PathVertex>> m_referenced_motion_path_vertices;};diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp b/Libraries/LibWeb/SVG/SVGAnimationElement.cppindex 00482a6be68..e93b732b812 100644--- a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.cpp@@ -7,18 +7,19 @@#include <LibWeb/SVG/SVGAnimationElement.h>#include <AK/Math.h>-#include <LibWeb/Animations/DocumentTimeline.h>+#include <LibWeb/Animations/AnimationTimeline.h>#include <LibWeb/CSS/PropertyNameAndID.h>+#include <LibWeb/CSS/StyleEngineInput.h>#include <LibWeb/CSS/StyleValues/StyleValue.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/EventNames.h>#include <LibWeb/HTML/Scripting/Environments.h>+#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/HTML/Window.h>#include <LibWeb/HighResolutionTime/TimeOrigin.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/SVG/AttributeNames.h>#include <LibWeb/SVG/AttributeParsing.h>-#include <LibWeb/SVG/SMILAnimation.h>#include <LibWeb/SVG/SMILTimeContainer.h>#include <LibWeb/SVG/SVGSVGElement.h>#include <LibWeb/SVG/TimeEvent.h>@@ -34,7 +35,16 @@ SVGAnimationElement::SVGAnimationElement(DOM::Document& document, DOM::Qualifiedvoid SVGAnimationElement::visit_edges(Cell::Visitor& visitor){Base::visit_edges(visitor);- visitor.visit(m_animation);+ if (m_animation.has_value())+ m_animation->visit_edges(visitor);+ visitor.visit(m_animation_time_container);+}++void SVGAnimationElement::finalize()+{+ Base::finalize();+ if (auto animation = exchange(m_animation, {}); animation.has_value())+ Animations::RustFFI::animations_smil_animation_let_go(&animation->record());}void SVGAnimationElement::inserted()@@ -142,16 +152,16 @@ double SVGAnimationElement::repeat_count() const}// https://svgwg.org/specs/animations/#FillAttribute-Bindings::FillMode SVGAnimationElement::fill_mode() const+Animations::RustFFI::FillMode SVGAnimationElement::fill_mode() const{// freeze// The animation effect F(t) is defined to freeze the effect value at the last value of the active duration.if (auto fill = get_attribute(AttributeNames::fill); fill.has_value() && *fill == "freeze"sv)- return Bindings::FillMode::Forwards;+ return Animations::RustFFI::FillMode::Forwards;// remove// The animation effect is removed (no longer applied) when the active duration of the animation is over.- return Bindings::FillMode::None;+ return Animations::RustFFI::FillMode::None;}// https://svgwg.org/specs/animations/#RestartAttribute@@ -252,25 +262,58 @@ double SVGAnimationElement::current_presentation_time()return time_container->current_time_in_milliseconds();}-Animations::BaseKeyframe SVGAnimationElement::keyframe(double offset, CSS::PropertyID property_id, CSS::StyleValue const& value)+SVGKeyframe SVGAnimationElement::keyframe(double offset, CSS::PropertyID property_id, CSS::StyleValue const& value){- Animations::BaseKeyframe keyframe;+ SVGKeyframe keyframe;keyframe.offset = offset;- keyframe.properties = Animations::BaseKeyframe::ParsedProperties {};set_keyframe_property(keyframe, property_id, value);return keyframe;}-void SVGAnimationElement::set_keyframe_property(Animations::BaseKeyframe& keyframe, CSS::PropertyID property_id, CSS::StyleValue const& value)+void SVGAnimationElement::set_keyframe_property(SVGKeyframe& keyframe, CSS::PropertyID property_id, CSS::StyleValue const& value){- keyframe.parsed_properties().set(CSS::PropertyNameAndID::from_id(property_id), CSS::RustStyleValueHandle::retained(value.rust_style_value_data()));+ keyframe.properties.set(CSS::PropertyNameAndID::from_id(property_id), CSS::RustStyleValueHandle::retained(value.rust_style_value_data()));+}++// The keyframe set of the keyframes, in their order.+static Animations::KeyframeSetHandle keyframe_set_of(Vector<SVGKeyframe> const& keyframes)+{+ Vector<Animations::RustFFI::FfiProcessedKeyframe> processed_keyframes;+ Vector<Animations::RustFFI::FfiProcessedKeyframeProperty> properties;+ processed_keyframes.ensure_capacity(keyframes.size());+ for (auto const& keyframe : keyframes) {+ Animations::RustFFI::FfiProcessedKeyframe processed_keyframe {};+ processed_keyframe.key = static_cast<u64>(keyframe.offset * 100 * 1000.0);+ processed_keyframe.composite = Animations::RustFFI::CompositeOperationOrAuto::Auto;+ if (keyframe.easing.has_value()) {+ processed_keyframe.has_easing = true;+ processed_keyframe.easing = keyframe.easing->descriptor();+ }+ processed_keyframe.first_property = static_cast<u32>(properties.size());+ for (auto const& [property, property_value] : keyframe.properties) {+ properties.append({+ .property_id = to_underlying(property.id()),+ .custom_name = property.is_custom_property() ? property.name().raw_identity() : 0,+ .value = property_value.data(),+ });+ }+ processed_keyframe.property_count = static_cast<u32>(properties.size()) - processed_keyframe.first_property;+ processed_keyframes.unchecked_append(processed_keyframe);+ }+ return Animations::KeyframeSetHandle::adopt(Animations::RustFFI::animations_keyframe_set_from_processed_keyframes(processed_keyframes.span(), properties.span()));}void SVGAnimationElement::update_animation(){- if (m_animation) {- m_animation->cancel();- m_animation = nullptr;+ if (auto animation = exchange(m_animation, {}); animation.has_value()) {+ exchange(m_animation_time_container, nullptr)->remove_animation(*animation);+ // NB: Cancelling an animation that is not idle runs in an execution context, as an Animation's does.+ Optional<HTML::TemporaryExecutionContext> execution_context;+ if (animation->timing_state().play_state != Animations::RustFFI::AnimationPlayState::Idle)+ execution_context.emplace(document().relevant_settings_object());+ Animations::RustFFI::animations_animation_cancel(&animation->record(), true, Animations::perform_host_effect);+ execution_context.clear();+ Animations::RustFFI::animations_smil_animation_let_go(&animation->record());}if (!is_connected())@@ -296,33 +339,46 @@ void SVGAnimationElement::update_animation()// FIXME: Resolve the interval from the other timing attributes.// FIXME: A running animation requests a rendering update on every frame, even when its output cannot change, as// with an indefinite one. This keeps the rendering loop running for as long as such an animation is active.- Animations::KeyframeEffect::Options options;- auto simple_duration = this->simple_duration();- auto repeat_count = this->repeat_count();- options.timing.delay = *begin_time;- options.timing.duration = simple_duration;- options.timing.iterations = repeat_count;- options.timing.fill = fill_mode();+ Animations::RustFFI::SpecifiedEffectTiming timing {+ .start_delay = *begin_time,+ .end_delay = 0,+ .iteration_duration = { .is_auto = false, .milliseconds = simple_duration() },+ .iteration_start = 0,+ .iteration_count = repeat_count(),+ .fill_mode = static_cast<Animations::RustFFI::FillMode>(to_underlying(fill_mode())),+ .playback_direction = Animations::RustFFI::PlaybackDirection::Normal,+ };+ Optional<CSS::EasingFunction> timing_function;// NB: An end time cuts the active duration short. With an indefinite simple duration, the animation holds the// value at its start for the active duration that remains.if (auto end_time = interval_end_time(); end_time.has_value()) {auto active_duration = *end_time - *begin_time;- if (isinf(simple_duration)) {- options.timing.duration = active_duration;- options.timing.iterations = 1;- options.timing.easing = "linear(0, 0)"_utf16;+ if (isinf(timing.iteration_duration.milliseconds)) {+ timing.iteration_duration.milliseconds = active_duration;+ timing.iteration_count = 1;+ timing_function = CSS::EasingFunction::parse("linear(0, 0)"_utf16);} else {- options.timing.iterations = min(repeat_count, active_duration / simple_duration);+ timing.iteration_count = min(timing.iteration_count, active_duration / timing.iteration_duration.milliseconds);}}- auto effect = MUST(Animations::KeyframeEffect::create_from_processed_keyframes(target, move(keyframes), options));- auto animation = SMILAnimation::create(*this, *time_container, *begin_time);- animation->set_timeline(document().timeline());- animation->set_effect(effect);- time_container->add_animation(animation);- m_animation = animation;+ auto keyframe_set = keyframe_set_of(keyframes);+ auto timing_function_descriptor = timing_function.has_value() ? timing_function->descriptor() : CSS::EasingFunction::Descriptor {};+ Utf16FlyString timing_function_serialization = timing_function.has_value() ? Utf16FlyString { timing_function->to_utf16_string() } : Utf16FlyString {};+ Animations::RustFFI::FfiSmilAnimation description {+ .animation_element = this,+ .target = target.ptr(),+ .keyframes = keyframe_set.ptr(),+ .timing = timing,+ .timing_function = timing_function.has_value() ? &timing_function_descriptor : nullptr,+ .timing_function_serialization = timing_function_serialization.raw_identity(),+ .begin_time = *begin_time,+ };+ m_animation = Animations::AnimationRef::adopt(*Animations::RustFFI::animations_smil_animation_create(&description, &document().timeline()->record(), Animations::perform_host_effect));+ CSS::record_attr_names_read_by_keyframes(*target, keyframe_set);+ m_animation_time_container = time_container;+ time_container->add_animation(*m_animation);// NB: Time events are raised for intervals that begin from now on.if (!m_time_events_last_checked_time.has_value())@@ -484,23 +540,45 @@ void SVGAnimationElement::end_element_at(float offset)update_animation();}-void SVGAnimationElement::queue_time_event(Utf16FlyString const& type, i32 detail)-{- // NB: Time events are dispatched along with the other animation events of the document.+void SVGAnimationElement::queue_time_event(Animations::RustFFI::TimeEventType type, i32 detail)+{+ // NB: Time events are dispatched along with the other animation events of the document, which creates each as it+ // dispatches it, with the time stamp of now.+ auto* timeline = static_cast<Animations::AnimationTimeline*>(Animations::RustFFI::animations_animation_timeline(&m_animation->record()));+ auto scheduled_event_time = timeline && timeline->can_convert_a_timeline_time_to_an_origin_relative_time()+ ? timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline->current_time())+ : Optional<double> {};+ document().append_pending_animation_event(*m_animation, {+ .kind = Animations::RustFFI::PendingAnimationEventKind::Time,+ .css_event_type = {},+ .playback_event_type = {},+ .time_event_type = type,+ .detail = detail,+ .elapsed_time = 0,+ .current_time = {},+ .timeline_time = {},+ .scheduled_event_time = Animations::to_ffi(scheduled_event_time),+ .time_stamp = HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this)),+ });+}++void SVGAnimationElement::dispatch_pending_time_event(Animations::RustFFI::FfiPendingAnimationEvent const& pending_event)+{+ auto const& type = [&] -> Utf16FlyString const& {+ switch (pending_event.time_event_type) {+ case Animations::RustFFI::TimeEventType::Begin:+ return HTML::EventNames::beginEvent;+ case Animations::RustFFI::TimeEventType::End:+ return HTML::EventNames::endEvent;+ case Animations::RustFFI::TimeEventType::Repeat:+ return HTML::EventNames::repeatEvent;+ }+ VERIFY_NOT_REACHED();+ }();auto& document = this->document();- auto event = TimeEvent::create(type, document.window() ? document.window()->window().ptr() : nullptr, detail,- HighResolutionTime::current_high_resolution_time(HTML::relevant_global_object(*this)));+ auto event = TimeEvent::create(type, document.window() ? document.window()->window().ptr() : nullptr, pending_event.detail, pending_event.time_stamp);event->set_is_trusted(true);-- auto timeline = m_animation->timeline();- document.append_pending_animation_event({- .event = event,- .animation = *m_animation,- .target = *this,- .scheduled_event_time = timeline && timeline->can_convert_a_timeline_time_to_an_origin_relative_time()- ? timeline->convert_a_timeline_time_to_an_origin_relative_time(timeline->current_time())- : Optional<double> {},- });+ dispatch_event(event);}// https://svgwg.org/specs/animations/#InterfaceTimeEvent@@ -508,7 +586,7 @@ void SVGAnimationElement::queue_time_events_if_necessary(){// FIXME: Raise time events for an animation element without a target or animated property too.auto time_container = is_connected() ? this->time_container() : nullptr;- if (!m_animation || !time_container || !time_container->has_begun())+ if (!m_animation.has_value() || !time_container || !time_container->has_begun())return;auto current_time = time_container->current_time_in_milliseconds();@@ -523,7 +601,7 @@ void SVGAnimationElement::queue_time_events_if_necessary()// another begin event, as the element restarts.if (m_time_events_reported_active && (!is_active || begin_time != m_time_events_begin_time)) {m_time_events_reported_active = false;- queue_time_event(HTML::EventNames::endEvent);+ queue_time_event(Animations::RustFFI::TimeEventType::End);}// beginEvent@@ -533,7 +611,7 @@ void SVGAnimationElement::queue_time_events_if_necessary()m_time_events_reported_active = true;m_time_events_begin_time = begin_time;m_time_events_iteration = isinf(simple_duration()) ? 0 : floor((current_time - *begin_time) / simple_duration());- queue_time_event(HTML::EventNames::beginEvent);+ queue_time_event(Animations::RustFFI::TimeEventType::Begin);return;}@@ -541,8 +619,8 @@ void SVGAnimationElement::queue_time_events_if_necessary()if (!is_active && begin_time.has_value() && begin_time != m_time_events_begin_time && last_checked_time.has_value()&& *begin_time >= *last_checked_time && *begin_time <= current_time) {m_time_events_begin_time = begin_time;- queue_time_event(HTML::EventNames::beginEvent);- queue_time_event(HTML::EventNames::endEvent);+ queue_time_event(Animations::RustFFI::TimeEventType::Begin);+ queue_time_event(Animations::RustFFI::TimeEventType::End);return;}@@ -555,7 +633,7 @@ void SVGAnimationElement::queue_time_events_if_necessary()auto iteration = floor((current_time - *begin_time) / simple_duration());auto previous_iteration = exchange(m_time_events_iteration, iteration);if (iteration > previous_iteration)- queue_time_event(HTML::EventNames::repeatEvent, static_cast<i32>(min(iteration, static_cast<double>(NumericLimits<i32>::max()))));+ queue_time_event(Animations::RustFFI::TimeEventType::Repeat, static_cast<i32>(min(iteration, static_cast<double>(NumericLimits<i32>::max()))));}}diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.h b/Libraries/LibWeb/SVG/SVGAnimationElement.hindex 59a934ee743..58658c242ff 100644--- a/Libraries/LibWeb/SVG/SVGAnimationElement.h+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.h@@ -7,13 +7,22 @@#pragma once#include <LibJS/Forward.h>-#include <LibWeb/Animations/KeyframeEffect.h>+#include <LibWeb/Animations/AnimationEffect.h>#include <LibWeb/CSS/PropertyID.h>+#include <LibWeb/CSS/PropertyNameAndID.h>+#include <LibWeb/CSS/StyleValues/StyleValue.h>#include <LibWeb/Export.h>#include <LibWeb/SVG/SVGElement.h>namespace Web::SVG {+// A keyframe of the animation of an SVG animation element, whose offset is always specified.+struct SVGKeyframe {+ double offset { 0 };+ Optional<CSS::EasingFunction> easing;+ HashMap<CSS::PropertyNameAndID, CSS::RustStyleValueHandle> properties;+};+class SVGAnimationElement : public SVGElement {WEB_WRAPPABLE(SVGAnimationElement, SVGElement);@@ -39,20 +48,22 @@ public:void end_element_at(float offset);void queue_time_events_if_necessary();+ void dispatch_pending_time_event(Animations::RustFFI::FfiPendingAnimationEvent const&);protected:SVGAnimationElement(DOM::Document&, DOM::QualifiedName);virtual void visit_edges(Cell::Visitor&) override;+ virtual void finalize() override;virtual void inserted() override;virtual void removed_from(IsSubtreeRoot, Node* old_ancestor, Node& old_root) override;virtual void moved_from(IsSubtreeRoot, GC::Ptr<Node> old_ancestor) override;virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;virtual Optional<CSS::PropertyID> target_property() const;- virtual Vector<Animations::BaseKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const = 0;- static Animations::BaseKeyframe keyframe(double offset, CSS::PropertyID, CSS::StyleValue const&);- static void set_keyframe_property(Animations::BaseKeyframe&, CSS::PropertyID, CSS::StyleValue const&);+ virtual Vector<SVGKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const = 0;+ static SVGKeyframe keyframe(double offset, CSS::PropertyID, CSS::StyleValue const&);+ static void set_keyframe_property(SVGKeyframe&, CSS::PropertyID, CSS::StyleValue const&);double simple_duration() const;@@ -61,7 +72,7 @@ protected:private:GC::Ptr<SMILTimeContainer> time_container();double repeat_count() const;- Bindings::FillMode fill_mode() const;+ Animations::RustFFI::FillMode fill_mode() const;enum class Restart : u8 {Always,@@ -75,9 +86,12 @@ private:Optional<double> interval_begin_time() const;Optional<double> interval_end_time() const;bool is_active_at(double time) const;- void queue_time_event(Utf16FlyString const& type, i32 detail = 0);+ void queue_time_event(Animations::RustFFI::TimeEventType, i32 detail = 0);- GC::Ptr<SMILAnimation> m_animation;+ // NB: The animation of the element, which the element holds until it lets go of it, and the time container of the+ // timeline it plays on.+ Optional<Animations::AnimationRef> m_animation;+ GC::Ptr<SMILTimeContainer> m_animation_time_container;// NB: The latest instance times that the DOM methods created, in milliseconds on the timeline of the SVG document// fragment.diff --git a/Libraries/LibWeb/SVG/SVGSetElement.cpp b/Libraries/LibWeb/SVG/SVGSetElement.cppindex a6688355ad5..b34c8c54e36 100644--- a/Libraries/LibWeb/SVG/SVGSetElement.cpp+++ b/Libraries/LibWeb/SVG/SVGSetElement.cpp@@ -25,7 +25,7 @@ void SVGSetElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16}// https://svgwg.org/specs/animations/#SetElementToAttribute-Vector<Animations::BaseKeyframe> SVGSetElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const+Vector<SVGKeyframe> SVGSetElement::keyframes(SVGElement const& target, CSS::PropertyID property_id) const{// Specifies the value for the attribute during the duration of the ‘set’ element. The argument value must match the// attribute type.diff --git a/Libraries/LibWeb/SVG/SVGSetElement.h b/Libraries/LibWeb/SVG/SVGSetElement.hindex a4be66f1c48..65a1d32a9d7 100644--- a/Libraries/LibWeb/SVG/SVGSetElement.h+++ b/Libraries/LibWeb/SVG/SVGSetElement.h@@ -19,7 +19,7 @@ private:virtual void attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_) override;- virtual Vector<Animations::BaseKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;+ virtual Vector<SVGKeyframe> keyframes(SVGElement const& target, CSS::PropertyID) const override;};}diff --git a/Meta/Generators/libweb_bindings/attributes.py b/Meta/Generators/libweb_bindings/attributes.pyindex 03029e20d43..e6af0e7965f 100644--- a/Meta/Generators/libweb_bindings/attributes.py+++ b/Meta/Generators/libweb_bindings/attributes.py@@ -19,6 +19,8 @@ from Generators.libweb_bindings.extended_attributes import wrap_with_extended_atfrom Generators.libweb_bindings.glue_headers import bindings_glue_header_for_interfacefrom Generators.libweb_bindings.includes import GeneratedIncludesfrom Generators.libweb_bindings.realms import member_realm_expr+from Generators.libweb_bindings.rust_types import is_member_implemented_in_rust+from Generators.libweb_bindings.rust_types import rust_member_definition_entry_pointfrom Generators.libweb_bindings.security_checks import implementation_checkfrom Generators.libweb_bindings.security_checks import interface_needs_security_checkfrom Generators.libweb_bindings.security_checks import on_the_window@@ -222,6 +224,16 @@ def define_the_attributes(# 1. For each attribute attr of attributes:for attribute in attributes:+ if is_member_implemented_in_rust(attribute):+ # NB: The Rust bindings define the accessor properties of an attribute that they implement.+ out.write(+ wrap_with_extended_attribute_exposure_checks(+ includes,+ attribute.extended_attributes,+ f" {rust_member_definition_entry_point(interface, attribute)}(&vm, &realm, &object);\n",+ )+ )+ continueif "FIXME" in attribute.extended_attributes:definition = f' object.define_unimplemented_property("{attribute.name}"_utf16_fly_string);\n'out.write(@@ -345,7 +357,7 @@ def write_attribute_getters(out: TextIO, context: GenerationContext, includes: GeneratedIncludes, interface: Interface) -> None:for attribute in interface.regular_attributes:- if "FIXME" in attribute.extended_attributes:+ if "FIXME" in attribute.extended_attributes or is_member_implemented_in_rust(attribute):continuewrite_attribute_getter(out, context, includes, interface, attribute)@@ -682,7 +694,7 @@ def write_attribute_setters(out: TextIO, context: GenerationContext, includes: GeneratedIncludes, interface: Interface) -> None:for attribute in interface.regular_attributes:- if "FIXME" in attribute.extended_attributes:+ if "FIXME" in attribute.extended_attributes or is_member_implemented_in_rust(attribute):continueif not attribute_has_setter(attribute):continuediff --git a/Meta/Generators/libweb_bindings/constructors.py b/Meta/Generators/libweb_bindings/constructors.pyindex 713a3576c39..3673162ea42 100644--- a/Meta/Generators/libweb_bindings/constructors.py+++ b/Meta/Generators/libweb_bindings/constructors.py@@ -20,16 +20,11 @@ from Utils.webidl_parser import Constructorfrom Utils.webidl_parser import Interface-def bindings_constructor_call(- interface: Interface, arguments: str, needs_argument_count: bool, needs_realm: bool-) -> str:+def bindings_constructor_call(interface: Interface, arguments: str, needs_realm: bool) -> str:arguments_with_leading_comma = f", {arguments}" if arguments else ""- argument_count = ", vm.argument_count()" if needs_argument_count else ""if needs_realm:- return f"Web::Bindings::construct_{idl_identifier_cpp_name(interface)}(realm{arguments_with_leading_comma}{argument_count})"- if arguments:- return f"Web::Bindings::construct_{idl_identifier_cpp_name(interface)}({arguments}{argument_count})"- return f"Web::Bindings::construct_{idl_identifier_cpp_name(interface)}({argument_count.removeprefix(', ')})"+ return f"Web::Bindings::construct_{idl_identifier_cpp_name(interface)}(realm{arguments_with_leading_comma})"+ return f"Web::Bindings::construct_{idl_identifier_cpp_name(interface)}({arguments})"def write_constructor_function(@@ -192,7 +187,6 @@ def write_constructor_steps(construct_impl_call = bindings_constructor_call(interface,arguments,- "NeedsArgumentCount" in constructor.extended_attributes,"RealmFreeConstructor" not in constructor.extended_attributes,)out.write(diff --git a/Meta/Generators/libweb_bindings/glue_headers.py b/Meta/Generators/libweb_bindings/glue_headers.pyindex f3abe24c809..8e45a062c53 100644--- a/Meta/Generators/libweb_bindings/glue_headers.py+++ b/Meta/Generators/libweb_bindings/glue_headers.py@@ -12,7 +12,6 @@ def bindings_glue_header_for_interface(interface: Interface, wrapper_interface_nmodule = interface.path.parent.namemodule_headers = {- "Animations": "LibWeb/Animations/BindingsGlue.h","CSS": "LibWeb/CSS/BindingsGlue.h","IndexedDB": "LibWeb/IndexedDB/BindingsGlue.h","WebRTC": "LibWeb/WebRTC/BindingsGlue.h",diff --git a/Meta/Generators/libweb_bindings/interface_declaration.py b/Meta/Generators/libweb_bindings/interface_declaration.pyindex db719240f21..7e5f3d64230 100644--- a/Meta/Generators/libweb_bindings/interface_declaration.py+++ b/Meta/Generators/libweb_bindings/interface_declaration.py@@ -23,6 +23,7 @@ from Generators.libweb_bindings.named_and_indexed_properties import write_legacyfrom Generators.libweb_bindings.named_and_indexed_properties import write_named_properties_object_declarationfrom Generators.libweb_bindings.namespaces import write_namespace_declarationfrom Generators.libweb_bindings.overload_resolution import operation_callback_names+from Generators.libweb_bindings.rust_types import is_member_implemented_in_rustfrom Generators.libweb_bindings.wrappers import LOCATION_WRAPPER_HOOKSfrom Generators.libweb_bindings.wrappers import create_wrapper_function_namefrom Generators.libweb_bindings.wrappers import cross_origin_property_function_declarations@@ -130,7 +131,7 @@ private:out.write(f" friend {declaration};\n")out.write("\n")for attribute in interface.regular_attributes:- if "FIXME" in attribute.extended_attributes:+ if "FIXME" in attribute.extended_attributes or is_member_implemented_in_rust(attribute):continueout.write(f" JS_DECLARE_NATIVE_FUNCTION({attribute_getter_callback_name(attribute)});\n")if attribute_has_setter(attribute):diff --git a/Meta/Generators/libweb_bindings/interfaces.py b/Meta/Generators/libweb_bindings/interfaces.pyindex 56a87a587a5..f190864ad20 100644--- a/Meta/Generators/libweb_bindings/interfaces.py+++ b/Meta/Generators/libweb_bindings/interfaces.py@@ -23,6 +23,8 @@ from Generators.libweb_bindings.includes import GeneratedIncludesfrom Generators.libweb_bindings.named_and_indexed_properties import interface_supports_named_propertiesfrom Generators.libweb_bindings.named_and_indexed_properties import legacy_platform_object_info_functionsfrom Generators.libweb_bindings.overload_resolution import parameter_list_length+from Generators.libweb_bindings.rust_types import rust_implemented_members+from Generators.libweb_bindings.rust_types import rust_member_definition_entry_pointfrom Generators.libweb_bindings.security_checks import interface_needs_security_checkfrom Generators.libweb_bindings.wrappers import create_wrapper_function_namefrom Generators.libweb_bindings.wrappers import interface_and_inherited_interfaces@@ -328,6 +330,14 @@ JS::ThrowCompletionOr<GC::Ref<JS::Object>> {interface.constructor_class}::constrfor overload_index, constructor in enumerate(interface.constructors):constructors.write_constructor_function(out, context, includes, interface, constructor, overload_index)+ rust_members = rust_implemented_members(interface)+ if rust_members is not None:+ for member in rust_members.regular_attributes + rust_members.regular_operations:+ out.write(+ f'extern "C" void {rust_member_definition_entry_point(interface, member)}(void* vm, void* realm, void* prototype);\n'+ )+ out.write("\n")+out.write(f"""void {interface.prototype_class}::initialize(JS::Realm& realm, JS::Object& object){{""")diff --git a/Meta/Generators/libweb_bindings/operations.py b/Meta/Generators/libweb_bindings/operations.pyindex e5b52689daf..0f0a8d9522a 100644--- a/Meta/Generators/libweb_bindings/operations.py+++ b/Meta/Generators/libweb_bindings/operations.py@@ -21,6 +21,8 @@ from Generators.libweb_bindings.glue_headers import bindings_glue_header_for_intfrom Generators.libweb_bindings.includes import GeneratedIncludesfrom Generators.libweb_bindings.realms import member_passes_realm_to_implementationfrom Generators.libweb_bindings.realms import member_realm_expr+from Generators.libweb_bindings.rust_types import is_member_implemented_in_rust+from Generators.libweb_bindings.rust_types import rust_member_definition_entry_pointfrom Generators.libweb_bindings.security_checks import implementation_checkfrom Generators.libweb_bindings.security_checks import interface_needs_security_checkfrom Generators.libweb_bindings.security_checks import on_the_window@@ -179,10 +181,21 @@ def define_the_regular_operations(interface: Interface,unforgeable: bool = False,) -> None:- for name, operations in overload_resolution.operation_overload_sets(interface).items():+ for name, operations in overload_resolution.operation_overload_sets(interface, with_rust_operations=True).items():if any("LegacyUnforgeable" in operation.extended_attributes for operation in operations) != unforgeable:continueoperation = operations[0]+ if is_member_implemented_in_rust(operation):+ # NB: The Rust bindings define the native function of an operation that they implement.+ out.write(+ wrap_with_extended_attribute_exposure_checks(+ includes,+ operation.extended_attributes,+ f" {rust_member_definition_entry_point(interface, operation)}(&vm, &realm, &object);\n\n",+ f"{interface.name}.{name}",+ )+ )+ continueout.write(wrap_with_extended_attribute_exposure_checks(includes,diff --git a/Meta/Generators/libweb_bindings/overload_resolution.py b/Meta/Generators/libweb_bindings/overload_resolution.pyindex 36bf68d4ee4..cca5e4baf89 100644--- a/Meta/Generators/libweb_bindings/overload_resolution.py+++ b/Meta/Generators/libweb_bindings/overload_resolution.py@@ -524,12 +524,18 @@ def distinguishability_category(idl_type: IDLType, context: GenerationContext) -return "InterfaceLike"-def operation_overload_sets(interface: Interface, static: bool = False) -> dict[str, list[Operation]]:+def operation_overload_sets(+ interface: Interface, static: bool = False, with_rust_operations: bool = False+) -> dict[str, list[Operation]]:+ """The overload sets of the operations that the C++ bindings implement. With with_rust_operations, those of the+ operations marked [ImplementedIn=Rust] as well, which the Rust bindings implement, in the order of the IDL."""overload_sets: dict[str, list[Operation]] = {}operations = interface.static_operations if static else interface.regular_operationsfor operation in operations:if "FIXME" in operation.extended_attributes:continue+ if not with_rust_operations and operation.extended_attributes.get("ImplementedIn") == "Rust":+ continueoverload_sets.setdefault(operation.name, []).append(operation)return overload_setsdiff --git a/Meta/Generators/libweb_bindings/rust_bindings.py b/Meta/Generators/libweb_bindings/rust_bindings.pyindex 8d9e4b5c847..7f7c209e6c0 100644--- a/Meta/Generators/libweb_bindings/rust_bindings.py+++ b/Meta/Generators/libweb_bindings/rust_bindings.py@@ -13,6 +13,11 @@## A wrapper is a platform object whose host data holds a GC cell of the implementation. Its wrappable slot stays# empty, so the C++ bindings see a platform object without a C++ implementation object.+#+# A regular attribute or operation of an interface implemented in C++ can be [ImplementedIn=Rust] as well. Its+# bindings are Rust code that calls a function of the Rust module of the interface's IDL file, which receives the+# wrapper of the object it runs on, and the C++ bindings call into the Rust bindings to define it on the interface+# prototype object.import textwrap@@ -62,13 +67,17 @@ from Generators.libweb_bindings.rust_types import holds_cellsfrom Generators.libweb_bindings.rust_types import inheriting_interfacesfrom Generators.libweb_bindings.rust_types import is_implemented_in_rustfrom Generators.libweb_bindings.rust_types import is_promise_type+from Generators.libweb_bindings.rust_types import rust_implemented_membersfrom Generators.libweb_bindings.rust_types import rust_interface_path+from Generators.libweb_bindings.rust_types import rust_member_definition_entry_point+from Generators.libweb_bindings.rust_types import rust_module_pathfrom Generators.libweb_bindings.rust_types import rust_parameter_typefrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_usage import DefinitionUsagefrom Generators.libweb_bindings.wrappers import wrapper_host_class_namefrom Generators.libweb_bindings.wrappers import wrapper_namefrom Utils.utils import title_case_to_snake_case+from Utils.webidl_parser import Attributefrom Utils.webidl_parser import Interfacefrom Utils.webidl_parser import Modulefrom Utils.webidl_parser import OperationParameter@@ -1153,7 +1162,7 @@ RUST_BINDINGS_IMPORTS = """ #![allow(unused_imports)]define_interface_object_properties, define_operation, define_to_string_tag, define_unimplemented_property,define_value_iterator_properties, entry_point_arguments, implementation_if, implementation_of,SecurityCheckType, prototype_from_new_target, realm_is_secure_context, realm_is_window, set_dictionary_member,- set_interface_prototype_object_prototype, this_object, to_interface,+ set_interface_prototype_object_prototype, this_cpp_object, this_object, to_interface,};use crate::bindings::async_iterable::{AsyncIterable, DefaultAsyncIterator, DefaultAsyncIteratorClasses, async_iterator_next, async_iterator_return,@@ -1214,6 +1223,56 @@ def write_rust_operation_set()+def write_rust_attributes(+ out: TextIO, context: GenerationContext, interface: Interface, attributes: List[RustAttribute]+) -> None:+ """The native functions of the getters and the setters of the attributes."""+ for attribute in attributes:+ name = attribute.attribute.name+ if attribute.event_type is not None:+ write_rust_event_handler_attribute(out, attribute)+ continue+ conversion = (+ "Ok(result)"+ if attribute.returns_js_value+ else rust_to_js_value(attribute.attribute.type, "result", "&cx", context, f"{interface.name}.{name}")+ )+ call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"+ if attribute.attribute.inherit:+ call = inherited_attribute_getter_call(context, interface, attribute)+ this_check = f'this_implementation(vm, "{name}", SecurityCheckType::Getter)?'+ if is_promise_type(attribute.attribute.type) and not attribute.attribute.type.nullable:+ # https://webidl.spec.whatwg.org/#dfn-attribute-getter+ this_check = f"""match this_implementation(vm, "{name}", SecurityCheckType::Getter) {{+ Ok(this) => this,+ // If the attribute's type is a promise type, a this value that does not implement the interface rejects+ // a new promise.+ Err(throw) => {{+ let realm = vm.current_realm().expect("a native function runs in a realm");+ return Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()));+ }}+ }}"""+ receiver = "(implementation, mut cx)"+ caller_realm_context = ""+ if "NeedsCallerRealm" in attribute.attribute.extended_attributes:+ receiver = "(implementation, _)"+ caller_realm_context = CALLER_REALM_CONTEXT+ out.write(+ f"""+ pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{+ let {receiver} = {this_check};+{caller_realm_context} let result = {call}+ .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;+ {conversion}+ }}+"""+ )+ if attribute.setter_method is not None:+ write_rust_attribute_setter(out, context, interface, attribute)+ elif attribute.put_forwards is not None:+ write_rust_put_forwards_setter(out, attribute)++def write_rust_interface(out: TextIO, context: GenerationContext, module: Module, interface: Interface, interface_name_value: int) -> None:@@ -1283,50 +1342,7 @@ def write_rust_interface(""")- for attribute in members.attributes:- name = attribute.attribute.name- if attribute.event_type is not None:- write_rust_event_handler_attribute(out, attribute)- continue- conversion = (- "Ok(result)"- if attribute.returns_js_value- else rust_to_js_value(attribute.attribute.type, "result", "&cx", context, f"{interface.name}.{name}")- )- call = f"Implementation::{attribute.getter_method}(&implementation, &mut cx)"- if attribute.attribute.inherit:- call = inherited_attribute_getter_call(context, interface, attribute)- this_check = f'this_implementation(vm, "{name}", SecurityCheckType::Getter)?'- if is_promise_type(attribute.attribute.type) and not attribute.attribute.type.nullable:- # https://webidl.spec.whatwg.org/#dfn-attribute-getter- this_check = f"""match this_implementation(vm, "{name}", SecurityCheckType::Getter) {{- Ok(this) => this,- // If the attribute's type is a promise type, a this value that does not implement the interface rejects- // a new promise.- Err(throw) => {{- let realm = vm.current_realm().expect("a native function runs in a realm");- return Ok(Value::from_object(create_rejected_promise(vm, realm, throw.value()).promise()));- }}- }}"""- receiver = "(implementation, mut cx)"- caller_realm_context = ""- if "NeedsCallerRealm" in attribute.attribute.extended_attributes:- receiver = "(implementation, _)"- caller_realm_context = CALLER_REALM_CONTEXT- out.write(- f"""- pub(super) fn {attribute.getter_function}(vm: &Vm) -> ThrowCompletionOr<Value> {{- let {receiver} = {this_check};-{caller_realm_context} let result = {call}- .map_err(|exception| exception.throw_in_current_realm(cx.vm()))?;- {conversion}- }}-"""- )- if attribute.setter_method is not None:- write_rust_attribute_setter(out, context, interface, attribute)- elif attribute.put_forwards is not None:- write_rust_put_forwards_setter(out, attribute)+ write_rust_attributes(out, context, interface, members.attributes)if interface.name == "CSSStyleProperties":write_css_property_accessors(out)@@ -2606,6 +2622,10 @@ def write_rust_bindings(write_rust_definitions(out, context, usage)for module in context.modules:interface = module.interface+ if rust_implemented_members(interface) is not None:+ assert interface is not None+ write_rust_members_of_cpp_interface(out, context, interface)+ continueif interface is None or not is_implemented_in_rust(interface):continueif interface.is_namespace:@@ -2616,6 +2636,92 @@ def write_rust_bindings(write_rust_wrap_for_cpp(out, context, usage)+def write_rust_members_of_cpp_interface(out: TextIO, context: GenerationContext, interface: Interface) -> None:+ """The bindings of the members of an interface implemented in C++ that are [ImplementedIn=Rust]. The functions of+ the Rust module of the interface's IDL file implement them, and receive the wrapper of the object they run on. The+ C++ bindings call an entry point for each to define it on the interface prototype object, in the order of the+ IDL."""+ rust_members_of_interface = rust_implemented_members(interface)+ assert rust_members_of_interface is not None+ members = rust_members(rust_members_of_interface)+ implementation = rust_module_path(interface.path)+ method_documentation = "".join(+ f"/// - `{signature.replace('&self', 'this: &CppInterface')}`\n"+ for signature in implementation_method_signatures(context, rust_members_of_interface, members)+ )+ out.write(+ f"""+/// The bindings of the members of {interface.name} that are implemented in Rust, which call these functions of+/// {implementation}:+{method_documentation}pub(crate) mod {rust_module_name(interface)} {{+{RUST_BINDINGS_IMPORTS}+ use {implementation} as Implementation;++ /// The wrapper of the object that an attribute or an operation runs on, and the context it runs in.+ fn this_implementation<'vm>(+ vm: &'vm Vm,+ identifier: &str,+ check_type: SecurityCheckType,+ ) -> ThrowCompletionOr<(CppInterface, CallContext<'vm>)> {{+ let (object, realm) = this_cpp_object(vm, {cpp_interface_name_constant(interface)}, "{interface.namespaced_name}", identifier, check_type)?;+ // SAFETY: The object is a wrapper of an object that implements the interface.+ Ok((unsafe {{ CppInterface::from_wrapper(object) }}, CallContext::new(vm, realm)))+ }}+"""+ )+ write_rust_attributes(out, context, rust_members_of_interface, members.attributes)+ for attribute in members.attributes:+ name = attribute.attribute.name+ getter = f"raw_native!({attribute.getter_function})"+ if attribute.is_cached:+ definition = f'define_cached_attribute(vm, realm, prototype, "{name}", {getter});'+ else:+ has_setter = not attribute.attribute.readonly or attribute.put_forwards is not None+ setter = f"raw_native!({attribute.setter_function})" if has_setter else "None"+ definition = f'define_attribute(vm, realm, prototype, "{name}", {getter}, {setter});'+ out.write(+ f"""+ /// Defines {interface.name}.{name} on the interface prototype object.+ ///+ /// # Safety+ ///+ /// The pointers must be the VM, a realm and the interface prototype object of the realm.+ #[unsafe(no_mangle)]+ pub unsafe extern "C" fn {rust_member_definition_entry_point(interface, attribute.attribute)}(+ vm: *mut c_void,+ realm: *mut c_void,+ prototype: *mut c_void,+ ) {{+ // SAFETY: The caller passes live pointers.+ let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};+ {definition}+ }}+"""+ )+ for operation_set in members.operation_sets:+ write_rust_operation_set(out, context, rust_members_of_interface, operation_set, write_rust_operation)+ out.write(+ f"""+ /// Defines {interface.name}.{operation_set.name}() on the interface prototype object.+ ///+ /// # Safety+ ///+ /// The pointers must be the VM, a realm and the interface prototype object of the realm.+ #[unsafe(no_mangle)]+ pub unsafe extern "C" fn {rust_member_definition_entry_point(interface, operation_set.overloads[0].operation)}(+ vm: *mut c_void,+ realm: *mut c_void,+ prototype: *mut c_void,+ ) {{+ // SAFETY: The caller passes live pointers.+ let (vm, realm, prototype) = unsafe {{ entry_point_arguments(vm, realm, prototype) }};+ define_operation(vm, realm, prototype, "{operation_set.name}", raw_native!({operation_set.function}), {operation_set.length});+ }}+"""+ )+ out.write("}\n")++def write_rust_wrap_for_cpp(out: TextIO, context: GenerationContext, usage: DefinitionUsage) -> None:"""The entry point through which the C++ bindings of the interfaces that name an interface implemented in Rustwrap an object of it, which C++ code holds as the cell of the object."""@@ -2710,4 +2816,40 @@ def check_rust_bindings(context: GenerationContext, usage: DefinitionUsage, intr)if is_implemented_in_rust(interface):check_interface_is_supported(interface, module, context)+ check_rust_members_of_interface(interface)write_rust_bindings(StringIO(), context, usage, intrinsics)+++def check_rust_members_of_interface(interface: Interface) -> None:+ """Raises an error for a member marked [ImplementedIn] that the bindings do not handle: so far, only the regular+ attributes and operations of an interface implemented in C++ that is not a global interface can be."""++ def fail(member: str, message: str) -> None:+ raise UnsupportedByRustBindings(+ f"{interface.path}: {interface.name}.{member} is [ImplementedIn=Rust], but {message}"+ )++ for member in interface.static_attributes + interface.static_operations:+ if "ImplementedIn" in member.extended_attributes:+ fail(member.name, "the Rust bindings implement no static member of an interface implemented in C++ yet")+ has_default_to_json = any(operation_is_default_to_json(operation) for operation in interface.regular_operations)+ rust_operation_names = set()+ for member in interface.regular_attributes + interface.regular_operations:+ implemented_in = member.extended_attributes.get("ImplementedIn")+ if implemented_in is None:+ continue+ if implemented_in != "Rust":+ fail(member.name, "the only value is Rust")+ if is_implemented_in_rust(interface):+ fail(member.name, "the interface is implemented in Rust as a whole")+ if interface.is_namespace or "Global" in interface.extended_attributes:+ fail(member.name, "the interface is a namespace or a global interface")+ if "LegacyUnforgeable" in member.extended_attributes:+ fail(member.name, "it is [LegacyUnforgeable]")+ if isinstance(member, Attribute) and has_default_to_json:+ fail(member.name, "the default toJSON() of the interface reads its attributes through the C++ bindings")+ if not isinstance(member, Attribute):+ rust_operation_names.add(member.name)+ for operation in interface.regular_operations:+ if operation.name in rust_operation_names and operation.extended_attributes.get("ImplementedIn") != "Rust":+ fail(operation.name, "not all of its overloads are")diff --git a/Meta/Generators/libweb_bindings/rust_to_idl_value.py b/Meta/Generators/libweb_bindings/rust_to_idl_value.pyindex 60f9e7515c6..bb3877d5b04 100644--- a/Meta/Generators/libweb_bindings/rust_to_idl_value.py+++ b/Meta/Generators/libweb_bindings/rust_to_idl_value.py@@ -45,6 +45,7 @@ from Generators.libweb_bindings.rust_types import rust_interface_pathfrom Generators.libweb_bindings.rust_types import rust_typefrom Generators.libweb_bindings.rust_types import rust_union_pathfrom Generators.libweb_bindings.rust_types import rust_union_variant+from Generators.libweb_bindings.rust_types import union_holds_sequence_of_cellsfrom Generators.libweb_bindings.rust_types import union_member_typesfrom Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import DictionaryMember@@ -592,6 +593,7 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLwhat = f"the union {union_type}"path = rust_union_path(union_type, context, what)members = union_members_by_kind(union_type, context, what)+ holds_sequence_of_cells = union_holds_sequence_of_cells(union_type, context)dictionary_type = members.dictionary_typestring_type = members.string_typesteps = []@@ -695,7 +697,20 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDL}}""")- if members.sequence_type is not None:+ if members.sequence_type is not None and holds_sequence_of_cells:+ element = rust_to_idl_value(members.sequence_type.parameters[0], {}, "value", "value", context, what)+ steps.append(+ f""" // 11. If V is an Object, then:+ // 2. If types includes a sequence type, then:+ // 1. Let method be ? GetMethod(V, %Symbol.iterator%).+ // 2. If method is not undefined, return the result of creating a sequence of that type from+ // V and method.+ if let Some(method) = iterator_method(vm, value)? {{+ return Ok(Self::Sequence(sequence_from_iterable(vm, value, method, MarkedVec::new(vm), |value| {element})?));+ }}+"""+ )+ elif members.sequence_type is not None:element = rust_sequence_element_to_idl_value(members.sequence_type, "value", context, what)steps.append(f""" // 11. If V is an Object, then:@@ -802,6 +817,13 @@ def write_union_from_js(out: TextIO, context: GenerationContext, union_type: IDLif members.names_numeric_argument:implementation = f"impl {path}"conversion = "pub(crate) fn from_js_with_identifier(vm: &Vm, value: Value, identifier: &str)"+ if holds_sequence_of_cells:+ # NB: The enum keeps the sequence alive in a MarkedVec for as long as the reference to the VM lives, a lifetime+ # that the result of FromJs::from_js() cannot have, so the conversion is its method.+ implementation = f"impl<'vm> {path}<'vm>"+ conversion = "pub(crate) fn from_js(vm: &'vm Vm, value: Value)"+ if members.names_numeric_argument:+ conversion = "pub(crate) fn from_js_with_identifier(vm: &'vm Vm, value: Value, identifier: &str)"out.write(f"""/// The conversion of a JS value to the union {union_type}, https://webidl.spec.whatwg.org/#js-uniondiff --git a/Meta/Generators/libweb_bindings/rust_types.py b/Meta/Generators/libweb_bindings/rust_types.pyindex 9a4e14d4165..688782efe38 100644--- a/Meta/Generators/libweb_bindings/rust_types.py+++ b/Meta/Generators/libweb_bindings/rust_types.py@@ -8,6 +8,7 @@import refrom collections.abc import Iterable+from dataclasses import replacefrom pathlib import Pathfrom typing import FrozenSetfrom typing import List@@ -126,6 +127,56 @@ def is_implemented_in_rust(interface: Optional[Interface]) -> bool:return interface is not None and interface.extended_attributes.get("ImplementedIn") == "Rust"+def is_member_implemented_in_rust(member) -> bool:+ """Whether an attribute or an operation of an interface implemented in C++ is [ImplementedIn=Rust]: its bindings+ and its steps are Rust code, which the C++ bindings call to define it on the interface prototype object."""+ return member.extended_attributes.get("ImplementedIn") == "Rust"+++def rust_member_definition_entry_point(interface: Interface, member) -> str:+ """The entry point of the Rust bindings that defines an [ImplementedIn=Rust] member of an interface implemented in+ C++ on its interface prototype object."""+ return f"web_rust_{title_case_to_snake_case(interface.name)}_define_{title_case_to_snake_case(member.name)}"+++def rust_implemented_members(interface: Optional[Interface]) -> Optional[Interface]:+ """The interface implemented in C++ with only its members that are [ImplementedIn=Rust], without that extended+ attribute, which is what the Rust bindings write bindings for. None if it has no such member."""+ if interface is None or is_implemented_in_rust(interface):+ return None+ attributes = [attribute for attribute in interface.regular_attributes if is_member_implemented_in_rust(attribute)]+ operations = [operation for operation in interface.regular_operations if is_member_implemented_in_rust(operation)]+ if not attributes and not operations:+ return None++ def without_implemented_in(member):+ extended_attributes = dict(member.extended_attributes)+ del extended_attributes["ImplementedIn"]+ return replace(member, extended_attributes=extended_attributes)++ return replace(+ interface,+ extended_attributes={},+ parent_name="",+ constants=[],+ regular_attributes=[without_implemented_in(attribute) for attribute in attributes],+ static_attributes=[],+ regular_operations=[without_implemented_in(operation) for operation in operations],+ static_operations=[],+ constructors=[],+ stringifier=None,+ iterable=None,+ async_iterable=None,+ named_property_getter=None,+ indexed_property_getter=None,+ named_property_setter=None,+ named_property_deleter=None,+ indexed_property_setter=None,+ maplike=None,+ setlike=None,+ )++# The interfaces implemented in C++ that an interface implemented in Rust can inherit from# (Libraries/LibWeb/Bindings/RustEventTarget.h).CPP_PARENT_INTERFACES = ("EventTarget", "Event")@@ -542,10 +593,23 @@ def is_record_of_cells(idl_type: IDLType, context: GenerationContext) -> bool:)+def union_holds_sequence_of_cells(idl_type: IDLType, context: GenerationContext) -> bool:+ """Whether the type is a union with a member that is a sequence of values that are or can hold cells, which the+ enum of the union keeps alive in a MarkedVec, for as long as the reference to the VM that it was converted with+ lives."""+ return isinstance(idl_type, IDLUnionType) and any(+ is_sequence_of_cells(member_type, context) for member_type in idl_type.flattened_member_types()+ )++def dictionary_holds_sequence_of_cells(dictionary: Dictionary, context: GenerationContext) -> bool:- """Whether a member of the dictionary is a sequence of values that are or can hold cells, which the struct of the- dictionary keeps alive in a MarkedVec, for as long as the reference to the VM that it was converted with lives."""- return any(is_sequence_of_cells(member.type, context) for member in dictionary.members)+ """Whether a member of the dictionary is a sequence of values that are or can hold cells, or a union with such a+ member, which the struct of the dictionary keeps alive in a MarkedVec, for as long as the reference to the VM that+ it was converted with lives."""+ return any(+ is_sequence_of_cells(member.type, context) or union_holds_sequence_of_cells(member.type, context)+ for member in dictionary.members+ )def rust_dictionary_type(dictionary: Dictionary, context: GenerationContext) -> str:diff --git a/Meta/Generators/libweb_bindings/rust_usage.py b/Meta/Generators/libweb_bindings/rust_usage.pyindex e6a08afddb9..bcae0bdf2a5 100644--- a/Meta/Generators/libweb_bindings/rust_usage.py+++ b/Meta/Generators/libweb_bindings/rust_usage.py@@ -17,8 +17,10 @@ from Generators.libweb_bindings.rust_members import rust_membersfrom Generators.libweb_bindings.rust_types import cpp_interfacefrom Generators.libweb_bindings.rust_types import inheriting_interfacesfrom Generators.libweb_bindings.rust_types import is_implemented_in_rust+from Generators.libweb_bindings.rust_types import is_member_implemented_in_rustfrom Generators.libweb_bindings.rust_types import is_named_unionfrom Generators.libweb_bindings.rust_types import runtime_union_type+from Generators.libweb_bindings.rust_types import rust_implemented_membersfrom Generators.libweb_bindings.rust_types import rust_interfacefrom Utils.webidl_parser import Dictionaryfrom Utils.webidl_parser import IDLType@@ -36,11 +38,17 @@ def types_named_by_interface(interface: Interface, with_unimplemented_members: btypes = []for attribute in interface.regular_attributes + interface.static_attributes:+ # NB: The Rust bindings convert the values of an attribute marked [ImplementedIn=Rust].+ if is_member_implemented_in_rust(attribute) and not is_implemented_in_rust(interface):+ continueif is_wanted(attribute.extended_attributes):types.append(attribute.type)for operation in interface.regular_operations + interface.static_operations:if not is_wanted(operation.extended_attributes):continue+ # NB: The Rust bindings convert the values of an operation marked [ImplementedIn=Rust].+ if is_member_implemented_in_rust(operation) and not is_implemented_in_rust(interface):+ continuetypes.append(operation.return_type)types.extend(parameter.type for parameter in operation.parameters)for constructor in interface.constructors:@@ -114,38 +122,48 @@ class DefinitionUsage:self._name_for_rust(IDLType(dictionary.name), from_js=True, to_js=False)for module in self.context.modules:interface = module.interface+ rust_members_of_cpp_interface = rust_implemented_members(interface)+ if rust_members_of_cpp_interface is not None:+ assert interface is not None+ # NB: The bindings of the members check that their this value implements the interface.+ self.cpp_interfaces_named_by_rust[interface.name] = interface+ self._name_members_for_rust(rust_members_of_cpp_interface)+ continueif interface is None or not is_implemented_in_rust(interface):continue- members = rust_members(interface)parent = self.context.interfaces.get(interface.parent_name)if parent is not None and not is_implemented_in_rust(parent):# NB: The bindings of the interface name the interface implemented in C++ it inherits from, whose# interface prototype object and interface object are the prototypes of its own.self.cpp_interfaces_named_by_rust[parent.name] = parent- for attribute in members.attributes:- if attribute.event_type is not None:- continue- has_setter = attribute.setter_method is not None- self._name_for_rust(attribute.attribute.type, from_js=has_setter, to_js=True)- operations = [- overload.operation- for operation_set in members.operation_sets + members.static_operation_sets- for overload in operation_set.overloads- ]- if members.indexed_property_getter is not None:- operations.append(members.indexed_property_getter.operation.operation)- if members.indexed_property_setter is not None:- self._name_for_rust(members.indexed_property_setter.value_parameter.type, from_js=True, to_js=False)- for operation in operations:- self._name_for_rust(operation.return_type, from_js=False, to_js=True)- for parameter in operation.parameters:- self._name_for_rust(parameter.type, from_js=True, to_js=False)- for constructor in members.constructors:- for parameter in constructor.constructor.parameters:- self._name_for_rust(parameter.type, from_js=True, to_js=False)- if members.async_iterator is not None:- for parameter in members.async_iterator.parameters:- self._name_for_rust(parameter.type, from_js=True, to_js=False)+ self._name_members_for_rust(interface)++ def _name_members_for_rust(self, interface: Interface) -> None:+ members = rust_members(interface)+ for attribute in members.attributes:+ if attribute.event_type is not None:+ continue+ has_setter = attribute.setter_method is not None+ self._name_for_rust(attribute.attribute.type, from_js=has_setter, to_js=True)+ operations = [+ overload.operation+ for operation_set in members.operation_sets + members.static_operation_sets+ for overload in operation_set.overloads+ ]+ if members.indexed_property_getter is not None:+ operations.append(members.indexed_property_getter.operation.operation)+ if members.indexed_property_setter is not None:+ self._name_for_rust(members.indexed_property_setter.value_parameter.type, from_js=True, to_js=False)+ for operation in operations:+ self._name_for_rust(operation.return_type, from_js=False, to_js=True)+ for parameter in operation.parameters:+ self._name_for_rust(parameter.type, from_js=True, to_js=False)+ for constructor in members.constructors:+ for parameter in constructor.constructor.parameters:+ self._name_for_rust(parameter.type, from_js=True, to_js=False)+ if members.async_iterator is not None:+ for parameter in members.async_iterator.parameters:+ self._name_for_rust(parameter.type, from_js=True, to_js=False)def _name_for_rust(self, idl_type: IDLType, from_js: bool, to_js: bool) -> None:if isinstance(idl_type, IDLUnionType):diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.pyindex 0e2ce50063c..7e854cce6fc 100755--- a/Meta/Linters/check_libweb_realm_mentions.py+++ b/Meta/Linters/check_libweb_realm_mentions.py@@ -35,7 +35,11 @@ CHECKED_SUFFIXES = {# This is intentionally exact. If a component goes down, tighten the baseline in# the same change. If it goes up, justify the architecture change here.ALLOWED_REALM_MENTIONS = {- "Animations": (5, 14, "animation callbacks/events and CSS value materialization still pass spec-selected realms"),+ "Animations": (+ 2,+ 8,+ "animation playback events, promise settling and CSS value materialization still pass spec-selected realms",+ ),"CSS": (7,11,diff --git a/Meta/Linters/check_rust_address_keys.py b/Meta/Linters/check_rust_address_keys.pyindex 5c84c9b8a40..64486357e20 100755--- a/Meta/Linters/check_rust_address_keys.py+++ b/Meta/Linters/check_rust_address_keys.py@@ -38,7 +38,6 @@ ALLOWED = {"css/rule/read.rs": 1,"css/style/bridge.rs": 1,"css/style/custom_property_environments.rs": 1,- "css/style/effect_descriptions.rs": 1,"css/style/engine_calls.rs": 1,"css/style/font_resolution.rs": 2,"css/style/kept_past_release.rs": 3,diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex aa86b13af1b..e873621946c 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -114,6 +114,9 @@ RENDER_STATE_ALLOWED = {**render_state_entries(IDENTITY,[+ "animations/animation.rs:NEXT",+ "animations/effect.rs:NEXT",+ "animations/timeline.rs:NEXT","cow_column.rs:NEXT","css/declaration_block.rs:NEXT_DECLARATION_BLOCK_IDENTITY","css/rule.rs:NEXT_RULE_IDENTITY",@@ -142,6 +145,7 @@ RENDER_STATE_ALLOWED = {**render_state_entries(BUILT_ONCE,[+ "animations/easing.rs:LINEAR","css/counter_representation.rs:DECIMAL","css/css_string.rs:EMPTY","css/custom_properties.rs:EMPTY",diff --git a/Meta/Utils/webidl_parser.py b/Meta/Utils/webidl_parser.pyindex 7fff5c43f4e..fabb992b88b 100644--- a/Meta/Utils/webidl_parser.py+++ b/Meta/Utils/webidl_parser.py@@ -58,7 +58,6 @@ ALLOWED_EXTENDED_ATTRIBUTES = frozenset("MissingValueDefault",# The construct exists only while the navigator claims the named engine, which alone has it."NavigatorCompatibilityMode",- "NeedsArgumentCount","NeedsCallerRealm","NewObject","PutForwards",diff --git a/Tests/LibWeb/Crash/Animations/percentage-start-time-moves-to-document-timeline.html b/Tests/LibWeb/Crash/Animations/percentage-start-time-moves-to-document-timeline.htmlnew file mode 100644index 00000000000..8f30b8009fc--- /dev/null+++ b/Tests/LibWeb/Crash/Animations/percentage-start-time-moves-to-document-timeline.html@@ -0,0 +1,19 @@+<!DOCTYPE html>+<style>+ #scroller {+ width: 100px;+ height: 100px;+ overflow: scroll;+ }+</style>+<div id="scroller"><div id="target"></div></div>+<script>+ // A start time set as a percentage while the scroll timeline is inactive, as nothing overflows its scroller, leaves+ // the current time unresolved, and moving the animation to the document timeline must not mix up the units of its+ // start time and its new timeline's times.+ const animation = target.animate({ opacity: [0, 1] }, { duration: 1000, timeline: new ScrollTimeline({ source: scroller }) });+ animation.startTime = CSS.percent(20);+ animation.timeline = document.timeline;+ animation.currentTime;+ animation.playState;+</script>diff --git a/Tests/LibWeb/Crash/Animations/update-playback-rate-of-finished-animation-on-inactive-timeline.html b/Tests/LibWeb/Crash/Animations/update-playback-rate-of-finished-animation-on-inactive-timeline.htmlnew file mode 100644index 00000000000..adb2a73b4c4--- /dev/null+++ b/Tests/LibWeb/Crash/Animations/update-playback-rate-of-finished-animation-on-inactive-timeline.html@@ -0,0 +1,33 @@+<!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>+ function animationFrame() {+ return new Promise(resolve => requestAnimationFrame(resolve));+ }++ (async () => {+ const animation = target.animate({ opacity: [0, 1] }, { duration: 1000, timeline: new ScrollTimeline({ source: scroller }) });+ await animation.ready;+ animation.finish();+ // The scroll timeline becomes inactive as its scroller stops overflowing, while the finished animation keeps+ // its hold time, and so stays finished.+ content.style.height = "0px";+ await animationFrame();+ await animationFrame();+ animation.updatePlaybackRate(2);+ animation.updatePlaybackRate(0);+ document.documentElement.classList.remove("test-wait");+ })();+</script>+</html>diff --git a/Tests/LibWeb/Text/expected/SVG/set-element-removed-and-collected.txt b/Tests/LibWeb/Text/expected/SVG/set-element-removed-and-collected.txtnew file mode 100644index 00000000000..fd9835a0705--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/set-element-removed-and-collected.txt@@ -0,0 +1,2 @@+animated: rgb(0, 128, 0)+target without its animation element: rgb(255, 0, 0)diff --git a/Tests/LibWeb/Text/expected/SVG/set-element-survives-gc.txt b/Tests/LibWeb/Text/expected/SVG/set-element-survives-gc.txtnew file mode 100644index 00000000000..00a74d02c57--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/set-element-survives-gc.txt@@ -0,0 +1,4 @@+before gc: rgb(0, 128, 0)+after gc: rgb(0, 128, 0)+after its end: rgb(255, 0, 0)+seeked back: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.txt b/Tests/LibWeb/Text/expected/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.txtnew file mode 100644index 00000000000..b292820132c--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.txt@@ -0,0 +1,3 @@+follows a scroll timeline: true+play state after display: none: idle+timeline kept: truediff --git a/Tests/LibWeb/Text/expected/WebAnimations/element-animations-garbage-collection.txt b/Tests/LibWeb/Text/expected/WebAnimations/element-animations-garbage-collection.txtnew file mode 100644index 00000000000..6e9dd1f326b--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAnimations/element-animations-garbage-collection.txt@@ -0,0 +1,4 @@+script: Animation running+css: CSSAnimation running+transition: CSSTransition running+target of a held animation: DIV, Animation runningdiff --git a/Tests/LibWeb/Text/expected/WebAnimations/keyframe-argument-conversion.txt b/Tests/LibWeb/Text/expected/WebAnimations/keyframe-argument-conversion.txtnew file mode 100644index 00000000000..9f0ceb63c32--- /dev/null+++ b/Tests/LibWeb/Text/expected/WebAnimations/keyframe-argument-conversion.txt@@ -0,0 +1,4 @@+keyframes from a typed array: 2+member order: get composite, convert composite, get easing, get offset+values: 0, 1+own opacity: true, own easing: truediff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txtindex 6b710eab4c5..e57a758e26f 100644--- a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt@@ -20,12 +20,14 @@ animation: 500 elementslayoutStyleColumns: within 28otherMaps: within 0styleValues: within 24- animationEffects: within 432+ animationEffects: within 416fontResolutions: within 0- cssAnimations: within 360- hostMemo: within 180+ cssAnimations: within 240+ hostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 856transition: 500 elementsinitial: within 0ruleStore: within 0@@ -48,9 +50,11 @@ transition: 500 elementslayoutStyleColumns: within 28otherMaps: within 0styleValues: within 0- animationEffects: within 456+ animationEffects: within 348fontResolutions: within 0cssAnimations: within 0- hostMemo: within 248+ hostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 1058diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txtindex 1e523d1729d..1b3d1772f39 100644--- a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt@@ -26,6 +26,8 @@ shared: 500 elements, 500 styledhostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0custom: 500 elements, 500 styledinitial: within 0ruleStore: within 0@@ -54,6 +56,8 @@ custom: 500 elements, 500 styledhostMemo: within 36cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0unique: 500 elements, 500 styledinitial: within 0ruleStore: within 0@@ -82,6 +86,8 @@ unique: 500 elements, 500 styledhostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0uniqueFont: 500 elements, 500 styledinitial: within 0ruleStore: within 0@@ -110,6 +116,8 @@ uniqueFont: 500 elements, 500 styledhostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0uniqueVisual: 500 elements, 500 styledinitial: within 0ruleStore: within 0@@ -138,6 +146,8 @@ uniqueVisual: 500 elements, 500 styledhostMemo: within 0cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0substituted: 500 elements, 500 styledinitial: within 0ruleStore: within 0@@ -166,3 +176,5 @@ substituted: 500 elements, 500 styledhostMemo: within 72cppInstalledStyles: within 8cppHintProperties: within 0+ animationObjects: within 0+ animationRecords: within 0diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/effect-updateTiming.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/effect-updateTiming.txtindex 44cde30b17e..24792a5cc46 100644--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/effect-updateTiming.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/effect-updateTiming.txt@@ -2,8 +2,8 @@ Harness status: OKFound 67 tests-65 Pass-2 Fail+66 Pass+1 FailPass Allows setting the delay to a positive numberPass Allows setting the delay to a negative numberPass Allows setting the delay of an animation in progress: positive delay that causes the animation to be no longer in-effect@@ -34,7 +34,7 @@ Pass Allows setting the iterations of an animation in progress with duration "auPass Allows creating scroll linked animation with duration InfinityPass Allows setting the duration to 123.45Pass Allows setting the duration to auto-Fail Allows setting the duration to Infinity+Pass Allows setting the duration to InfinityPass Throws when setting invalid duration: -1Pass Throws when setting invalid duration: NaNPass Throws when setting invalid duration: -Infinitydiff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/setting-timeline.tentative.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/setting-timeline.tentative.txtindex 688c8bd6d6a..11cf9661788 100644--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/setting-timeline.tentative.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/scroll-timelines/setting-timeline.tentative.txt@@ -2,8 +2,8 @@ Harness status: OKFound 16 tests-11 Pass-5 Fail+13 Pass+3 FailPass Setting a scroll timeline on a play-pending animation synchronizes currentTime of the animation with the scroll position.Pass Setting a scroll timeline on a pause-pending animation fixes the currentTime of the animation based on the scroll position once resumedPass Setting a scroll timeline on a reversed play-pending animation synchronizes the currentTime of the animation with the scroll position.@@ -14,9 +14,9 @@ Pass Transitioning from a scroll timeline to a document timeline on a running anPass Transitioning from a scroll timeline to a document timeline on a pause-pending animation preserves currentTimePass Transition from a scroll timeline to a document timeline on a reversed paused animation maintains correct currentTimePass Transitioning from a scroll timeline to a null timeline on a running animation preserves current progress.-Fail Switching from a null timeline to a scroll timeline on an animation with a resolved start time preserved the play state+Pass Switching from a null timeline to a scroll timeline on an animation with a resolved start time preserved the play stateFail Switching from one scroll timeline to another updates currentTimePass Switching from a document timeline to a scroll timeline updates currentTime when unpaused via CSS.Pass Switching from a document timeline to a scroll timeline and updating currentTime preserves the progress while paused.-Fail Switching from a document timeline to a scroll timeline on an infinite duration animation.+Pass Switching from a document timeline to a scroll timeline on an infinite duration animation.Fail Changing from a scroll-timeline to a view-timeline updates start time.\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/SVG/set-element-removed-and-collected.html b/Tests/LibWeb/Text/input/SVG/set-element-removed-and-collected.htmlnew file mode 100644index 00000000000..91fc41af738--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/set-element-removed-and-collected.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg id="svg">+ <rect id="kept" width="100" height="100" fill="red">+ <set id="set" attributeName="fill" to="green"/>+ </rect>+ <g id="group">+ <rect width="100" height="100" fill="red">+ <set attributeName="fill" to="green"/>+ </rect>+ </g>+</svg>+<script>+ asyncTest(async done => {+ const nextFrame = () => new Promise(requestAnimationFrame);+ await new Promise(resolve => window.addEventListener("load", resolve));+ await nextFrame();+ await nextFrame();+ println(`animated: ${getComputedStyle(kept).fill}`);++ // Remove an animated element with its running animation element, and an animation element from its target.+ document.getElementById("group").remove();+ document.getElementById("set").remove();+ await nextFrame();+ internals.gc();+ await nextFrame();+ await nextFrame();+ internals.gc();+ await nextFrame();+ println(`target without its animation element: ${getComputedStyle(kept).fill}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/SVG/set-element-survives-gc.html b/Tests/LibWeb/Text/input/SVG/set-element-survives-gc.htmlnew file mode 100644index 00000000000..ca1b8579003--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/set-element-survives-gc.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg id="svg">+ <rect id="rect" width="100" height="100" fill="red">+ <set attributeName="fill" to="green" dur="2s"/>+ </rect>+</svg>+<script>+ asyncTest(async done => {+ const nextFrame = () => new Promise(requestAnimationFrame);+ await new Promise(resolve => window.addEventListener("load", resolve));+ svg.pauseAnimations();+ svg.setCurrentTime(1);+ await nextFrame();+ println(`before gc: ${getComputedStyle(rect).fill}`);+ internals.gc();+ await nextFrame();+ await nextFrame();+ println(`after gc: ${getComputedStyle(rect).fill}`);+ svg.setCurrentTime(3);+ await nextFrame();+ println(`after its end: ${getComputedStyle(rect).fill}`);+ svg.setCurrentTime(1);+ await nextFrame();+ println(`seeked back: ${getComputedStyle(rect).fill}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.html b/Tests/LibWeb/Text/input/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.htmlnew file mode 100644index 00000000000..20cacc76a1e--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAnimations/css-animation-canceled-by-display-none-keeps-timeline.html@@ -0,0 +1,40 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<style>+ @keyframes fade {+ from { opacity: 0.25; }+ to { opacity: 0.75; }+ }+ #scroller {+ overflow: scroll;+ height: 100px;+ scroll-timeline-name: --scroller;+ }+ #spacer {+ height: 300px;+ }+ #target {+ animation: fade 1s linear;+ animation-timeline: --scroller;+ }+</style>+<div id="scroller"><div id="target"></div><div id="spacer"></div></div>+<script>+ function animationFrame() {+ return new Promise(resolve => requestAnimationFrame(resolve));+ }++ asyncTest(async done => {+ // A CSS animation canceled by display: none no longer follows the named timeline it was created with.+ const animation = target.getAnimations()[0];+ const timeline = animation.timeline;+ println(`follows a scroll timeline: ${timeline instanceof ScrollTimeline}`);+ target.style.display = "none";+ println(`play state after display: none: ${animation.playState}`);+ scroller.style.scrollTimelineName = "--other";+ await animationFrame();+ await animationFrame();+ println(`timeline kept: ${animation.timeline === timeline}`);+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/WebAnimations/element-animations-garbage-collection.html b/Tests/LibWeb/Text/input/WebAnimations/element-animations-garbage-collection.htmlnew file mode 100644index 00000000000..75de65fa13f--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAnimations/element-animations-garbage-collection.html@@ -0,0 +1,49 @@+<!DOCTYPE html>+<style>+ @keyframes grow {+ from { width: 0px; }+ to { width: 100px; }+ }+ #css {+ animation: grow 100s;+ }+ #transition {+ height: 0px;+ transition: height 100s;+ }+</style>+<body>+<script src="../include.js"></script>+<div id="script"></div>+<div id="css"></div>+<div id="transition"></div>+<script>+ function describe(animations) {+ return animations.map(animation => `${animation.constructor.name} ${animation.playState}`).join(", ");+ }++ test(() => {+ // An element alone keeps its animations alive.+ document.getElementById("script").animate([{ opacity: 0 }, { opacity: 1 }], 100000);+ const transition = document.getElementById("transition");+ getComputedStyle(transition).height;+ transition.style.height = "100px";+ getComputedStyle(transition).height;+ internals.gc();+ for (const id of ["script", "css", "transition"])+ println(`${id}: ${describe(document.getElementById(id).getAnimations())}`);++ // An animation alone keeps the element it targets alive.+ let animation;+ {+ const element = document.createElement("div");+ document.body.appendChild(element);+ animation = element.animate([{ opacity: 0 }, { opacity: 1 }], 100000);+ element.remove();+ }+ internals.gc();+ println(`target of a held animation: ${animation.effect.target.tagName}, ${describe(animation.effect.target.getAnimations())}`);+ animation.cancel();+ });+</script>+</body>diff --git a/Tests/LibWeb/Text/input/WebAnimations/keyframe-argument-conversion.html b/Tests/LibWeb/Text/input/WebAnimations/keyframe-argument-conversion.htmlnew file mode 100644index 00000000000..335f8a55542--- /dev/null+++ b/Tests/LibWeb/Text/input/WebAnimations/keyframe-argument-conversion.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ test(() => {+ // An iterable that is not an array converts to a list of values.+ const fromTypedArray = new KeyframeEffect(null, { opacity: new Float32Array([0, 1]) });+ println(`keyframes from a typed array: ${fromTypedArray.getKeyframes().length}`);++ // Each member is converted before the next is read.+ const order = [];+ new KeyframeEffect(null, {+ get composite() {+ order.push("get composite");+ return { toString() { order.push("convert composite"); return "add"; } };+ },+ get easing() { order.push("get easing"); return "linear"; },+ get offset() { order.push("get offset"); return null; },+ });+ println(`member order: ${order.join(", ")}`);++ // Each element of a list is converted before the next is read.+ const values = [];+ values.push({ toString() { values[1] = "1"; return "0"; } }, "0");+ const fromChangingList = new KeyframeEffect(null, { opacity: values });+ println(`values: ${fromChangingList.getKeyframes().map(keyframe => keyframe.opacity).join(", ")}`);++ // The returned keyframes have own properties even where the prototype has setters.+ Object.defineProperty(Object.prototype, "opacity", { configurable: true, set(value) {} });+ Object.defineProperty(Object.prototype, "easing", { configurable: true, set(value) {} });+ const keyframe = new KeyframeEffect(null, { opacity: [0, 1] }).getKeyframes()[0];+ delete Object.prototype.opacity;+ delete Object.prototype.easing;+ println(`own opacity: ${Object.hasOwn(keyframe, "opacity")}, own easing: ${Object.hasOwn(keyframe, "easing")}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.htmlindex 3f8f611c00b..068a3d27641 100644--- a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html@@ -46,8 +46,10 @@// - animationEffects: describes each running animation for sampling (its effect, beside the keyframes it shares// with every element running the same @keyframes rule).// - cssAnimations: each CSS animation's name and applied definition.- // - hostMemo: the versions of the effects the host described to the engine.// - styleValues: the animated value of the longhand the payload of its group holds.+ // - animationObjects: the Animation objects, which a CSS animation or transition only has once script asks for it.+ // - animationRecords: the records the animation and its effect keep their state in, a transition's keyframes, and+ // the element's lists of its animations and of the effect descriptions it published to the engine.const animationBudgets = {records: 464,payloads: 656,@@ -59,10 +61,11 @@heldRecordMaps: 12,layoutStyleColumns: 28,styleValues: 24,- animationEffects: 432,- cssAnimations: 360,- hostMemo: 180,+ animationEffects: 416,+ cssAnimations: 240,cppInstalledStyles: 8,+ animationObjects: 0,+ animationRecords: 856,};const transitionBudgets = {records: 464,@@ -74,9 +77,10 @@hostTree: 24,heldRecordMaps: 12,layoutStyleColumns: 28,- animationEffects: 456,- hostMemo: 248,+ animationEffects: 348,cppInstalledStyles: 8,+ animationObjects: 0,+ animationRecords: 1058,};// NB: What a transaction in flight holds of earlier generations, and what the style threads keep for the next