Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / animations / keyframe_effect.lucb

#==============================================================================================
#
#   keyframe_effect - Animations::KeyframeEffect: a keyframe effect's target, composite order,
#                     keyframes and computed properties
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Animations/KeyframeEffect.cpp (lines 1-574 and 627-975) with
#       the inline members of KeyframeEffect.h, by region p4a: computing the missing keyframe
#       offsets, the loosely-sorted check, the composite order of two keyframe effects,
#       creating one (and copying one), its target element and pseudo-element, setKeyframes(),
#       the constructor, initialize, visit_edges, and update_computed_properties (which runs
#       StyleComputer::collect_animation_into for the effect's target). Region r39 ported
#       generate_initial_and_final_frames (keyframe_effect_key_frame_set). Processing a
#       keyframe-like object or a keyframes argument and getKeyframes() make and read JS
#       objects: phase 3.
#
#       Copyright (c) 2023-2024, Matthew Olsson <mattco@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Accessors (KeyframeEffect.h) ============================================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:85 Web::Animations::KeyframeEffect::target (override).
pub func animations_keyframe_effect_target_impl(base: AnimationsAnimationEffect*) -> DomElement*?:
    let this = (AnimationsKeyframeEffect*)base
    return this.m_target_element

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:96 Web::Animations::KeyframeEffect::set_pseudo_element.
pub func animations_keyframe_effect_set_pseudo_element_css_selector_pseudo_element_selector(this: AnimationsKeyframeEffect*, pseudo_element: CssSelectorPseudoElementSelector?):
    this.m_target_pseudo_selector = pseudo_element

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:98 Web::Animations::KeyframeEffect::composite.
pub func animations_keyframe_effect_composite(this: AnimationsKeyframeEffect*) -> BindCompositeOperation:
    return this.m_composite

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:99 Web::Animations::KeyframeEffect::set_composite.
pub func animations_keyframe_effect_set_composite(this: AnimationsKeyframeEffect*, value: BindCompositeOperation):
    this.m_composite = value

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:104 Web::Animations::KeyframeEffect::key_frame_set.
pub func animations_keyframe_effect_key_frame_set(this: AnimationsKeyframeEffect*) -> const AnimationsKeyframeEffectKeyFrameSet*?:
    return this.m_key_frame_set

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:105 Web::Animations::KeyframeEffect::set_key_frame_set.
pub func animations_keyframe_effect_set_key_frame_set(this: AnimationsKeyframeEffect*, key_frame_set: const AnimationsKeyframeEffectKeyFrameSet*?):
    this.m_key_frame_set = key_frame_set

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.h:107 Web::Animations::KeyframeEffect::is_keyframe_effect (override).
pub func animations_keyframe_effect_is_keyframe_effect_impl(base: AnimationsAnimationEffect*) -> bool:
    return true

# mark: Keyframes ===============================================================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:228 Web::Animations::compute_missing_keyframe_offsets.
# https://www.w3.org/TR/web-animations-1/#compute-missing-keyframe-offsets
func animations_compute_missing_keyframe_offsets(keyframes: ak.Vector[AnimationsBaseKeyframe]*):
    let frames = ak.vector_span(keyframes)

    # 1. For each keyframe, in keyframes, let the computed keyframe offset of the keyframe be equal to its keyframe
    #    offset value.
    for i in 0..<frames.length:
        frames[i].computed_offset = frames[i].offset

    # 2. If keyframes contains more than one keyframe and the computed keyframe offset of the first keyframe in
    #    keyframes is null, set the computed keyframe offset of the first keyframe to 0.
    if frames.length > 1 and frames[0].computed_offset == none:
        frames[0].computed_offset = 0.0

    # 3. If the computed keyframe offset of the last keyframe in keyframes is null, set its computed keyframe offset
    #    to 1.
    if frames.length > 0 and frames[frames.length - 1].computed_offset == none:
        frames[frames.length - 1].computed_offset = 1.0

    # 4. For each pair of keyframes A and B where:
    #    - A appears before B in keyframes, and
    #    - A and B have a computed keyframe offset that is not null, and
    #    - all keyframes between A and B have a null computed keyframe offset,
    var index_a = animations_find_next_index_of_keyframe_with_computed_offset(frames, 0) else return
    var maybe_index_b = animations_find_next_index_of_keyframe_with_computed_offset(frames, index_a + 1)

    while let index_b = maybe_index_b:
        # calculate the computed keyframe offset of each keyframe between A and B as follows:
        for keyframe_index in (index_a + 1)..<index_b:
            # 1. Let offsetk be the computed keyframe offset of a keyframe k.
            let offset_a = frames[index_a].computed_offset else trap("VERIFY: Optional::value()")
            let offset_b = frames[index_b].computed_offset else trap("VERIFY: Optional::value()")

            # 2. Let n be the number of keyframes between and including A and B minus 1.
            let n = f64(index_b - index_a)

            # 3. Let index refer to the position of keyframe in the sequence of keyframes between A and B such that the
            #    first keyframe after A has an index of 1.
            let index = f64(keyframe_index - index_a)

            # 4. Set the computed keyframe offset of keyframe to offsetA + (offsetB − offsetA) × index / n.
            # donor bug: the C++ parenthesizes (offsetA + (offsetB − offsetA)) × index / n; kept.
            frames[keyframe_index].computed_offset = (offset_a + (offset_b - offset_a)) * index / n

        index_a = index_b
        maybe_index_b = animations_find_next_index_of_keyframe_with_computed_offset(frames, index_b + 1)

