Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_element_5.lucb

#==============================================================================================
#
#   html_element_5 - HTML::HTMLElement: nearest popovers, popover toggle events, light dismiss,
#                    focus of editing hosts, and the removing and moving steps
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLElement.cpp (lines 1816-2096): the nearest inclusive open and
#       target popovers, queueing a popover toggle event task (its task is a capture struct
#       allocated in managed memory, DESIGN.md ยง2.7), light dismissing open popovers, the
#       popover stack position, the topmost clicked popover, did_receive_focus /
#       did_lose_focus for contenteditable elements, and the HTML element removing and moving
#       steps.
#
#==============================================================================================

# mark: Nearest popovers ========================================================================

## `current_node->first_flat_tree_ancestor_of_type<HTMLElement>()`.
func html_element_flat_tree_parent_html_element(node: DomNode*) -> HtmlElement*?:
    let parent = dom_node_first_flat_tree_ancestor_of_type(node, &html_element_class) else return none
    return as_html_element(parent)

## Ported from HTMLElement.cpp:1818 Web::HTML::HTMLElement::nearest_inclusive_open_popover.
# https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-open-popover
func html_element_nearest_inclusive_open_popover(this: HtmlElement*) -> HtmlElement*?:
    # To find the nearest inclusive open popover given a Node node, perform the following steps. They return an HTML element or null.

    # 1. Let currentNode be node.
    var current_node: HtmlElement*? = this

    # 2. While currentNode is not null:
    while let current = current_node:
        # 1. If currentNode's popover attribute is in the Auto state or the Hint state, and currentNode's popover visibility state is showing, then return currentNode.
        if html_element_optional_is_auto_or_hint(html_element_popover(current)) and current.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing:
            return current

        # 2. Set currentNode to currentNode's parent in the flat tree.
        current_node = html_element_flat_tree_parent_html_element(current.dom_node())

    # 3. Return null.
    return none

## Ported from HTMLElement.cpp:1840 Web::HTML::HTMLElement::nearest_inclusive_target_popover.
# https://html.spec.whatwg.org/multipage/popover.html#nearest-inclusive-target-popover
func html_element_nearest_inclusive_target_popover(this: HtmlElement*) -> HtmlElement*?:
    # To find the nearest inclusive target popover given a Node node:

    # 1. Let currentNode be node.
    var current_node: HtmlElement*? = this

    # 2. While currentNode is not null:
    while let current = current_node:
        # 1. Let targetPopover be currentNode's popover target element.
        let target_popover = html_popover_target_attributes_get_the_popover_target_element(current.dom_node())

        # 2. If targetPopover is not null and targetPopover's popover attribute is in the Auto state or the Hint state, and targetPopover's popover visibility state is showing, then return targetPopover.
        if let target = target_popover:
            if html_element_optional_is_auto_or_hint(html_element_popover(target)) and target.m_popover_visibility_state == HtmlElementPopoverVisibilityState.showing:
                return target

        # 3. Set currentNode to currentNode's ancestor in the flat tree.
        current_node = html_element_flat_tree_parent_html_element(current.dom_node())

    return none

# mark: Popover toggle events ===================================================================

## The captures of queue_a_popover_toggle_event_task's task: `[this, old_state, new_state = move(new_state), source]`.
struct HtmlElementPopoverToggleEventTask:
    var this: HtmlElement*
    var old_state: ak.String
    var new_state: ak.String
    var source: HtmlElement*?

    ## The task's steps.
    static func run(context: void*?):
        let captures = (HtmlElementPopoverToggleEventTask*)(context else trap("popover toggle task: no captures"))
        let this = captures.this

        # 1. Fire an event named toggle at element, using ToggleEvent, with the oldState attribute initialized to
        #    oldState, the newState attribute initialized to newState, and the source attribute initialized to source.
        var event_init = HtmlToggleEventInit()
        event_init.old_state = captures.old_state
        event_init.new_state = captures.new_state
        if let source = captures.source:
            event_init.source = source.dom_element()

        _ = dom_event_target_dispatch_event(this.dom_event_target(), html_toggle_event_create(html_element_realm(this), html_event_names_toggle, event_init).dom_event())

        # 2. Set element's popover toggle task tracker to null.
        this.m_popover_toggle_task_tracker = none

