Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / css / style_computer_4.lucb

#==============================================================================================
#
#   style_computer_4 - CSS::StyleComputer: dimension attributes and CSS transitions
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/StyleComputer.cpp (lines 997-1266): collect_dimension_attribute,
#       compute_transitioned_properties and start_needed_transitions (css-transitions). The
#       Animatable and CSSTransition members they call are region p4a's.
#
#       Copyright (c) 2018-2025, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2021, the SerenityOS developers.
#       Copyright (c) 2021-2025, Sam Atkins <sam@ladybird.org>
#       Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

## AK/Debug.h's CSS_TRANSITIONS_DEBUG (0 in the reference build).
let css_css_transitions_debug: bool = false

# mark: Dimension attributes and transitions ====================================================

## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:997 Web::CSS::collect_dimension_attribute.
func css_collect_dimension_attribute(properties: ak.Vector[CssStyleProperty]*, element: DomElement*, attribute_name: ak.FlyString, property_id: css_data.PropertyId):
    let attribute = dom_element_attribute(element, attribute_name) else return

    let parsed_value = html_parse_dimension_value(ak.string_bytes_as_string_view(&attribute)) else return

    ak.vector_append_t(properties, CssStyleProperty(important = css_syntax.Important.no, property_id = property_id, value = parsed_value))

## compute_transitioned_properties' `value_is_list_containing_a_single_time_of_zero_seconds` lambda.
func css_value_is_list_containing_a_single_time_of_zero_seconds(value: CssStyleValue*) -> bool:
    if not css_style_value_is_value_list(value):
        return false

    let value_list = css_style_value_list_values(css_style_value_as_value_list(value))

    if ak.vector_size(&value_list) != 1:
        return false

    let first = *ak.vector_at_const(&value_list, 0)
    if not css_style_value_is_time(first):
        return false

    let time = css_time_style_value_time(css_style_value_as_time(first))
    return css_time_to_seconds(&time) == 0.0

## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:1010 Web::CSS::compute_transitioned_properties.
func css_compute_transitioned_properties(style: CssComputedProperties*, abstract_element: DomAbstractElement):
    # FIXME: For now we don't bother registering transitions on the first computation since they can't run (because
    #        there is nothing to transition from) but this will change once we implement @starting-style
    if dom_abstract_element_computed_properties(&abstract_element) == none:
        return
    # FIXME: Add transition helpers on AbstractElement.
    let element = dom_abstract_element_element_const(&abstract_element)
    let pseudo_element = dom_abstract_element_pseudo_element(&abstract_element)

    animations_animatable_clear_registered_transitions(&element.animatable, pseudo_element)

    let delay = css_computed_properties_property(style, css_data.PropertyId.transition_delay)
    let duration = css_computed_properties_property(style, css_data.PropertyId.transition_duration)

    # OPTIMIZATION: Registered transitions with a "combined duration" of less than or equal to 0s are equivalent to not
    #               having a transition registered at all, except in the case that we already have an associated
    #               transition for that property, so we can skip registering them. This implementation intentionally
    #               ignores some of those cases (e.g. transitions being registered but for other properties, multiple
    #               transitions, negative delays, etc) since it covers the common (initial property values) case and
    #               the other cases are rare enough that the cost of identifying them would likely more than offset any
    #               gains.
    let existing_transitions = animations_animatable_property_ids_with_existing_transitions(&element.animatable, pseudo_element)
    if ak.vector_is_empty(&existing_transitions) and css_value_is_list_containing_a_single_time_of_zero_seconds(delay) and css_value_is_list_containing_a_single_time_of_zero_seconds(duration):
        return

    let transitions = css_computed_properties_transitions(style)
    animations_animatable_add_transitioned_properties(&element.animatable, pseudo_element, &transitions)

## start_needed_transitions' `combined_duration` lambda.
# https://drafts.csswg.org/css-transitions/#transition-combined-duration
func css_combined_duration(transition_attributes: const AnimationsAnimatableTransitionAttributes*) -> f64:
    # Define the combined duration of the transition as the sum of max(matching transition duration, 0s) and the matching transition delay.
    return ak.max_f64(transition_attributes.duration, 0.0) + transition_attributes.delay

