Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_element_4.lucb

#==============================================================================================
#
#   html_element_4 - HTML::HTMLElement: hiding and toggling popovers, popover lists and the
#                    topmost popover ancestor
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLElement.cpp (lines 1386-1815): hidePopover() and the hide
#       popover algorithm, togglePopover(), hide all popovers until, hide popover stack until,
#       close entire popover list and the topmost popover ancestor algorithm (its checkAncestor
#       lambda is a function over a capture struct). The popover lists are passed by pointer, as
#       C++ passes them by reference: hiding a popover removes it from the very list the loops
#       read.
#
#==============================================================================================

# mark: Hiding a popover ========================================================================

## Ported from HTMLElement.cpp:1388 Web::HTML::HTMLElement::hide_popover_for_bindings.
# https://html.spec.whatwg.org/multipage/popover.html#dom-hidepopover
# https://whatpr.org/html/9457/popover.html#dom-hidepopover
pub func html_element_hide_popover_for_bindings(this: HtmlElement*) -> !:
    # The hidePopover() method steps are to run the hide popover algorithm given this, true, true, true, false, and null.
    try html_element_hide_popover(this, HtmlFocusPreviousElement.yes, HtmlFireEvents.yes, HtmlThrowExceptions.yes, HtmlIgnoreDomState.no, none)

## hide_popover's cleanupSteps: `[&nested_hide, this] {...}`.
func html_element_hide_popover_cleanup_steps(this: HtmlElement*, nested_hide: bool):
    # 6.1. If nestedHide is false, then set element's popover showing or hiding to false.
    # donor quirk: the C++ tests `if (nested_hide)`, the opposite of the step it quotes.
    if nested_hide:
        this.m_popover_showing_or_hiding = false
    # 6.2. If element's popover close watcher is not null, then:
    if let close_watcher = this.m_popover_close_watcher:
        # 6.2.1. Destroy element's popover close watcher.
        html_close_watcher_destroy(close_watcher)
        # 6.2.2. Set element's popover close watcher to null.
        this.m_popover_close_watcher = none

