Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / animations / animation_2.lucb

#==============================================================================================
#
#   animation_2 - Animations::Animation: start and current times, the playback rate, the play
#                 state, relevance and replacement
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Animations/Animation.cpp (lines 218-626), by region p4a:
#       validating a CSSNumberish time (a CSSNumericValue is the typed OM, phase 3), setting
#       the start time, auto-aligning the start time, the current time and setting it, setting
#       the playback rate, the play state, relevance, replaceability and the replace state, and
#       the onfinish/oncancel/onremove event handler attributes.
#
#       Copyright (c) 2023-2024, Matthew Olsson <mattco@serenityos.org>.
#       Copyright (c) 2025, Jelle Raaijmakers <jelle@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Start and current times =================================================================

## Whether the animation is associated with a progress-based timeline.
func animations_animation_has_progress_based_timeline(this: AnimationsAnimation*) -> bool:
    let timeline = this.m_timeline else return false
    return animations_animation_timeline_is_progress_based(timeline)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:218 Web::Animations::Animation::validate_a_css_numberish_time (private).
# https://drafts.csswg.org/web-animations-2/#validating-a-css-numberish-time
func animations_animation_validate_a_css_numberish_time(this: AnimationsAnimation*, time: AnimationsNullableCssNumberish) -> AnimationsTimeValue?!:
    # The procedure to validate a CSSNumberish time for an input value of time is based on the first condition that matches:
    # (A CSSNumericValue's type is the typed OM, phase 3: a time that holds one traps below.)

    # If all of the following conditions are true:
    # - The animation is associated with a progress-based timeline, and
    # - time is not a CSSNumeric value with percent units:
    if animations_animation_has_progress_based_timeline(this):
        match time:
            .css_numeric_value(value):
                _ = value
                trap("unported (P3): CSSNumericValue::type (validate a CSSNumberish time)")
            _:
                # throw a TypeError.
                # return false;
                return try idl_throw_simple(IdlSimpleExceptionType.type_error, .string_view(ak.sv("CSSNumberish must be a percentage for progress-based animations")))

    # If all of the following conditions are true:
    # - The animation is not associated with a progress-based timeline, and
    # - time is a CSSNumericValue, and
    # - the units of time are not duration units:
    # - AD-HOC: While it's not mentioned in the spec WPT also expects us to support CSSNumericValue number value, see
    #           https://github.com/w3c/csswg-drafts/issues/13196
    # throw a TypeError.
    # return false.

    # Otherwise
    # return true.

    # AD-HOC: The spec doesn't say when we should absolutize the validated value so we do it here and return the
    #         absolutized value instead of a boolean
    match time:
        .empty:
            return none
        .double_(value):
            # FIXME: Figure out which element we should use for this, for now we just use the document element of the current
            #        window
            let window = as_html_window((gc.Cell*)realm_global_object(bind_platform_object_realm(this.bind_platform_object())))
            let document_element = dom_document_document_element(html_window_associated_document(window)) else trap("a null document element")
            var abstract_element: DomAbstractElement = ---
            dom_abstract_element_construct(&abstract_element, document_element)
            return animations_time_value_from_css_numberish(CssCssNumberish.double_(value), &abstract_element)
        .css_numeric_value(value):
            _ = value
            trap("unported (P3): CSSNumericValue::type (validate a CSSNumberish time)")

