Truly independent web browser
LibWeb: Implement Animation.commitStyles()
sideshowbarkerd111bc6ad5f5
diff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cppindex 506d81b9bda..006967b46fe 100644--- a/Libraries/LibWeb/Animations/Animation.cpp+++ b/Libraries/LibWeb/Animations/Animation.cpp@@ -12,6 +12,7 @@#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>@@ -20,12 +21,18 @@#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>@@ -34,6 +41,8 @@#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>@@ -41,6 +50,114 @@ 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-animationGC::Ref<Animation> Animation::create(HTML::EnvironmentSettingsObject& environment, GC::Ptr<AnimationEffect> effect, GC::Ptr<AnimationTimeline> timeline){diff --git a/Libraries/LibWeb/Animations/Animation.h b/Libraries/LibWeb/Animations/Animation.hindex c8cc1dddc2b..09bcf1a2dee 100644--- a/Libraries/LibWeb/Animations/Animation.h+++ b/Libraries/LibWeb/Animations/Animation.h@@ -150,6 +150,7 @@ public: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;diff --git a/Libraries/LibWeb/Animations/Animation.idl b/Libraries/LibWeb/Animations/Animation.idlindex 130074d97d0..f0b7db432ca 100644--- a/Libraries/LibWeb/Animations/Animation.idl+++ b/Libraries/LibWeb/Animations/Animation.idl@@ -29,7 +29,7 @@ interface Animation : EventTarget {undefined updatePlaybackRate(double playbackRate);undefined reverse();undefined persist();- [FIXME, CEReactions] undefined commitStyles();+ [CEReactions] undefined commitStyles();};// https://drafts.csswg.org/web-animations-2/#dictdef-timelinerangeoffsetdiff --git a/Libraries/LibWeb/Animations/AnimationEffect.cpp b/Libraries/LibWeb/Animations/AnimationEffect.cppindex 448740e43d4..098f8eafe6d 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.cpp+++ b/Libraries/LibWeb/Animations/AnimationEffect.cpp@@ -616,13 +616,16 @@ AnimationEffect::Phase AnimationEffect::phase() constreturn phase(local_time());}-AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_time) const+AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_time, EndpointInclusiveActiveInterval endpoint_inclusive) const{// This is a convenience method that returns the phase of the animation effect, to avoid having to call all of the// phase functions separately.if (!local_time.has_value())return Phase::Idle;+ // https://drafts.csswg.org/web-animations-1/#animation-effect-phases-and-states+ // Furthermore, an endpoint-inclusive active interval flag may be specified when determining the phase. If not+ // specified, it is assumed to be false.auto at_timeline_boundary = this->is_at_timeline_boundary();auto before_active_boundary_time = this->before_active_boundary_time();@@ -632,7 +635,7 @@ AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_t// 1. the local time is less than the before-active boundary time, or// 2. the animation direction is "backwards" and the local time is equal to the before-active boundary time and// not at timeline boundary.- if (local_time.value() < before_active_boundary_time || (animation_direction() == AnimationDirection::Backwards && local_time.value() == before_active_boundary_time && !at_timeline_boundary))+ if (local_time.value() < before_active_boundary_time || (animation_direction() == AnimationDirection::Backwards && local_time.value() == before_active_boundary_time && !at_timeline_boundary && endpoint_inclusive == EndpointInclusiveActiveInterval::No))return Phase::Before;auto after_active_boundary_time = this->after_active_boundary_time();@@ -641,7 +644,7 @@ AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_t// 1. the local time is greater than the active-after boundary time, or// 2. the animation direction is "forwards" and the local time is equal to the active-after boundary time and not// at timeline boundary.- if (local_time.value() > after_active_boundary_time || (animation_direction() == AnimationDirection::Forwards && local_time.value() == after_active_boundary_time && !at_timeline_boundary))+ if (local_time.value() > after_active_boundary_time || (animation_direction() == AnimationDirection::Forwards && local_time.value() == after_active_boundary_time && !at_timeline_boundary && endpoint_inclusive == EndpointInclusiveActiveInterval::No))return Phase::After;// https://www.w3.org/TR/web-animations-1/#animation-effect-active-phase@@ -650,10 +653,10 @@ AnimationEffect::Phase AnimationEffect::phase(Optional<TimeValue> const& local_treturn Phase::Active;}-AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing() const+AnimationEffect::ResolvedTiming AnimationEffect::resolve_timing(EndpointInclusiveActiveInterval endpoint_inclusive) const{auto local_time = this->local_time();- auto phase = this->phase(local_time);+ auto phase = this->phase(local_time, endpoint_inclusive);auto active_time = active_time_for_phase(phase, local_time, m_fill_mode);return {.phase = phase,@@ -794,9 +797,9 @@ Optional<double> AnimationEffect::current_iteration(ResolvedTiming const& timing}// https://www.w3.org/TR/web-animations-1/#transformed-progress-Optional<double> AnimationEffect::transformed_progress() const+Optional<double> AnimationEffect::transformed_progress(EndpointInclusiveActiveInterval endpoint_inclusive) const{- auto timing = resolve_timing();+ auto timing = resolve_timing(endpoint_inclusive);// 1. If the directed progress is unresolved, return unresolved.auto directed_progress = this->directed_progress(timing);@@ -851,19 +854,6 @@ AnimationUpdateContext::~AnimationUpdateContext()publish();}-template<typename Iterator, typename Callback>-static void at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback)-{- if (timelines == end)- return callback();- auto& timeline = **timelines;- ++timelines;- if (!timeline.was_observed_ahead_in_current_task())- return at_times_observed_ahead(timelines, end, callback);- AnimationTimeline::CurrentTimeOverrideScope override { timeline, timeline.current_time_for_observation() };- at_times_observed_ahead(timelines, end, callback);-}-void AnimationUpdateContext::publish(){// Each element's effects, sampled over the style it holds.@@ -945,7 +935,7 @@ void AnimationUpdateContext::publish()// A timeline script observed ahead of its current time in this task is sampled at that time, as an update of the// effects needing it is, or the style installed here and the one that update sampled would keep disagreeing about// an effect that ended between the two times.- at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), [&] {+ AnimationTimeline::at_times_observed_ahead(document.associated_animation_timelines().begin(), document.associated_animation_timelines().end(), [&] {style_computer.refresh_animations_into_each(read, requests);});diff --git a/Libraries/LibWeb/Animations/AnimationEffect.h b/Libraries/LibWeb/Animations/AnimationEffect.hindex 0aad86ea856..b3a5b4cb88d 100644--- a/Libraries/LibWeb/Animations/AnimationEffect.h+++ b/Libraries/LibWeb/Animations/AnimationEffect.h@@ -136,7 +136,11 @@ public:Optional<TimeValue> active_time;Optional<double> overall_progress;};- ResolvedTiming resolve_timing() const;+ enum class EndpointInclusiveActiveInterval {+ No,+ Yes,+ };+ ResolvedTiming resolve_timing(EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;Phase previous_phase() const { return m_previous_phase; }void set_previous_phase(Phase value) { m_previous_phase = value; }@@ -145,7 +149,7 @@ public:Optional<double> current_iteration() const;Optional<double> current_iteration(ResolvedTiming const&) const;- Optional<double> transformed_progress() const;+ Optional<double> transformed_progress(EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;void normalize_specified_timing();@@ -173,7 +177,7 @@ protected:GC::Ptr<AnimationTimeline> associated_timeline() const;Optional<TimeValue> timeline_duration() const;- Phase phase(Optional<TimeValue> const& local_time) const;+ Phase phase(Optional<TimeValue> const& local_time, EndpointInclusiveActiveInterval = EndpointInclusiveActiveInterval::No) const;bool is_at_timeline_boundary() const;Optional<TimeValue> active_time_for_phase(Phase, Optional<TimeValue> const& local_time, Bindings::FillMode) const;Optional<double> overall_progress_for_phase(Phase, Optional<TimeValue> const& active_time) const;diff --git a/Libraries/LibWeb/Animations/AnimationTimeline.h b/Libraries/LibWeb/Animations/AnimationTimeline.hindex c71e7586e3c..c2565422a66 100644--- a/Libraries/LibWeb/Animations/AnimationTimeline.h+++ b/Libraries/LibWeb/Animations/AnimationTimeline.h@@ -39,6 +39,11 @@ public:// 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;+ // 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;@@ -112,4 +117,17 @@ private:bool m_has_current_time_override_for_style_sampling { false };};+template<typename Iterator, typename Callback>+void AnimationTimeline::at_times_observed_ahead(Iterator timelines, Iterator end, Callback const& callback)+{+ if (timelines == end)+ return callback();+ auto& timeline = **timelines;+ ++timelines;+ if (!timeline.was_observed_ahead_in_current_task())+ return at_times_observed_ahead(timelines, end, callback);+ CurrentTimeOverrideScope override { timeline, timeline.current_time_for_observation() };+ at_times_observed_ahead(timelines, end, callback);+}+}diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp b/Libraries/LibWeb/CSS/CSSStyleProperties.cppindex 4f8a620fb01..4a4539aece1 100644--- a/Libraries/LibWeb/CSS/CSSStyleProperties.cpp+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.cpp@@ -222,6 +222,27 @@ Optional<StyleProperty const&> CSSStyleProperties::custom_property(Utf16FlyStrinreturn custom_properties().get(custom_property_name);}+void CSSStyleProperties::set_computed_properties(OrderedHashMap<PropertyNameAndID, NonnullRefPtr<StyleValue const>> const& properties)+{+ prepare_to_update_style_attribute();+ bool updated = false;+ for (auto const& [property, value] : properties) {+ if (property.is_custom_property()) {+ auto existing = custom_property(property.name());+ if (!existing.has_value() || existing->important != Important::No || *existing->value != *value) {+ m_declarations.set_custom(property.name(), { .important = Important::No, .property_id = property.id(), .value = value });+ updated = true;+ }+ } else {+ updated |= m_declarations.set_expanding_shorthands(property.id(), *value, Important::No);+ }+ }+ if (updated) {+ update_style_attribute();+ invalidate_owners();+ }+}+// https://drafts.csswg.org/cssom/#dom-cssstyledeclaration-setpropertyWebIDL::ExceptionOr<void> CSSStyleProperties::set_property(Utf16FlyString const& property_name, Utf16View value, Utf16View priority){diff --git a/Libraries/LibWeb/CSS/CSSStyleProperties.h b/Libraries/LibWeb/CSS/CSSStyleProperties.hindex a05c6ef84eb..794636b8216 100644--- a/Libraries/LibWeb/CSS/CSSStyleProperties.h+++ b/Libraries/LibWeb/CSS/CSSStyleProperties.h@@ -68,6 +68,7 @@ public:virtual Utf16String serialized() const final override;virtual WebIDL::ExceptionOr<void> set_css_text(Utf16View) override;+ void set_computed_properties(OrderedHashMap<PropertyNameAndID, NonnullRefPtr<StyleValue const>> const&);void set_declarations_from_text(Utf16View);// Takes `source`'s declarations as they are, sharing them until either side changes.void set_declarations_from(CSSStyleProperties const& source);diff --git a/Libraries/LibWeb/CSS/StyleComputer.cpp b/Libraries/LibWeb/CSS/StyleComputer.cppindex e2e9c24c36e..562a8e05103 100644--- a/Libraries/LibWeb/CSS/StyleComputer.cpp+++ b/Libraries/LibWeb/CSS/StyleComputer.cpp@@ -496,6 +496,7 @@ struct StyleComputer::AnimationSample {DOM::AbstractElement abstract_element;ComputedStyleWorkingSet& computed_properties;} context;+ AnimationSamplePurpose purpose { AnimationSamplePurpose::Rendering };Vector<ComputedValuesFFI::FfiSampledAnimationEffect, 1> sampled_effects;Vector<Vector<Compositing::RustFFI::FfiLinearEasingPoint>, 1> easing_points;Vector<u8> document_supported_color_scheme_codes;@@ -607,16 +608,30 @@ void StyleComputer::collect_animation_effects_into(Layout::BegunRead const& readfinish_animation_sample(*sample, result);}-NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement abstract_element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects, ComputedStyleWorkingSet& computed_properties) const+NonnullRefPtr<ComputedStyleWorkingSet> StyleComputer::compute_style_for_animation_commit(Layout::BegunRead const& read, DOM::AbstractElement element, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> 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);+ });+ 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{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);- record_element_animation_effect_descriptions(abstract_element.element(), animation_slot, effects);+ 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 host computes the key only for a timing the engine cannot decide.+ // the engine's. The host computes endpoint-inclusive keys for committing styles, and otherwise only for a timing+ // the engine cannot decide.auto& sampled_effects = sample->sampled_effects;auto& easing_points = sample->easing_points;sampled_effects.ensure_capacity(effects.size());@@ -627,8 +642,11 @@ NonnullOwnPtr<StyleComputer::AnimationSample> StyleComputer::begin_animation_samcontinue;auto timing = style_engine_effect_timing(*effect, *animation);Optional<double> current_key;- if (!timing.decidable) {- if (auto output_progress = effect->transformed_progress(); output_progress.has_value())+ if (purpose == AnimationSamplePurpose::CommitStyles || !timing.decidable) {+ auto endpoint_inclusive = purpose == AnimationSamplePurpose::CommitStyles+ ? Animations::AnimationEffect::EndpointInclusiveActiveInterval::Yes+ : Animations::AnimationEffect::EndpointInclusiveActiveInterval::No;+ if (auto output_progress = effect->transformed_progress(endpoint_inclusive); output_progress.has_value())current_key = clamp(*output_progress * 100.0 * Animations::KeyframeEffect::AnimationKeyFrameKeyScaleFactor, static_cast<double>(NumericLimits<i64>::min()), static_cast<double>(NumericLimits<i64>::max()));}easing_points.unchecked_append({});@@ -739,11 +757,11 @@ void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedVal// What the substituted values read is what the element's style now depends on, as for a value its cascade// substituted.auto& element = abstract_element.element();- if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_ATTR)+ if (sample.purpose == AnimationSamplePurpose::Rendering && result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_ATTR)element.set_style_uses_attr_css_function();- if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_IF)+ if (sample.purpose == AnimationSamplePurpose::Rendering && result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_IF)element.set_style_uses_if_css_function();- if (result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_CUSTOM_FUNCTION)+ if (sample.purpose == AnimationSamplePurpose::Rendering && result.substitution_marks & ComputedValuesFFI::SUBSTITUTION_MARK_CUSTOM_FUNCTION)element.set_style_uses_custom_function();switch (result.outcome) {@@ -760,7 +778,7 @@ void StyleComputer::finish_animation_sample(AnimationSample& sample, ComputedValcomputed_properties.set_depends_on_viewport_metrics();if (result.font_metrics_depend_on_viewport_metrics)computed_properties.set_font_metrics_depend_on_viewport_metrics();- if (result.uses_tree_counting_function)+ if (sample.purpose == AnimationSamplePurpose::Rendering && result.uses_tree_counting_function)element.set_style_uses_tree_counting_function();for (auto const& property : ReadonlySpan<ComputedValuesFFI::FfiAnimatedCustomPropertyResult> { result.animated_custom_properties, result.animated_custom_property_count }) {auto value = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(property.value)));diff --git a/Libraries/LibWeb/CSS/StyleComputer.h b/Libraries/LibWeb/CSS/StyleComputer.hindex 9f3d989d1bb..b854d27f8ba 100644--- a/Libraries/LibWeb/CSS/StyleComputer.h+++ b/Libraries/LibWeb/CSS/StyleComputer.h@@ -165,6 +165,8 @@ 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;+void begin_transition_stabilization_epoch();// https://drafts.csswg.org/css-transitions-2/#defining-before-change-style// Keeps `before_change_style` as the style a later pass of the stabilization epoch decides the element's@@ -190,8 +192,12 @@ 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;+ enum class AnimationSamplePurpose {+ Rendering,+ CommitStyles,+ };struct AnimationSample;- [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, ComputedStyleWorkingSet&) const;+ [[nodiscard]] NonnullOwnPtr<AnimationSample> begin_animation_sample(Layout::BegunRead const& read, DOM::AbstractElement, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>, 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;diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cppindex 759d19f983e..a301ee89950 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp@@ -2405,6 +2405,13 @@ void record_element_animation_effect_descriptions(DOM::Element& element, u8 slotif (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;@@ -2487,14 +2494,20 @@ void record_element_animation_effect_descriptions(DOM::Element& element, u8 slotffi_effects.unchecked_append(row);}- StyleEngineFFI::style_engine_set_element_animation_effect_descriptions(style_engine->host(),- element.style_node_id().value(), slot,- ffi_effects.data(), ffi_effects.size(),- ffi_keyframes.data(), ffi_keyframes.size(),- ffi_declarations.data(), ffi_declarations.size(),- ffi_custom_declarations.data(), ffi_custom_declarations.size(),- ffi_points.data(), ffi_points.size(),- base_url_bytes.data(), base_url_bytes.size());+ 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 plusdiff --git a/Libraries/LibWeb/CSS/StyleEngineInput.h b/Libraries/LibWeb/CSS/StyleEngineInput.hindex 66b93061a34..75c40080bea 100644--- a/Libraries/LibWeb/CSS/StyleEngineInput.h+++ b/Libraries/LibWeb/CSS/StyleEngineInput.h@@ -16,6 +16,7 @@namespace Web::CSS::StyleEngineFFI {struct FfiAppliedAnimationDefinition;+struct FfiAnimationEffectDescriptions;enum class FfiElementDeclarationKind : u8;}@@ -156,6 +157,7 @@ WEB_API void record_element_css_defined_animations(DOM::Element&, u8 slot, Reado// 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>>);// Report that a child of an element arrived, left, or changed in a way that can move whether thediff --git a/Libraries/LibWeb/DOM/Document.h b/Libraries/LibWeb/DOM/Document.hindex a3a6da685a2..ba40ecee901 100644--- a/Libraries/LibWeb/DOM/Document.h+++ b/Libraries/LibWeb/DOM/Document.h@@ -156,6 +156,7 @@ enum class InvalidateLayoutTreeReason {// when it reads geometry as well, and neither is anything that mutates. False is the conservative// answer, and is what every reason whose call sites have not been checked keeps.#define ENUMERATE_UPDATE_LAYOUT_REASONS(X) \+ X(AnimationCommitStyles, false) \X(AutoScrollSelection, false) \X(ChildDocumentStyleUpdate, false) \X(CursorLineNavigation, true) \diff --git a/Libraries/LibWeb/Rust/build.rs b/Libraries/LibWeb/Rust/build.rsindex 22beee9770b..ae16032a7db 100644--- a/Libraries/LibWeb/Rust/build.rs+++ b/Libraries/LibWeb/Rust/build.rs@@ -3003,6 +3003,15 @@ fn main() -> Result<(), Box<dyn Error>> {// 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);+ computed_values_config.export.rename.insert(+ "FfiAnimationEffectDescriptions".to_string(),+ "Web::CSS::StyleEngineFFI::FfiAnimationEffectDescriptions".to_string(),+ );+ computed_values_config+ .after_includes+ .get_or_insert_with(String::new)+ .push_str("\nnamespace Web::CSS::StyleEngineFFI { struct FfiAnimationEffectDescriptions; }");+let libgfx_font_source = manifest_dir.join("../../LibGfx/Rust/src/font.rs");println!("cargo:rerun-if-changed={}", libgfx_font_source.display());generate_ffi_header(diff --git a/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs b/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rsindex 43cfd5b760a..57f7adf9173 100644--- a/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs+++ b/Libraries/LibWeb/Rust/src/css/style/bridge/animations.rs@@ -70,6 +70,42 @@ pub struct FfiPublishedLinearEasingPoint {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.@@ -103,23 +139,11 @@ pub struct FfiAnimationEffectVersion {/// 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)]-#[allow(clippy::too_many_arguments)]pub unsafe extern "C" fn style_engine_set_element_animation_effect_descriptions(host: &DocumentHost,node: u32,slot: u32,- effects: *const FfiPublishedAnimationEffect,- effect_count: usize,- keyframes: *const FfiPublishedAnimationKeyframe,- keyframe_count: usize,- declarations: *const FfiPublishedAnimationDeclaration,- declaration_count: usize,- custom_declarations: *const FfiPublishedAnimationCustomDeclaration,- custom_declaration_count: usize,- linear_points: *const FfiPublishedLinearEasingPoint,- linear_point_count: usize,- base_url_bytes: *const u8,- base_url_byte_count: usize,+ 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;@@ -127,17 +151,7 @@ pub unsafe extern "C" fn style_engine_set_element_animation_effect_descriptions(return;};// SAFETY: Guaranteed by the caller.- let effects = unsafe {- crate::css::style::effect_descriptions::PublishedEffectBuffers {- effects: ak::slice_from_raw_parts(effects, effect_count),- keyframes: ak::slice_from_raw_parts(keyframes, keyframe_count),- declarations: ak::slice_from_raw_parts(declarations, declaration_count),- custom_declarations: ak::slice_from_raw_parts(custom_declarations, custom_declaration_count),- linear_points: ak::slice_from_raw_parts(linear_points, linear_point_count),- base_url_bytes: ak::slice_from_raw_parts(base_url_bytes, base_url_byte_count),- }- .effects()- };+ 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 },diff --git a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rsindex 98add2323bb..63e41e8baab 100644--- a/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs+++ b/Libraries/LibWeb/Rust/src/css/style/engine_sample.rs@@ -602,6 +602,7 @@ impl super::StyleEngine {root_effective_zoom: self.root_effective_zoom(),};let input = AnimationSampleInput {+ record_dependencies: true,style_node: node.raw(),pseudo_kind: crate::css::cascaded_properties::NO_PSEUDO_ELEMENT,effects: HostSampledEffects::none(),diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex 05be2385918..0213a24e76e 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -6646,6 +6646,7 @@ impl<'a> HostSampledEffects<'a> {/// 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>,@@ -6766,6 +6767,7 @@ impl FfiHostAnimationSample {};let input = AnimationSampleInput {style_node: self.style_node,+ record_dependencies: true,pseudo_kind: self.pseudo_kind,effects,longhands,@@ -6822,6 +6824,63 @@ pub unsafe extern "C" fn rust_sample_animation_effects(finish_sample_with_host(&sample, &mut callbacks, host, read, step)}+/// Sample an isolated effect list at the endpoint-inclusive keys supplied by the host.+///+/// # Safety+/// The inputs and every value in the descriptions must remain live for the call.+#[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::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()+ .iter()+ .filter_map(|effect| {+ let description = descriptions+ .iter()+ .find(|description| description.identity == effect.identity)?;+ if description.keyframes().len() < 2 {+ return None;+ }+ Some(anim::FfiSampledAnimationEffect {+ effect: anim::FfiAnimationPreparationEffect {+ identity: effect.identity,+ generation: effect.generation,+ },+ current_key: Option::<f64>::from(effect.current_key)?,+ })+ })+ .collect();+ let step = with_engine_and_arena(read, host, |engine, arena| {+ let element_box = crate::layout::node_data::NodeSlotId {+ index: sample.element_box_slot,+ };+ let reference_box =+ crate::painting::ffi::committed_transform_reference_box(&arena.paintable_rows(), element_box);+ let step = begin_animation_sample(+ &sample,+ &mut callbacks,+ engine,+ &descriptions,+ composed,+ reference_box,+ Default::default(),+ );+ finish_sample_in_engine(&sample, &mut callbacks, engine, reference_box, step)+ });+ finish_sample_with_host(&sample, &mut callbacks, host, read, step)+}+/// Sample each of `count` elements' animation effects onto its working set's overlay, as/// [`rust_sample_animation_effects`] samples one, in one call of the style engine, and write what/// each sample found to `results`. Every element is one of the same document's.@@ -6878,7 +6937,7 @@ fn sample_in_engine(};let reference_box = crate::painting::ffi::committed_transform_reference_box(&arena.paintable_rows(), element_box);let composed = host_sampled_effects(input, engine);- match begin_animation_sample(+ let step = begin_animation_sample(input,host,engine,@@ -6886,7 +6945,18 @@ fn sample_in_engine(composed,reference_box,Default::default(),- ) {+ );+ finish_sample_in_engine(input, host, engine, reference_box, step)+}++fn finish_sample_in_engine(+ input: &AnimationSampleInput,+ host: &mut dyn AnimationSampleHost,+ engine: &mut crate::css::style::StyleEngine,+ reference_box: Option<CssPixelRect>,+ step: AnimationSampleStep,+) -> AnimationSampleStep {+ match step {AnimationSampleStep::Resolved(sample) => match engine_length_contexts(input, engine, &sample) {Some(length_contexts) => AnimationSampleStep::Sampled(finish_animation_sample(input,@@ -7204,7 +7274,7 @@ fn finish_animation_sample(mut result,} = sample;let table = input.longhands;- if input.pseudo_kind == crate::css::cascaded_properties::NO_PSEUDO_ELEMENT {+ if input.record_dependencies && input.pseudo_kind == crate::css::cascaded_properties::NO_PSEUDO_ELEMENT {engine.note_keyframes_read_parent_reset_values(node, result.keyframes_inherited_non_inherited_style_groups != 0);}diff --git a/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-crash.html b/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-crash.htmlnew file mode 100644index 00000000000..063fe5a4ebf--- /dev/null+++ b/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-crash.html@@ -0,0 +1,26 @@+<!doctype html>+<link rel=help href="https://bugzilla.mozilla.org/show_bug.cgi?id=1741491">+<script>+ class CustomElement0 extends HTMLElement {+ constructor () {+ super()+ }++ static get observedAttributes () { return ["style"] }++ async attributeChangedCallback () {+ const animation = this.animate([{+ "boxShadow": "none",+ "visibility": "collapse"+ }], 1957)+ animation.commitStyles()+ }+ }++ customElements.define("custom-element-0", CustomElement0)+ window.addEventListener("load", () => {+ const custom = document.createElement("custom-element-0")+ document.documentElement.appendChild(custom)+ custom.style.fontFamily = "family_name_0"+ })+</script>diff --git a/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-svg-crash.html b/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-svg-crash.htmlnew file mode 100644index 00000000000..7fc1fef9ce2--- /dev/null+++ b/Tests/LibWeb/Crash/wpt-import/web-animations/interfaces/Animation/commitStyles-svg-crash.html@@ -0,0 +1,12 @@+<!DOCTYPE html>+<html class=test-wait>+<link rel=help href="https://crbug.com/1385691">+<svg id=svg></svg>+<script>+ let anim = svg.animate({'svg-viewBox': '1 1 1 1'}, 1);+ anim.ready.then(() => {+ anim.commitStyles();+ document.documentElement.classList.remove('test-wait');+ });+</script>+</html>diff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-custom-property-initial.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-custom-property-initial.txtnew file mode 100644index 00000000000..b1e8fe992be--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-custom-property-initial.txt@@ -0,0 +1,8 @@+base none: 96px, 7+without registration: 96px, 7+base zoom: 2: 96px, 7+without registration: 96px, 7+base --unrelated: 1: 96px, 7+without registration: 96px, 7+base --length: 24px; --number: 3: 24px, 3+without registration: 24px, 3diff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-finished-popup.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-finished-popup.txtnew file mode 100644index 00000000000..189ef37b8e6--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-finished-popup.txt@@ -0,0 +1,4 @@+typeof Animation.prototype.commitStyles: function+teaser.style.transform: translate(0px, -30px)+panel visibility: visible+transform after cancel: matrix(1, 0, 0, 1, 0, -30)diff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-important-base.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-important-base.txtnew file mode 100644index 00000000000..95a31a8d32a--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-important-base.txt@@ -0,0 +1 @@+committed opacity: 0.2diff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-important-custom-property.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-important-custom-property.txtnew file mode 100644index 00000000000..f7479ffdac0--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-important-custom-property.txt@@ -0,0 +1,17 @@+normal+progress: 0.5+rendered before commit: 0.5+committed value: 0.5+rendered after commit: 0.5+after removing important declaration: 0.5+important without flush+progress: 0.5+committed value: 0.2+rendered after commit: 0.2+after removing important declaration: 0.2+important after flush+progress: 0.5+rendered before commit: 0.2+committed value: 0.2+rendered after commit: 0.2+after removing important declaration: 0.2diff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-pending-style.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-pending-style.txtnew file mode 100644index 00000000000..9f3d4cb38ec--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-pending-style.txt@@ -0,0 +1,2 @@+pending color committed: rgb(40, 50, 60)+pending display:none: InvalidStateErrordiff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-state.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-state.txtnew file mode 100644index 00000000000..999e537c49c--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-state.txt@@ -0,0 +1,13 @@+Animations without a target do nothing+display:contents opacity: 0.5+committed endpoint: 1+normal timing progress: null+normal rendered opacity: 0.25+lower committed opacity: 0.2+upper still rendered: 0.4+upper still advances: 0.8+two-property mutation count: 1+unchanged mutation count: 0+CSS animation margin: 10px 20px 30px 40px+inherited animated width before commit: 100px+inherited animated width after parent change: 200pxdiff --git a/Tests/LibWeb/Text/expected/Animations/commit-styles-zoom.txt b/Tests/LibWeb/Text/expected/Animations/commit-styles-zoom.txtnew file mode 100644index 00000000000..abe03290063--- /dev/null+++ b/Tests/LibWeb/Text/expected/Animations/commit-styles-zoom.txt@@ -0,0 +1,24 @@+zoom 1 * 2:+width: 100px+margin-left: 20px+padding-top: 15px+border-top-left-radius: 20px 30px+opacity: 0.5+translation: 20px+position and size preserved: true+zoom 2 * 1.5:+width: 100px+margin-left: 20px+padding-top: 15px+border-top-left-radius: 20px 30px+opacity: 0.5+translation: 20px+position and size preserved: true+zoom 1 * 0.5:+width: 100px+margin-left: 20px+padding-top: 15px+border-top-left-radius: 20px 30px+opacity: 0.5+translation: 20px+position and size preserved: truediff --git a/Tests/LibWeb/Text/expected/wpt-import/css/css-transforms/animation/transform-interpolation-inline-value.txt b/Tests/LibWeb/Text/expected/wpt-import/css/css-transforms/animation/transform-interpolation-inline-value.txtindex e43af1dd0e9..9d04fd4b00d 100644--- a/Tests/LibWeb/Text/expected/wpt-import/css/css-transforms/animation/transform-interpolation-inline-value.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/css/css-transforms/animation/transform-interpolation-inline-value.txt@@ -2,45 +2,46 @@ Harness status: OKFound 41 tests-41 Fail+26 Pass+15 FailFail Interpolation between translateX(0px) and translateX(50px) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translateX(0%) and translateX(50%) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translateY(0%) and translateX(50%) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translateX(50px) and translateY(50px) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translateX(50px) and translateZ(50px) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translateZ(50px) and translateX(50px) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translateX(50px) and translateY(50px) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translateX(50px) and translateZ(50px) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translateZ(50px) and translateX(50px) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translateZ(-50px) and translateZ(50px) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translate(0%) and translate(50%) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translate(50%) and translate(100%, 50%) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translate(0%, 50%) and translate(50%, 100%) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between translate3d(0,0,-50px) and translateZ(50px) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translate(50%) and translate(100%, 50%) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translate(0%, 50%) and translate(50%, 100%) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between translate3d(0,0,-50px) and translateZ(50px) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translate(50px, 0px) and translate(100px, 0px) gives the correct computed value halfway according to commitStyles.Fail Interpolation between translate(50px, -50px) and translate(100px, 50px) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between rotate(30deg) and rotate(90deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between rotate(30deg) and rotate(90deg) gives the correct computed value halfway according to commitStyles.Fail Interpolation between rotateZ(30deg) and rotateZ(90deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between rotate(0deg) and rotateZ(90deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between rotate(0deg) and rotateZ(90deg) gives the correct computed value halfway according to commitStyles.Fail Interpolation between rotateX(0deg) and rotateX(90deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between rotate(0deg) and rotateX(90deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between rotate(0deg) and rotateX(90deg) gives the correct computed value halfway according to commitStyles.Fail Interpolation between scale(1) and scale(2) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scale(1, 3) and scale(2) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scale(1, 3) and scale(2) gives the correct computed value halfway according to commitStyles.Fail Interpolation between scaleX(1) and scaleX(2) gives the correct computed value halfway according to commitStyles.Fail Interpolation between scaleY(1) and scaleY(2) gives the correct computed value halfway according to commitStyles.Fail Interpolation between scaleZ(1) and scaleZ(2) gives the correct computed value halfway according to commitStyles.Fail Interpolation between scaleX(2) and scaleY(2) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scaleX(2) and scaleY(3) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scaleZ(1) and scale(2) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scale(1, 2) and scale(3, 4) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scale3d(1, 2, 3) and scale3d(4, 5, 6) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scale3d(1, 2, 3) and scale(4, 5) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between scale(1, 2) and scale3d(3, 4, 5) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between skewX(0deg) and skewX(60deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between skewX(0deg) and skewX(90deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between skewX(0deg) and skewX(180deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between skew(0deg, 0deg) and skew(60deg, 60deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between skew(45deg, 0deg) and skew(0deg, 45deg) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between perspective(10px) and perspective(2.5px) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between perspective(10px) and perspective(none) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between perspective(none) and perspective(none) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scaleX(2) and scaleY(3) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scaleZ(1) and scale(2) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scale(1, 2) and scale(3, 4) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scale3d(1, 2, 3) and scale3d(4, 5, 6) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scale3d(1, 2, 3) and scale(4, 5) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between scale(1, 2) and scale3d(3, 4, 5) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between skewX(0deg) and skewX(60deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between skewX(0deg) and skewX(90deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between skewX(0deg) and skewX(180deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between skew(0deg, 0deg) and skew(60deg, 60deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between skew(45deg, 0deg) and skew(0deg, 45deg) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between perspective(10px) and perspective(2.5px) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between perspective(10px) and perspective(none) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between perspective(none) and perspective(none) gives the correct computed value halfway according to commitStyles.Fail Interpolation between matrix(2, 0, 0, 2, 10, 30) and matrix(4, 0, 0, 6, 14, 10) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between matrix3d(1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 5, 10, 4, 1) and matrix3d(3, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, -11, 2, 2, 1) gives the correct computed value halfway according to commitStyles.-Fail Interpolation between matrix3d(1, 0, 0, 3, 0, 1, 0, 2, 0, 0, 1, 8, 0, 0, 0, 1) and matrix3d(1, 0, 0, 5, 0, 1, 0, 8, 0, 0, 1, 14, 0, 0, 0, 1) gives the correct computed value halfway according to commitStyles.\ No newline at end of file+Pass Interpolation between matrix3d(1, 0, 0, 0, 0, 4, 0, 0, 0, 0, 1, 0, 5, 10, 4, 1) and matrix3d(3, 0, 0, 0, 0, 2, 0, 0, 0, 0, 3, 0, -11, 2, 2, 1) gives the correct computed value halfway according to commitStyles.+Pass Interpolation between matrix3d(1, 0, 0, 3, 0, 1, 0, 2, 0, 0, 1, 8, 0, 0, 0, 1) and matrix3d(1, 0, 0, 5, 0, 1, 0, 8, 0, 0, 1, 14, 0, 0, 0, 1) gives the correct computed value halfway according to commitStyles.\ No newline at end of filediff --git a/Tests/LibWeb/Text/expected/wpt-import/web-animations/idlharness.window.txt b/Tests/LibWeb/Text/expected/wpt-import/web-animations/idlharness.window.txtindex eb600d35b64..19700dc67fa 100644--- a/Tests/LibWeb/Text/expected/wpt-import/web-animations/idlharness.window.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/web-animations/idlharness.window.txt@@ -2,8 +2,8 @@ Harness status: OKFound 230 tests-162 Pass-68 Fail+164 Pass+66 FailPass idl_test setupPass idl_test validationPass Partial interface Document: original interface defined@@ -92,7 +92,7 @@ Pass Animation interface: operation pause()Pass Animation interface: operation updatePlaybackRate(double)Pass Animation interface: operation reverse()Pass Animation interface: operation persist()-Fail Animation interface: operation commitStyles()+Pass Animation interface: operation commitStyles()Pass Animation interface: attribute startTimePass Animation interface: attribute currentTimeFail Animation interface: attribute trigger@@ -119,7 +119,7 @@ Pass Animation interface: new Animation() must inherit property "updatePlaybackRPass Animation interface: calling updatePlaybackRate(double) on new Animation() with too few arguments must throw TypeErrorPass Animation interface: new Animation() must inherit property "reverse()" with the proper typePass Animation interface: new Animation() must inherit property "persist()" with the proper type-Fail Animation interface: new Animation() must inherit property "commitStyles()" with the proper type+Pass Animation interface: new Animation() must inherit property "commitStyles()" with the proper typePass Animation interface: new Animation() must inherit property "startTime" with the proper typePass Animation interface: new Animation() must inherit property "currentTime" with the proper typeFail Animation interface: new Animation() must inherit property "trigger" with the proper typediff --git a/Tests/LibWeb/Text/expected/wpt-import/web-animations/interfaces/Animation/commitStyles.txt b/Tests/LibWeb/Text/expected/wpt-import/web-animations/interfaces/Animation/commitStyles.txtnew file mode 100644index 00000000000..45d0912f462--- /dev/null+++ b/Tests/LibWeb/Text/expected/wpt-import/web-animations/interfaces/Animation/commitStyles.txt@@ -0,0 +1,41 @@+Harness status: OK++Found 36 tests++36 Pass+Pass Throws if the target element is not something with a style attribute+Pass Throws if the target element is a pseudo element+Pass Checks the pseudo element condition before the not rendered condition+Pass Throws if the target effect is disconnected+Pass Throws if the target effect is display:none+Pass Throws if the target effect's ancestor is display:none+Pass Treats display:contents as rendered+Pass Treats display:contents in a display:none subtree as not rendered+Pass Commits styles+Pass Commits styles for backwards animation+Pass Commits values calculated mid-interval+Pass Commits values during the start delay+Pass Commits value after the active interval+Pass Commits the intermediate value of an animation in the middle of stack+Pass Commits the intermediate value of an animation up to the middle of the stack+Pass Commits styles for an animation that has been removed+Pass Calling commitStyles() on a canceled animation with a removed replace state does not throw+Pass Does not commit the value of the replacing animation when committing a canceled animation with a removed replace state+Pass Does not commit values of animations with a higher composite order when the animation is not in effect+Pass Commits values of animations with a lower composite order when the animation is not in effect+Pass Commit composites on top of the underlying value+Pass Commit styles of an animation when another animation runs with a different prop+Pass Commits logical properties+Pass Commits logical properties as physical properties+Pass Commits em units as pixel values+Pass Commits custom variables+Pass Commits variable references as their computed values+Pass Commits relative line-height+Pass Commits transforms+Pass Commits styles for individual transform properties+Pass Commits transforms as a transform list+Pass Commits matrix-interpolated relative transforms+Pass Commits 'none' transform+Pass Commits shorthand styles+Pass Triggers mutation observers when updating style+Pass Does NOT trigger mutation observers when the change to style is redundant\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-custom-property-initial.html b/Tests/LibWeb/Text/input/Animations/commit-styles-custom-property-initial.htmlnew file mode 100644index 00000000000..831f3281dad--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-custom-property-initial.html@@ -0,0 +1,33 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ test(() => {+ const registration = document.head.appendChild(document.createElement("style"));+ registration.textContent = `+ @property --length { syntax: "<length>"; inherits: false; initial-value: 1in; }+ @property --number { syntax: "<number>"; inherits: true; initial-value: 7; }+ `;+ for (const base of ["", "zoom: 2", "--unrelated: 1", "--length: 24px; --number: 3"]) {+ const target = document.body.appendChild(document.createElement("div"));+ target.style.cssText = base;+ const animation = target.animate(+ { "--length": ["200px", "400px"], "--number": [10, 20] },+ { duration: 100, delay: 100 }+ );+ animation.pause();+ animation.currentTime = 0;+ animation.commitStyles();+ animation.cancel();+ println(+ `base ${base || "none"}: ${target.style.getPropertyValue("--length")}, ${target.style.getPropertyValue("--number")}`+ );+ registration.sheet.disabled = true;+ println(+ `without registration: ${getComputedStyle(target).getPropertyValue("--length")}, ${getComputedStyle(target).getPropertyValue("--number")}`+ );+ registration.sheet.disabled = false;+ target.remove();+ }+ registration.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-finished-popup.html b/Tests/LibWeb/Text/input/Animations/commit-styles-finished-popup.htmlnew file mode 100644index 00000000000..98ddac56589--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-finished-popup.html@@ -0,0 +1,34 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ #teaser,+ #panel {+ position: fixed;+ right: 20px;+ }+ #teaser {+ bottom: 20px;+ }+ #panel {+ bottom: 90px;+ visibility: hidden;+ }+</style>+<div id="teaser">Teaser</div>+<div id="panel">Panel opened</div>+<script>+ promiseTest(async () => {+ println(`typeof Animation.prototype.commitStyles: ${typeof Animation.prototype.commitStyles}`);+ const animation = teaser.animate([{ transform: "translateY(0)" }, { transform: "translateY(-30px)" }], {+ duration: 300,+ fill: "both",+ });+ await animation.finished;+ animation.commitStyles();+ animation.cancel();+ println(`teaser.style.transform: ${teaser.style.transform}`);+ panel.style.visibility = "visible";+ println(`panel visibility: ${getComputedStyle(panel).visibility}`);+ println(`transform after cancel: ${getComputedStyle(teaser).transform}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-important-base.html b/Tests/LibWeb/Text/input/Animations/commit-styles-important-base.htmlnew file mode 100644index 00000000000..a8afe8d0cd2--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-important-base.html@@ -0,0 +1,18 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ #target {+ opacity: 0.2 !important;+ }+</style>+<div id="target"></div>+<script>+ test(() => {+ const animation = target.animate({ opacity: [0, 1] }, { duration: 100, fill: "both" });+ animation.pause();+ animation.currentTime = 50;+ animation.commitStyles();+ animation.cancel();+ println(`committed opacity: ${target.style.opacity}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-important-custom-property.html b/Tests/LibWeb/Text/input/Animations/commit-styles-important-custom-property.htmlnew file mode 100644index 00000000000..ffd99419200--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-important-custom-property.html@@ -0,0 +1,31 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ @property --value {+ syntax: "<number>";+ inherits: false;+ initial-value: 0;+ }+ #target { --value: 0.2 !important; }+</style>+<div id="target"></div>+<script>+ test(() => {+ for (const [label, important, flush] of [["normal", false, true], ["important without flush", true, false], ["important after flush", true, true]]) {+ document.styleSheets[0].cssRules[1].style.setProperty("--value", "0.2", important ? "important" : "");+ target.style.removeProperty("--value");+ println(label);+ const animation = target.animate({ "--value": [0, 1] }, { duration: 100, fill: "both" });+ animation.pause();+ animation.currentTime = 50;+ println(`progress: ${animation.effect.getComputedTiming().progress}`);+ if (flush) println(`rendered before commit: ${getComputedStyle(target).getPropertyValue("--value")}`);+ animation.commitStyles();+ println(`committed value: ${target.style.getPropertyValue("--value")}`);+ println(`rendered after commit: ${getComputedStyle(target).getPropertyValue("--value")}`);+ animation.cancel();+ document.styleSheets[0].cssRules[1].style.removeProperty("--value");+ println(`after removing important declaration: ${getComputedStyle(target).getPropertyValue("--value")}`);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-pending-style.html b/Tests/LibWeb/Text/input/Animations/commit-styles-pending-style.htmlnew file mode 100644index 00000000000..72bdda8f643--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-pending-style.html@@ -0,0 +1,24 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ test(() => {+ const target = document.body.appendChild(document.createElement("div"));+ target.style.color = "rgb(10, 20, 30)";+ const animation = target.animate({ color: ["red", "blue"] }, { duration: 100, delay: 100 });+ animation.pause();+ animation.currentTime = 0;+ target.getBoundingClientRect();+ target.style.color = "rgb(40, 50, 60)";+ animation.commitStyles();+ println(`pending color committed: ${target.style.color}`);+ target.style.display = "none";+ try {+ animation.commitStyles();+ println("hidden target did not throw");+ } catch (error) {+ println(`pending display:none: ${error.name}`);+ }+ animation.cancel();+ target.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-state.html b/Tests/LibWeb/Text/input/Animations/commit-styles-state.htmlnew file mode 100644index 00000000000..54a663464b4--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-state.html@@ -0,0 +1,78 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ @keyframes margins {+ to {+ margin: 10px 20px 30px 40px;+ }+ }+</style>+<script>+ test(() => {+ new Animation().commitStyles();+ new Animation(new KeyframeEffect(null, { opacity: 0 }, 100)).commitStyles();+ println("Animations without a target do nothing");++ const target = document.body.appendChild(document.createElement("div"));+ target.style.display = "contents";+ const contents = target.animate({ opacity: [0, 1] }, 100);+ contents.currentTime = 50;+ contents.commitStyles();+ contents.cancel();+ println(`display:contents opacity: ${target.style.opacity}`);++ target.style.display = "block";+ const finished = target.animate({ opacity: [0, 1] }, 100);+ finished.finish();+ finished.commitStyles();+ println(`committed endpoint: ${target.style.opacity}`);+ println(`normal timing progress: ${finished.effect.getComputedTiming().progress}`);+ target.style.opacity = "0.25";+ println(`normal rendered opacity: ${getComputedStyle(target).opacity}`);+ finished.cancel();++ const lower = target.animate({ opacity: [0, 0.4] }, { duration: 100, fill: "both" });+ const upper = target.animate({ opacity: [0, 0.8] }, { duration: 100, fill: "both" });+ lower.currentTime = upper.currentTime = 50;+ lower.commitStyles();+ println(`lower committed opacity: ${target.style.opacity}`);+ println(`upper still rendered: ${getComputedStyle(target).opacity}`);+ upper.currentTime = 100;+ println(`upper still advances: ${getComputedStyle(target).opacity}`);+ lower.cancel();+ upper.cancel();++ const observer = new MutationObserver(() => {});+ observer.observe(target, { attributes: true, attributeFilter: ["style"] });+ const pair = target.animate({ opacity: 0.5, marginLeft: "12px" }, { duration: 100, fill: "both" });+ pair.finish();+ pair.commitStyles();+ println(`two-property mutation count: ${observer.takeRecords().length}`);+ pair.commitStyles();+ println(`unchanged mutation count: ${observer.takeRecords().length}`);+ observer.disconnect();+ pair.cancel();+ target.style.animation = "margins 100s both";+ const cssAnimation = target.getAnimations()[0];+ cssAnimation.finish();+ cssAnimation.commitStyles();+ cssAnimation.cancel();+ println(`CSS animation margin: ${target.style.margin}`);+ const parent = document.body.appendChild(document.createElement("div"));+ const child = parent.appendChild(document.createElement("div"));+ parent.style.width = "100px";+ const opacity = child.animate({ opacity: [0, 1] }, { duration: 100, fill: "both" });+ const width = child.animate({ width: ["inherit", "inherit"] }, { duration: 100, fill: "both" });+ opacity.currentTime = width.currentTime = 50;+ println(`inherited animated width before commit: ${getComputedStyle(child).width}`);+ opacity.commitStyles();+ getComputedStyle(child).width;+ opacity.commitStyles();+ parent.style.width = "200px";+ println(`inherited animated width after parent change: ${getComputedStyle(child).width}`);+ opacity.cancel();+ width.cancel();+ parent.remove();+ target.remove();+ });+</script>diff --git a/Tests/LibWeb/Text/input/Animations/commit-styles-zoom.html b/Tests/LibWeb/Text/input/Animations/commit-styles-zoom.htmlnew file mode 100644index 00000000000..87aa7a0c895--- /dev/null+++ b/Tests/LibWeb/Text/input/Animations/commit-styles-zoom.html@@ -0,0 +1,41 @@+<!doctype html>+<script src="../include.js"></script>+<script>+ test(() => {+ for (const [parentZoom, ownZoom] of [+ [1, 2],+ [2, 1.5],+ [1, 0.5],+ ]) {+ const parent = document.body.appendChild(document.createElement("div"));+ parent.style.cssText = `zoom: ${parentZoom}; width: 400px`;+ const target = parent.appendChild(document.createElement("div"));+ target.style.zoom = ownZoom;+ const animation = target.animate(+ {+ width: ["80px", "120px"],+ marginLeft: ["10px", "30px"],+ paddingTop: ["10px", "20px"],+ borderTopLeftRadius: ["10px 20px", "30px 40px"],+ transform: ["translateX(10px)", "translateX(30px)"],+ opacity: [0.2, 0.8],+ },+ { duration: 100, fill: "both" }+ );+ animation.pause();+ animation.currentTime = 50;+ const before = target.getBoundingClientRect().toJSON();+ animation.commitStyles();+ animation.cancel();+ const after = target.getBoundingClientRect();+ println(`zoom ${parentZoom} * ${ownZoom}:`);+ for (const property of ["width", "margin-left", "padding-top", "border-top-left-radius", "opacity"])+ println(`${property}: ${target.style.getPropertyValue(property)}`);+ println(`translation: ${new DOMMatrix(target.style.transform).m41}px`);+ println(+ `position and size preserved: ${["x", "y", "width", "height"].every(key => Math.abs(before[key] - after[key]) < 0.01)}`+ );+ parent.remove();+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/wpt-import/web-animations/interfaces/Animation/commitStyles.html b/Tests/LibWeb/Text/input/wpt-import/web-animations/interfaces/Animation/commitStyles.htmlnew file mode 100644index 00000000000..70417d017f6--- /dev/null+++ b/Tests/LibWeb/Text/input/wpt-import/web-animations/interfaces/Animation/commitStyles.html@@ -0,0 +1,832 @@+<!doctype html>+<meta charset=utf-8>+<title>Animation.commitStyles</title>+<link rel="help" href="https://drafts.csswg.org/web-animations/#dom-animation-commitstyles">+<script src="../../../resources/testharness.js"></script>+<script src="../../../resources/testharnessreport.js"></script>+<script src="../../testcommon.js"></script>+<style>+.pseudo::before {content: '';}+.pseudo::after {content: '';}+.pseudo::marker {content: '';}+</style>+<body>+<div id="log"></div>+<script>+'use strict';++function assert_numeric_style_equals(opacity, expected, description) {+ return assert_approx_equals(+ parseFloat(opacity),+ expected,+ 0.0001,+ description+ );+}++// -------------------------+// Tests covering elements not capable of having a style attribute+// --------------------++test(t => {+ const animation = createDiv(t).animate(+ { opacity: 0 },+ { duration: 1 }+ );++ const nonStyleElement = document.createElementNS(+ 'http://example.org/test',+ 'test'+ );+ document.body.appendChild(nonStyleElement);+ animation.effect.target = nonStyleElement;++ assert_throws_dom('NoModificationAllowedError', () => {+ animation.commitStyles();+ });++ nonStyleElement.remove();+}, 'Throws if the target element is not something with a style attribute');++test(t => {+ const div = createDiv(t);+ div.classList.add('pseudo');+ const animation = div.animate(+ { opacity: 0 },+ { duration: 1, pseudoElement: '::before' }+ );++ assert_throws_dom('NoModificationAllowedError', () => {+ animation.commitStyles();+ });+}, 'Throws if the target element is a pseudo element');++test(t => {+ const div = createDiv(t);+ div.classList.add('pseudo');+ const animation = div.animate(+ { opacity: 0 },+ { duration: 1, pseudoElement: '::before' }+ );++ div.remove();++ assert_throws_dom('NoModificationAllowedError', () => {+ animation.commitStyles();+ });+}, 'Checks the pseudo element condition before the not rendered condition');++// -------------------------+// Tests covering elements that are not being rendered+// -------------------------++test(t => {+ const div = createDiv(t);+ const animation = div.animate(+ { opacity: 0 },+ { duration: 1 }+ );++ div.remove();++ assert_throws_dom('InvalidStateError', () => {+ animation.commitStyles();+ });+}, 'Throws if the target effect is disconnected');++test(t => {+ const div = createDiv(t);+ const animation = div.animate(+ { opacity: 0 },+ { duration: 1 }+ );++ div.style.display = 'none';++ assert_throws_dom('InvalidStateError', () => {+ animation.commitStyles();+ });+}, 'Throws if the target effect is display:none');++test(t => {+ const container = createDiv(t);+ const div = createDiv(t);+ container.append(div);++ const animation = div.animate(+ { opacity: 0 },+ { duration: 1 }+ );++ container.style.display = 'none';++ assert_throws_dom('InvalidStateError', () => {+ animation.commitStyles();+ });+}, "Throws if the target effect's ancestor is display:none");++test(t => {+ const container = createDiv(t);+ const div = createDiv(t);+ container.append(div);++ const animation = div.animate(+ { opacity: 0 },+ { duration: 1 }+ );++ container.style.display = 'contents';++ // Should NOT throw+ animation.commitStyles();+}, 'Treats display:contents as rendered');++test(t => {+ const container = createDiv(t);+ const div = createDiv(t);+ container.append(div);++ const animation = div.animate(+ { opacity: 0 },+ { duration: 1 }+ );++ div.style.display = 'contents';+ container.style.display = 'none';++ assert_throws_dom('InvalidStateError', () => {+ animation.commitStyles();+ });+}, 'Treats display:contents in a display:none subtree as not rendered');++// -------------------------+// Tests covering various parts of the active interval+// -------------------------++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animation = div.animate(+ { opacity: 0.2 },+ { duration: 1 }+ );+ animation.finish();++ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.2);+}, 'Commits styles');++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animation = div.animate(+ { opacity: [0.5, 1] },+ { duration: 1 }+ );+ animation.playbackRate = -1;+ animation.finish();++ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.5);+}, 'Commits styles for backwards animation');++test(t => {+ const div = createDiv(t);+ div.style.marginLeft = '10px';++ const animation = div.animate({ opacity: [0.2, 0.7] }, 1000);+ animation.currentTime = 500;+ animation.commitStyles();+ animation.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.45);+}, 'Commits values calculated mid-interval');++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0';++ const animation = div.animate(+ { opacity: 1 },+ { duration: 1000, delay: 1000 }+ );+ animation.currentTime = 500;+ animation.commitStyles();+ animation.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0);+}, 'Commits values during the start delay');++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0';++ const animation = div.animate(+ { opacity: 1 },+ { duration: 1000, delay: 1000 }+ );+ animation.currentTime = 2100;+ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0);+}, 'Commits value after the active interval');++// -------------------------+// Tests covering various parts of the stack+// -------------------------++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate(+ { opacity: '0.2' },+ { duration: 1, fill: 'forwards' }+ );+ const animB = div.animate(+ { opacity: '0.2', composite: 'add' },+ { duration: 1 }+ );+ const animC = div.animate(+ { opacity: '0.3', composite: 'add' },+ { duration: 1 }+ );++ animA.persist();+ animB.persist();++ await animB.finished;++ // The values above have been chosen such that various error conditions+ // produce results that all differ from the desired result:+ //+ // Expected result:+ //+ // animA + animB = 0.4+ //+ // Likely error results:+ //+ // <underlying> = 0.1+ // (Commit didn't work at all)+ //+ // animB = 0.2+ // (Didn't add at all when resolving)+ //+ // <underlying> + animB = 0.3+ // (Added to the underlying value instead of lower-priority animations when+ // resolving)+ //+ // <underlying> + animA + animB = 0.5+ // (Didn't respect the composite mode of lower-priority animations)+ //+ // animA + animB + animC = 0.7+ // (Resolved the whole stack, not just up to the target effect)+ //++ animB.commitStyles();++ animA.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.4);+}, 'Commits the intermediate value of an animation in the middle of stack');++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate(+ { opacity: '0.2' },+ { duration: 1 }+ );+ const animB = div.animate(+ { opacity: '0.2', composite: 'add' },+ { duration: 1 }+ );+ const animC = div.animate(+ { opacity: '0.3', composite: 'add' },+ { duration: 1 }+ );++ animA.persist();+ animB.persist();++ await animB.finished;++ // The values above have been chosen such that various error conditions+ // produce results that all differ from the desired result:+ //+ // Expected result:+ //+ // animA + animB = 0.4+ //+ // Likely error results:+ //+ // <underlying> = 0.1+ // (Commit didn't work at all)+ //+ // animB = 0.2+ // (Didn't add at all when resolving)+ //+ // <underlying> + animB = 0.3+ // (Added to the underlying value instead of lower-priority animations when+ // resolving)+ //+ // <underlying> + animA + animB = 0.5+ // (Didn't respect the composite mode of lower-priority animations)+ //+ // animA + animB + animC = 0.7+ // (Resolved the whole stack, not just up to the target effect)+ //++ animA.commitStyles();+ animB.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.4);+}, 'Commits the intermediate value of an animation up to the middle of the stack');++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate(+ { opacity: 0.2 },+ { duration: 1 }+ );+ const animB = div.animate(+ { opacity: 0.3 },+ { duration: 1 }+ );++ await animA.finished;++ animB.cancel();++ animA.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.2);+}, 'Commits styles for an animation that has been removed');++promise_test(async t => {+ const div = createDiv(t);++ const animation = div.animate(+ { opacity: 0.2 },+ { duration: 1, fill: 'forwards' }+ );+ await animation.finished;++ const replacingAnimation = div.animate(+ { opacity: 0.3 },+ { duration: 1, fill: 'forwards' }+ );+ await replacingAnimation.finished;++ assert_equals(animation.replaceState, 'removed');++ animation.cancel();++ assert_equals(animation.replaceState, 'removed');+ assert_equals(animation.currentTime, null);++ animation.commitStyles();+}, 'Calling commitStyles() on a canceled animation with a removed replace'+ + ' state does not throw');++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animation = div.animate(+ { opacity: 0.2 },+ { duration: 1, fill: 'forwards' }+ );+ await animation.finished;++ const replacingAnimation = div.animate(+ { opacity: 0.3 },+ { duration: 1, fill: 'forwards' }+ );+ await replacingAnimation.finished;++ assert_equals(animation.replaceState, 'removed');++ animation.cancel();+ animation.commitStyles();+ replacingAnimation.cancel();++ // The canceled animation is not in effect, and the replacing animation has a+ // higher composite order, so neither should contribute to the committed+ // value.+ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.1);+}, 'Does not commit the value of the replacing animation when committing a'+ + ' canceled animation with a removed replace state');++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate(+ { opacity: 0.2 },+ { duration: 1000, delay: 1000 }+ );+ const animB = div.animate({ opacity: 0.5 }, 1000);+ animA.currentTime = 500;+ animB.currentTime = 500;++ // animA is in its start delay, so it is not in effect. animB has a higher+ // composite order, so it should not contribute to the committed value.+ animA.commitStyles();+ animA.cancel();+ animB.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.1);+}, 'Does not commit values of animations with a higher composite order when'+ + ' the animation is not in effect');++test(t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate({ opacity: 0.2 }, 1000);+ const animB = div.animate(+ { opacity: 0.5 },+ { duration: 1000, delay: 1000 }+ );+ const animC = div.animate({ opacity: 0.7 }, 1000);+ animA.currentTime = 500;+ animB.currentTime = 500;+ animC.currentTime = 500;++ // animB is in its start delay, so it is not in effect. The committed value+ // should be the result of animA alone: 0.1 + (0.2 - 0.1) * 0.5 = 0.15.+ animB.commitStyles();+ animA.cancel();+ animB.cancel();+ animC.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.15);+}, 'Commits values of animations with a lower composite order when the'+ + ' animation is not in effect');++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ const animA = div.animate(+ { opacity: '0.2', composite: 'add' },+ { duration: 1, fill: 'forwards' }+ );+ const animB = div.animate(+ { opacity: '0.2', composite: 'add' },+ { duration: 1 }+ );+ const animC = div.animate(+ { opacity: '0.3', composite: 'add' },+ { duration: 1 }+ );++ animA.persist();+ animB.persist();+ await animB.finished;++ // The error cases are similar to the above test with one additional case;+ // verifying that the animations composite on top of the correct underlying+ // base style.+ //+ // Expected result:+ //+ // <underlying> + animA + animB = 0.5+ //+ // Additional error results:+ //+ // <underlying> + animA + animB + animC + animA + animB = 1.0 (saturates)+ // (Added to the computed value instead of underlying value when+ // resolving)+ //+ // animA + animB = 0.4+ // Failed to composite on top of underlying value.+ //++ animB.commitStyles();++ animA.cancel();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.5);+}, 'Commit composites on top of the underlying value');++// -------------------------+// Tests of concurrent animations with different props+// -------------------------++test(t => {+ const div = createDiv(t);+ div.style.left = "0px";+ div.style.top = "0px";++ const animA = div.animate({ left: "200px" }, { duration: 30_000 });+ const animB = div.animate({ top: "200px" }, { duration: 50_000 });++ animA.finish();+ animA.commitStyles();+ assert_equals(getComputedStyle(div).left, "200px");++ animB.finish();+ animB.commitStyles();+ assert_equals(getComputedStyle(div).top, "200px");+}, 'Commit styles of an animation when another animation runs with a different prop');++// -------------------------+// Tests covering handling of logical properties+// -------------------------++test(t => {+ const div = createDiv(t);+ div.style.marginLeft = '10px';++ const animation = div.animate(+ { marginInlineStart: '20px' },+ { duration: 1 }+ );+ animation.finish();++ animation.commitStyles();++ assert_equals(getComputedStyle(div).marginLeft, '20px');+}, 'Commits logical properties');++test(t => {+ const div = createDiv(t);+ div.style.marginLeft = '10px';++ const animation = div.animate(+ { marginInlineStart: '20px' },+ { duration: 1 }+ );+ animation.finish();++ animation.commitStyles();++ assert_equals(div.style.marginLeft, '20px');+}, 'Commits logical properties as physical properties');++test(t => {+ const div = createDiv(t);+ div.style.fontSize = '10px';++ const animation = div.animate(+ { width: '10em' },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).width, 100);++ div.style.fontSize = '20px';+ assert_numeric_style_equals(+ getComputedStyle(div).width,+ 100,+ 'Changes to the font-size should have no effect'+ );+}, 'Commits em units as pixel values');++// -------------------------+// Tests covering CSS variables+// -------------------------++test(t => {+ const div = createDiv(t);+ div.style.setProperty('--target', '0.5');+ div.style.opacity = 'var(--target)';+ const animation = div.animate(+ { '--target': 0.8 },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.8);+}, 'Commits custom variables');++test(t => {+ const div = createDiv(t);+ div.style.setProperty('--target', '0.5');++ const animation = div.animate(+ { opacity: 'var(--target)' },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.5);++ // Changes to the variable should have no effect+ div.style.setProperty('--target', '1');++ assert_numeric_style_equals(getComputedStyle(div).opacity, 0.5);+}, 'Commits variable references as their computed values');++// -------------------------+// Tests covering the composition of specific properties+// (e.g. line-height, transforms)+// -------------------------++test(t => {+ const div = createDiv(t);+ div.style.fontSize = '10px';++ const animation = div.animate(+ { lineHeight: '1.5' },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_numeric_style_equals(getComputedStyle(div).lineHeight, 15);+ assert_equals(+ div.style.lineHeight,+ '1.5',+ 'line-height is committed as a relative value'+ );++ div.style.fontSize = '20px';+ assert_numeric_style_equals(+ getComputedStyle(div).lineHeight,+ 30,+ 'Changes to the font-size should affect the committed line-height'+ );+}, 'Commits relative line-height');++test(t => {+ const div = createDiv(t);+ const animation = div.animate(+ { transform: 'translate(20px, 20px)' },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_equals(+ getComputedStyle(div).transform,+ 'matrix(1, 0, 0, 1, 20, 20)'+ );+}, 'Commits transforms');++test(t => {+ const div = createDiv(t);+ div.style.translate = '100px';+ div.style.rotate = '45deg';+ div.style.scale = '2';++ const animation = div.animate(+ { translate: '200px', rotate: '90deg', scale: 3 },+ { duration: 1 }+ );+ animation.finish();++ animation.commitStyles();++ assert_equals(getComputedStyle(div).translate, '200px');+ assert_equals(getComputedStyle(div).rotate, '90deg');+ assert_numeric_style_equals(getComputedStyle(div).scale, 3);+}, 'Commits styles for individual transform properties');++test(t => {+ const div = createDiv(t);+ const animation = div.animate(+ { transform: 'translate(20px, 20px)' },+ { duration: 1 }+ );+ animation.finish();+ animation.commitStyles();++ assert_equals(div.style.transform, 'translate(20px, 20px)');+}, 'Commits transforms as a transform list');++test(t => {+ const div = createDiv(t);+ div.style.width = '200px';+ div.style.height = '200px';++ const animation = div.animate(+ { transform: ['translate(100%, 0%)', 'scale(3)'] },+ 1000+ );+ animation.currentTime = 500;+ animation.commitStyles();+ animation.cancel();++ // TODO(https://github.com/w3c/csswg-drafts/issues/2854):+ // We can't check the committed value directly since it is not specced yet in this case,+ // but it should still produce the correct resolved value.+ assert_equals(+ getComputedStyle(div).transform,+ 'matrix(2, 0, 0, 2, 100, 0)',+ 'Resolved transform is correct after commit.'+ );+}, 'Commits matrix-interpolated relative transforms');++test(t => {+ const div = createDiv(t);+ div.style.width = '200px';+ div.style.height = '200px';++ const animation = div.animate({ transform: ['none', 'none'] }, 1000);+ animation.currentTime = 500;+ animation.commitStyles();+ animation.cancel();++ assert_equals(+ div.style.transform,+ 'none',+ 'Resolved transform is correct after commit.'+ );+}, "Commits 'none' transform");++test(t => {+ const div = createDiv(t);+ div.style.margin = '10px';++ const animation = div.animate(+ { margin: '20px' },+ { duration: 1 }+ );+ animation.finish();++ animation.commitStyles();++ assert_equals(div.style.marginLeft, '20px');+}, 'Commits shorthand styles');++// -------------------------+// Tests related to setting the style attributes+// (e.g. mutation observer related ones)+// -------------------------++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.1';++ // Setup animation+ const animation = div.animate(+ { opacity: 0.2 },+ { duration: 1 }+ );+ animation.finish();++ // Setup observer+ const mutationRecords = [];+ const observer = new MutationObserver(mutations => {+ mutationRecords.push(...mutations);+ });+ observer.observe(div, { attributes: true, attributeOldValue: true });++ animation.commitStyles();++ // Wait for mutation records to be dispatched+ await Promise.resolve();++ assert_equals(mutationRecords.length, 1, 'Should have one mutation record');++ const mutation = mutationRecords[0];+ assert_equals(mutation.type, 'attributes');+ assert_equals(mutation.oldValue, 'opacity: 0.1;');++ observer.disconnect();+}, 'Triggers mutation observers when updating style');++promise_test(async t => {+ const div = createDiv(t);+ div.style.opacity = '0.2';++ // Setup animation+ const animation = div.animate(+ { opacity: 0.2 },+ { duration: 1 }+ );+ animation.finish();++ // Setup observer+ const mutationRecords = [];+ const observer = new MutationObserver(mutations => {+ mutationRecords.push(...mutations);+ });+ observer.observe(div, { attributes: true });++ animation.commitStyles();++ // Wait for mutation records to be dispatched+ await Promise.resolve();++ assert_equals(mutationRecords.length, 0, 'Should have no mutation records');++ observer.disconnect();+}, 'Does NOT trigger mutation observers when the change to style is redundant');++</script>+</body>