## compute_missing_keyframe_offsets' `find_next_index_of_keyframe_with_computed_offset` lambda.
func animations_find_next_index_of_keyframe_with_computed_offset(keyframes: AnimationsBaseKeyframe[], starting_index: usize) -> usize?:
    for index in starting_index..<keyframes.length:
        if keyframes[index].computed_offset != none:
            return index

    return none

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:291 Web::Animations::is_loosely_sorted_by_offset. (Its caller,
## process_a_keyframes_argument's JS steps, is phase 3; public until then.)
# https://www.w3.org/TR/web-animations-1/#loosely-sorted-by-offset
pub func animations_is_loosely_sorted_by_offset(keyframes: const ak.Vector[AnimationsBaseKeyframe]*) -> bool:
    # The list of keyframes for a keyframe effect must be loosely sorted by offset which means that for each keyframe
    # in the list that has a keyframe offset that is not null, the offset is greater than or equal to the offset of the
    # previous keyframe in the list with a keyframe offset that is not null, if any.

    var last_offset: f64? = none
    for keyframe in ak.vector_span_const(keyframes):
        let offset = keyframe.offset else continue

        if let last = last_offset:
            if offset < last:
                return false

        last_offset = offset

    return true

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:312 Web::Animations::process_a_keyframes_argument.
# https://www.w3.org/TR/web-animations-1/#process-a-keyframes-argument
func animations_process_a_keyframes_argument(realm: Realm*, object: JsObject*?) -> ak.Vector[AnimationsBaseKeyframe]!:
    _ = realm

    # 1. If object is null, return an empty sequence of keyframes.
    if object == none:
        return ak.Vector[AnimationsBaseKeyframe]()

    # 2.-8. The keyframes are read from the JS object (its iterator or its property-indexed members), JS: phase 3.
    trap("unported (P3): Web::Animations::process_a_keyframes_argument (a JS keyframes object)")

# mark: Composite order and creation ============================================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:629 Web::Animations::KeyframeEffect::composite_order.
# https://www.w3.org/TR/web-animations-1/#animation-composite-order
pub func animations_keyframe_effect_composite_order(a: AnimationsKeyframeEffect*, b: AnimationsKeyframeEffect*) -> i32:
    # The relative composite order of any two keyframe effects A and B within an effect stack is established by
    # comparing their properties as follows:
    let a_animation = animations_animation_effect_associated_animation(a.animations_animation_effect()) else trap("a null associated animation")
    let b_animation = animations_animation_effect_associated_animation(b.animations_animation_effect()) else trap("a null associated animation")

    # 1. Sort A and B by applying the following conditions in turn until the order is resolved,

    #    1. If A and B’s associated animations differ by class, sort by any inter-class composite order defined for
    #       the corresponding classes.
    let a_class = animations_animation_animation_class(a_animation)
    let b_class = animations_animation_animation_class(b_animation)

    # From https://www.w3.org/TR/css-animations-2/#animation-composite-order:
    # "CSS Animations with an owning element have a later composite order than CSS Transitions but an earlier
    # composite order than animations without a specific animation class."
    if a_class != b_class:
        return (i32)a_class - (i32)b_class

    #    2. If A and B are still not sorted, sort by any class-specific composite order defined by the common class of
    #       A and B’s associated animations.
    let order = animations_animation_class_specific_composite_order(a_animation, b_animation)
    if order != 0:
        return order

    #    3. If A and B are still not sorted, sort by the position of their associated animations in the global
    #       animation list.
    # (unsigned int subtraction converted to int, as the C++ return does)
    return (i32)(animations_animation_global_animation_list_order(a_animation) -% animations_animation_global_animation_list_order(b_animation))

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:659 Web::Animations::KeyframeEffect::create.
pub func animations_keyframe_effect_create(realm: Realm*) -> AnimationsKeyframeEffect*:
    return realm_create_animations_keyframe_effect(realm, realm)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:665 Web::Animations::KeyframeEffect::construct_impl (target,
## keyframes, options).
# https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect
pub func animations_keyframe_effect_construct_impl(realm: Realm*, target: DomElement*?, keyframes: JsObject*?, options: F64OrAnimationsKeyframeEffectOptions) -> AnimationsKeyframeEffect*!:
    # (The constructor's keyframes and options come from a JS call: phase 3.)
    _ = realm
    _ = target
    _ = keyframes
    _ = options
    trap("unported (P3): Web::Animations::KeyframeEffect::construct_impl (the JS constructor)")

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:738 Web::Animations::KeyframeEffect::construct_impl (source).
# https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-keyframeeffect-source
pub func animations_keyframe_effect_construct_impl_keyframe_effect(realm: Realm*, source: AnimationsKeyframeEffect*) -> AnimationsKeyframeEffect*!:
    # 1. Create a new KeyframeEffect object, effect.
    let effect = realm_create_animations_keyframe_effect(realm, realm)
    let effect_base = effect.animations_animation_effect()
    let source_base = source.animations_animation_effect()

    # 2. Set the following properties of effect using the corresponding values of source:

    #   - effect target,
    effect.m_target_element = animations_animation_effect_target(source_base)

    #   - keyframes,
    effect.m_keyframes = ak.vector_clone(&source.m_keyframes)

    #   - composite operation, and
    animations_keyframe_effect_set_composite(effect, animations_keyframe_effect_composite(source))

    #   - all specified timing properties:

    # AD-HOC: This is defined in the web-animations level 1 spec so doesn't explicitly mention the level 2 properties
    #         (specified start delay, specified end delay, specified iteration duration) but it is required that we
    #         copy these and then normalize them as opposed to copying the already normalized values which may be
    #         invalid in this context i.e. if the existing effect was associated with a progress-based timeline

    #     - specified start delay,
    effect_base.m_specified_start_delay = source_base.m_specified_start_delay

    #     - specified end delay,
    effect_base.m_specified_end_delay = source_base.m_specified_end_delay

    #     - fill mode,
    effect_base.m_fill_mode = source_base.m_fill_mode

    #     - iteration start,
    effect_base.m_iteration_start = source_base.m_iteration_start

    #     - iteration count,
    effect_base.m_iteration_count = source_base.m_iteration_count

    #     - specified iteration duration,
    effect_base.m_specified_iteration_duration = source_base.m_specified_iteration_duration

    #     - playback direction, and
    effect_base.m_playback_direction = source_base.m_playback_direction

    #     - timing function.
    effect_base.m_timing_function = source_base.m_timing_function

    animations_animation_effect_normalize_specified_timing(effect_base)

    return effect

# mark: Target ==================================================================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:790 Web::Animations::KeyframeEffect::set_target(DOM::Element*).
pub func animations_keyframe_effect_set_target(this: AnimationsKeyframeEffect*, target: DomElement*?):
    if let animation = animations_animation_effect_associated_animation(this.animations_animation_effect()):
        if let old_target = this.m_target_element:
            animations_animatable_disassociate_with_animation(&old_target.animatable, animation)
        if let new_target = target:
            animations_animatable_associate_with_animation(&new_target.animatable, animation)
    this.m_target_element = target

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:801 Web::Animations::KeyframeEffect::pseudo_element.
pub func animations_keyframe_effect_pseudo_element(this: AnimationsKeyframeEffect*) -> ak.String?:
    let selector = this.m_target_pseudo_selector else return none
    return css_selector_pseudo_element_selector_serialize(&selector)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:809 Web::Animations::KeyframeEffect::set_pseudo_element.
# https://drafts.csswg.org/web-animations-1/#dom-keyframeeffect-pseudoelement
pub func animations_keyframe_effect_set_pseudo_element(this: AnimationsKeyframeEffect*, value: ak.String?) -> !:
    # On setting, sets the target pseudo-selector of the animation effect to the result of
    # pseudo-element parsing on the provided value, defined as the following:
    # NOTE: The actual definition is in pseudo_element_parsing().
    this.m_target_pseudo_selector = try animations_pseudo_element_parsing(bind_platform_object_realm(this.bind_platform_object()), value)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:818 Web::Animations::KeyframeEffect::target_abstract_element.
pub func animations_keyframe_effect_target_abstract_element(this: AnimationsKeyframeEffect*) -> DomAbstractElement?:
    let target = this.m_target_element else return none
    var abstract_element: DomAbstractElement = ---
    dom_abstract_element_construct(&abstract_element, target, animations_keyframe_effect_pseudo_element_type(this))
    return abstract_element

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:825 Web::Animations::KeyframeEffect::set_target(DOM::AbstractElement).
pub func animations_keyframe_effect_set_target_dom_abstract_element(this: AnimationsKeyframeEffect*, abstract_element: DomAbstractElement):
    var element_reference = abstract_element
    animations_keyframe_effect_set_target(this, dom_abstract_element_element(&element_reference))
    if let pseudo_element = dom_abstract_element_pseudo_element(&element_reference):
        var selector: CssSelectorPseudoElementSelector = ---
        css_selector_pseudo_element_selector_construct_css_selector_pseudo_element_se(&selector, pseudo_element)
        this.m_target_pseudo_selector = selector
    else:
        this.m_target_pseudo_selector = none

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:831 Web::Animations::KeyframeEffect::pseudo_element_type.
pub func animations_keyframe_effect_pseudo_element_type(this: AnimationsKeyframeEffect*) -> css_data.PseudoElement?:
    let selector = this.m_target_pseudo_selector else return none
    return css_selector_pseudo_element_selector_type(&selector)

# mark: Keyframes from script ===================================================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:839 Web::Animations::KeyframeEffect::get_keyframes.
# https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-getkeyframes
pub func animations_keyframe_effect_get_keyframes(this: AnimationsKeyframeEffect*) -> ak.Vector[JsObject*]!:
    # (Each keyframe becomes a JS object with its offsets, easing, composite and properties: phase 3.)
    _ = this
    trap("unported (P3): Web::Animations::KeyframeEffect::get_keyframes (JS keyframe objects)")

## The `[&](CSS::PropertyID longhand_id, CSS::StyleValue const&)` callback of set_keyframes' expansion of a property:
## record the longhand as a target property.
func animations_keyframe_effect_set_keyframes_target_property(context: void*?, longhand_id: css_data.PropertyId, value: CssStyleValue*):
    _ = value
    let this = (AnimationsKeyframeEffect*)(context else trap("no captures"))
    _ = ak.hash_table_set(&this.animation_effect.m_target_properties, longhand_id)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:882 Web::Animations::KeyframeEffect::set_keyframes.
# https://www.w3.org/TR/web-animations-1/#dom-keyframeeffect-setkeyframes
pub func animations_keyframe_effect_set_keyframes(this: AnimationsKeyframeEffect*, keyframe_object: JsObject*?) -> !:
    ak.vector_clear(&this.m_keyframe_objects)
    this.m_keyframes = try animations_process_a_keyframes_argument(bind_platform_object_realm(this.bind_platform_object()), keyframe_object)
    # FIXME: After processing the keyframe argument, we need to turn the set of keyframes into a set of computed
    #        keyframes using the procedure outlined in the second half of
    #        https://www.w3.org/TR/web-animations-1/#calculating-computed-keyframes. For now, just compute the
    #        missing keyframe offsets
    animations_compute_missing_keyframe_offsets(&this.m_keyframes)

    let keyframe_set = (new AnimationsKeyframeEffectKeyFrameSet) else trap("out of memory")
    ak.hash_table_clear(&this.animation_effect.m_target_properties)

    for keyframe in ak.vector_span(&this.m_keyframes):
        var resolved_keyframe = animations_keyframe_effect_key_frame_set_resolved_key_frame_new()
        resolved_keyframe.composite = keyframe.composite
        match keyframe.easing:
            .css_easing_function(easing):
                resolved_keyframe.easing = EmptyOrCssEasingFunctionOrCssStyleValue.css_easing_function(easing)
            .string(value):
                _ = value

        let computed_offset = keyframe.computed_offset else trap("VERIFY: Optional::value()")
        let key = (u64)(computed_offset * 100.0 * animations_keyframe_effect_animation_key_frame_key_scale_factor)

        match keyframe.properties:
            .parsed_properties(properties):
                for entry in ak.hash_map_begin_const(&properties):
                    _ = ak.hash_map_set(&resolved_keyframe.properties, entry.key, AnimationsKeyframeEffectKeyFrameSetUseInitialOrCssStyleValue.css_style_value(entry.value))
                    css_style_computer_for_each_property_expanding_shorthands(entry.key, entry.value, ak.Function2[css_data.PropertyId, CssStyleValue*, unit](call = animations_keyframe_effect_set_keyframes_target_property, context = this))
            .unparsed_properties(properties):
                _ = properties
                trap("VERIFY: Variant::get<ParsedProperties>()")

        ak.red_black_tree_insert(&keyframe_set.keyframes_by_key, key, resolved_keyframe)

    animations_keyframe_effect_generate_initial_and_final_frames(keyframe_set, &this.animation_effect.m_target_properties)
    this.m_key_frame_set = keyframe_set

# mark: Construction, edges and computed properties =============================================

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:919 Web::Animations::KeyframeEffect::KeyframeEffect (private).
func animations_keyframe_effect_construct(this: AnimationsKeyframeEffect*, realm: Realm*):
    animations_animation_effect_construct(this.animations_animation_effect(), realm)
    # The C++ default member initializers.
    this.m_composite = BindCompositeOperation.replace

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:924 Web::Animations::KeyframeEffect::initialize (override).
func animations_keyframe_effect_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.keyframe_effect)
    animations_animation_effect_initialize_impl(base, realm)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:930 Web::Animations::KeyframeEffect::visit_edges (override).
func animations_keyframe_effect_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (AnimationsKeyframeEffect*)base
    animations_animation_effect_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_target_element)
    for object in ak.vector_span_const(&this.m_keyframe_objects):
        gc.cell_visitor_visit_cell_2(visitor, (gc.Cell*)object)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:937 Web::Animations::KeyframeEffect::update_computed_properties (override).
