Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / layout / flex_formatting_context_3.lucb

#==============================================================================================
#
#   flex_formatting_context_3 - Layout::FlexFormattingContext: flex base sizes, automatic
#                               minimum sizes, flex lines and flexible lengths
#
#   DESCRIPTION:
#       Port of LibWeb/Layout/FlexFormattingContext.cpp (lines 655-1192): the flex base size
#       and hypothetical main size of an item (steps A-E of
#       https://drafts.csswg.org/css-flexbox-1/#algo-main-item), the automatic minimum size and
#       its specified, content and transferred size suggestions, collecting items into flex
#       lines, and resolving the flexible lengths of each line (freezing inflexible items,
#       distributing free space by flex factors, fixing min/max violations).
#
#       Copyright (c) 2021-2025, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
#       Copyright (c) 2025, Jelle Raaijmakers <jelle@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: The flex base size ======================================================================

## `flex_basis.has<CSS::FlexBasisContent>()`.
func layout_flex_formatting_context_flex_basis_is_content(flex_basis: CssFlexBasis) -> bool:
    return layout_flex_formatting_context_flex_basis_size(flex_basis) == none

## The `used_flex_basis_is_definite` lambda of FlexFormattingContext::determine_flex_base_size.
func layout_flex_formatting_context_flex_basis_is_definite(this: LayoutFlexFormattingContext*, flex_basis: CssFlexBasis) -> bool:
    let size = layout_flex_formatting_context_flex_basis_size(flex_basis) else return false
    if css_size_is_auto(&size) or css_size_is_none(&size) or css_size_is_intrinsic_sizing_constraint(&size):
        return false
    if css_size_is_length(&size):
        return true

    let can_resolve_percentages = layout_state_used_values_has_definite_width(this.m_flex_container_state) if layout_flex_formatting_context_main_axis_is_horizontal(this) else layout_state_used_values_has_definite_height(this.m_flex_container_state)

    if css_size_is_calculated(&size):
        let calc_value = css_size_calculated(&size)
        if css_calculated_style_value_resolves_to_percentage(calc_value):
            return can_resolve_percentages
        if css_calculated_style_value_resolves_to_length(calc_value):
            if css_calculated_style_value_contains_percentage(calc_value):
                return can_resolve_percentages
            return true
        return false
    assert(css_size_is_percentage(&size))
    return can_resolve_percentages

