Truly independent web browser
LibWeb: Support the dur and fill attributes of SVG animation elements
Jelle Raaijmakers6692d6ef6d93
diff --git a/Libraries/LibWeb/Rust/src/svg/attribute_parser.rs b/Libraries/LibWeb/Rust/src/svg/attribute_parser.rsindex 15c2845b98c..9b87e945258 100644--- a/Libraries/LibWeb/Rust/src/svg/attribute_parser.rs+++ b/Libraries/LibWeb/Rust/src/svg/attribute_parser.rs@@ -249,6 +249,89 @@ fn parse_view_box(input: Input<'_>) -> Option<[f64; 4]> {parser.done().then_some(values)}+fn is_digits(value: &str) -> bool {+ !value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())+}++// https://svgwg.org/specs/animations/#ClockValueSyntax+// Timecount ::= DIGIT++// Fraction ::= DIGIT++// NB: This parses a Timecount ("." Fraction)?, which also matches a Seconds ("." Fraction)?.+fn parse_digits_with_optional_fraction(value: &str) -> Option<f64> {+ let (integer, fraction) = value.split_once('.').unwrap_or((value, "0"));+ if !is_digits(integer) || !is_digits(fraction) {+ return None;+ }+ value.parse().ok()+}++// https://svgwg.org/specs/animations/#ClockValueSyntax+// Minutes ::= 2DIGIT; range from 00 to 59+// Seconds ::= 2DIGIT; range from 00 to 59+fn parse_minutes_or_seconds(value: &str) -> Option<f64> {+ if value.len() != 2 || !is_digits(value) {+ return None;+ }+ let value = value.parse().ok()?;+ (value < 60.0).then_some(value)+}++// https://svgwg.org/specs/animations/#ClockValueSyntax+// Seconds ("." Fraction)?+fn parse_seconds_with_optional_fraction(value: &str) -> Option<f64> {+ let (seconds, _) = value.split_once('.').unwrap_or((value, ""));+ parse_minutes_or_seconds(seconds)?;+ parse_digits_with_optional_fraction(value)+}++// https://svgwg.org/specs/animations/#ClockValueSyntax+fn parse_clock_value_in_milliseconds(input: Input<'_>) -> Option<f64> {+ // No embedded white space is allowed in clock values, although leading and trailing white space characters will+ // be ignored.+ let mut parser = Parser::new(input);+ parser.parse_whitespace();+ let clock_value = String::from_utf16(&token(&mut parser)).ok()?;+ parser.parse_whitespace();+ if !parser.done() {+ return None;+ }++ let fields = clock_value.split(':').collect::<Vec<_>>();+ let seconds = match fields.as_slice() {+ // Full-clock-val ::= Hours ":" Minutes ":" Seconds ("." Fraction)?+ // Hours ::= DIGIT+; any positive number+ [hours, minutes, seconds] => {+ if !is_digits(hours) {+ return None;+ }+ hours.parse::<f64>().ok()? * 3600.0+ + parse_minutes_or_seconds(minutes)? * 60.0+ + parse_seconds_with_optional_fraction(seconds)?+ }+ // Partial-clock-val ::= Minutes ":" Seconds ("." Fraction)?+ [minutes, seconds] => {+ parse_minutes_or_seconds(minutes)? * 60.0 + parse_seconds_with_optional_fraction(seconds)?+ }+ // Timecount-val ::= Timecount ("." Fraction)? (Metric)?+ // Metric ::= "h" | "min" | "s" | "ms"+ // For Timecount values, the default metric suffix is "s" (for seconds).+ [timecount] => {+ let (timecount, milliseconds_per_unit) =+ [("h", 3_600_000.0), ("min", 60_000.0), ("ms", 1.0), ("s", 1000.0)]+ .into_iter()+ .find_map(|(metric, milliseconds_per_unit)| {+ timecount+ .strip_suffix(metric)+ .map(|timecount| (timecount, milliseconds_per_unit))+ })+ .unwrap_or((timecount, 1000.0));+ return Some(parse_digits_with_optional_fraction(timecount)? * milliseconds_per_unit);+ }+ _ => return None,+ };+ Some(seconds * 1000.0)+}+fn is_whitespace(unit: u16) -> bool {matches!(unit, 0x09 | 0x0a | 0x0c | 0x0d | 0x20)}@@ -419,6 +502,17 @@ pub unsafe extern "C" fn rust_parse_svg_view_box(true}+/// # Safety+/// `input` must satisfy [`FfiSvgInput::input`]'s requirements and `value` must be writable.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn rust_parse_svg_clock_value_in_milliseconds(input: FfiSvgInput, value: *mut f64) -> bool {+ let Some(parsed_value) = with_input(input, parse_clock_value_in_milliseconds).flatten() else {+ return false;+ };+ unsafe { value.write(parsed_value) };+ true+}+#[cfg(test)]mod tests {use super::*;@@ -479,6 +573,35 @@ mod tests {assert_eq!(parse_transform(input("translate()")), None);}+ #[test]+ fn parses_clock_values() {+ let milliseconds = |source| parse_clock_value_in_milliseconds(input(source));+ assert_eq!(milliseconds("02:30:03"), Some(9_003_000.0));+ assert_eq!(milliseconds("50:00:10.25"), Some(180_010_250.0));+ assert_eq!(milliseconds("02:33"), Some(153_000.0));+ assert_eq!(milliseconds("00:10.5"), Some(10_500.0));+ assert_eq!(milliseconds("3.2h"), Some(11_520_000.0));+ assert_eq!(milliseconds("45min"), Some(2_700_000.0));+ assert_eq!(milliseconds("30s"), Some(30_000.0));+ assert_eq!(milliseconds("5ms"), Some(5.0));+ assert_eq!(milliseconds("12.467"), Some(12_467.0));+ assert_eq!(milliseconds("00.5s"), Some(500.0));+ assert_eq!(milliseconds("00:00.005"), Some(5.0));+ assert_eq!(milliseconds(" 2s\t"), Some(2000.0));++ assert_eq!(milliseconds(""), None);+ assert_eq!(milliseconds("2 s"), None);+ assert_eq!(milliseconds(".5s"), None);+ assert_eq!(milliseconds("1."), None);+ assert_eq!(milliseconds("-1s"), None);+ assert_eq!(milliseconds("1sec"), None);+ assert_eq!(milliseconds("indefinite"), None);+ assert_eq!(milliseconds("2:30"), None);+ assert_eq!(milliseconds("00:60"), None);+ assert_eq!(milliseconds("1:60:00"), None);+ assert_eq!(milliseconds("00:00:005"), None);+ }+#[test]fn parses_view_box() {assert_eq!(parse_view_box(input(" 1, 2 3 4 ")), Some([1.0, 2.0, 3.0, 4.0]));diff --git a/Libraries/LibWeb/SVG/AttributeNames.h b/Libraries/LibWeb/SVG/AttributeNames.hindex 2c8f876eeba..3beeeb3241a 100644--- a/Libraries/LibWeb/SVG/AttributeNames.h+++ b/Libraries/LibWeb/SVG/AttributeNames.h@@ -27,6 +27,7 @@ namespace Web::SVG::AttributeNames {__ENUMERATE_SVG_ATTRIBUTE(cy, "cy") \__ENUMERATE_SVG_ATTRIBUTE(d, "d") \__ENUMERATE_SVG_ATTRIBUTE(diffuseConstant, "diffuseConstant") \+ __ENUMERATE_SVG_ATTRIBUTE(dur, "dur") \__ENUMERATE_SVG_ATTRIBUTE(dx, "dx") \__ENUMERATE_SVG_ATTRIBUTE(dy, "dy") \__ENUMERATE_SVG_ATTRIBUTE(edgeMode, "edgeMode") \diff --git a/Libraries/LibWeb/SVG/AttributeParsing.cpp b/Libraries/LibWeb/SVG/AttributeParsing.cppindex 28deddd4e37..ef4a1f2c90b 100644--- a/Libraries/LibWeb/SVG/AttributeParsing.cpp+++ b/Libraries/LibWeb/SVG/AttributeParsing.cpp@@ -158,4 +158,12 @@ Optional<ViewBox> parse_viewbox(Utf16View input)return ViewBox { min_x, min_y, width, height };}+Optional<double> parse_clock_value_in_milliseconds(Utf16View input)+{+ double value;+ if (!RustFFI::rust_parse_svg_clock_value_in_milliseconds(ffi_svg_input(input), &value))+ return {};+ return value;+}+}diff --git a/Libraries/LibWeb/SVG/AttributeParsing.h b/Libraries/LibWeb/SVG/AttributeParsing.hindex 5faa77d20a2..6839df6aaf1 100644--- a/Libraries/LibWeb/SVG/AttributeParsing.h+++ b/Libraries/LibWeb/SVG/AttributeParsing.h@@ -130,5 +130,6 @@ WEB_API Optional<SVGUnits> parse_units(Utf16View);WEB_API Vector<float> parse_table_values(Utf16View);WEB_API Optional<SpreadMethod> parse_spread_method(Utf16View);WEB_API Optional<ViewBox> parse_viewbox(Utf16View);+WEB_API Optional<double> parse_clock_value_in_milliseconds(Utf16View);}diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp b/Libraries/LibWeb/SVG/SVGAnimationElement.cppindex f36de2cf53c..51cca082f11 100644--- a/Libraries/LibWeb/SVG/SVGAnimationElement.cpp+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.cpp@@ -10,10 +10,13 @@#include <LibWeb/Animations/DocumentTimeline.h>#include <LibWeb/DOM/Document.h>#include <LibWeb/HTML/EventNames.h>+#include <LibWeb/HTML/Scripting/Environments.h>#include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>#include <LibWeb/Layout/Node.h>#include <LibWeb/SVG/AttributeNames.h>+#include <LibWeb/SVG/AttributeParsing.h>#include <LibWeb/SVG/SMILAnimation.h>+#include <LibWeb/WebIDL/DOMException.h>namespace Web::SVG {@@ -49,7 +52,7 @@ void SVGAnimationElement::moved_from(IsSubtreeRoot is_subtree_root, GC::Ptr<Nodevoid SVGAnimationElement::attribute_changed(Utf16FlyString const& name, Optional<Utf16String> const& old_value, Optional<Utf16String> const& value, Optional<Utf16FlyString> const& namespace_){Base::attribute_changed(name, old_value, value, namespace_);- if (name == AttributeNames::attributeName && !namespace_.has_value())+ if (first_is_one_of(name, AttributeNames::attributeName, AttributeNames::dur, AttributeNames::fill) && !namespace_.has_value())update_animation();}@@ -82,6 +85,37 @@ Optional<CSS::PropertyID> SVGAnimationElement::target_property() constreturn property_id;}+// https://svgwg.org/specs/animations/#DurAttribute+double SVGAnimationElement::simple_duration() const+{+ // If the animation does not have a ‘dur’ attribute, the simple duration is indefinite.+ auto dur = get_attribute(AttributeNames::dur);+ if (!dur.has_value())+ return AK::Infinity<double>;++ // Clock-value+ // Specifies the length of the simple duration in presentation time. Value must be greater than 0.+ if (auto duration = parse_clock_value_in_milliseconds(*dur); duration.has_value() && *duration > 0)+ return *duration;++ // NB: An "indefinite" value specifies an indefinite simple duration, SVG ignores a "media" value, and SMIL+ // Animation ignores a value with any error in its syntax. Each leaves the simple duration indefinite.+ return AK::Infinity<double>;+}++// https://svgwg.org/specs/animations/#FillAttribute+Bindings::FillMode SVGAnimationElement::fill_mode() const+{+ // freeze+ // The animation effect F(t) is defined to freeze the effect value at the last value of the active duration.+ if (auto fill = get_attribute(AttributeNames::fill); fill.has_value() && *fill == "freeze"sv)+ return Bindings::FillMode::Forwards;++ // remove+ // The animation effect is removed (no longer applied) when the active duration of the animation is over.+ return Bindings::FillMode::None;+}+void SVGAnimationElement::update_animation(){if (m_animation) {@@ -101,13 +135,15 @@ void SVGAnimationElement::update_animation()if (keyframes.is_empty())return;- // FIXME: Resolve the interval to play from the begin, dur and end attributes, and the other timing attributes.+ // FIXME: Resolve the interval to play from the begin and end attributes, and the other timing attributes.// FIXME: A running animation requests a rendering update on every frame, even when its output cannot change, as- // with this indefinite one. This keeps the rendering loop running for as long as the element is connected.- auto effect = MUST(Animations::KeyframeEffect::create_from_processed_keyframes(target, move(keyframes), AK::Infinity<double>));+ // with an indefinite one. This keeps the rendering loop running for as long as such an animation is active.+ auto effect = MUST(Animations::KeyframeEffect::create_from_processed_keyframes(target, move(keyframes), simple_duration()));+ effect->set_fill_mode(fill_mode());- // AD-HOC: Animations begin once their element is connected, on the document's default timeline. They should- // begin at the document begin of their SVG document fragment, which is the time of its load event.+ // AD-HOC: Animations begin once their element is connected, and begin again whenever an attribute they depend on+ // changes, on the document's default timeline. They should begin at the document begin of their SVG+ // document fragment, which is the time of its load event.auto animation = SMILAnimation::create(*this);animation->set_timeline(document().timeline());animation->set_effect(effect);@@ -152,4 +188,16 @@ GC::Ptr<WebIDL::CallbackType> SVGAnimationElement::onrepeat()return event_handler_attribute(HTML::EventNames::repeatEvent);}+// https://svgwg.org/specs/animations/#__svg__SVGAnimationElement__getSimpleDuration+WebIDL::ExceptionOr<float> SVGAnimationElement::get_simple_duration()+{+ // Returns the number of seconds for the simple duration for this animation. If the simple duration is undefined+ // (e.g., the end time is indefinite), then an exception is raised.+ // NB: The exception is a DOMException with code NOT_SUPPORTED_ERR.+ auto duration = simple_duration();+ if (isinf(duration))+ return WebIDL::NotSupportedError::create(HTML::relevant_realm(*this), "The simple duration is indefinite"_utf16);+ return static_cast<float>(duration / 1000.);+}+}diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.h b/Libraries/LibWeb/SVG/SVGAnimationElement.hindex f5cbc4c708e..6e1624ddbab 100644--- a/Libraries/LibWeb/SVG/SVGAnimationElement.h+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.h@@ -29,6 +29,8 @@ public:void set_onrepeat(GC::Ptr<WebIDL::CallbackType>);GC::Ptr<WebIDL::CallbackType> onrepeat();+ WebIDL::ExceptionOr<float> get_simple_duration();+protected:SVGAnimationElement(DOM::Document&, DOM::QualifiedName);@@ -44,6 +46,8 @@ protected:private:Optional<CSS::PropertyID> target_property() const;+ double simple_duration() const;+ Bindings::FillMode fill_mode() const;GC::Ptr<SMILAnimation> m_animation;};diff --git a/Libraries/LibWeb/SVG/SVGAnimationElement.idl b/Libraries/LibWeb/SVG/SVGAnimationElement.idlindex 5139a8dcf7c..b3eac84a5b7 100644--- a/Libraries/LibWeb/SVG/SVGAnimationElement.idl+++ b/Libraries/LibWeb/SVG/SVGAnimationElement.idl@@ -10,7 +10,7 @@ interface SVGAnimationElement : SVGElement {[FIXME] float getStartTime();[FIXME] float getCurrentTime();- [FIXME] float getSimpleDuration();+ float getSimpleDuration();[FIXME] undefined beginElement();[FIXME] undefined beginElementAt(float offset);diff --git a/Tests/LibWeb/Text/expected/SVG/animation-element-get-simple-duration.txt b/Tests/LibWeb/Text/expected/SVG/animation-element-get-simple-duration.txtnew file mode 100644index 00000000000..77d46348ea9--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/animation-element-get-simple-duration.txt@@ -0,0 +1,6 @@+clock value: 62.5+milliseconds: 0.25+no dur: NotSupportedError+indefinite: NotSupportedError+zero: NotSupportedError+invalid: NotSupportedErrordiff --git a/Tests/LibWeb/Text/expected/SVG/set-element-dur-and-fill.txt b/Tests/LibWeb/Text/expected/SVG/set-element-dur-and-fill.txtnew file mode 100644index 00000000000..97b6693e9eb--- /dev/null+++ b/Tests/LibWeb/Text/expected/SVG/set-element-dur-and-fill.txt@@ -0,0 +1,6 @@+removed: rgb(0, 128, 0)+frozen: rgb(0, 128, 0)+active: rgb(0, 128, 0)+zero: rgb(0, 128, 0)+invalid: rgb(0, 128, 0)+indefinite: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/wpt-import/svg/idlharness.window.txt b/Tests/LibWeb/Text/expected/wpt-import/svg/idlharness.window.txtindex 76cec12be4b..249fd41587f 100644--- a/Tests/LibWeb/Text/expected/wpt-import/svg/idlharness.window.txt+++ b/Tests/LibWeb/Text/expected/wpt-import/svg/idlharness.window.txt@@ -2,8 +2,8 @@ Harness status: OKFound 1780 tests-1126 Pass-654 Fail+1128 Pass+652 FailPass idl_test setupPass idl_test validationPass Partial interface Document: original interface defined@@ -1649,7 +1649,7 @@ Pass SVGAnimationElement interface: attribute onendPass SVGAnimationElement interface: attribute onrepeatFail SVGAnimationElement interface: operation getStartTime()Fail SVGAnimationElement interface: operation getCurrentTime()-Fail SVGAnimationElement interface: operation getSimpleDuration()+Pass SVGAnimationElement interface: operation getSimpleDuration()Fail SVGAnimationElement interface: operation beginElement()Fail SVGAnimationElement interface: operation beginElementAt(float)Fail SVGAnimationElement interface: operation endElement()@@ -1698,7 +1698,7 @@ Pass SVGAnimationElement interface: objects.set must inherit property "onend" wiPass SVGAnimationElement interface: objects.set must inherit property "onrepeat" with the proper typeFail SVGAnimationElement interface: objects.set must inherit property "getStartTime()" with the proper typeFail SVGAnimationElement interface: objects.set must inherit property "getCurrentTime()" with the proper type-Fail SVGAnimationElement interface: objects.set must inherit property "getSimpleDuration()" with the proper type+Pass SVGAnimationElement interface: objects.set must inherit property "getSimpleDuration()" with the proper typeFail SVGAnimationElement interface: objects.set must inherit property "beginElement()" with the proper typeFail SVGAnimationElement interface: objects.set must inherit property "beginElementAt(float)" with the proper typeFail SVGAnimationElement interface: calling beginElementAt(float) on objects.set with too few arguments must throw TypeErrordiff --git a/Tests/LibWeb/Text/input/SVG/animation-element-get-simple-duration.html b/Tests/LibWeb/Text/input/SVG/animation-element-get-simple-duration.htmlnew file mode 100644index 00000000000..0658c64ad54--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/animation-element-get-simple-duration.html@@ -0,0 +1,23 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg>+ <rect width="10" height="10">+ <set data-label="clock value" attributeName="fill" to="green" dur="01:02.5"/>+ <set data-label="milliseconds" attributeName="fill" to="green" dur="250ms"/>+ <set data-label="no dur" attributeName="fill" to="green"/>+ <set data-label="indefinite" attributeName="fill" to="green" dur="indefinite"/>+ <set data-label="zero" attributeName="fill" to="green" dur="0s"/>+ <set data-label="invalid" attributeName="fill" to="green" dur="1 s"/>+ </rect>+</svg>+<script>+ test(() => {+ for (const element of document.querySelectorAll("set")) {+ try {+ println(`${element.getAttribute("data-label")}: ${element.getSimpleDuration()}`);+ } catch (error) {+ println(`${element.getAttribute("data-label")}: ${error.name}`);+ }+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/SVG/set-element-dur-and-fill.html b/Tests/LibWeb/Text/input/SVG/set-element-dur-and-fill.htmlnew file mode 100644index 00000000000..a4d1b8616f2--- /dev/null+++ b/Tests/LibWeb/Text/input/SVG/set-element-dur-and-fill.html@@ -0,0 +1,34 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<svg>+ <rect id="removed" width="10" height="10" fill="green">+ <set attributeName="fill" to="red" dur="1ms"/>+ </rect>+ <rect id="frozen" width="10" height="10" fill="red">+ <set attributeName="fill" to="green" dur="1ms" fill="freeze"/>+ </rect>+ <rect id="active" width="10" height="10" fill="red">+ <set attributeName="fill" to="green" dur="01:00:00"/>+ </rect>+ <rect id="zero" width="10" height="10" fill="red">+ <set attributeName="fill" to="green" dur="0s"/>+ </rect>+ <rect id="invalid" width="10" height="10" fill="red">+ <set attributeName="fill" to="green" dur="1 s"/>+ </rect>+ <rect id="indefinite" width="10" height="10" fill="red">+ <set attributeName="fill" to="green" dur="indefinite"/>+ </rect>+</svg>+<script>+ asyncTest(async done => {+ const nextFrame = () => new Promise(requestAnimationFrame);+ await nextFrame();+ await new Promise(resolve => setTimeout(resolve, 20));+ await nextFrame();+ await nextFrame();+ for (const id of ["removed", "frozen", "active", "zero", "invalid", "indefinite"])+ println(`${id}: ${getComputedStyle(document.getElementById(id)).fill}`);+ done();+ });+</script>