Skip to main content

script/dom/animations/
keyframeeffect.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::ffi::CString;
6use std::ops::ControlFlow;
7use std::ptr::{self, NonNull};
8use std::sync::LazyLock;
9
10use cssparser::{Parser, ParserInput};
11use dom_struct::dom_struct;
12use js::context::JSContext;
13use js::conversions::{
14    ConversionResult, FromJSValConvertible, ToJSValConvertible, jsstr_to_string,
15};
16use js::gc::{HandleValue, RootedVec};
17use js::jsapi::{HandleId, Heap, JS_GetPropertyById, JSITER_OWNONLY, JSObject, JSPROP_ENUMERATE};
18use js::jsval::{ObjectValue, UndefinedValue};
19use js::rust::wrappers2::{GetPropertyKeys, JS_DefineProperty, JS_IdToValue, JS_NewObject};
20use js::rust::{
21    ForOfIterationFailure, HandleObject, IdVector, IntoHandle, IntoMutableHandle, for_of,
22};
23use rustc_hash::FxHashMap;
24use script_bindings::cell::DomRefCell;
25use script_bindings::codegen::GenericBindings::KeyframeEffectBinding::{
26    BaseKeyframe, CompositeOperationOrAuto,
27};
28use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
29use script_bindings::codegen::GenericUnionTypes::UnrestrictedDoubleOrKeyframeEffectOptions;
30use script_bindings::conversions::StringificationBehavior;
31use script_bindings::error::{Error, Fallible};
32use script_bindings::inheritance::Castable;
33use script_bindings::num::Finite;
34use script_bindings::reflector::reflect_dom_object_with_proto;
35use script_bindings::root::DomRoot;
36use script_bindings::str::DOMString;
37use style::parser::ParserContext;
38use style::properties::generated::PropertyDeclaration;
39use style::properties::{
40    Importance, LonghandId, NonCustomPropertyId, PropertyDeclarationBlock, PropertyId,
41    SourcePropertyDeclaration,
42};
43use style::stylesheets::CssRuleType;
44use style_traits::{CssWriter, ParsingMode, ToCss};
45
46use crate::css::css::parser_context_for_document;
47use crate::dom::Document;
48use crate::dom::animationeffect::AnimationEffect;
49use crate::dom::bindings::codegen::Bindings::KeyframeEffectBinding::{
50    BaseComputedKeyframe, KeyframeEffectMethods,
51};
52use crate::dom::bindings::root::MutNullableDom;
53use crate::dom::element::Element;
54use crate::dom::window::Window;
55
56/// <https://drafts.csswg.org/web-animations-1/#keyframeeffect>
57#[dom_struct]
58pub(crate) struct KeyframeEffect {
59    animationeffect: AnimationEffect,
60
61    /// <https://drafts.csswg.org/web-animations-1/#effect-target-target-element>
62    // FIXME: Store a target pseudo-selector
63    // to fully match the concept of the effect target
64    //
65    // https://drafts.csswg.org/web-animations-1/#effect-target-target-pseudo-selector
66    // https://drafts.csswg.org/web-animations-1/#keyframe-effect-effect-target.
67    target_element: MutNullableDom<Element>,
68
69    /// <https://drafts.csswg.org/web-animations-1/#keyframe>
70    keyframes: DomRefCell<Vec<Keyframe>>,
71}
72
73impl KeyframeEffect {
74    pub(crate) fn new_inherited(window: &Window) -> Self {
75        Self {
76            animationeffect: AnimationEffect::new_inherited(window),
77            target_element: Default::default(),
78            keyframes: Default::default(),
79        }
80    }
81
82    fn new_with_proto(
83        cx: &mut JSContext,
84        window: &Window,
85        proto: Option<HandleObject>,
86    ) -> DomRoot<Self> {
87        reflect_dom_object_with_proto(cx, Box::new(Self::new_inherited(window)), window, proto)
88    }
89
90    pub(crate) fn new(cx: &mut JSContext, window: &Window) -> DomRoot<Self> {
91        Self::new_with_proto(cx, window, None)
92    }
93}
94
95impl KeyframeEffectMethods<crate::DomTypeHolder> for KeyframeEffect {
96    /// <https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-keyframeeffect>
97    fn Constructor(
98        cx: &mut JSContext,
99        window: &Window,
100        _: Option<HandleObject>,
101        target: Option<&Element>,
102        keyframes: *mut JSObject,
103        _options: UnrestrictedDoubleOrKeyframeEffectOptions,
104    ) -> DomRoot<KeyframeEffect> {
105        // Step 1. Create a new KeyframeEffect object, effect.
106        let effect = KeyframeEffect::new(cx, window);
107
108        // Step 2. Set the target element of effect to target.
109        effect.target_element.set(target);
110
111        // TODO: Step 3. Set the target pseudo-selector to the result corresponding to
112        // the first matching condition below:
113
114        // TODO: Step 4. Let timing input be the result corresponding to the first matching
115        // condition below:
116
117        // Step 5. Call the procedure to update the timing properties of an animation effect of
118        // effect from timing input.
119        // If that procedure causes an exception to be thrown, propagate the exception and abort this procedure.
120
121        // TODO: Step 6. If options is a KeyframeEffectOptions object, assign the composite property of effect
122        // to the corresponding value from options.
123        //
124        // When assigning this property, the error-handling defined for the corresponding setter on the
125        //  KeyframeEffect interface is applied. If the setter requires an exception to be thrown for the value
126        //  specified by options, this procedure must throw the same exception and abort all further steps.
127
128        // Step 7. Initialize the set of keyframes by performing the procedure defined for setKeyframes()
129        // passing keyframes as the input.
130        effect.SetKeyframes(cx, keyframes);
131
132        effect
133    }
134
135    /// <https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-getkeyframes>
136    #[expect(unsafe_code)]
137    fn GetKeyframes(
138        &self,
139        cx: &mut JSContext,
140        result: &mut RootedVec<'_, Box<Heap<*mut JSObject>>>,
141    ) -> Fallible<()> {
142        let mut layout = self.upcast::<AnimationEffect>().window().layout_mut();
143        let stylist = layout.stylist_mut();
144
145        // Step 1. Let result be an empty sequence of objects.
146        debug_assert!(result.is_empty());
147
148        // Step 2. Let keyframes be one of the following:
149        // If this keyframe effect is associated with a CSSAnimation, and its keyframes have not been replaced
150        // by a successful call to setKeyframes(),
151        // the computed keyframes for this keyframe effect.
152        // Otherwise,
153        // the result of applying the procedure compute missing keyframe offsets to the keyframes for this keyframe effect.
154        // TODO: We don't compute missing keyframe offsets yet. But that will likely happen in stylo, not here.
155        let keyframes = self.keyframes.borrow();
156
157        // Step 3. For each keyframe in keyframes perform the following steps:
158        for keyframe in keyframes.iter() {
159            // Step 3.1 Initialize a dictionary object, output keyframe, using the following definition:
160            // TODO Step 3.2 Set the offset, computedOffset, easing, and composite members of output keyframe
161            // to the respective keyframe offset, computed keyframe offset, keyframe-specific easing function,
162            // and keyframe-specific composite operation values of keyframe.
163            let base_keyframe = BaseComputedKeyframe {
164                composite: keyframe.composite,
165                offset: keyframe.offset,
166                // FIXME: We don't post-process the offset of keyframes to find suitable offset values for null
167                // keyframe offsets yet, so we just use the offset as-is.
168                computedOffset: keyframe.offset,
169                easing: keyframe.easing_function.clone(),
170            };
171            rooted!(&in(cx) let mut output_keyframe = unsafe { JS_NewObject(cx, ptr::null()) });
172            base_keyframe.to_jsobject(cx, output_keyframe.handle_mut());
173
174            // Step 3.3 For each animation property-value pair declaration in keyframe, perform the following steps:
175            for property_value_pair in &keyframe.declarations {
176                debug_assert!(property_value_pair.property_id.is_animatable());
177
178                // Step 3.3.1 Let property name be the result of applying the animation property name to IDL attribute
179                // name algorithm to the property name of declaration.
180                let mut property_name = String::new();
181                let mut writer = CssWriter::new(&mut property_name);
182                if property_value_pair.property_id.to_css(&mut writer).is_err() {
183                    continue;
184                }
185                let property_name = animation_property_name_to_idl_attribute_name(&property_name);
186
187                // Step 3.3.2 Let IDL value be the result of serializing the property value of declaration
188                // by passing declaration to the algorithm to serialize a CSS value [CSSOM].
189                let mut value_string = String::new();
190                if property_value_pair
191                    .block
192                    .single_value_to_css(
193                        &property_value_pair.property_id,
194                        &mut value_string,
195                        None,
196                        stylist,
197                    )
198                    .is_err()
199                {
200                    continue;
201                }
202
203                // Step 3.3.3 Let value be the result of converting IDL value to an ECMAScript String value.
204                rooted!(&in(cx) let mut value = UndefinedValue());
205                value_string.to_jsval(cx, value.handle_mut());
206
207                // Step 3.3.4 Call the [[DefineOwnProperty]] internal method on output keyframe with property
208                // name property name, Property Descriptor { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]:
209                // true, [[Value]]: value } and Boolean flag false.
210                let Ok(property_name) = CString::new(property_name) else {
211                    continue;
212                };
213
214                let success = unsafe {
215                    JS_DefineProperty(
216                        cx,
217                        output_keyframe.handle(),
218                        property_name.as_ptr(),
219                        value.handle(),
220                        JSPROP_ENUMERATE as u32,
221                    )
222                };
223                if !success {
224                    if cfg!(debug_assertions) {
225                        unreachable!("Setting a property on output_keyframe should never fail");
226                    }
227                    return Err(Error::Operation(None));
228                }
229            }
230
231            // Step 3.4 Append output keyframe to result.
232            result.push(Heap::boxed(output_keyframe.get()))
233        }
234
235        // Step 4. Return result.
236        Ok(())
237    }
238
239    /// <https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-setkeyframes>
240    fn SetKeyframes(&self, cx: &mut JSContext, keyframes: *mut JSObject) {
241        // > This effect’s set of keyframes is replaced with the result of performing the procedure to
242        // > process a keyframes argument. If that procedure throws an exception, this effect’s
243        // > keyframes are not modified.
244        let document = self.upcast::<AnimationEffect>().window().Document();
245        let Ok(keyframes) = process_a_keyframes_argument(cx, &document, keyframes) else {
246            return;
247        };
248        *self.keyframes.safe_borrow_mut(cx.no_gc()) = keyframes;
249    }
250}
251
252/// <https://drafts.csswg.org/web-animations-1/#process-a-keyframes-argument>
253fn process_a_keyframes_argument(
254    cx: &mut JSContext,
255    document: &Document,
256    keyframes: *mut JSObject,
257) -> Fallible<Vec<Keyframe>> {
258    // Step 1. If object is null, return an empty sequence of keyframes.
259    if keyframes.is_null() {
260        return Ok(Vec::new());
261    }
262
263    // Step 2. Let processed keyframes be an empty sequence of keyframes.
264
265    // Step 3. Let method be the result of GetMethod(object, @@iterator).
266    // Step 4. Check the completion record of method.
267    // Step 5. Perform the steps corresponding to the first matching condition below:
268    rooted!(&in(cx) let iterable = ObjectValue(keyframes));
269    let mut keyframes = Vec::new();
270    let result = for_of(cx, iterable.handle(), |cx, iterator_element| {
271        // Step 5.3.6 If Type(nextItem) is not Undefined, Null or Object, then throw a TypeError
272        // and abort these steps.
273        //
274        // Note: nextItem is later passed to "process a keyframe like object" which cannot handle undefined
275        // or null values. This seems to be a bug in the specification which is tracked by
276        // https://github.com/w3c/csswg-drafts/issues/14113
277        if !iterator_element.is_object() {
278            return Err(ForOfIterationFailure::Other(Error::Type(
279                c"Keyframe must be an object".to_owned(),
280            )));
281        }
282
283        // Step 5.3.7 Append to processed keyframes the result of running the procedure to process a
284        // keyframe-like object passing nextItem as the keyframe input with the allow lists flag set to false.
285        keyframes.push(keyframe_from_value(cx, document, iterator_element)?);
286
287        Ok(ControlFlow::Continue(()))
288    });
289    match result {
290        Ok(()) => Ok(keyframes),
291        Err(ForOfIterationFailure::ValueIsNotIterable) => {
292            // TODO: Step 5, Otherwise:
293            Err(Error::Operation(None))
294        },
295        Err(ForOfIterationFailure::JSFailed) => Err(Error::JSFailed),
296        Err(ForOfIterationFailure::Other(error)) => Err(error),
297    }
298}
299
300/// <https://drafts.csswg.org/web-animations-1/#keyframe>
301#[derive(JSTraceable, MallocSizeOf)]
302struct Keyframe {
303    offset: Option<Finite<f64>>,
304    easing_function: DOMString,
305    composite: CompositeOperationOrAuto,
306    declarations: Vec<KeyframePropertyDeclaration>,
307}
308
309#[derive(JSTraceable, MallocSizeOf)]
310struct KeyframePropertyDeclaration {
311    #[no_trace]
312    property_id: PropertyId,
313    /// The block is known to only contain declarations for `property_id`. There might
314    /// be more than one value if `property_id` is a shorthand.
315    #[no_trace]
316    block: PropertyDeclarationBlock,
317}
318
319/// Step 5 (for iterable keyframes) of <https://drafts.csswg.org/web-animations-1/#process-a-keyframes-argument>.
320fn keyframe_from_value(
321    cx: &mut JSContext,
322    document: &Document,
323    value: HandleValue<'_>,
324) -> Fallible<Keyframe> {
325    // Step 3.4 Let nextItem be IteratorValue(next).
326    // NOTE: This is "current_value"
327    // Step 3.5 Check the completion record of nextItem.
328
329    // Step 3.6 If Type(nextItem) is not Undefined, Null or Object,
330    // then throw a TypeError and abort these steps.
331    if !value.is_null_or_undefined() && !value.is_object() {
332        return Err(Error::Type(c"Invalid keyframe value".to_owned()));
333    }
334
335    // Step 3.7 Append to processed keyframes the result of running the procedure to process
336    // a keyframe-like object passing nextItem as the keyframe input with the allow lists
337    // flag set to false.
338    process_a_keyframe_like_object(cx, document, value)
339}
340
341/// <https://drafts.csswg.org/web-animations-1/#process-a-keyframe-like-object>
342fn process_a_keyframe_like_object(
343    cx: &mut JSContext,
344    document: &Document,
345    value: HandleValue,
346) -> Fallible<Keyframe> {
347    // Step 1. Run the procedure to convert an ECMAScript value to a dictionary type [WEBIDL] with keyframe input
348    // as the ECMAScript value, and the dictionary type depending on the value of the allow lists flag as follows:
349    // If allow lists is true,
350    // Use the following dictionary type:
351    //
352    // dictionary BasePropertyIndexedKeyframe {
353    //   (double? or sequence<double?>)                         offset = [];
354    //   (DOMString or sequence<DOMString>)                     easing = [];
355    //   (CompositeOperationOrAuto or sequence<CompositeOperationOrAuto>) composite = [];
356    // };
357    //
358    // Otherwise,
359    //     Use the following dictionary type:
360    //
361    //     dictionary BaseKeyframe {
362    //       double?                  offset = null;
363    //       DOMString                easing = "linear";
364    //       CompositeOperationOrAuto composite = "auto";
365    //     };
366    //
367    // Store the result of this procedure as keyframe output.
368    //
369    // Note: 'allow lists' is currently never true.
370    // Use the following dictionary type:
371    let Ok(keyframe_output) = BaseKeyframe::from_jsval(cx, value, ()) else {
372        return Err(Error::JSFailed);
373    };
374    let ConversionResult::Success(keyframe_output) = keyframe_output else {
375        return Err(Error::Operation(None));
376    };
377
378    // From Step 2 onwards our implementation diverges from the specification. The spec
379    // wants us to build a list of animatable CSS properties and a list of properties on
380    // the object, then compute the union between the two.
381    //
382    // Instead, we iterate over all properties on the object and then check if they correspond
383    // to an animatable property.
384    let urlextradata = document.url().into_url().into();
385    let parser_context = parser_context_for_document(
386        document,
387        CssRuleType::Style,
388        ParsingMode::DEFAULT,
389        &urlextradata,
390    );
391    rooted!(&in(cx) let object = value.to_object());
392
393    // Steps 2 - 6 are in get_property_declarations
394    let declarations = get_property_declarations(cx, object.handle(), &parser_context)?;
395
396    // Step 7. Return keyframe output.
397    Ok(Keyframe {
398        offset: keyframe_output.offset,
399        easing_function: keyframe_output.easing,
400        composite: keyframe_output.composite,
401        declarations,
402    })
403}
404
405/// Implements Step 2-6 of  <https://drafts.csswg.org/web-animations-1/#process-a-keyframe-like-object>.
406#[expect(unsafe_code)]
407fn get_property_declarations(
408    cx: &mut JSContext,
409    object: HandleObject,
410    parser_context: &ParserContext<'_>,
411) -> Fallible<Vec<KeyframePropertyDeclaration>> {
412    // The spec tells us to iterate over all animatable properties and see if they're defined
413    // on the object. Instead we can iterate over the own properties of the object and see
414    // if they're animated properties, that's easier.
415    let mut ids = IdVector::new(cx);
416    if !unsafe { GetPropertyKeys(cx, object, JSITER_OWNONLY, ids.handle_mut()) } {
417        return Ok(Vec::new());
418    }
419
420    let mut declarations = Vec::with_capacity(ids.len());
421    for id in ids.iter() {
422        rooted!(&in(cx) let id = *id);
423
424        // See if the id for the current property on the object represents a animatable CSS property.
425        if !id.is_string() {
426            continue;
427        }
428        rooted!(&in(cx) let mut key_value = UndefinedValue());
429        let raw_id: HandleId = id.handle().into();
430        if !unsafe { JS_IdToValue(cx, *raw_id.ptr, key_value.handle_mut()) } {
431            continue;
432        }
433        rooted!(&in(cx) let js_string = key_value.to_string());
434        let Some(js_string) = NonNull::new(js_string.get()) else {
435            continue;
436        };
437        let property_name = unsafe { jsstr_to_string(cx, js_string) };
438
439        let Some(property_id) = lookup_css_property_by_idl_attribute_name(&property_name) else {
440            continue;
441        };
442        debug_assert!(property_id.is_animatable());
443
444        // Step 6.1 Let raw value be the result of calling the [[Get]] internal method on keyframe input,
445        // with property name as the property key and keyframe input as the receiver.
446        // Step 6.2 Check the completion record of raw value.
447        rooted!(&in(cx) let mut property_value = UndefinedValue());
448        if !unsafe {
449            JS_GetPropertyById(
450                cx.raw_cx(),
451                object.into_handle(),
452                id.handle().into_handle(),
453                property_value.handle_mut().into_handle_mut(),
454            )
455        } {
456            continue;
457        }
458
459        // Step 6.3 Convert raw value to a DOMString or to a sequence of DOMStrings property values as follows:
460        // If allow lists is true, [..] (Note: We don't implement "allow lists")
461        // Otherwise,
462        // Let property values be the result of converting raw value to a DOMString using the procedure
463        // for converting an ECMAScript value to a DOMString [WEBIDL].
464        let property_value = match DOMString::from_jsval(
465            cx,
466            property_value.handle(),
467            StringificationBehavior::Default,
468        ) {
469            Ok(ConversionResult::Success(property_value)) => property_value,
470            Ok(ConversionResult::Failure(error_message)) => {
471                return Err(Error::Operation(
472                    error_message
473                        .to_str()
474                        .ok()
475                        .map(|message| message.to_owned()),
476                ));
477            },
478            Err(_) => return Err(Error::JSFailed),
479        };
480
481        // Step 6.4 Calculate the normalized property name as the result of applying the IDL attribute name
482        // to animation property name algorithm to property name.
483        // Note: Due to the way our implementation differs from the spec (refer to the comment at
484        // the top of this function), we already have the normalized property name.
485
486        // Parse the property value as a value for the given animatable CSS property.
487        // The specification continues to treat the value as a plain string, but there's not much point.
488        let Some(declaration) =
489            parse_single_property_declaration(property_id, &property_value.str(), parser_context)
490        else {
491            continue;
492        };
493
494        // Step 6.5 Add a property to keyframe output with normalized property name as the property name,
495        // and property values as the property value.
496        declarations.push(declaration);
497    }
498
499    Ok(declarations)
500}
501
502/// Parses `input` as a value for `property`, returning `None` on failure.
503fn parse_single_property_declaration(
504    property: NonCustomPropertyId,
505    input: &str,
506    parser_context: &ParserContext<'_>,
507) -> Option<KeyframePropertyDeclaration> {
508    let mut declaration = SourcePropertyDeclaration::default();
509    let mut input = ParserInput::new(input);
510    let mut parser = Parser::new(&mut input);
511
512    // TODO: Consider reporting parse errors somewhere useful, like the devtools console.
513    parser
514        .parse_entirely(|parser| {
515            PropertyDeclaration::parse_into(
516                &mut declaration,
517                PropertyId::NonCustom(property),
518                parser_context,
519                parser,
520            )
521        })
522        .ok()?;
523
524    let mut block = PropertyDeclarationBlock::new();
525    block.extend(declaration.drain(), Importance::Normal);
526
527    Some(KeyframePropertyDeclaration {
528        property_id: PropertyId::NonCustom(property),
529        block,
530    })
531}
532
533/// This is the inverse of <https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name>.
534fn lookup_css_property_by_idl_attribute_name(attribute_name: &str) -> Option<NonCustomPropertyId> {
535    // TODO: Step 1. If property follows the <custom-property-name> production, return property.
536
537    // Step 2. If property refers to the CSS float property, return the string "cssFloat".
538    if attribute_name == "cssFloat" {
539        return Some(LonghandId::Float.into());
540    }
541
542    // Step 3. If property refers to the CSS offset property, return the string "cssOffset".
543    // NOTE: "offset" is not supported yet.
544
545    // Step 4. Otherwise, return the result of applying the CSS property to IDL attribute algorithm
546    // [CSSOM] to property.
547    static IDL_ATTRIBUTE_TO_ANIMATED_PROPERTY_LOOKUP_TABLE: LazyLock<
548        FxHashMap<String, NonCustomPropertyId>,
549    > = LazyLock::new(|| {
550        log::debug!("Initializing map from IDL attribute names to CSS properties");
551
552        NonCustomPropertyId::iter()
553            .filter(|non_custom_property| non_custom_property.is_animatable())
554            .filter(|non_custom_property| {
555                non_custom_property
556                    .to_property_id()
557                    .enabled_for_all_content()
558            })
559            .map(|non_custom_property| {
560                let idl_attribute_name =
561                    animation_property_name_to_idl_attribute_name(non_custom_property.name());
562                (idl_attribute_name, non_custom_property)
563            })
564            .collect()
565    });
566    IDL_ATTRIBUTE_TO_ANIMATED_PROPERTY_LOOKUP_TABLE
567        .get(attribute_name)
568        .copied()
569}
570
571/// <https://drafts.csswg.org/web-animations-1/#animation-property-name-to-idl-attribute-name>
572///
573/// # Panics
574/// Panics when the property name is empty or consists only of `-` characters.
575/// In general it is assumed that `property_name` is a CSS property.
576fn animation_property_name_to_idl_attribute_name(property_name: &str) -> String {
577    let mut idl_attribute_name = String::with_capacity(property_name.len());
578
579    let mut chunks = property_name.split('-');
580    let Some(first_chunk) = chunks.next() else {
581        unreachable!("CSS property name should not consist only of dashes");
582    };
583    idl_attribute_name.push_str(first_chunk);
584    for chunk in chunks {
585        let mut characters = chunk.chars();
586        let Some(to_capitalize) = characters.next() else {
587            continue;
588        };
589        idl_attribute_name.push(to_capitalize.to_ascii_uppercase());
590        idl_attribute_name.push_str(characters.as_str());
591    }
592
593    idl_attribute_name
594}