func animations_keyframe_effect_update_computed_properties_impl(base: AnimationsAnimationEffect*, context: AnimationsAnimationUpdateContext*):
    let this = (AnimationsKeyframeEffect*)base
    let target = animations_animation_effect_target(base) else return
    if not dom_node_is_connected(target.dom_node()):
        return

    if dom_node_has_inclusive_ancestor_with_display_none_ignoring_animations(target.dom_node()):
        # FIXME: Reaching this point means we failed to cancel animation for an element that started
        #        being nested in "display: none".
        #        For now this hack is needed to avoid lots of unnecessary work.
        return

    let computed_properties = dom_element_computed_properties(target, animations_keyframe_effect_pseudo_element_type(this)) else return
    var abstract_element: DomAbstractElement = ---
    dom_abstract_element_construct(&abstract_element, target, animations_keyframe_effect_pseudo_element_type(this))
    if not ak.hash_map_contains_k(&context.elements, abstract_element):
        # context.elements.ensure(abstract_element, [computed_properties] { ... }): the element's animated properties
        # before this update, and its style.
        let old_animated_properties = css_computed_properties_animated_property_values(computed_properties)
        css_computed_properties_reset_non_inherited_animated_properties(computed_properties)
        let element_data = new AnimationsAnimationUpdateContextElementData(animated_properties_before_update = old_animated_properties, target_style = computed_properties) else trap("out of memory")
        _ = ak.hash_map_set(&context.elements, abstract_element, element_data)

    css_style_computer_collect_animation_into(dom_document_style_computer(dom_node_document(target.dom_node())), abstract_element, this, computed_properties)

## Ported from Libraries/LibWeb/Animations/KeyframeEffect.cpp:963 Web::Animations::css_animation_composition_to_bindings_composite_operation.
pub func animations_css_animation_composition_to_bindings_composite_operation(composition: css_data.AnimationComposition) -> BindCompositeOperation:
    match composition:
        .accumulate:
            return BindCompositeOperation.accumulate
        .add:
            return BindCompositeOperation.add
        .replace:
            return BindCompositeOperation.replace
        _:
            trap("VERIFY_NOT_REACHED")