## Ported from HTMLElement.cpp:1397 Web::HTML::HTMLElement::hide_popover.
# https://html.spec.whatwg.org/multipage/popover.html#hide-popover-algorithm
# https://whatpr.org/html/9457/popover.html#hide-popover-algorithm
pub func html_element_hide_popover(this: HtmlElement*, focus_previous_element: HtmlFocusPreviousElement, fire_events_argument: HtmlFireEvents, throw_exceptions: HtmlThrowExceptions, ignore_dom_state: HtmlIgnoreDomState, source: HtmlElement*?) -> !:
    var fire_events = fire_events_argument

    # 1. If the result of running check popover validity given element, true, throwExceptions, null and ignoreDomState is false, then return.
    if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.yes, throw_exceptions, none, ignore_dom_state):
        return

    # 2. Let document be element's node document.
    let document = html_element_document(this)

    # 3. Let nestedHide be element's popover showing or hiding.
    let nested_hide = this.m_popover_showing_or_hiding

    # 4. Set element's popover showing or hiding to true.
    this.m_popover_showing_or_hiding = true

    # 5. If nestedHide is true, then set fireEvents to false.
    if nested_hide:
        fire_events = HtmlFireEvents.no

    # 6. Let cleanupSteps be the following steps: (html_element_hide_popover_cleanup_steps)

    # 7. If element's opened in popover mode is "auto" or "hint", then:
    if html_element_optional_is_auto_or_hint(this.m_opened_in_popover_mode):
        # 7.1. Run hide all popovers until given element, focusPreviousElement, and fireEvents.
        html_element_hide_all_popovers_until(.html_element(this), focus_previous_element, fire_events)

        # 7.2. If the result of running check popover validity given element, true, throwExceptions, and ignoreDomState is false, then run cleanupSteps and return.
        if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.yes, throw_exceptions, none, ignore_dom_state):
            html_element_hide_popover_cleanup_steps(this, nested_hide)
            return
    # 8. Let autoPopoverListContainsElement be true if document's showing auto popover list's last item is element, otherwise false.
    let showing_popovers = dom_document_showing_auto_popover_list(document)
    let auto_popover_list_contains_element = html_element_list_ends_with(showing_popovers, this)

    # 9. If fireEvents is true:
    if fire_events == HtmlFireEvents.yes:
        # 1. Fire an event named beforetoggle, using ToggleEvent, with the oldState attribute initialized to "open",
        #    the newState attribute initialized to "closed", and the source attribute set to source at element.
        var event_init = HtmlToggleEventInit()
        event_init.old_state = ak.string_from_str("open")
        event_init.new_state = ak.string_from_str("closed")
        if let source_element = source:
            event_init.source = source_element.dom_element()
        _ = dom_event_target_dispatch_event(this.dom_event_target(), html_toggle_event_create(html_element_realm(this), html_event_names_beforetoggle, event_init).dom_event())

        # 2. If autoPopoverListContainsElement is true and document's showing auto popover list's last item is not
        #    element, then run hide all popovers until given element, focusPreviousElement, and false.
        if auto_popover_list_contains_element and not html_element_list_ends_with(showing_popovers, this):
            html_element_hide_all_popovers_until(.html_element(this), focus_previous_element, HtmlFireEvents.no)

        # 3. If the result of running check popover validity given element, true, throwExceptions, null, and
        #    ignoreDomState is false, then run cleanupSteps and return.
        if not try html_element_check_popover_validity(this, HtmlExpectedToBeShowing.yes, throw_exceptions, none, ignore_dom_state):
            html_element_hide_popover_cleanup_steps(this, nested_hide)
            return
        # 9.4. Request an element to be removed from the top layer given element.
        dom_document_request_an_element_to_be_remove_from_the_top_layer(document, this.dom_element())
    # 10. Otherwise, remove an element from the top layer immediately given element.
    else:
        dom_document_remove_an_element_from_the_top_layer_immediately(document, this.dom_element())

    # AD-HOC: The following block of code is all ad-hoc.
    # Spec issue: https://github.com/whatwg/html/issues/11007

    # If element's opened in popover mode is "auto" or "hint":
    if html_element_optional_is_auto_or_hint(this.m_opened_in_popover_mode):
        # If document's showing hint popover list's last item is element:
        let hint_popovers = dom_document_showing_hint_popover_list(document)
        if html_element_list_ends_with(hint_popovers, this):
            # Assert: element's opened in popover mode is "hint".
            assert(html_element_optional_is(this.m_opened_in_popover_mode, "hint"))

            # Remove the last item from document's showing hint popover list.
            ak.vector_remove(hint_popovers, ak.vector_size(hint_popovers) - 1)
        # Otherwise:
        else:
            # Assert: document's showing auto popover list's last item is element.
            let auto_popovers = dom_document_showing_auto_popover_list(document)
            assert(html_element_list_ends_with(auto_popovers, this))

            # Remove the last item from document's showing auto popover list.
            ak.vector_remove(auto_popovers, ak.vector_size(auto_popovers) - 1)

    # 11. Set element's popover trigger to null.
    this.m_popover_trigger = none

    # 12. Set element's opened in popover mode to null.
    this.m_opened_in_popover_mode = none

    # 13. Set element's popover visibility state to hidden.
    this.m_popover_visibility_state = HtmlElementPopoverVisibilityState.hidden

    # 14. If fireEvents is true, then queue a popover toggle event task given element, "open", "closed", and source.
    if fire_events == HtmlFireEvents.yes:
        html_element_queue_a_popover_toggle_event_task(this, ak.string_from_str("open"), ak.string_from_str("closed"), source)

    # FIXME: 15. Let previouslyFocusedElement be element's previously focused element.

    # FIXME: 16. If previouslyFocusedElement is not null, then:
    # FIXME: 16.1. Set element's previously focused element to null.
    # FIXME: 16.2. If focusPreviousElement is true and document's focused area of the document's DOM anchor is a shadow-including inclusive descendant of element, then run the focusing steps for previouslyFocusedElement; the viewport should not be scrolled by doing this step.

    # 17. Run cleanupSteps.
    html_element_hide_popover_cleanup_steps(this, nested_hide)