## queue_a_popover_toggle_event_task's remove_tasks_matching predicate: `task.id() == tracker->task_id`.
func html_element_task_has_id(context: void*?, task: HtmlTask*) -> bool:
    let task_id = (const (u64?)*)(context else trap("no task id"))
    let tracked = *task_id else return false
    return html_task_id(task) == tracked

## Ported from HTMLElement.cpp:1866 Web::HTML::HTMLElement::queue_a_popover_toggle_event_task.
# https://html.spec.whatwg.org/multipage/popover.html#queue-a-popover-toggle-event-task
func html_element_queue_a_popover_toggle_event_task(this: HtmlElement*, old_state_argument: ak.String, new_state: ak.String, source: HtmlElement*?):
    var old_state = old_state_argument

    # 1. If element's popover toggle task tracker is not null, then:
    if let tracker = this.m_popover_toggle_task_tracker:
        # 1. Set oldState to element's popover toggle task tracker's old state.
        old_state = tracker.old_state

        # 2. Remove element's popover toggle task tracker's task from its task queue.
        var task_id = tracker.task_id
        html_task_queue_remove_tasks_matching(html_event_loop_task_queue(html_main_thread_event_loop()), ak.Function1[HtmlTask*, bool](call = html_element_task_has_id, context = &task_id))

        # 3. Set element's popover toggle task tracker to null.
        # (C++ clears the tracker's task id; the tracker itself stays set until it is replaced below.)
        var cleared = tracker
        cleared.task_id = none
        this.m_popover_toggle_task_tracker = cleared

    # 2. Queue an element task given the DOM manipulation task source and element to run the following steps:
    let captures = new HtmlElementPopoverToggleEventTask(this = this, old_state = old_state, new_state = new_state, source = source) else trap("out of memory")
    let task_id = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.dom_manipulation, ak.Function0[unit](call = HtmlElementPopoverToggleEventTask.run, context = captures))

    # 3. Set element's popover toggle task tracker to a struct with task set to the just-queued task and old state set to oldState.
    this.m_popover_toggle_task_tracker = HtmlToggleTaskTracker(task_id = task_id, old_state = old_state)

## Ported from HTMLElement.cpp:1903 Web::HTML::HTMLElement::light_dismiss_open_popovers.
# https://html.spec.whatwg.org/multipage/popover.html#light-dismiss-open-popovers
pub func html_element_light_dismiss_open_popovers(event: UiEventsPointerEvent*, target: DomNode*?):
    # (PointerEvent is opaque until phase 4; it is a DOM::Event first.)
    let dom_event = (DomEvent*)event

    # To light dismiss open popovers, given a PointerEvent event:

    # 1. Assert: event's isTrusted attribute is true.
    assert(dom_event_is_trusted(dom_event))

    # 2. Let target be event's target.
    # FIXME: The event's target hasn't been initialized yet, so it's passed as an argument

    # 3. Let document be target's node document.
    let document = dom_node_document(target else trap("VERIFY: GC::Ptr<Node>::operator-> on null"))

    # 4. Let topmostPopover be the result of running topmost auto popover given document.
    let topmost_popover = dom_document_topmost_auto_or_hint_popover(document)

    # 5. If topmostPopover is null, then return.
    if topmost_popover == none:
        return

    # 6. If event's type is "pointerdown", then: set document's popover pointerdown target to the result of running topmost clicked popover given target.
    let type_ = dom_event_type(dom_event)
    if ak.fly_string_eq_fly_string(&type_, &ui_events_event_names_pointerdown):
        dom_document_set_popover_pointerdown_target(document, html_element_topmost_clicked_popover(target))

    # 7. If event's type is "pointerup", then:
    if ak.fly_string_eq_fly_string(&type_, &ui_events_event_names_pointerup):
        # 1. Let ancestor be the result of running topmost clicked popover given target.
        let ancestor = html_element_topmost_clicked_popover(target)

        # 2. Let sameTarget be true if ancestor is document's popover pointerdown target.
        let same_target = ancestor == dom_document_popover_pointerdown_target(document)

        # 3. Set document's popover pointerdown target to null.
        dom_document_set_popover_pointerdown_target(document, none)

        # 4. If ancestor is null, then set ancestor to document.
        var ancestor_or_document = HtmlElementOrDomDocument.html_element(ancestor)
        if ancestor == none:
            ancestor_or_document = .dom_document(document)

        # 5. If sameTarget is true, then run hide all popovers until given ancestor, false, and true.
        if same_target:
            html_element_hide_all_popovers_until(ancestor_or_document, HtmlFocusPreviousElement.no, HtmlFireEvents.yes)

