Truly independent web browser
LibWeb: Implement Animation.rangeStart and rangeEnd
Andreas Klingc13ff5b16c8c
diff --git a/Libraries/LibWeb/Animations/Animatable.cpp b/Libraries/LibWeb/Animations/Animatable.cppindex dbc23fea981..f31f56e519a 100644--- a/Libraries/LibWeb/Animations/Animatable.cpp+++ b/Libraries/LibWeb/Animations/Animatable.cpp@@ -96,7 +96,23 @@ WebIDL::ExceptionOr<GC::Ref<Animation>> Animatable::animate(Vector<BaseKeyframe>WebIDL::ExceptionOr<GC::Ref<Animation>> Animatable::animate(JS::Realm& realm, GC::Ptr<JS::Object> keyframes, Variant<double, Bindings::KeyframeAnimationOptions> const& options){- auto animation = TRY(animate(TRY(process_keyframes(realm, keyframes)), TRY(keyframe_animation_options_from_bindings(options))));+ auto processed_keyframes = TRY(process_keyframes(realm, keyframes));++ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend+ // INTEROP: Like Chrome, the keyframes are processed before the range is parsed, so the keyframes' getters run first.+ Optional<AnimationAttachmentRange> range;+ if (auto const* animation_options = options.get_pointer<Bindings::KeyframeAnimationOptions>()) {+ auto& document = static_cast<DOM::Element*>(this)->document();+ range = AnimationAttachmentRange {+ .start = TRY(parse_timeline_range_edge(document, animation_options->range_start, TimelineRangeEdgeSide::Start)),+ .end = TRY(parse_timeline_range_edge(document, animation_options->range_end, TimelineRangeEdgeSide::End)),+ };+ }++ auto animation = TRY(animate(move(processed_keyframes), TRY(keyframe_animation_options_from_bindings(options))));+ if (range.has_value())+ animation->set_range(*range);return animation;}diff --git a/Libraries/LibWeb/Animations/Animatable.idl b/Libraries/LibWeb/Animations/Animatable.idlindex d0c5f40385d..9bef3c8a9c9 100644--- a/Libraries/LibWeb/Animations/Animatable.idl+++ b/Libraries/LibWeb/Animations/Animatable.idl@@ -8,6 +8,11 @@ interface mixin Animatable {dictionary KeyframeAnimationOptions : KeyframeEffectOptions {[FlyString] DOMString id = "";AnimationTimeline? timeline;++ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+ (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeStart = "normal";+ // https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangeend+ (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeEnd = "normal";};// https://drafts.csswg.org/web-animations-1/#dictdef-getanimationsoptionsdiff --git a/Libraries/LibWeb/Animations/Animation.cpp b/Libraries/LibWeb/Animations/Animation.cppindex e32d84957f5..42449f010c5 100644--- a/Libraries/LibWeb/Animations/Animation.cpp+++ b/Libraries/LibWeb/Animations/Animation.cpp@@ -6,6 +6,7 @@*/#include <AK/TemporaryChange.h>+#include <AK/Utf16StringBuilder.h>#include <LibGC/Heap.h>#include <LibJS/Runtime/Realm.h>#include <LibWeb/Animations/Animation.h>@@ -17,9 +18,13 @@#include <LibWeb/Bindings/Wrappable.h>#include <LibWeb/Bindings/WrapperWorld.h>#include <LibWeb/CSS/CSSAnimation.h>+#include <LibWeb/CSS/CSSKeywordValue.h>+#include <LibWeb/CSS/CSSMathSum.h>#include <LibWeb/CSS/CSSNumericValue.h>#include <LibWeb/CSS/CSSTransition.h>+#include <LibWeb/CSS/CSSUnitValue.h>#include <LibWeb/CSS/Length.h>+#include <LibWeb/CSS/Parser/Parser.h>#include <LibWeb/CSS/StyleValues/ComputationContext.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/Scripting/Environments.h>@@ -408,6 +413,95 @@ void Animation::calculate_auto_aligned_start_time()m_hold_time = {};}+// https://drafts.csswg.org/web-animations-2/#dom-keyframeanimationoptions-rangestart+WebIDL::ExceptionOr<TimelineRangeEdge> parse_timeline_range_edge(DOM::Document& document, TimelineRangeBindingValue const& value, TimelineRangeEdgeSide side)+{+ auto property = side == TimelineRangeEdgeSide::Start ? CSS::PropertyID::AnimationRangeStart : CSS::PropertyID::AnimationRangeEnd;+ // A DOMString value is parsed as an 'animation-range-start' (or 'animation-range-end') value to yield a+ // TimelineRangeOffset rangeName and offset or alternatively a CSSKeywordValue with the value of "normal"; a+ // CSSNumericValue is interpreted as a TimelineRangeOffset with that offset and a null rangeName.+ auto parse = [&](Utf16String const& string) -> WebIDL::ExceptionOr<TimelineRangeEdge> {+ auto parsed = parse_css_value(CSS::Parser::ParsingParams { document }, string, property);+ // NB: Arbitrary substitution functions and CSS-wide keywords have nothing to substitute or inherit from here.+ if (!parsed || parsed->is_css_wide_keyword() || parsed->is_unresolved() || parsed->is_pending_substitution())+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };+ auto computed = parsed->absolutized(CSS::ComputationContext { .length_resolution_context = CSS::Length::ResolutionContext::for_document(document) });+ CSS::ComputedValuesFFI::FfiAnimationRangeEdge edge {};+ if (!CSS::ComputedValuesFFI::rust_animation_range_edge(computed->rust_style_value_data(), side == TimelineRangeEdgeSide::End, &edge))+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };+ return TimelineRangeEdge { static_cast<TimelineRangeName>(edge.name), edge.offset_px, edge.offset_percentage };+ };+ return value.visit(+ [&](Bindings::TimelineRangeOffset const& offset) -> WebIDL::ExceptionOr<TimelineRangeEdge> {+ Utf16StringBuilder builder;+ if (offset.range_name.has_value() && offset.range_name->has_value())+ builder.append(**offset.range_name);+ if (offset.offset) {+ builder.append_ascii(' ');+ builder.append(offset.offset->to_string({}));+ }+ // NB: A TimelineRangeOffset that gives neither a range name nor an offset is the default edge.+ if (builder.is_empty())+ return parse("normal"_utf16);+ return parse(builder.to_string());+ },+ [&](GC::Ref<CSS::CSSNumericValue> const& offset) { return parse(offset->to_string({})); },+ // Passing a CSSKeywordValue with a value other than "normal" as the rangeStart or rangeEnd value to any API+ // defined to accept KeyframeAnimationOptions throws a TypeError.+ [&](GC::Ref<CSS::CSSKeywordValue> const& keyword) -> WebIDL::ExceptionOr<TimelineRangeEdge> {+ if (!keyword->value().equals_ignoring_ascii_case("normal"sv))+ return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Invalid timeline range"_utf16 };+ return parse("normal"_utf16);+ },+ [&](Utf16String const& string) { return parse(string); });+}++// When reading the attribute, the returned value is either a TimelineRangeOffset or the DOMString "normal".+static TimelineRangeBindingValue timeline_range_edge_to_bindings(TimelineRangeEdge const& edge, TimelineRangeEdge const& normal)+{+ if (edge == normal)+ return "normal"_utf16;++ auto px = CSS::CSSUnitValue::create(edge.offset_px, "px"_utf16_fly_string);+ auto percentage = CSS::CSSUnitValue::create(edge.offset_percentage, "percent"_utf16_fly_string);+ GC::Ref<CSS::CSSNumericValue> offset = edge.offset_px == 0 ? GC::Ref<CSS::CSSNumericValue> { percentage } : GC::Ref<CSS::CSSNumericValue> { px };+ if (edge.offset_px != 0 && edge.offset_percentage != 0)+ offset = MUST(CSS::CSSMathSum::create_for_constructor(Vector<CSS::CSSNumberish> { GC::Ref<CSS::CSSNumericValue> { px }, GC::Ref<CSS::CSSNumericValue> { percentage } }));++ Bindings::TimelineRangeOffset range_offset {};+ range_offset.range_name = edge.name == TimelineRangeName::None ? Optional<Utf16String> {} : Utf16String::from_utf8_without_validation(timeline_range_name_to_string(edge.name).bytes());+ range_offset.offset = offset;+ return range_offset;+}++TimelineRangeBindingValue Animation::range_start_for_bindings() const+{+ update_style_if_needed();+ return timeline_range_edge_to_bindings(m_range.start, AnimationAttachmentRange {}.start);+}++TimelineRangeBindingValue Animation::range_end_for_bindings() const+{+ update_style_if_needed();+ return timeline_range_edge_to_bindings(m_range.end, AnimationAttachmentRange {}.end);+}++WebIDL::ExceptionOr<void> Animation::set_range_start_for_bindings(TimelineRangeBindingValue const& value)+{+ auto range = m_range;+ range.start = TRY(parse_timeline_range_edge(HTML::relevant_window(relevant_global_object()).associated_document(), value, TimelineRangeEdgeSide::Start));+ set_range(range);+ return {};+}++WebIDL::ExceptionOr<void> Animation::set_range_end_for_bindings(TimelineRangeBindingValue const& value)+{+ auto range = m_range;+ range.end = TRY(parse_timeline_range_edge(HTML::relevant_window(relevant_global_object()).associated_document(), value, TimelineRangeEdgeSide::End));+ set_range(range);+ return {};+}+void Animation::set_range(AnimationAttachmentRange const& range){if (m_range == range)diff --git a/Libraries/LibWeb/Animations/Animation.h b/Libraries/LibWeb/Animations/Animation.hindex 174a66b0fbc..cb317003f4f 100644--- a/Libraries/LibWeb/Animations/Animation.h+++ b/Libraries/LibWeb/Animations/Animation.h@@ -31,6 +31,16 @@ using AnimationReplaceState = Bindings::AnimationReplaceState;using AnimationPlayState = Bindings::AnimationPlayState;// https://www.w3.org/TR/web-animations-1/#the-animation-interface+// (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString)+using TimelineRangeBindingValue = Variant<Bindings::TimelineRangeOffset, GC::Ref<CSS::CSSNumericValue>, GC::Ref<CSS::CSSKeywordValue>, Utf16String>;++// Parses an attachment range edge script gives, as KeyframeAnimationOptions's rangeStart and rangeEnd take it.+enum class TimelineRangeEdgeSide : u8 {+ Start,+ End,+};+WebIDL::ExceptionOr<TimelineRangeEdge> parse_timeline_range_edge(DOM::Document&, TimelineRangeBindingValue const&, TimelineRangeEdgeSide);+class Animation : public DOM::EventTarget {WEB_WRAPPABLE(Animation, DOM::EventTarget);GC_DECLARE_ALLOCATOR(Animation);@@ -72,6 +82,13 @@ public:// https://drafts.csswg.org/scroll-animations-1/#animation-attachment-rangeAnimationAttachmentRange const& range() const { return m_range; }void set_range(AnimationAttachmentRange const&);++ // https://drafts.csswg.org/web-animations-2/#dom-animation-rangestart+ TimelineRangeBindingValue range_start_for_bindings() const;+ virtual WebIDL::ExceptionOr<void> set_range_start_for_bindings(TimelineRangeBindingValue const&);+ // https://drafts.csswg.org/web-animations-2/#dom-animation-rangeend+ TimelineRangeBindingValue range_end_for_bindings() const;+ virtual WebIDL::ExceptionOr<void> set_range_end_for_bindings(TimelineRangeBindingValue const&);// The start and the end of the attachment range on a progress-based timeline, as timeline times.Optional<AttachmentInterval> attachment_interval() const;diff --git a/Libraries/LibWeb/Animations/Animation.idl b/Libraries/LibWeb/Animations/Animation.idlindex 81326310ea0..130074d97d0 100644--- a/Libraries/LibWeb/Animations/Animation.idl+++ b/Libraries/LibWeb/Animations/Animation.idl@@ -10,6 +10,8 @@ interface Animation : EventTarget {[ImplementedAs=start_time_for_bindings] attribute CSSNumberish? startTime;[ImplementedAs=current_time_for_bindings] attribute CSSNumberish? currentTime;attribute double playbackRate;+ [ImplementedAs=range_start_for_bindings] attribute (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeStart;+ [ImplementedAs=range_end_for_bindings] attribute (TimelineRangeOffset or CSSNumericValue or CSSKeywordValue or DOMString) rangeEnd;[ImplementedAs=play_state_for_bindings] readonly attribute AnimationPlayState playState;readonly attribute AnimationReplaceState replaceState;[ImplementedAs=pending_for_bindings] readonly attribute boolean pending;@@ -30,6 +32,12 @@ interface Animation : EventTarget {[FIXME, CEReactions] undefined commitStyles();};+// https://drafts.csswg.org/web-animations-2/#dictdef-timelinerangeoffset+dictionary TimelineRangeOffset {+ CSSOMString? rangeName;+ CSSNumericValue offset;+};+// https://drafts.csswg.org/web-animations-1/#the-animationplaystate-enumerationenum AnimationPlayState { "idle", "running", "paused", "finished" };diff --git a/Libraries/LibWeb/Animations/TimelineRange.h b/Libraries/LibWeb/Animations/TimelineRange.hindex f5b9cde135d..8559c362bd4 100644--- a/Libraries/LibWeb/Animations/TimelineRange.h+++ b/Libraries/LibWeb/Animations/TimelineRange.h@@ -6,6 +6,7 @@#pragma once+#include <AK/StringView.h>#include <AK/Types.h>#include <LibWeb/Animations/TimeValue.h>@@ -24,6 +25,30 @@ enum class TimelineRangeName : u8 {Scroll,};+// https://drafts.csswg.org/scroll-animations-1/#typedef-timeline-range-name+inline StringView timeline_range_name_to_string(TimelineRangeName name)+{+ switch (name) {+ case TimelineRangeName::None:+ return "normal"sv;+ case TimelineRangeName::Cover:+ return "cover"sv;+ case TimelineRangeName::Contain:+ return "contain"sv;+ case TimelineRangeName::Entry:+ return "entry"sv;+ case TimelineRangeName::Exit:+ return "exit"sv;+ case TimelineRangeName::EntryCrossing:+ return "entry-crossing"sv;+ case TimelineRangeName::ExitCrossing:+ return "exit-crossing"sv;+ case TimelineRangeName::Scroll:+ return "scroll"sv;+ }+ VERIFY_NOT_REACHED();+}+// One edge of an animation attachment range: a point measured from the start of a named timeline range, as a length// plus a percentage of the range.// https://drafts.csswg.org/scroll-animations-1/#animation-range-startdiff --git a/Libraries/LibWeb/CSS/CSSAnimation.cpp b/Libraries/LibWeb/CSS/CSSAnimation.cppindex 14720d0e40b..838396f75ea 100644--- a/Libraries/LibWeb/CSS/CSSAnimation.cpp+++ b/Libraries/LibWeb/CSS/CSSAnimation.cpp@@ -192,7 +192,13 @@ void CSSAnimation::apply_css_properties(AnimationProperties const& animation_proHTML::TemporaryExecutionContext context(relevant_settings_object());set_timeline(materialize_timeline(animation_properties.timeline, timeline_target));}- set_range(animation_properties.range);+ // NB: An edge of the range that script set is no longer the style's to change.+ auto range = animation_properties.range;+ if (m_ignored_css_properties.contains(PropertyID::AnimationRangeStart))+ range.start = this->range().start;+ if (m_ignored_css_properties.contains(PropertyID::AnimationRangeEnd))+ range.end = this->range().end;+ set_range(range);effect.set_specified_iteration_duration(animation_properties.duration);effect.set_specified_start_delay(animation_properties.delay);@@ -307,6 +313,22 @@ WebIDL::ExceptionOr<void> CSSAnimation::reverse()return result;}+// AD-HOC: Like the timeline, a range edge script sets takes precedence over the animation-range-start or+// animation-range-end property from then on, as WPT expects (scroll-animations/css/animation-range-ignored.html).+WebIDL::ExceptionOr<void> CSSAnimation::set_range_start_for_bindings(Animations::TimelineRangeBindingValue const& value)+{+ TRY(Animations::Animation::set_range_start_for_bindings(value));+ m_ignored_css_properties.set(PropertyID::AnimationRangeStart);+ return {};+}++WebIDL::ExceptionOr<void> CSSAnimation::set_range_end_for_bindings(Animations::TimelineRangeBindingValue const& value)+{+ TRY(Animations::Animation::set_range_end_for_bindings(value));+ m_ignored_css_properties.set(PropertyID::AnimationRangeEnd);+ return {};+}+void CSSAnimation::set_timeline_for_bindings(GC::Ptr<Animations::AnimationTimeline> timeline){// AD-HOC: When the timeline of a CSS animation is modified by the author from JS we should no longer apply changesdiff --git a/Libraries/LibWeb/CSS/CSSAnimation.h b/Libraries/LibWeb/CSS/CSSAnimation.hindex a54b2a1d38c..edbe2e0a873 100644--- a/Libraries/LibWeb/CSS/CSSAnimation.h+++ b/Libraries/LibWeb/CSS/CSSAnimation.h@@ -36,6 +36,8 @@ public:EasingFunction const& default_easing() const { return m_default_easing; }virtual void set_timeline_for_bindings(GC::Ptr<Animations::AnimationTimeline> timeline) override;+ virtual WebIDL::ExceptionOr<void> set_range_start_for_bindings(Animations::TimelineRangeBindingValue const&) override;+ virtual WebIDL::ExceptionOr<void> set_range_end_for_bindings(Animations::TimelineRangeBindingValue const&) override;virtual WebIDL::ExceptionOr<void> set_start_time_for_bindings(Animations::NullableCSSNumberish const&) override;virtual WebIDL::ExceptionOr<void> set_current_time_for_bindings(Animations::NullableCSSNumberish const&) override;diff --git a/Libraries/LibWeb/Rust/src/css/style_compute.rs b/Libraries/LibWeb/Rust/src/css/style_compute.rsindex f70784e4415..5d2fbafb006 100644--- a/Libraries/LibWeb/Rust/src/css/style_compute.rs+++ b/Libraries/LibWeb/Rust/src/css/style_compute.rs@@ -4882,6 +4882,43 @@ fn animation_range_edge(value: &StyleValueData, default_percentage: f64) -> (u8,}}+/// One edge of an animation attachment range, as `animation_range_edge` describes it.+#[repr(C)]+pub struct FfiAnimationRangeEdge {+ pub name: u8,+ pub offset_px: f64,+ pub offset_percentage: f64,+}++/// The edge a computed `animation-range-start` or `animation-range-end` value with a single item describes, for a range+/// script sets. Answers false where the value has more than one item.+///+/// # Safety+/// `value` must point at live style value data.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_animation_range_edge(+ value: *const c_void,+ is_end: bool,+ out: &mut FfiAnimationRangeEdge,+) -> bool {+ // SAFETY: Guaranteed by the caller.+ let value = unsafe { &*value.cast::<StyleValueData>() };+ let item = match value {+ StyleValueData::ValueList { values, separator, .. } if *separator == 1 => match values.as_slice() {+ [item] => item.data(),+ _ => return false,+ },+ value => value,+ };+ let (name, offset_px, offset_percentage) = animation_range_edge(item, if is_end { 100.0 } else { 0.0 });+ *out = FfiAnimationRangeEdge {+ name,+ offset_px,+ offset_percentage,+ };+ true+}+/// Which of an element's animation lists a computation belongs to, in the host's own numbering:/// zero for the element itself, and the pseudo-element's value plus one for each pseudo-element.fn animation_slot(pseudo_kind: u8) -> crate::css::style::animations::AnimationSlot {diff --git a/Tests/LibWeb/Text/expected/animate-reads-keyframes-before-range.txt b/Tests/LibWeb/Text/expected/animate-reads-keyframes-before-range.txtnew file mode 100644index 00000000000..382ab8d35e6--- /dev/null+++ b/Tests/LibWeb/Text/expected/animate-reads-keyframes-before-range.txt@@ -0,0 +1 @@+keyframes, TypeErrordiff --git a/Tests/LibWeb/Text/expected/animation-range-scroll-name.txt b/Tests/LibWeb/Text/expected/animation-range-scroll-name.txtnew file mode 100644index 00000000000..6c7075bf6f2--- /dev/null+++ b/Tests/LibWeb/Text/expected/animation-range-scroll-name.txt@@ -0,0 +1,3 @@+supports: true+computed: scroll 10% scroll 90%+rangeStart: scroll 20%diff --git a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/css/animation-range-scroll-timeline.txt b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/css/animation-range-scroll-timeline.txtindex 12ad00ca1eb..525d9213150 100644--- a/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/css/animation-range-scroll-timeline.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/scroll-animations/css/animation-range-scroll-timeline.txt@@ -2,9 +2,8 @@ Harness status: OKFound 4 tests-2 Pass-2 Fail-Fail The animation-range-start CSS property maps to Animation's 'rangeStart' property-Fail The animation-range-end CSS property maps to Animation's 'rangeEnd' property+4 Pass+Pass The animation-range-start CSS property maps to Animation's 'rangeStart' property+Pass The animation-range-end CSS property maps to Animation's 'rangeEnd' propertyPass The auto-aligned start time accounts for the animation-range-start propertyPass The effect duration accounts for the animation-range-* properties\ No newline at end of filediff --git a/Tests/LibWeb/Text/input/animate-reads-keyframes-before-range.html b/Tests/LibWeb/Text/input/animate-reads-keyframes-before-range.htmlnew file mode 100644index 00000000000..52c77ea3435--- /dev/null+++ b/Tests/LibWeb/Text/input/animate-reads-keyframes-before-range.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="include.js"></script>+<div id="target"></div>+<script>+ // animate() processes its keyframes before it parses the range, as Chrome does, so the keyframe getters run+ // before an invalid range throws.+ test(() => {+ const log = [];+ try {+ document.getElementById("target").animate({+ get opacity() {+ log.push("keyframes");+ return [0, 1];+ },+ }, { duration: 1, rangeStart: "bogus" });+ } catch (error) {+ log.push(error.name);+ }+ println(log.join(", "));+ });+</script>diff --git a/Tests/LibWeb/Text/input/animation-range-scroll-name.html b/Tests/LibWeb/Text/input/animation-range-scroll-name.htmlnew file mode 100644index 00000000000..66ae0a685da--- /dev/null+++ b/Tests/LibWeb/Text/input/animation-range-scroll-name.html@@ -0,0 +1,14 @@+<!DOCTYPE html>+<script src="include.js"></script>+<div id="target"></div>+<script>+ // `scroll` is a named timeline range, for animation-range and for the range of an animation from script.+ test(() => {+ const target = document.getElementById("target");+ println(`supports: ${CSS.supports("animation-range", "scroll 10% scroll 90%")}`);+ target.style.animationRange = "scroll 10% scroll 90%";+ println(`computed: ${getComputedStyle(target).animationRange}`);+ const animation = target.animate(null, { duration: 1000, rangeStart: "scroll 20%" });+ println(`rangeStart: ${animation.rangeStart.rangeName} ${animation.rangeStart.offset}`);+ });+</script>