## Ported from HTMLElement.cpp:1525 Web::HTML::HTMLElement::toggle_popover.
# https://html.spec.whatwg.org/multipage/popover.html#dom-togglepopover
# https://whatpr.org/html/9457/popover.html#dom-togglepopover
pub func html_element_toggle_popover(this: HtmlElement*, options: HtmlTogglePopoverOptionsOrForceBoolean) -> bool!:
    # 1. Let force be null.
    var force: bool? = none
    var source: HtmlElement*? = none

    # 2. If options is a boolean, set force to options.
    match options:
        .bool_(force_bool):
            force = force_bool
        .html_toggle_popover_options(toggle_options):
            # 3. Otherwise, if options["force"] exists, set force to options["force"].
            force = toggle_options.force
            # 4. Let source be options["source"] if it exists; otherwise, null.
            source = toggle_options.show_popover_options.source

    # 5. If this's popover visibility state is showing, and force is null or false, then run the hide popover algorithm given this, true, true, true, false, and null.
    if this.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing and (force == none or force == false):
        try html_element_hide_popover(this, HtmlFocusPreviousElement.yes, HtmlFireEvents.yes, HtmlThrowExceptions.yes, HtmlIgnoreDomState.no, none)
    # 6. Otherwise, if force is not present or true, then run show popover given this true, and source.
    elif force == none or force == true:
        try html_element_show_popover(this, HtmlThrowExceptions.yes, source)
    # 7. Otherwise:
    else:
        # 7.1 Let expectedToBeShowing be true if this's popover visibility state is showing; otherwise false.
        let expected_to_be_showing = HtmlExpectedToBeShowing.yes if this.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing else HtmlExpectedToBeShowing.no
        # 7.2 Run check popover validity given expectedToBeShowing, true, null, and false.
        _ = try html_element_check_popover_validity(this, expected_to_be_showing, HtmlThrowExceptions.yes, none, HtmlIgnoreDomState.no)
    # 8. Return true if this's popover visibility state is showing; otherwise false.
    return this.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing

# mark: Popover lists ===========================================================================