## Ported from HTMLElement.cpp:1952 Web::HTML::HTMLElement::popover_stack_position.
# https://html.spec.whatwg.org/multipage/popover.html#get-the-popover-stack-position
func html_element_popover_stack_position(this: HtmlElement*) -> usize:
    # To get the popover stack position, given an HTML element popover:

    # 1. Let hintList be popover's node document's showing hint popover list.
    let hint_list = dom_document_showing_hint_popover_list(html_element_document(this))

    # 2. Let autoList be popover's node document's showing auto popover list.
    let auto_list = dom_document_showing_auto_popover_list(html_element_document(this))

    # 3. If popover is in hintList, then return the index of popover in hintList + the size of autoList + 1.
    if html_element_list_contains(hint_list, this):
        return (ak.vector_find_first_index(hint_list, this) else trap("Optional::value() of the hint index")) + ak.vector_size(auto_list) + 1

    # 4. If popover is in autoList, then return the index of popover in autoList + 1.
    if html_element_list_contains(auto_list, this):
        return (ak.vector_find_first_index(auto_list, this) else trap("Optional::value() of the auto index")) + 1

    # 5. Return 0.
    return 0

## Ported from HTMLElement.cpp:1975 Web::HTML::HTMLElement::topmost_clicked_popover.
# https://html.spec.whatwg.org/multipage/popover.html#topmost-clicked-popover
func html_element_topmost_clicked_popover(node: DomNode*?) -> HtmlElement*?:
    # To find the topmost clicked popover, given a Node node:
    let present_node = node else trap("VERIFY: GC::Ptr<Node>::operator* on null")

    var nearest_element = as_if_html_element(present_node)
    if nearest_element == none:
        nearest_element = html_element_flat_tree_parent_html_element(present_node)

    let nearest = nearest_element else return none

    # 1. Let clickedPopover be the result of running nearest inclusive open popover given node.
    let clicked_popover = html_element_nearest_inclusive_open_popover(nearest)

    # 2. Let targetPopover be the result of running nearest inclusive target popover given node.
    let target_popover = html_element_nearest_inclusive_target_popover(nearest)

    let clicked = clicked_popover else return target_popover

    let target = target_popover else return clicked_popover

    # 3. If the result of getting the popover stack position given clickedPopover is greater than the result of
    #    getting the popover stack position given targetPopover, then return clickedPopover.
    if html_element_popover_stack_position(clicked) > html_element_popover_stack_position(target):
        return clicked

    # 4. Return targetPopover.
    return target

# mark: Focus of editing hosts ==================================================================

## `first_is_one_of(m_content_editable_state, ContentEditableState::True, ContentEditableState::PlaintextOnly)`.
func html_element_is_true_or_plaintext_only(this: HtmlElement*) -> bool:
    return this.m_content_editable_state == HtmlContentEditableState.true_ or this.m_content_editable_state == HtmlContentEditableState.plaintext_only

## Ported from HTMLElement.cpp:2007 Web::HTML::HTMLElement::did_receive_focus (override).
pub func html_element_did_receive_focus_impl(base: DomElement*):
    let this = (HtmlElement*)base
    if not html_element_is_true_or_plaintext_only(this):
        return

    let editing_host = dom_document_editing_host_manager(html_element_document(this))
    dom_editing_host_manager_set_active_contenteditable_element(editing_host, this.dom_node())

    # Don't update the selection if we're already part of the active range.
    let selection = dom_document_get_selection(html_element_document(this)) else trap("VERIFY: GC::Ptr<Selection>::operator-> on null")
    if let range = selection_selection_range(selection):
        if tree_node_is_inclusive_ancestor_of(this.dom_node(), dom_abstract_range_start_container(range.dom_abstract_range())) or tree_node_is_inclusive_ancestor_of(this.dom_node(), dom_abstract_range_end_container(range.dom_abstract_range())):
            return

    var text: DomText*? = none
    for node in dom_node_inclusive_subtree(this.dom_node()):
        if let text_node = as_if_dom_text(node):
            text = text_node

    if text == none:
        dom_editing_host_manager_set_selection_anchor_impl(&editing_host.input_events_target, this.dom_node(), 0)
        return
    let last_text = text else trap("unreachable")
    dom_editing_host_manager_set_selection_anchor_impl(&editing_host.input_events_target, last_text.dom_node(), dom_node_length(last_text.dom_node()))