## start_needed_transitions' `start_a_transition` lambda.
func css_style_computer_start_a_transition(this: CssStyleComputer*, abstract_element: DomAbstractElement, new_style: CssComputedProperties*, property_id: css_data.PropertyId, delay: f64, start_time: f64, end_time: f64, start_value: CssStyleValue*, end_value: CssStyleValue*, reversing_adjusted_start_value: CssStyleValue*, reversing_shortening_factor: f64):
    if css_css_transitions_debug:
        let name = css_data.string_from_property_id(property_id)
        let start_string = css_style_value_to_string(start_value, css_syntax.SerializationMode.normal)
        let end_string = css_style_value_to_string(end_value, css_syntax.SerializationMode.normal)
        ak.dbgln(f"Starting a transition of {(str)ak.fly_string_bytes(&name)} from {css_style_computer_debug_text(&start_string)} to {css_style_computer_debug_text(&end_string)}")

    let transition = css_transition_start_a_transition(abstract_element, property_id, dom_document_transition_generation(css_style_computer_document(this)), delay, start_time, end_time, start_value, end_value, reversing_adjusted_start_value, reversing_shortening_factor)
    # Immediately set the property's value to the transition's current value, to prevent single-frame jumps.
    let effect = animations_animation_effect(transition.animations_animation()) else trap("VERIFY: the transition has an effect")
    css_style_computer_collect_animation_into(this, abstract_element, as_animations_keyframe_effect(effect), new_style)

## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:1058 Web::CSS::StyleComputer::start_needed_transitions.
# https://drafts.csswg.org/css-transitions/#starting
pub func css_style_computer_start_needed_transitions(this: CssStyleComputer*, previous_style: CssComputedProperties*, new_style: CssComputedProperties*, abstract_element: DomAbstractElement):
    # For each element and property, the implementation must act as follows:
    # NB: We know that a DocumentTimeline's current time is always in milliseconds
    let timeline = dom_document_timeline(this.m_document).animations_animation_timeline()
    let current_time = animations_animation_timeline_current_time(timeline) else trap("VERIFY: the document timeline has a current time")
    assert(current_time.type_ == AnimationsTimeValueType.milliseconds)
    let style_change_event_time = current_time.value

    # FIXME: Add some transition helpers to AbstractElement.
    let element = dom_abstract_element_element_const(&abstract_element)
    let pseudo_element = dom_abstract_element_pseudo_element(&abstract_element)
    let animatable = &element.animatable

    # OPTIMIZATION: Instead of iterating over all properties we split the logic into two loops, one for the properties
    #               which appear in transition-property and one for those which have existing transitions
    let matching_property_ids = animations_animatable_property_ids_with_matching_transition_property_entry(animatable, pseudo_element)
    for property_id in ak.vector_span_const(&matching_property_ids):
        let matching_transition_properties = animations_animatable_property_transition_attributes(animatable, pseudo_element, property_id) else trap("VERIFY: matching transition attributes")
        let before_change_value = css_computed_properties_property(previous_style, property_id, CssComputedPropertiesWithAnimationsApplied.yes)
        let after_change_value = css_computed_properties_property(new_style, property_id, CssComputedPropertiesWithAnimationsApplied.no)

        let existing_transition = animations_animatable_property_transition(animatable, pseudo_element, property_id)
        var has_running_transition = false
        var has_completed_transition = false
        if let transition = existing_transition:
            let transition_animation = transition.animations_animation()
            has_running_transition = not animations_animation_is_finished(transition_animation) and not animations_animation_is_idle(transition_animation)
            has_completed_transition = animations_animation_is_finished(transition_animation) or animations_animation_is_idle(transition_animation)

        # 1. If all of the following are true:
        # - the element does not have a running transition for the property,
        # - there is a matching transition-property value, and
        # NOTE: We only iterate over properties for which this is true
        # - the before-change style is different from the after-change style for that property, and the values for the property are transitionable,
        # - the element does not have a completed transition for the property
        #   or the end value of the completed transition is different from the after-change style for the property,
        # - the combined duration is greater than 0s,
        if not has_running_transition and (not css_style_value_equals(before_change_value, after_change_value) and css_property_values_are_transitionable(property_id, before_change_value, after_change_value, element, matching_transition_properties.transition_behavior)) and (not has_completed_transition or not css_style_value_equals(css_transition_transition_end_value(existing_transition else trap("unreachable: completed")), after_change_value)) and (css_combined_duration(matching_transition_properties) > 0.0):
            if css_css_transitions_debug:
                ak.dbgln("Transition step 1.")

            # then implementations must remove the completed transition (if present) from the set of completed transitions
            if has_completed_transition:
                animations_animatable_remove_transition(animatable, pseudo_element, property_id)
            # and start a transition whose:

            # AD-HOC: We pass delay to the constructor separately so we can use it to construct the contained KeyframeEffect
            let delay = matching_transition_properties.delay

            # - start time is the time of the style change event plus the matching transition delay,
            let start_time = style_change_event_time

            # - end time is the start time plus the matching transition duration,
            let end_time = start_time + matching_transition_properties.duration

            # - start value is the value of the transitioning property in the before-change style,
            let start_value = before_change_value

            # - end value is the value of the transitioning property in the after-change style,
            let end_value = after_change_value

            # - reversing-adjusted start value is the same as the start value, and
            let reversing_adjusted_start_value = start_value

            # - reversing shortening factor is 1.
            let reversing_shortening_factor: f64 = 1.0

            css_style_computer_start_a_transition(this, abstract_element, new_style, property_id, delay, start_time, end_time, start_value, end_value, reversing_adjusted_start_value, reversing_shortening_factor)

        # 2. Otherwise, if the element has a completed transition for the property
        #    and the end value of the completed transition is different from the after-change style for the property,
        #    then implementations must remove the completed transition from the set of completed transitions.
        elif has_completed_transition and not css_style_value_equals(css_transition_transition_end_value(existing_transition else trap("unreachable: completed")), after_change_value):
            if css_css_transitions_debug:
                ak.dbgln("Transition step 2.")
            animations_animatable_remove_transition(animatable, pseudo_element, property_id)

        # NOTE: Step 3 is handled in a separate loop below for performance reasons

        # 4. If the element has a running transition for the property,
        #    there is a matching transition-property value,
        #    and the end value of the running transition is not equal to the value of the property in the after-change style, then:
        if has_running_transition:
            let running_transition = existing_transition else trap("unreachable: running")
            let running_animation = running_transition.animations_animation()
            if not css_style_value_equals(css_transition_transition_end_value(running_transition), after_change_value):
                if css_css_transitions_debug:
                    ak.dbgln("Transition step 4.")
                # 1. If the current value of the property in the running transition is equal to the value of the property in the after-change style,
                #    or if these two values are not transitionable,
                #    then implementations must cancel the running transition.
                let current_value = css_computed_properties_property(new_style, property_id, CssComputedPropertiesWithAnimationsApplied.yes)
                if css_style_value_equals(current_value, after_change_value) or not css_property_values_are_transitionable(property_id, current_value, after_change_value, element, matching_transition_properties.transition_behavior):
                    if css_css_transitions_debug:
                        ak.dbgln("Transition step 4.1")
                    animations_animation_cancel(running_animation)

                # 2. Otherwise, if the combined duration is less than or equal to 0s,
                #    or if the current value of the property in the running transition is not transitionable with the value of the property in the after-change style,
                #    then implementations must cancel the running transition.
                elif css_combined_duration(matching_transition_properties) <= 0.0 or not css_property_values_are_transitionable(property_id, current_value, after_change_value, element, matching_transition_properties.transition_behavior):
                    if css_css_transitions_debug:
                        ak.dbgln("Transition step 4.2")
                    animations_animation_cancel(running_animation)

                # 3. Otherwise, if the reversing-adjusted start value of the running transition is the same as the value of the property in the after-change style
                #    (see the section on reversing of transitions for why these case exists),
                elif css_style_value_equals(css_transition_reversing_adjusted_start_value(running_transition), after_change_value):
                    if css_css_transitions_debug:
                        ak.dbgln("Transition step 4.3")
                    # implementations must cancel the running transition and start a new transition whose:
                    animations_animation_cancel(running_animation)
                    # AD-HOC: Remove the cancelled transition, otherwise it breaks the invariant that there is only one
                    # running or completed transition for a property at once.
                    animations_animatable_remove_transition(animatable, pseudo_element, property_id)

                    # - reversing-adjusted start value is the end value of the running transition,
                    let reversing_adjusted_start_value = css_transition_transition_end_value(running_transition)

                    # - reversing shortening factor is the absolute value, clamped to the range [0, 1], of the sum of:
                    #   1. the output of the timing function of the old transition at the time of the style change event,
                    #      times the reversing shortening factor of the old transition
                    let term_1 = css_transition_timing_function_output_at_time(running_transition, style_change_event_time) * css_transition_reversing_shortening_factor(running_transition)
                    #   2. 1 minus the reversing shortening factor of the old transition.
                    let term_2 = 1.0 - css_transition_reversing_shortening_factor(running_transition)
                    let reversing_shortening_factor = ak.clamp_f64(math.abs(term_1 + term_2), 0.0, 1.0)

                    # AD-HOC: We pass delay to the constructor separately so we can use it to construct the contained KeyframeEffect
                    var delay = reversing_shortening_factor * matching_transition_properties.delay
                    if matching_transition_properties.delay >= 0.0:
                        delay = matching_transition_properties.delay

                    # - start time is the time of the style change event plus:
                    #   1. if the matching transition delay is nonnegative, the matching transition delay, or
                    #   2. if the matching transition delay is negative, the product of the new transition’s reversing shortening factor and the matching transition delay,
                    let start_time = style_change_event_time

                    # - end time is the start time plus the product of the matching transition duration and the new transition’s reversing shortening factor,
                    let end_time = start_time + (matching_transition_properties.duration * reversing_shortening_factor)

                    # - start value is the current value of the property in the running transition,
                    let start_value = current_value

                    # - end value is the value of the property in the after-change style,
                    let end_value = after_change_value

                    css_style_computer_start_a_transition(this, abstract_element, new_style, property_id, delay, start_time, end_time, start_value, end_value, reversing_adjusted_start_value, reversing_shortening_factor)

                # 4. Otherwise,
                else:
                    if css_css_transitions_debug:
                        ak.dbgln("Transition step 4.4")
                    # implementations must cancel the running transition and start a new transition whose:
                    animations_animation_cancel(running_animation)
                    # AD-HOC: Remove the cancelled transition, otherwise it breaks the invariant that there is only one
                    # running or completed transition for a property at once.
                    animations_animatable_remove_transition(animatable, pseudo_element, property_id)

                    # AD-HOC: We pass delay to the constructor separately so we can use it to construct the contained KeyframeEffect
                    let delay = matching_transition_properties.delay

                    # - start time is the time of the style change event plus the matching transition delay,
                    let start_time = style_change_event_time

                    # - end time is the start time plus the matching transition duration,
                    let end_time = start_time + matching_transition_properties.duration

                    # - start value is the current value of the property in the running transition,
                    let start_value = current_value

                    # - end value is the value of the property in the after-change style,
                    let end_value = after_change_value

                    # - reversing-adjusted start value is the same as the start value, and
                    let reversing_adjusted_start_value = start_value

                    # - reversing shortening factor is 1.
                    let reversing_shortening_factor: f64 = 1.0

                    css_style_computer_start_a_transition(this, abstract_element, new_style, property_id, delay, start_time, end_time, start_value, end_value, reversing_adjusted_start_value, reversing_shortening_factor)

    let existing_property_ids = animations_animatable_property_ids_with_existing_transitions(animatable, pseudo_element)
    for property_id in ak.vector_span_const(&existing_property_ids):
        # 3. If the element has a running transition or completed transition for the property, and there is not a
        #    matching transition-property value, then implementations must cancel the running transition or remove the
        #    completed transition from the set of completed transitions.
        if animations_animatable_property_transition_attributes(animatable, pseudo_element, property_id) != none:
            continue

        let existing_transition = animations_animatable_property_transition(animatable, pseudo_element, property_id) else trap("VERIFY: an existing transition")
        let existing_animation = existing_transition.animations_animation()

        if css_css_transitions_debug:
            ak.dbgln("Transition step 3.")
        if not animations_animation_is_finished(existing_animation) and not animations_animation_is_idle(existing_animation):
            animations_animation_cancel(existing_animation)
        else:
            animations_animatable_remove_transition(animatable, pseudo_element, property_id)