## Ported from HTMLElement.cpp:1563 Web::HTML::HTMLElement::hide_all_popovers_until.
# AD-HOC: This implementation checks "opened in popover mode" instead of the current popover state.
# Spec issue: https://github.com/whatwg/html/issues/10996.
# https://html.spec.whatwg.org/multipage/popover.html#hide-all-popovers-until
pub func html_element_hide_all_popovers_until(endpoint: HtmlElementOrDomDocument, focus_previous_element: HtmlFocusPreviousElement, fire_events: HtmlFireEvents):
    # To hide all popovers until, given an HTML element or Document endpoint, a boolean focusPreviousElement, and a boolean fireEvents:

    var endpoint_is_element = false
    var endpoint_element: HtmlElement*? = none
    var endpoint_document: DomDocument*? = none
    match endpoint:
        .html_element(element):
            endpoint_is_element = true
            endpoint_element = element
        .dom_document(document_or_none):
            endpoint_document = document_or_none

    # 1. If endpoint is an HTML element and endpoint is not in the popover showing state, then return.
    if endpoint_is_element and (endpoint_element else trap("VERIFY: GC::Ptr<HTMLElement>::operator-> on null")).m_popover_visibility_state != HtmlElementPopoverVisibilityState.showing:
        return

    # 2. Let document be endpoint's node document.
    let document_node = (endpoint_document else trap("VERIFY: GC::Ptr<Document>::operator-> on null")).dom_node() if not endpoint_is_element else (endpoint_element else trap("unreachable")).dom_node()
    let document = dom_node_document(document_node)

    # 3. Assert: endpoint is a Document or endpoint's popover visibility state is showing.
    assert(not endpoint_is_element or (endpoint_element else trap("unreachable")).m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing)

    # 4. Assert: endpoint is a Document or endpoint's popover attribute is in the auto state or endpoint's popover attribute is in the hint state.
    if endpoint_is_element:
        let element = endpoint_element else trap("unreachable")
        let mode = element.m_opened_in_popover_mode else trap("VERIFY: Optional::operator-> on an empty opened in popover mode")
        assert(ak.string_eq_string_view(&mode, ak.sv("auto")) or ak.string_eq_string_view(&mode, ak.sv("hint")))

    # 5. If endpoint is a Document:
    if not endpoint_is_element:
        # 1. Run close entire popover list given document's showing hint popover list, focusPreviousElement, and fireEvents.
        html_element_close_entire_popover_list(dom_document_showing_hint_popover_list(document), focus_previous_element, fire_events)

        # 2. Run close entire popover list given document's showing auto popover list, focusPreviousElement, and fireEvents.
        html_element_close_entire_popover_list(dom_document_showing_auto_popover_list(document), focus_previous_element, fire_events)

        # 3. Return.
        return

    # 6. If document's showing hint popover list contains endpoint:
    let element = endpoint_element else trap("unreachable")
    if html_element_list_contains(dom_document_showing_hint_popover_list(document), element):
        # 1. Assert: endpoint's popover attribute is in the hint state.
        assert(html_element_optional_is(element.m_opened_in_popover_mode, "hint"))

        # 2. Run hide popover stack until given endpoint, document's showing hint popover list, focusPreviousElement, and fireEvents.
        html_element_hide_popover_stack_until(element, dom_document_showing_hint_popover_list(document), focus_previous_element, fire_events)

        # 3. Return.
        return

    # 7. Run close entire popover list given document's showing hint popover list, focusPreviousElement, and fireEvents.
    html_element_close_entire_popover_list(dom_document_showing_hint_popover_list(document), focus_previous_element, fire_events)

    # 8. If document's showing auto popover list does not contain endpoint, then return.
    if not html_element_list_contains(dom_document_showing_auto_popover_list(document), element):
        return

    # 9. Run hide popover stack until given endpoint, document's showing auto popover list, focusPreviousElement, and fireEvents.
    html_element_hide_popover_stack_until(element, dom_document_showing_auto_popover_list(document), focus_previous_element, fire_events)

## Ported from HTMLElement.cpp:1626 Web::HTML::HTMLElement::hide_popover_stack_until.
# https://html.spec.whatwg.org/multipage/popover.html#hide-popover-stack-until
func html_element_hide_popover_stack_until(this: HtmlElement*, popover_list: const ak.Vector[HtmlElement*]*, focus_previous_element: HtmlFocusPreviousElement, fire_events_argument: HtmlFireEvents):
    var fire_events = fire_events_argument

    # To hide popover stack until, given an HTML element endpoint, a list popoverList, a boolean focusPreviousElement, and a boolean fireEvents:

    # 1. Let repeatingHide be false.
    var repeating_hide = false

    # 2. Perform the following steps at least once:
    while true:
        # 1. Let lastToHide be null.
        var last_to_hide: HtmlElement*? = none

        # 2. For each popover in popoverList:
        # AD-HOC: This needs to be iterated in reverse because step 4 hides items in reverse.
        var index = ak.vector_size(popover_list)
        while index > 0:
            index -= 1
            let popover = *ak.vector_at_const(popover_list, index)
            # 1. If popover is endpoint, then break.
            if popover == this:
                break

            # 2. Set lastToHide to popover.
            last_to_hide = popover

        # 3. If lastToHide is null, then return.
        let to_hide = last_to_hide else return

        # 4. While lastToHide's popover visibility state is showing:
        while to_hide.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing:
            # 1. Assert: popoverList is not empty.
            assert(not ak.vector_is_empty(popover_list))

            # 2. Run the hide popover algorithm given the last item in popoverList, focusPreviousElement, fireEvents, false, and null.
            html_element_hide_popover(*ak.vector_last_const(popover_list), focus_previous_element, fire_events, HtmlThrowExceptions.no, HtmlIgnoreDomState.no, none) else trap("MUST: hide_popover")

        # 5. Assert: repeatingHide is false or popoverList's last item is endpoint.
        assert(not repeating_hide or *ak.vector_last_const(popover_list) == this)

        # 6. Set repeatingHide to true if popoverList contains endpoint and popoverList's last item is not endpoint, otherwise false.
        repeating_hide = html_element_list_contains(popover_list, this) and *ak.vector_last_const(popover_list) != this

        # 7. If repeatingHide is true, then set fireEvents to false.
        if repeating_hide:
            fire_events = HtmlFireEvents.no

        # and keep performing them while repeatingHide is true.
        if not repeating_hide:
            break