## The lambda of FlexFormattingContext::determine_flex_base_size that answers the item's flex base size (it also
## records the item's used flex basis and whether it is definite).
func layout_flex_formatting_context_flex_base_size_of_item(this: LayoutFlexFormattingContext*, item: LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels:
    let used_flex_basis = layout_flex_formatting_context_used_flex_basis_for_item(this, item)
    item.used_flex_basis = used_flex_basis

    item.used_flex_basis_is_definite = layout_flex_formatting_context_flex_basis_is_definite(this, used_flex_basis)

    # A. If the item has a definite used flex basis, that’s the flex base size.
    if item.used_flex_basis_is_definite:
        let size = layout_flex_formatting_context_flex_basis_size(used_flex_basis) else trap("VERIFY: a definite flex basis is a size")
        if layout_flex_formatting_context_main_axis_is_horizontal(this):
            return layout_flex_formatting_context_get_pixel_width(this, item, size)
        return layout_flex_formatting_context_get_pixel_height(this, item, size)

    let available_space_for_items = layout_flex_formatting_context_available_space_for_items(this)

    # AD-HOC: If we're sizing the flex container under a min-content constraint in the main axis,
    #         non-replaced flex items resolve percentages in the main axis to 0.
    # https://drafts.csswg.org/css-sizing-3/#cyclic-percentage-contribution
    let computed_main_size = layout_flex_formatting_context_computed_main_size(this, item.box)
    if layout_node_is_replaced_box(item.box.layout_node()) and layout_available_size_is_min_content(&available_space_for_items.main) and css_size_contains_percentage(&computed_main_size):
        return layout_zero_px()

    # B. If the flex item has ...
    #    - an intrinsic aspect ratio,
    #    - a used flex basis of content, and
    #    - a definite cross size,
    if layout_box_has_preferred_aspect_ratio(item.box) and layout_flex_formatting_context_flex_basis_is_content(used_flex_basis) and layout_flex_formatting_context_has_definite_cross_size_layout_flex_formatting_context(this, item):
        # flex_base_size is calculated from definite cross size and intrinsic aspect ratio

        # AD-HOC: Mark that we resolved the main size from the aspect ratio,
        #         so that we can mark the item as having definite main size after resolving flexible lengths.
        item.main_size_was_resolved_from_aspect_ratio = true

        let aspect_ratio = layout_box_preferred_aspect_ratio(item.box) else trap("VERIFY: the box has a preferred aspect ratio")
        return layout_flex_formatting_context_adjust_main_size_through_aspect_ratio_for_cross_size_min_max_constraints(
            this,
            item.box,
            layout_flex_formatting_context_calculate_main_size_from_cross_size_and_aspect_ratio(this, layout_flex_formatting_context_inner_cross_size_layout_flex_formatting_context(this, item), aspect_ratio),
            layout_flex_formatting_context_computed_cross_min_size(this, item.box),
            layout_flex_formatting_context_computed_cross_max_size(this, item.box),
        )

    # C. If the used flex basis is content or depends on its available space,
    #    and the flex container is being sized under a min-content or max-content constraint
    #    (e.g. when performing automatic table layout [CSS21]), size the item under that constraint.
    #    The flex base size is the item’s resulting main size.
    if layout_flex_formatting_context_flex_basis_is_content(used_flex_basis) and layout_available_size_is_intrinsic_sizing_constraint(&available_space_for_items.main):
        if layout_available_size_is_min_content(&available_space_for_items.main):
            return layout_flex_formatting_context_calculate_min_content_main_size(this, item)
        return layout_flex_formatting_context_calculate_max_content_main_size(this, item)

    # D. Otherwise, if the used flex basis is content or depends on its available space,
    #    the available main size is infinite, and the flex item’s inline axis is parallel to the main axis,
    #    lay the item out using the rules for a box in an orthogonal flow [CSS3-WRITING-MODES].
    #    The flex base size is the item’s max-content main size.
    # if (item.used_flex_basis->has<CSS::FlexBasisContent>()
    #     // FIXME: && main_size is infinite && inline axis is parallel to the main axis
    #     && false && false) {
    #     TODO();
    #     // Use rules for a flex_container in orthogonal flow
    # }

    # E. Otherwise, size the item into the available space using its used flex basis in place of its main size,
    #    treating a value of content as max-content. If a cross size is needed to determine the main size
    #    (e.g. when the flex item’s main size is in its block axis) and the flex item’s cross size is auto and not definite,
    #    in this calculation use fit-content as the flex item’s cross size.
    #    The flex base size is the item’s resulting main size.

    if let size = layout_flex_formatting_context_flex_basis_size(used_flex_basis):
        if css_size_is_fit_content(&size):
            return layout_flex_formatting_context_calculate_fit_content_main_size(this, item)
        if css_size_is_max_content(&size):
            return layout_flex_formatting_context_calculate_max_content_main_size(this, item)
        if css_size_is_min_content(&size):
            return layout_flex_formatting_context_calculate_min_content_main_size(this, item)

    # NOTE: If the flex item has a definite main size, just use that as the flex base size.
    if layout_flex_formatting_context_has_definite_main_size_layout_flex_formatting_context(this, item):
        return layout_flex_formatting_context_inner_main_size_layout_flex_formatting_context(this, item)

    # NOTE: There's a fundamental problem with many CSS specifications in that they neglect to mention
    #       which width to provide when calculating the intrinsic height of a box in various situations.
    #       Spec bug: https://github.com/w3c/csswg-drafts/issues/2890

    # NOTE: This is one of many situations where that causes trouble: if this is a flex column layout,
    #       we may need to calculate the intrinsic height of a flex item. This requires a width, but a
    #       width won't be determined until later on in the flex layout algorithm.
    #       In the specific case above (E), the spec mentions using `fit-content` in place of `auto`
    #       if "a cross size is needed to determine the main size", so that's exactly what we do.

    # NOTE: Finding a suitable width for intrinsic height determination actually happens elsewhere,
    #       in the various helpers that calculate the intrinsic sizes of a flex item,
    #       e.g. calculate_min_content_main_size().

    if layout_flex_formatting_context_flex_basis_is_content(used_flex_basis):
        return layout_flex_formatting_context_calculate_max_content_main_size(this, item)

    return layout_flex_formatting_context_calculate_fit_content_main_size(this, item)

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:656 Web::Layout::FlexFormattingContext::determine_flex_base_size.
# https://drafts.csswg.org/css-flexbox-1/#algo-main-item
func layout_flex_formatting_context_determine_flex_base_size(this: LayoutFlexFormattingContext*, item: LayoutFlexFormattingContextFlexItem*):
    let child_box = item.box

    item.flex_base_size = layout_flex_formatting_context_flex_base_size_of_item(this, item)

    # AD-HOC: This is not mentioned in the spec, but if the item has an aspect ratio, we may need
    #         to adjust the main size in these ways:
    #         - using stretch-fit main size if the flex basis is indefinite, there is no
    #           intrinsic size and no cross size to resolve the ratio against.
    #         - in response to cross size min/max constraints.
    let auto_size = layout_box_auto_content_box_size(item.box)
    if css_size_with_aspect_ratio_has_aspect_ratio(&auto_size):
        if not item.used_flex_basis_is_definite and not css_size_with_aspect_ratio_has_width(&auto_size) and not css_size_with_aspect_ratio_has_height(&auto_size) and not layout_flex_formatting_context_has_definite_cross_size_layout_flex_formatting_context(this, item):
            item.flex_base_size = layout_flex_formatting_context_inner_main_size_layout_state_used_values(this, this.m_flex_container_state)
        item.flex_base_size = layout_flex_formatting_context_adjust_main_size_through_aspect_ratio_for_cross_size_min_max_constraints(this, child_box, item.flex_base_size, layout_flex_formatting_context_computed_cross_min_size(this, child_box), layout_flex_formatting_context_computed_cross_max_size(this, child_box))

    # NOTE: We don't clamp the main size until we have them for all items.

# mark: The automatic minimum size ==============================================================

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:805 Web::Layout::FlexFormattingContext::automatic_minimum_size.
# https://drafts.csswg.org/css-flexbox-1/#min-size-auto
func layout_flex_formatting_context_automatic_minimum_size(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels:
    # To provide a more reasonable default minimum size for flex items,
    # the used value of a main axis automatic minimum size on a flex item that is not a scroll container is its content-based minimum size;
    # for scroll containers the automatic minimum size is zero, as usual.
    if not layout_node_with_style_is_scroll_container(item.box.layout_node_with_style()):
        return layout_flex_formatting_context_content_based_minimum_size(this, item)
    return layout_zero_px()

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:816 Web::Layout::FlexFormattingContext::specified_size_suggestion.
# https://drafts.csswg.org/css-flexbox-1/#specified-size-suggestion
func layout_flex_formatting_context_specified_size_suggestion(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels?:
    # If the item’s preferred main size is definite and not automatic,
    # then the specified size suggestion is that size. It is otherwise undefined.
    if layout_flex_formatting_context_has_definite_main_size_layout_flex_formatting_context(this, item) and not layout_flex_formatting_context_should_treat_main_size_as_auto(this, item.box):
        # NOTE: We use get_pixel_{width,height} to ensure that CSS box-sizing is respected.
        if layout_flex_formatting_context_main_axis_is_horizontal(this):
            return layout_flex_formatting_context_get_pixel_width(this, item, layout_flex_formatting_context_computed_main_size(this, item.box))
        return layout_flex_formatting_context_get_pixel_height(this, item, layout_flex_formatting_context_computed_main_size(this, item.box))
    return none

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:828 Web::Layout::FlexFormattingContext::content_size_suggestion.
# https://drafts.csswg.org/css-flexbox-1/#content-size-suggestion
func layout_flex_formatting_context_content_size_suggestion(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels:
    var suggestion = layout_flex_formatting_context_calculate_min_content_main_size(this, item)

    if layout_box_has_preferred_aspect_ratio(item.box):
        suggestion = layout_flex_formatting_context_adjust_main_size_through_aspect_ratio_for_cross_size_min_max_constraints(this, item.box, suggestion, layout_flex_formatting_context_computed_cross_min_size(this, item.box), layout_flex_formatting_context_computed_cross_max_size(this, item.box))

    return suggestion

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:840 Web::Layout::FlexFormattingContext::transferred_size_suggestion.
# https://drafts.csswg.org/css-flexbox-1/#transferred-size-suggestion
func layout_flex_formatting_context_transferred_size_suggestion(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels?:
    # If the item has a preferred aspect ratio and its preferred cross size is definite,
    # then the transferred size suggestion is that size
    # (clamped by its minimum and maximum cross sizes if they are definite), converted through the aspect ratio.
    if layout_box_has_preferred_aspect_ratio(item.box) and layout_flex_formatting_context_has_definite_cross_size_layout_flex_formatting_context(this, item):
        let aspect_ratio = layout_box_preferred_aspect_ratio(item.box) else trap("VERIFY: the box has a preferred aspect ratio")
        return layout_flex_formatting_context_adjust_main_size_through_aspect_ratio_for_cross_size_min_max_constraints(
            this,
            item.box,
            layout_flex_formatting_context_calculate_main_size_from_cross_size_and_aspect_ratio(this, layout_flex_formatting_context_inner_cross_size_layout_flex_formatting_context(this, item), aspect_ratio),
            layout_flex_formatting_context_computed_cross_min_size(this, item.box),
            layout_flex_formatting_context_computed_cross_max_size(this, item.box),
        )

    # It is otherwise undefined.
    return none

## The `unclamped_size` lambda of FlexFormattingContext::content_based_minimum_size.
func layout_flex_formatting_context_unclamped_content_based_minimum_size(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels:
    # The content-based minimum size of a flex item differs depending on whether the flex item is replaced or not:
    # -> For replaced elements
    if layout_node_is_replaced_box(item.box.layout_node()):
        # Use the smaller of the content size suggestion and the transferred size suggestion (if one exists),
        # capped by the specified size suggestion (if one exists).
        var replaced_size = layout_flex_formatting_context_content_size_suggestion(this, item)
        if let transferred_size_suggestion = layout_flex_formatting_context_transferred_size_suggestion(this, item):
            replaced_size = ak.min(replaced_size, transferred_size_suggestion)
        if let specified_size_suggestion = layout_flex_formatting_context_specified_size_suggestion(this, item):
            replaced_size = ak.min(replaced_size, specified_size_suggestion)
        return replaced_size

    # -> For non-replaced elements
    # Use the larger of the content size suggestion and the transferred size suggestion (if one exists),
    # capped by the specified size suggestion (if one exists).
    var size = layout_flex_formatting_context_content_size_suggestion(this, item)
    if let transferred_size_suggestion = layout_flex_formatting_context_transferred_size_suggestion(this, item):
        size = ak.max(size, transferred_size_suggestion)
    if let specified_size_suggestion = layout_flex_formatting_context_specified_size_suggestion(this, item):
        size = ak.min(size, specified_size_suggestion)
    return size

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:859 Web::Layout::FlexFormattingContext::content_based_minimum_size.
# https://drafts.csswg.org/css-flexbox-1/#content-based-minimum-size
func layout_flex_formatting_context_content_based_minimum_size(this: LayoutFlexFormattingContext*, item: const LayoutFlexFormattingContextFlexItem*) -> gfx.CssPixels:
    let unclamped_size = layout_flex_formatting_context_unclamped_content_based_minimum_size(this, item)

    # In either case, the size is clamped by the maximum main size if it’s definite.
    if layout_flex_formatting_context_has_main_max_size(this, item.box):
        return ak.min(unclamped_size, layout_flex_formatting_context_specified_main_max_size(this, item))
    return unclamped_size

# mark: Flex lines ==============================================================================

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:900 Web::Layout::FlexFormattingContext::collect_flex_items_into_flex_lines.
# https://www.w3.org/TR/css-flexbox-1/#algo-line-break
func layout_flex_formatting_context_collect_flex_items_into_flex_lines(this: LayoutFlexFormattingContext*):
    let items = ak.vector_span(&this.m_flex_items)

    # If the flex container is single-line, collect all the flex items into a single flex line.
    if layout_flex_formatting_context_is_single_line(this):
        var single_line = LayoutFlexFormattingContextFlexLine()
        for single_line_item in &items:
            if layout_flex_formatting_context_is_direction_reverse(this):
                ak.vector_prepend_u(&single_line.items, single_line_item)
            else:
                ak.vector_append_t(&single_line.items, single_line_item)
        ak.vector_append_t(&this.m_flex_lines, single_line)
        return

    # Otherwise, starting from the first uncollected item, collect consecutive items one by one
    # until the first time that the next collected item would not fit into the flex container’s inner main size
    # (or until a forced break is encountered, see §10 Fragmenting Flex Layout).
    # If the very first uncollected item wouldn't fit, collect just it into the line.

    # For this step, the size of a flex item is its outer hypothetical main size. (Note: This can be negative.)

    # Repeat until all flex items have been collected into flex lines.

    let available_main = layout_flex_formatting_context_available_space_for_items(this).main
    var line = LayoutFlexFormattingContextFlexLine()
    var line_main_size = layout_zero_px()
    for item in &items:
        let outer_hypothetical_main_size = layout_flex_formatting_context_flex_item_outer_hypothetical_main_size(item)
        if not ak.vector_is_empty(&line.items) and layout_gt(line_main_size.add(outer_hypothetical_main_size), available_main):
            ak.vector_append_t(&this.m_flex_lines, line)
            line = LayoutFlexFormattingContextFlexLine()
            line_main_size = layout_zero_px()

        if layout_flex_formatting_context_is_direction_reverse(this):
            ak.vector_prepend_u(&line.items, item)
        else:
            ak.vector_append_t(&line.items, item)

        line_main_size = line_main_size.add(outer_hypothetical_main_size)
        # CSS-FLEXBOX-2: Account for gap between flex items.
        line_main_size = line_main_size.add(layout_flex_formatting_context_main_gap(this))
    ak.vector_append_t(&this.m_flex_lines, line)

# mark: Flexible lengths ========================================================================

## Resolving the flexible lengths of a line: the factor FlexFormattingContext::resolve_flexible_lengths_for_line's
## local `enum FlexFactor` names (the flex grow or the flex shrink factor).
enum LayoutFlexFormattingContextFlexFactor:
    flex_grow_factor
    flex_shrink_factor

## The `calculate_remaining_free_space` lambda of FlexFormattingContext::resolve_flexible_lengths_for_line.
func layout_flex_formatting_context_calculate_remaining_free_space(this: LayoutFlexFormattingContext*, line: const LayoutFlexFormattingContextFlexLine*, available_main_size: LayoutAvailableSize) -> gfx.CssPixels?:
    # AD-HOC: If the container is sized under max-content constraints, then remaining_free_space won't have
    #         a value to avoid leaking an infinite value into layout calculations.
    if layout_available_size_is_intrinsic_sizing_constraint(&available_main_size):
        return none
    var sum = layout_zero_px()
    for item in ak.vector_span_const(&line.items):
        if item.frozen:
            sum = sum.add(layout_flex_formatting_context_flex_item_outer_target_main_size(item))
        else:
            sum = sum.add(layout_flex_formatting_context_flex_item_outer_flex_base_size(item))
    # CSS-FLEXBOX-2: Account for gap between flex items.
    sum = sum.add(layout_flex_formatting_context_mul_count(layout_flex_formatting_context_main_gap(this), ak.vector_size(&line.items) -% 1))

    # AD-HOC: Note that we're using our own "available main size" explained above
    #         instead of the flex container’s inner main size.
    return layout_available_size_to_px_or_zero(&available_main_size).sub(sum)

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:949 Web::Layout::FlexFormattingContext::resolve_flexible_lengths_for_line.
# https://drafts.csswg.org/css-flexbox-1/#resolve-flexible-lengths
func layout_flex_formatting_context_resolve_flexible_lengths_for_line(this: LayoutFlexFormattingContext*, line: LayoutFlexFormattingContextFlexLine*):
    # AD-HOC: The spec tells us to use the "flex container’s inner main size" in this algorithm,
    #         but that doesn't work when we're sizing under a max-content constraint.
    #         In that case, there is effectively infinite size available in the main axis,
    #         but the inner main size has not been assigned yet.
    #         We solve this by calculating our own "available main size" here, which is essentially
    #         infinity under max-content, 0 under min-content, and the inner main size otherwise.
    var available_main_size = layout_available_size_make_indefinite()
    let available_space_for_items = layout_flex_formatting_context_available_space_for_items(this)
    if layout_available_size_is_intrinsic_sizing_constraint(&available_space_for_items.main):
        available_main_size = available_space_for_items.main
    else:
        available_main_size = layout_available_size_make_definite(layout_flex_formatting_context_inner_main_size_layout_state_used_values(this, this.m_flex_container_state))

    let items = ak.vector_span(&line.items)

    # 1. Determine the used flex factor.

    # Sum the outer hypothetical main sizes of all items on the line.
    # If the sum is less than the flex container’s inner main size,
    # use the flex grow factor for the rest of this algorithm; otherwise, use the flex shrink factor
    var sum_of_outer_hypothetical_main_sizes = layout_zero_px()
    for hypothetical_item in items:
        sum_of_outer_hypothetical_main_sizes = sum_of_outer_hypothetical_main_sizes.add(layout_flex_formatting_context_flex_item_outer_hypothetical_main_size(hypothetical_item))
    # CSS-FLEXBOX-2: Account for gap between flex items.
    sum_of_outer_hypothetical_main_sizes = sum_of_outer_hypothetical_main_sizes.add(layout_flex_formatting_context_mul_count(layout_flex_formatting_context_main_gap(this), items.length -% 1))
    # AD-HOC: Note that we're using our own "available main size" explained above
    #         instead of the flex container’s inner main size.
    let used_flex_factor = LayoutFlexFormattingContextFlexFactor.flex_grow_factor if layout_lt_css_pixels(sum_of_outer_hypothetical_main_sizes, available_main_size) else LayoutFlexFormattingContextFlexFactor.flex_shrink_factor

    # 2. Each item in the flex line has a target main size, initially set to its flex base size.
    #    Each item is initially unfrozen and may become frozen.
    for target_item in items:
        target_item.target_main_size = target_item.flex_base_size
        target_item.frozen = false

    # 3. Size inflexible items.

    for inflexible_item in items:
        let computed_values = layout_box_computed(inflexible_item.box)
        if used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_grow_factor:
            inflexible_item.flex_factor = (f64)css_computed_values_flex_grow(computed_values)
        elif used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_shrink_factor:
            inflexible_item.flex_factor = (f64)css_computed_values_flex_shrink(computed_values)
        # Freeze, setting its target main size to its hypothetical main size…
        # - any item that has a flex factor of zero
        # - if using the flex grow factor: any item that has a flex base size greater than its hypothetical main size
        # - if using the flex shrink factor: any item that has a flex base size smaller than its hypothetical main size
        let flex_factor = inflexible_item.flex_factor else trap("VERIFY: the item has a flex factor")
        if flex_factor == 0.0 or (used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_grow_factor and inflexible_item.flex_base_size.gt(inflexible_item.hypothetical_main_size)) or (used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_shrink_factor and inflexible_item.flex_base_size.lt(inflexible_item.hypothetical_main_size)):
            inflexible_item.frozen = true
            inflexible_item.target_main_size = inflexible_item.hypothetical_main_size

    # 4. Calculate initial free space

    # Sum the outer sizes of all items on the line, and subtract this from the flex container’s inner main size.
    # For frozen items, use their outer target main size; for other items, use their outer flex base size.
    # (calculate_remaining_free_space is layout_flex_formatting_context_calculate_remaining_free_space.)
    let initial_free_space = layout_flex_formatting_context_calculate_remaining_free_space(this, line, available_main_size)

    # 5. Loop
    while true:
        # a. Check for flexible items.
        #    If all the flex items on the line are frozen, exit this loop.
        var all_frozen = true
        for frozen_item in items:
            if not frozen_item.frozen:
                all_frozen = false
                break
        if all_frozen:
            break

        # b. Calculate the remaining free space as for initial free space, above.
        line.remaining_free_space = layout_flex_formatting_context_calculate_remaining_free_space(this, line, available_main_size)

        # If the sum of the unfrozen flex items’ flex factors is less than one, multiply the initial free space by this sum.
        let sum_of_flex_factor_of_unfrozen_items = layout_flex_formatting_context_flex_line_sum_of_flex_factor_of_unfrozen_items(line)
        if sum_of_flex_factor_of_unfrozen_items < 1.0 and initial_free_space != none:
            let initial = initial_free_space else trap("unreachable: the initial free space has a value")
            let value = gfx.css_pixels_nearest_value_for_f64(gfx.mul_css_pixels_f64(initial, sum_of_flex_factor_of_unfrozen_items))
            # If the magnitude of this value is less than the magnitude of the remaining free space, use this as the remaining free space.
            let remaining = line.remaining_free_space else trap("VERIFY: the remaining free space has a value")
            if value.abs().lt(remaining.abs()):
                line.remaining_free_space = value

        # AD-HOC: We allow the remaining free space to be infinite, but we can't let infinity
        #         leak into the layout geometry, so we treat infinity as zero when used in arithmetic.
        let remaining_free_space_or_zero_if_infinite = line.remaining_free_space else layout_zero_px()

        # c. If the remaining free space is non-zero, distribute it proportional to the flex factors:
        # (`line.remaining_free_space != 0`: an empty Optional is not equal to zero.)
        var remaining_free_space_is_zero = false
        if let remaining_free_space = line.remaining_free_space:
            remaining_free_space_is_zero = gfx.eq_css_pixels_int(remaining_free_space, 0)
        if not remaining_free_space_is_zero:
            # If using the flex grow factor
            if used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_grow_factor:
                # For every unfrozen item on the line,
                # find the ratio of the item’s flex grow factor to the sum of the flex grow factors of all unfrozen items on the line.
                let sum_of_flex_grow_factors = layout_flex_formatting_context_flex_line_sum_of_flex_factor_of_unfrozen_items(line)
                for growing_item in items:
                    if growing_item.frozen:
                        continue
                    let ratio = (growing_item.flex_factor else trap("VERIFY: the item has a flex factor")) / sum_of_flex_grow_factors
                    # Set the item’s target main size to its flex base size plus a fraction of the remaining free space proportional to the ratio.
                    growing_item.target_main_size = growing_item.flex_base_size.add(gfx.css_pixels_scaled_f64(&remaining_free_space_or_zero_if_infinite, ratio))
            # If using the flex shrink factor
            elif used_flex_factor == LayoutFlexFormattingContextFlexFactor.flex_shrink_factor:
                # For every unfrozen item on the line, multiply its flex shrink factor by its inner flex base size, and note this as its scaled flex shrink factor.
                for scaled_item in items:
                    if scaled_item.frozen:
                        continue
                    scaled_item.scaled_flex_shrink_factor = (scaled_item.flex_factor else trap("VERIFY: the item has a flex factor")) * scaled_item.flex_base_size.to_double()
                let sum_of_scaled_flex_shrink_factors_of_all_unfrozen_items_on_line = layout_flex_formatting_context_flex_line_sum_of_scaled_flex_shrink_factor_of_unfrozen_items(line)
                for shrinking_item in items:
                    if shrinking_item.frozen:
                        continue
                    # Find the ratio of the item’s scaled flex shrink factor to the sum of the scaled flex shrink factors of all unfrozen items on the line.
                    var ratio = 1.0
                    if sum_of_scaled_flex_shrink_factors_of_all_unfrozen_items_on_line != 0.0:
                        ratio = shrinking_item.scaled_flex_shrink_factor / sum_of_scaled_flex_shrink_factors_of_all_unfrozen_items_on_line

                    # Set the item’s target main size to its flex base size minus a fraction of the absolute value of the remaining free space proportional to the ratio.
                    # (Note this may result in a negative inner main size; it will be corrected in the next step.)
                    let absolute_remaining_free_space = remaining_free_space_or_zero_if_infinite.abs()
                    shrinking_item.target_main_size = shrinking_item.flex_base_size.sub(gfx.css_pixels_scaled_f64(&absolute_remaining_free_space, ratio))

        # d. Fix min/max violations.
        var total_violation = layout_zero_px()

        # Clamp each non-frozen item’s target main size by its used min and max main sizes and floor its content-box size at zero.
        for clamped_item in items:
            if clamped_item.frozen:
                continue
            let used_min_main_size = layout_flex_formatting_context_specified_main_min_size(this, clamped_item) if layout_flex_formatting_context_has_main_min_size(this, clamped_item.box) else layout_flex_formatting_context_automatic_minimum_size(this, clamped_item)

            let used_max_main_size = layout_flex_formatting_context_specified_main_max_size(this, clamped_item) if layout_flex_formatting_context_has_main_max_size(this, clamped_item.box) else gfx.css_pixels_max()

            let original_target_main_size = clamped_item.target_main_size
            clamped_item.target_main_size = layout_css_clamp(clamped_item.target_main_size, used_min_main_size, used_max_main_size)
            clamped_item.target_main_size = ak.max(clamped_item.target_main_size, layout_zero_px())

            # If the item’s target main size was made smaller by this, it’s a max violation.
            if clamped_item.target_main_size.lt(original_target_main_size):
                clamped_item.is_max_violation = true

            # If the item’s target main size was made larger by this, it’s a min violation.
            if clamped_item.target_main_size.gt(original_target_main_size):
                clamped_item.is_min_violation = true

            total_violation = total_violation.add(clamped_item.target_main_size.sub(original_target_main_size))

        # e. Freeze over-flexed items.
        #    The total violation is the sum of the adjustments from the previous step ∑(clamped size - unclamped size).

        # If the total violation is:
        # Zero
        #   Freeze all items.
        if gfx.eq_css_pixels_int(total_violation, 0):
            for zero_violation_item in items:
                if not zero_violation_item.frozen:
                    zero_violation_item.frozen = true
        # Positive
        #   Freeze all the items with min violations.
        elif gfx.gt_css_pixels_int(total_violation, 0):
            for min_violation_item in items:
                if not min_violation_item.frozen and min_violation_item.is_min_violation:
                    min_violation_item.frozen = true
        # Negative
        #   Freeze all the items with max violations.
        else:
            for max_violation_item in items:
                if not max_violation_item.frozen and max_violation_item.is_max_violation:
                    max_violation_item.frozen = true
        # NOTE: This freezes at least one item, ensuring that the loop makes progress and eventually terminates.

        # f. Return to the start of this loop.

    # NOTE: Calculate the remaining free space once again here, since it's needed later when aligning items.
    line.remaining_free_space = layout_flex_formatting_context_calculate_remaining_free_space(this, line, available_main_size)

    # 6. Set each item’s used main size to its target main size.
    let flex_container = layout_flex_formatting_context_flex_container(this)
    for used_item in items:
        used_item.main_size = used_item.target_main_size
        layout_flex_formatting_context_set_main_size_layout_flex_formatting_context(this, used_item, used_item.target_main_size)

        # https://drafts.csswg.org/css-flexbox-1/#definite-sizes
        # 1. If the flex container has a definite main size, then the post-flexing main sizes of its flex items are treated as definite.
        # 2. If a flex item’s flex basis is definite, then its post-flexing main size is also definite.
        # AD-HOC: 3. If a flex item’s main size was resolved from its intrinsic aspect ratio, then its post-flexing main size is also definite.
        let item_is_orthogonal = layout_flex_formatting_context_inline_axis_is_horizontal(this, used_item.box) != layout_flex_formatting_context_inline_axis_is_horizontal(this, flex_container)
        let flex_container_has_vertical_inline_main_axis = layout_flex_formatting_context_is_row_layout(this) and not layout_flex_formatting_context_inline_axis_is_horizontal(this, flex_container)
        if layout_flex_formatting_context_has_definite_main_size_layout_state_used_values(this, this.m_flex_container_state) or used_item.used_flex_basis_is_definite or used_item.main_size_was_resolved_from_aspect_ratio or flex_container_has_vertical_inline_main_axis or (item_is_orthogonal and layout_flex_formatting_context_main_axis_is_parallel_to_inline_axis(this, used_item.box)):
            layout_flex_formatting_context_set_has_definite_main_size(this, used_item)

## Ported from Libraries/LibWeb/Layout/FlexFormattingContext.cpp:1187 Web::Layout::FlexFormattingContext::resolve_flexible_lengths.
# https://drafts.csswg.org/css-flexbox-1/#resolve-flexible-lengths
func layout_flex_formatting_context_resolve_flexible_lengths(this: LayoutFlexFormattingContext*):
    let lines = ak.vector_span(&this.m_flex_lines)
    for line in &lines:
        layout_flex_formatting_context_resolve_flexible_lengths_for_line(this, line)