## Ported from HTMLElement.cpp:2034 Web::HTML::HTMLElement::did_lose_focus (override).
pub func html_element_did_lose_focus_impl(base: DomElement*):
    let this = (HtmlElement*)base
    if not html_element_is_true_or_plaintext_only(this):
        return

    dom_editing_host_manager_set_active_contenteditable_element(dom_document_editing_host_manager(html_element_document(this)), none)

# mark: Removing and moving steps ===============================================================

## Ported from HTMLElement.cpp:2043 Web::HTML::HTMLElement::removed_from (override).
# https://html.spec.whatwg.org/multipage/infrastructure.html#dom-trees:concept-node-remove-ext
pub func html_element_removed_from_impl(base: DomNode*, is_subtree_root: DomNodeIsSubtreeRoot, old_ancestor: DomNode*?, old_root: DomNode*):
    let this = (HtmlElement*)base
    dom_element_removed_from_impl(base, is_subtree_root, old_ancestor, old_root)

    # FIXME: 1. Let document be removedNode's node document.
    # FIXME: 2. If document's focused area is removedNode, then set document's focused area to document's viewport,
    #   and set document's relevant global object's navigation API's focus changed during ongoing navigation to false.

    # 3. If removedNode is an element whose namespace is the HTML namespace, and this standard defines HTML element
    #    removing steps for removedNode's local name, then run the corresponding HTML element removing steps given
    #    removedNode, isSubtreeRoot, and oldAncestor.
    # NB: This is done by overriding removed_from() in subclasses.

    # 4. If removedNode is a form-associated element with a non-null form owner and removedNode and its form owner are
    #    no longer in the same tree, then reset the form owner of removedNode.
    # FIXME: Follow the spec here.
    if html_form_associated_element_is_form_associated_element(&this.form_associated_element):
        html_form_associated_element_form_node_was_removed(&this.form_associated_element)
        html_form_associated_element_form_associated_element_was_removed(&this.form_associated_element, old_ancestor)

    # 5. If removedNode's popover attribute is not in the No Popover state, then run the hide popover algorithm given
    #    removedNode, false, false, false, true, and null.
    if html_element_popover(this) != none:
        html_element_hide_popover(this, HtmlFocusPreviousElement.no, HtmlFireEvents.no, HtmlThrowExceptions.no, HtmlIgnoreDomState.yes, none) else trap("MUST: hide_popover")

    # AD-HOC: Update inertness
    if let ancestor = old_ancestor:
        var parent_html_element = as_if_html_element(ancestor)
        if parent_html_element == none:
            if let parent = tree_node_first_ancestor_of_type(ancestor, &html_element_class):
                parent_html_element = as_html_element(parent)
        if let parent = parent_html_element:
            if html_element_is_inert(parent) and not dom_element_has_attribute(this.dom_element(), html_attribute_names_inert):
                html_element_set_subtree_inertness(this, false)

## Ported from HTMLElement.cpp:2080 Web::HTML::HTMLElement::moved_from (override).
# https://html.spec.whatwg.org/multipage/infrastructure.html#dom-trees:concept-node-move-ext
pub func html_element_moved_from_impl(base: DomNode*, is_subtree_root: DomNodeIsSubtreeRoot, old_ancestor: DomNode*?):
    let this = (HtmlElement*)base
    dom_element_moved_from_impl(base, is_subtree_root, old_ancestor)

    # 1. If movedNode is an element whose namespace is the HTML namespace, and this standard defines HTML element
    #    moving steps for movedNode's local name, then run the corresponding HTML element moving steps given
    #    movedNode, isSubtreeRoot, and oldAncestor.
    # NB: This is done by overriding moved_from() in subclasses.

    # 2. If movedNode is a form-associated element with a non-null form owner and movedNode and its form owner are no
    #    longer in the same tree, then reset the form owner of movedNode.
    # FIXME: Follow the spec here.
    if html_form_associated_element_is_form_associated_element(&this.form_associated_element):
        html_form_associated_element_form_node_was_moved(&this.form_associated_element)
        html_form_associated_element_form_associated_element_was_moved(&this.form_associated_element, old_ancestor)