## Ported from HTMLElement.cpp:1705 Web::HTML::HTMLElement::close_entire_popover_list.
# https://html.spec.whatwg.org/multipage/popover.html#close-entire-popover-list
func html_element_close_entire_popover_list(popover_list: const ak.Vector[HtmlElement*]*, focus_previous_element: HtmlFocusPreviousElement, fire_events: HtmlFireEvents):
    # To close entire popover list given a list popoverList, a boolean focusPreviousElement, and a boolean fireEvents:

    # FIXME: If an event handler opens a new popover then this could be an infinite loop.
    # 1. While popoverList is not empty:
    while not ak.vector_is_empty(popover_list):
        # 1. Run the hide popover algorithm given popoverList's last item, focusPreviousElement, fireEvents, false, and null.
        html_element_hide_popover(*ak.vector_last_const(popover_list), focus_previous_element, fire_events, HtmlThrowExceptions.no, HtmlIgnoreDomState.no, none) else trap("MUST: hide_popover")

# mark: The topmost popover ancestor ============================================================

## The captures of topmost_popover_ancestor's checkAncestor lambda (`[&]`).
struct HtmlElementTopmostPopoverAncestorCheck:
    var popover_positions: ak.OrderedHashMap[HtmlElement*, i32, ak.PtrTraits[HtmlElement]]*
    var is_popover: HtmlIsPopover
    var new_popover: HtmlElement*?
    var topmost_popover_ancestor: HtmlElement*?

## topmost_popover_ancestor's checkAncestor: `[&](auto candidate) {...}`.
func html_element_topmost_popover_ancestor_check_ancestor(captures: HtmlElementTopmostPopoverAncestorCheck*, candidate_argument: HtmlElement*?):
    # 1. If candidate is null, then return.
    var candidate = candidate_argument else return

    # 2. Let okNesting be false.
    var ok_nesting = false

    # 3. Let candidateAncestor be null.
    var candidate_ancestor: HtmlElement*? = none

    # 4. While okNesting is false:
    while not ok_nesting:
        # 1. Set candidateAncestor to the result of running nearest inclusive open popover given candidate.
        candidate_ancestor = html_element_nearest_inclusive_open_popover(candidate)

        # 2. If candidateAncestor is null or popoverPositions does not contain candidateAncestor, then return.
        let ancestor = candidate_ancestor else return
        if not ak.ordered_hash_map_contains_k(captures.popover_positions, ancestor):
            return

        # 3. Assert: candidateAncestor's popover attribute is not in the manual or none state.
        let ancestor_popover = html_element_popover(ancestor)
        assert(ancestor_popover == none or not html_element_optional_is(ancestor_popover, "manual"))

        # 4. Set okNesting to true if isPopover is false, newPopoverOrTopLayerElement's popover attribute is in the hint state, or candidateAncestor's popover attribute is in the auto state.
        if captures.is_popover == HtmlIsPopover.no or html_element_optional_is(html_element_popover(captures.new_popover else trap("VERIFY: new popover")), "hint") or html_element_optional_is(ancestor_popover, "auto"):
            ok_nesting = true

        # 5. If okNesting is false, then set candidate to candidateAncestor's parent in the flat tree.
        if not ok_nesting:
            let parent = dom_node_first_flat_tree_ancestor_of_type(ancestor.dom_node(), &html_element_class) else trap("VERIFY: GC::Ptr<HTMLElement>::operator-> on null")
            candidate = as_html_element(parent)

    # 5. Let candidatePosition be popoverPositions[candidateAncestor].
    let ancestor = candidate_ancestor else trap("unreachable")
    let candidate_position = *(ak.ordered_hash_map_get_k(captures.popover_positions, ancestor) else trap("Optional::value() of the candidate position"))

    # 6. If topmostPopoverAncestor is null or popoverPositions[topmostPopoverAncestor] is less than candidatePosition, then set topmostPopoverAncestor to candidateAncestor.
    if let topmost = captures.topmost_popover_ancestor:
        let topmost_position = *(ak.ordered_hash_map_get_k(captures.popover_positions, topmost) else trap("Optional::value() of the topmost position"))
        if topmost_position < candidate_position:
            captures.topmost_popover_ancestor = ancestor
    else:
        captures.topmost_popover_ancestor = ancestor