## Ported from Libraries/LibWeb/Animations/Animation.cpp:276 Web::Animations::Animation::set_start_time_for_bindings.
# https://www.w3.org/TR/web-animations-1/#dom-animation-starttime
# https://www.w3.org/TR/web-animations-1/#set-the-start-time
pub func animations_animation_set_start_time_for_bindings(this: AnimationsAnimation*, raw_new_start_time: AnimationsNullableCssNumberish) -> !:
    # Setting this attribute updates the start time using the procedure to set the start time of this object to the new
    # value.

    # 1. Let valid start time be the result of running the validate a CSSNumberish time procedure with new start time
    #    as the input.
    # 2. If valid start time is false, abort this procedure.
    # AD-HOC: The validate_a_css_numberish_time throws on validation failure which is handled by the TRY() macro so
    #         there is no need to assign the `valid start time` variable here.
    let new_start_time = try animations_animation_validate_a_css_numberish_time(this, raw_new_start_time)

    # 3. Set auto align start time to false.
    this.m_auto_align_start_time = false

    # 4. Let timeline time be the current time value of the timeline that animation is associated with. If there is no
    #    timeline associated with animation or the associated timeline is inactive, let the timeline time be
    #    unresolved.
    var timeline_time: AnimationsTimeValue? = none
    if let timeline = this.m_timeline:
        if not animations_animation_timeline_is_inactive(timeline):
            timeline_time = animations_animation_timeline_current_time(timeline)

    # 5. If timeline time is unresolved and new start time is resolved, make animation’s hold time unresolved.
    if timeline_time == none and new_start_time != none:
        this.m_hold_time = none

    # 6. Let previous current time be animation’s current time.
    let previous_current_time = animations_animation_current_time(this)

    # 7. Apply any pending playback rate on animation.
    animations_animation_apply_any_pending_playback_rate(this)

    # 8. Set animation’s start time to new start time.
    this.m_start_time = new_start_time

    # 9. Update animation’s hold time based on the first matching condition from the following,

    # -> If new start time is resolved,
    if new_start_time != none:
        # If animation’s playback rate is not zero, make animation’s hold time unresolved.
        if this.m_playback_rate != 0.0:
            this.m_hold_time = none
    # -> Otherwise (new start time is unresolved),
    else:
        # Set animation’s hold time to previous current time even if previous current time is unresolved.
        this.m_hold_time = previous_current_time

    # 10. If animation has a pending play task or a pending pause task, cancel that task and resolve animation’s current
    #    ready promise with animation.
    if animations_animation_pending(this):
        this.m_pending_play_task = AnimationsAnimationTaskState.none_
        this.m_pending_pause_task = AnimationsAnimationTaskState.none_
        idl_resolve_promise(bind_platform_object_realm(this.bind_platform_object()), animations_animation_current_ready_promise(this), bind_platform_object_wrapper(this.bind_platform_object()))

    # 11. Run the procedure to update an animation’s finished state for animation with the did seek flag set to true,
    #    and the synchronously notify flag set to false.
    animations_animation_update_finished_state(this, AnimationsAnimationDidSeek.yes, AnimationsAnimationSynchronouslyNotify.no)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:339 Web::Animations::Animation::calculate_auto_aligned_start_time.
# https://drafts.csswg.org/web-animations-2/#auto-aligning-start-time
pub func animations_animation_calculate_auto_aligned_start_time(this: AnimationsAnimation*):
    assert(animations_animation_has_progress_based_timeline(this))

    # 1. If the auto-align start time flag is false, abort this procedure.
    if not this.m_auto_align_start_time:
        return

    # 2. If the timeline is inactive, abort this procedure.
    let timeline = this.m_timeline else return
    if animations_animation_timeline_is_inactive(timeline):
        return

    # 3. If play state is idle, abort this procedure.
    if animations_animation_is_idle(this):
        return

    # 4. If play state is paused, and hold time is resolved, abort this procedure.
    if animations_animation_play_state(this) == BindAnimationPlayState.paused and this.m_hold_time != none:
        return

    # 5. FIXME: Let start offset be the resolved timeline time corresponding to the start of the animation attachment
    #           range. In the case of view timelines, it requires a calculation based on the proportion of the cover
    #           range.
    let start_offset = AnimationsTimeValue(type_ = AnimationsTimeValueType.percentage, value = 0.0)

    # 6. FIXME: Let end offset be the resolved timeline time corresponding to the end of the animation attachment
    #           range. In the case of view timelines, it requires a calculation based on the proportion of the cover
    #           range.
    let end_offset = AnimationsTimeValue(type_ = AnimationsTimeValueType.percentage, value = 100.0)

    # 7. Set start time to start offset if effective playback rate ≥ 0, and end offset otherwise.
    if animations_animation_effective_playback_rate(this) >= 0.0:
        this.m_start_time = start_offset
    else:
        this.m_start_time = end_offset

    # 8. Clear hold time.
    this.m_hold_time = none