## Ported from HTMLElement.cpp:1719 Web::HTML::HTMLElement::topmost_popover_ancestor.
# https://html.spec.whatwg.org/multipage/popover.html#topmost-popover-ancestor
pub func html_element_topmost_popover_ancestor(new_popover_or_top_layer_element: DomNode*?, popover_list: const ak.Vector[HtmlElement*]*, source: HtmlElement*?, is_popover: HtmlIsPopover) -> HtmlElement*?:
    # To find the topmost popover ancestor, given a Node newPopoverOrTopLayerElement, a list popoverList, an HTML
    # element or null source, and a boolean isPopover, perform the following steps. They return an HTML element or null.
    let new_node = new_popover_or_top_layer_element else trap("VERIFY: GC::Ptr<Node>::operator* on null")

    # 1. If isPopover is true:
    let new_popover = as_if_html_element(new_node)
    if is_popover == HtmlIsPopover.yes:
        # 1. Assert: newPopoverOrTopLayerElement is an HTML element.
        let popover = new_popover else trap("VERIFY: new_popover")

        # 2. Assert: newPopoverOrTopLayerElement's popover attribute is not in the No Popover state or the manual state.
        let state = html_element_popover(popover)
        assert(state == none or not html_element_optional_is(state, "manual"))

        # 3. Assert: newPopoverOrTopLayerElement's popover visibility state is not in the popover showing state.
        assert(popover.m_popover_visibility_state != HtmlElementPopoverVisibilityState.showing)
    # 2. Otherwise:
    else:
        # 1. Assert: source is null.
        assert(source == none)

    # 3. Let popoverPositions be an empty ordered map.
    var popover_positions: ak.OrderedHashMap[HtmlElement*, i32, ak.PtrTraits[HtmlElement]]

    # 4. Let index be 0.
    var index: i32 = 0

    # 5. For each popover of popoverList:
    for popover in ak.vector_span_const(popover_list):
        # 1. Set popoverPositions[popover] to index.
        _ = ak.ordered_hash_map_set(&popover_positions, popover, index)

        # 2. Increment index by 1.
        index += 1

    # 6. If isPopover is true, then set popoverPositions[newPopoverOrTopLayerElement] to index.
    if is_popover == HtmlIsPopover.yes:
        _ = ak.ordered_hash_map_set(&popover_positions, new_popover else trap("unreachable"), index)

    # 7. Increment index by 1.
    index += 1

    # 8. Let topmostPopoverAncestor be null.
    # 9. Let checkAncestor be an algorithm which performs the following steps given candidate:
    var captures = HtmlElementTopmostPopoverAncestorCheck(popover_positions = &popover_positions, is_popover = is_popover, new_popover = new_popover, topmost_popover_ancestor = none)

    # 10. Run checkAncestor given newPopoverOrTopLayerElement's parent node within the flat tree.
    var parent_in_flat_tree: HtmlElement*? = none
    if let parent = dom_node_first_flat_tree_ancestor_of_type(new_node, &html_element_class):
        parent_in_flat_tree = as_html_element(parent)
    html_element_topmost_popover_ancestor_check_ancestor(&captures, parent_in_flat_tree)

    # 11. Run checkAncestor given source.
    html_element_topmost_popover_ancestor_check_ancestor(&captures, source)

    # 12. Return topmostPopoverAncestor.
    return captures.topmost_popover_ancestor