## Ported from Libraries/LibWeb/Animations/Animation.cpp:380 Web::Animations::Animation::current_time.
# https://www.w3.org/TR/web-animations-1/#animation-current-time
pub func animations_animation_current_time(this: AnimationsAnimation*) -> AnimationsTimeValue?:
    # The current time is calculated from the first matching condition from below:

    # -> If the animation’s hold time is resolved,
    if let hold_time = this.m_hold_time:
        # The current time is the animation’s hold time.
        return hold_time

    # -> If any of the following are true:
    #    - the animation has no associated timeline, or
    #    - the associated timeline is inactive, or
    #    - the animation’s start time is unresolved.
    let timeline = this.m_timeline else return none
    if animations_animation_timeline_is_inactive(timeline):
        return none
    # The current time is an unresolved time value.
    let start_time = this.m_start_time else return none

    # -> Otherwise,
    #    current time = (timeline time - start time) × playback rate
    #    Where timeline time is the current time value of the associated timeline. The playback rate value is defined
    #    in §4.4.15 Speed control.
    let timeline_time = animations_animation_timeline_current_time(timeline) else trap("VERIFY: Optional::value()")
    return animations_time_value_mul(animations_time_value_sub(timeline_time, start_time), animations_animation_playback_rate(this))

## Ported from Libraries/LibWeb/Animations/Animation.cpp:407 Web::Animations::Animation::set_current_time_for_bindings.
# https://www.w3.org/TR/web-animations-1/#animation-set-the-current-time
pub func animations_animation_set_current_time_for_bindings(this: AnimationsAnimation*, raw_seek_time: AnimationsNullableCssNumberish) -> !:
    # AD-HOC: We validate here instead of within silently_set_current_time so we have access to the `TimeValue`
    #         value within this function.
    let seek_time = try animations_animation_validate_a_css_numberish_time(this, raw_seek_time)

    # 1. Run the steps to silently set the current time of animation to seek time.
    try animations_animation_silently_set_current_time(this, seek_time)

    # 2. If animation has a pending pause task, synchronously complete the pause operation by performing the following
    #    steps:
    if this.m_pending_pause_task == AnimationsAnimationTaskState.scheduled:
        # 1. Set animation’s hold time to seek time.
        this.m_hold_time = seek_time

        # 2. Apply any pending playback rate to animation.
        animations_animation_apply_any_pending_playback_rate(this)

        # 3. Make animation’s start time unresolved.
        this.m_start_time = none

        # 4. Cancel the pending pause task.
        this.m_pending_pause_task = AnimationsAnimationTaskState.none_

        # 5 Resolve animation’s current ready promise with animation.
        idl_resolve_promise(bind_platform_object_realm(this.bind_platform_object()), animations_animation_current_ready_promise(this), bind_platform_object_wrapper(this.bind_platform_object()))

    # 3. Run the procedure to update an animation’s finished state for animation with the did seek flag set to true,
    #    and the synchronously notify flag set to false.
    animations_animation_update_finished_state(this, AnimationsAnimationDidSeek.yes, AnimationsAnimationSynchronouslyNotify.no)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:444 Web::Animations::Animation::set_playback_rate.
# https://www.w3.org/TR/web-animations-1/#dom-animation-playbackrate
# https://www.w3.org/TR/web-animations-1/#set-the-playback-rate
pub func animations_animation_set_playback_rate(this: AnimationsAnimation*, new_playback_rate: f64) -> !:
    # Setting this attribute follows the procedure to set the playback rate of this object to the new value.

    # 1. Clear any pending playback rate on animation.
    this.m_pending_playback_rate = none

    # 2. Let previous time be the value of the current time of animation before changing the playback rate.
    let previous_time = animations_animation_current_time(this)

    # 3. Let previous playback rate be the current effective playback rate of animation.
    let previous_playback_rate = animations_animation_playback_rate(this)

    # 4. Set the playback rate to new playback rate.
    this.m_playback_rate = new_playback_rate

    # 5. Perform the steps corresponding to the first matching condition from the following, if any:
    let timeline = this.m_timeline else return

    # -> If animation is associated with a monotonically increasing timeline and the previous time is resolved,
    if animations_animation_timeline_is_monotonically_increasing(timeline) and previous_time != none:
        # set the current time of animation to previous time.
        let time = previous_time else trap("unreachable: checked above")
        let realm = bind_platform_object_realm(this.bind_platform_object())
        try animations_animation_set_current_time_for_bindings(this, animations_nullable_css_numberish_from_css_numberish(animations_time_value_as_css_numberish(time, realm)))
    # -> If animation is associated with a non-null timeline that is not monotonically increasing, the start time of
    #    animation is resolved, associated effect end is not infinity, and either:
    #    - the previous playback rate < 0 and the new playback rate ≥ 0, or
    #    - the previous playback rate ≥ 0 and the new playback rate < 0,
    elif not animations_animation_timeline_is_monotonically_increasing(timeline) and this.m_start_time != none and not math.is_infinite(animations_animation_associated_effect_end(this).value) and ((previous_playback_rate < 0.0 and new_playback_rate >= 0.0) or (previous_playback_rate >= 0.0 and new_playback_rate < 0.0)):
        # Set animation’s start time to the result of evaluating associated effect end - start time for animation.
        let start_time = this.m_start_time else trap("unreachable: checked above")
        this.m_start_time = animations_time_value_sub(animations_animation_associated_effect_end(this), start_time)

# mark: Play state ==============================================================================

## Ported from Libraries/LibWeb/Animations/Animation.cpp:480 Web::Animations::Animation::play_state_for_bindings.
# https://www.w3.org/TR/web-animations-1/#animation-play-state
pub func animations_animation_play_state_for_bindings(this: AnimationsAnimation*) -> BindAnimationPlayState:
    if let owning_element = this.m_owning_element:
        dom_document_update_style(dom_abstract_element_document(&owning_element))

    return animations_animation_play_state(this)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:488 Web::Animations::Animation::play_state.
pub func animations_animation_play_state(this: AnimationsAnimation*) -> BindAnimationPlayState:
    # The play state of animation, animation, at a given moment is the state corresponding to the first matching
    # condition from the following:

    # -> All of the following conditions are true:
    #    - The current time of animation is unresolved, and
    #    - the start time of animation is unresolved, and
    #    - animation does not have either a pending play task or a pending pause task,
    let current_time = animations_animation_current_time(this)
    if current_time == none and this.m_start_time == none and not animations_animation_pending(this):
        # → idle
        return BindAnimationPlayState.idle

    # -> Either of the following conditions are true:
    #    - animation has a pending pause task, or
    #    - both the start time of animation is unresolved and it does not have a pending play task,
    if this.m_pending_pause_task == AnimationsAnimationTaskState.scheduled or (this.m_start_time == none and this.m_pending_play_task == AnimationsAnimationTaskState.none_):
        # → paused
        return BindAnimationPlayState.paused

    # -> For animation, current time is resolved and either of the following conditions are true:
    #    - animation’s effective playback rate > 0 and current time ≥ associated effect end; or
    #    - animation’s effective playback rate < 0 and current time ≤ 0,
    let effective_playback_rate = animations_animation_effective_playback_rate(this)
    if let time = current_time:
        if (effective_playback_rate > 0.0 and animations_time_value_ge(time, animations_animation_associated_effect_end(this))) or (effective_playback_rate < 0.0 and time.value <= 0.0):
            # → finished
            return BindAnimationPlayState.finished

    # -> Otherwise,
    #    → running
    return BindAnimationPlayState.running

## Ported from Libraries/LibWeb/Animations/Animation.cpp:526 Web::Animations::Animation::is_relevant.
# https://www.w3.org/TR/web-animations-1/#animation-relevant
pub func animations_animation_is_relevant(this: AnimationsAnimation*) -> bool:
    # An animation is relevant if:
    # - Its associated effect is current or in effect, and
    # - Its replace state is not removed.
    let effect = this.m_effect else return false
    return (animations_animation_effect_is_current(effect) or animations_animation_effect_is_in_effect(effect)) and animations_animation_replace_state(this) != BindAnimationReplaceState.removed

## Ported from Libraries/LibWeb/Animations/Animation.cpp:535 Web::Animations::Animation::is_replaceable.
# https://www.w3.org/TR/web-animations-1/#replaceable-animation
pub func animations_animation_is_replaceable(this: AnimationsAnimation*) -> bool:
    # An animation is replaceable if all of the following conditions are true:

    # - The existence of the animation is not prescribed by markup. That is, it is not a CSS animation with an owning
    #   element, nor a CSS transition with an owning element.
    if (animations_animation_is_css_animation(this) or animations_animation_is_css_transition(this)) and animations_animation_owning_element(this) != none:
        return false

    # - The animation's play state is finished.
    if animations_animation_play_state(this) != BindAnimationPlayState.finished:
        return false

    # - The animation's replace state is not removed.
    if animations_animation_replace_state(this) == BindAnimationReplaceState.removed:
        return false

    # - The animation is associated with a monotonically increasing timeline.
    let timeline = this.m_timeline else return false
    if not animations_animation_timeline_is_monotonically_increasing(timeline):
        return false

    # - The animation has an associated effect.
    let effect = this.m_effect else return false

    # - The animation's associated effect is in effect.
    if not animations_animation_effect_is_in_effect(effect):
        return false

    # - The animation's associated effect has an effect target.
    if animations_animation_effect_target(effect) == none:
        return false

    return true

## Ported from Libraries/LibWeb/Animations/Animation.cpp:571 Web::Animations::Animation::set_replace_state.
pub func animations_animation_set_replace_state(this: AnimationsAnimation*, value: BindAnimationReplaceState):
    if value == BindAnimationReplaceState.removed:
        # Remove the associated effect from its target, if applicable
        if let effect = this.m_effect:
            if let target = animations_animation_effect_target(effect):
                animations_animatable_disassociate_with_animation(&target.animatable, this)

        # Remove this animation from its timeline
        let timeline = this.m_timeline else trap("a null timeline: m_timeline->disassociate_with_animation()")
        animations_animation_timeline_disassociate_with_animation(timeline, this)
    elif value == BindAnimationReplaceState.persisted and this.m_replace_state == BindAnimationReplaceState.removed:
        # This animation was removed, but is now being "unremoved"; undo the effects from the if-statement above
        if let effect = this.m_effect:
            if let target = animations_animation_effect_target(effect):
                animations_animatable_associate_with_animation(&target.animatable, this)
        let timeline = this.m_timeline else trap("a null timeline: m_timeline->associate_with_animation()")
        animations_animation_timeline_associate_with_animation(timeline, this)

    this.m_replace_state = value

# mark: Event handlers ==========================================================================

## Ported from Libraries/LibWeb/Animations/Animation.cpp:591 Web::Animations::Animation::onfinish.
# https://www.w3.org/TR/web-animations-1/#dom-animation-onfinish
pub func animations_animation_onfinish(this: AnimationsAnimation*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_finish)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:597 Web::Animations::Animation::set_onfinish.
# https://www.w3.org/TR/web-animations-1/#dom-animation-onfinish
pub func animations_animation_set_onfinish(this: AnimationsAnimation*, event_handler: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_finish, event_handler)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:603 Web::Animations::Animation::oncancel.
# https://www.w3.org/TR/web-animations-1/#dom-animation-oncancel
pub func animations_animation_oncancel(this: AnimationsAnimation*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_cancel)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:609 Web::Animations::Animation::set_oncancel.
# https://www.w3.org/TR/web-animations-1/#dom-animation-oncancel
pub func animations_animation_set_oncancel(this: AnimationsAnimation*, event_handler: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_cancel, event_handler)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:615 Web::Animations::Animation::onremove.
# https://www.w3.org/TR/web-animations-1/#dom-animation-onremove
pub func animations_animation_onremove(this: AnimationsAnimation*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_remove)

## Ported from Libraries/LibWeb/Animations/Animation.cpp:621 Web::Animations::Animation::set_onremove.
# https://www.w3.org/TR/web-animations-1/#dom-animation-onremove
pub func animations_animation_set_onremove(this: AnimationsAnimation*, event_handler: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_remove, event_handler)