Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / focus.lucb

#==============================================================================================
#
#   focus - HTML::Focus: the focusing steps, the unfocusing steps and the focus update steps
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/Focus.cpp (lines 1-333): firing a focus event, the focus update
#       steps, the focus chain, and the focusing and unfocusing steps. The static helpers are
#       private. C++'s `Vector<GC::Root<DOM::Node>>` chains are vectors of node pointers (roots
#       are plain pointers on the conservatively scanned stack and heap, DESIGN.md ยง3.4), and its
#       `&entry == &chain.last()` identity tests compare indices.
#
#==============================================================================================

# mark: Focus events ============================================================================

## Ported from Focus.cpp:26 Web::HTML::fire_a_focus_event.
# https://html.spec.whatwg.org/multipage/interaction.html#fire-a-focus-event
func html_fire_a_focus_event(focus_event_target: DomEventTarget*?, related_focus_target: DomEventTarget*?, event_name: ak.FlyString, bubbles: bool):
    let target = focus_event_target else trap("VERIFY: GC::Ptr<EventTarget>::operator-> on null")
    let realm = bind_platform_object_realm(target.bind_platform_object())

    # To fire a focus event named e at an element t with a given related target r, fire an event named e at t, using FocusEvent,
    # with the relatedTarget attribute initialized to r, the view attribute initialized to t's node document's relevant global
    # object, and the composed flag set.
    var focus_event_init = UiEventsFocusEventInit()
    focus_event_init.related_target = related_focus_target
    focus_event_init.ui_event_init.view = html_window_window(as_html_window((gc.Cell*)realm_global_object(realm)))

    let focus_event = ui_events_focus_event_create(realm, event_name, focus_event_init)
    # AD-HOC: support bubbling focus events, used for focusin & focusout.
    #         See: https://github.com/whatwg/html/issues/3514
    dom_event_set_bubbles(focus_event, bubbles)
    dom_event_set_composed(focus_event, true)
    _ = dom_event_target_dispatch_event(target, focus_event)

## `as<Window>(relevant_global_object(node))`.
func html_focus_relevant_window(node: DomNode*) -> HtmlWindow*:
    return as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)node))

## Ported from Focus.cpp:44 Web::HTML::run_focus_update_steps.
# https://html.spec.whatwg.org/multipage/interaction.html#focus-update-steps
func html_run_focus_update_steps(old_chain_argument: ak.Vector[DomNode*], new_chain_argument: ak.Vector[DomNode*], new_focus_target: DomNode*?):
    var old_chain = old_chain_argument
    var new_chain = new_chain_argument

    # The focus update steps, given an old chain, a new chain, and a new focus target respectively, are as follows:

    # 1. If the last entry in old chain and the last entry in new chain are the same, pop the last entry from old chain
    #    and the last entry from new chain and redo this step.
    while not ak.vector_is_empty(&old_chain) and not ak.vector_is_empty(&new_chain) and *ak.vector_last(&old_chain) == *ak.vector_last(&new_chain):
        _ = ak.vector_take_last(&old_chain)
        _ = ak.vector_take_last(&new_chain)

    # 2. For each entry entry in old chain, in order, run these substeps:
    for index in 0..<ak.vector_size(&old_chain):
        let entry = *ak.vector_at(&old_chain, index)

        # 1. If entry is an input element
        if let input_element = as_if_html_input_element(entry):
            # FIXME: Spec issue: It doesn't make sense to check if the element has a defined activation behavior, as
            #        that is always true. Instead, we check if it has an *input* activation behavior.
            #        https://github.com/whatwg/html/issues/9973
            # and the change event applies to the element, and the element does not have a defined activation behavior,
            # and the user has changed the element's value or its list of selected files while the control was focused
            # without committing that change (such that it is different to what it was when the control was first
            # focused), then:
            if html_input_element_change_event_applies(input_element) and not html_input_element_has_input_activation_behavior(input_element) and html_input_element_has_uncommitted_changes(input_element):
                # 1. Set entry's user validity to true.
                html_input_element_set_user_validity(input_element, true)

                # 2. Fire an event named change at the element, with the bubbles attribute initialized to true.
                html_input_element_commit_pending_changes(input_element)

        # 2. If entry is an element, let blur event target be entry.
        #    If entry is a Document object, let blur event target be that Document object's relevant global object.
        #    Otherwise, let blur event target be null.
        var blur_event_target: DomEventTarget*? = none
        if is_dom_element(entry):
            blur_event_target = entry.dom_event_target()
        elif is_dom_document(entry):
            blur_event_target = html_focus_relevant_window(entry).dom_event_target()

        # 3. If entry is the last entry in old chain, and entry is an Element, and the last entry in new chain is also
        #    an Element, then let related blur target be the last entry in new chain. Otherwise, let related blur
        #    target be null.
        var related_blur_target: DomEventTarget*? = none
        if not ak.vector_is_empty(&old_chain) and index == ak.vector_size(&old_chain) - 1 and is_dom_element(entry) and not ak.vector_is_empty(&new_chain) and is_dom_element(*ak.vector_last(&new_chain)):
            related_blur_target = (*ak.vector_last(&new_chain)).dom_event_target()

        # 4. If blur event target is not null, fire a focus event named blur at blur event target, with related blur
        #    target as the related target.
        # FIXME: NOTE: In some cases, e.g., if entry is an area element's shape, a scrollable region, or a viewport, no event
        #       is fired.
        if blur_event_target != none:
            html_fire_a_focus_event(blur_event_target, related_blur_target, html_event_names_blur, false)

            # AD-HOC: dispatch focusout
            html_fire_a_focus_event(blur_event_target, related_blur_target, html_event_names_focusout, true)

    # FIXME: 3. Apply any relevant platform-specific conventions for focusing new focus target. (For example, some platforms
    #    select the contents of a text control when that control is focused.)

    # 4. For each entry entry in new chain, in reverse order, run these substeps:
    var reverse_index = ak.vector_size(&new_chain)
    while reverse_index > 0:
        reverse_index -= 1
        let entry = *ak.vector_at(&new_chain, reverse_index)

        # 1. If entry is a focusable area, and the focused area of the document is not entry:
        if dom_node_is_document(entry):
            if dom_document_focused_area(dom_node_document(entry)) != none:
                html_navigation_set_focus_changed_during_ongoing_navigation(html_window_navigation(html_focus_relevant_window(entry)), true)

                # AD-HOC: null focused_area indicates "viewport focus".
                dom_document_set_focused_area(dom_node_document(entry), none)
        elif dom_event_target_is_focusable(entry.dom_event_target()) and dom_document_focused_area(dom_node_document(entry)) != entry:
            html_navigation_set_focus_changed_during_ongoing_navigation(html_window_navigation(html_focus_relevant_window(entry)), true)

            # 2. Designate entry as the focused area of the document.
            dom_document_set_focused_area(dom_node_document(entry), entry)

        # 2. If entry is an element, let focus event target be entry.
        #    If entry is a Document object, let focus event target be that Document object's relevant global object.
        #    Otherwise, let focus event target be null.
        var focus_event_target: DomEventTarget*? = none
        if is_dom_document(entry):
            focus_event_target = html_focus_relevant_window(entry).dom_event_target()
        elif is_dom_element(entry):
            focus_event_target = entry.dom_event_target()

        # 3. If entry is the last entry in new chain, and entry is an Element, and the last entry in old chain is also
        #    an Element, then let related focus target be the last entry in old chain. Otherwise, let related focus
        #    target be null.
        var related_focus_target: DomEventTarget*? = none
        if not ak.vector_is_empty(&new_chain) and reverse_index == ak.vector_size(&new_chain) - 1 and is_dom_element(entry) and not ak.vector_is_empty(&old_chain) and is_dom_element(*ak.vector_last(&old_chain)):
            related_focus_target = (*ak.vector_last(&old_chain)).dom_event_target()

        # 4. If focus event target is not null, fire a focus event named focus at focus event target, with related
        #    focus target as the related target.
        # FIXME: NOTE: In some cases, e.g. if entry is an area element's shape, a scrollable region, or a viewport, no event
        #       is fired.
        if focus_event_target != none:
            html_fire_a_focus_event(focus_event_target, related_focus_target, html_event_names_focus, false)

            # AD-HOC: dispatch focusin
            html_fire_a_focus_event(focus_event_target, related_focus_target, html_event_names_focusin, true)

# mark: Focus chains ============================================================================

## Ported from Focus.cpp:167 Web::HTML::focus_chain.
# https://html.spec.whatwg.org/multipage/interaction.html#focus-chain
func html_focus_chain(subject: DomNode*?) -> ak.Vector[DomNode*]:
    var output: ak.Vector[DomNode*]

    # FIXME: Move this somewhere more spec-friendly.
    let subject_node = subject else return output

    # 1. Let output be an empty list.

    # 2. Let currentObject be subject.
    var current_object = subject_node

    # 3. While true:
    while true:
        # 1. Append currentObject to output.
        ak.vector_append_t(&output, current_object)

        # FIXME: 2. If currentObject is an area element's shape, then append that area element to output.

        # FIXME:    Otherwise, if currentObject's DOM anchor is an element that is not currentObject itself, then append currentObject's DOM anchor to output.

        # FIXME: Everything below needs work. The conditions are not entirely right.
        if not is_dom_document(current_object):
            # 3. If currentObject is a focusable area, then set currentObject to currentObject's DOM anchor's node document.
            current_object = dom_node_document(current_object).dom_node()
        elif is_dom_document(current_object) and dom_node_navigable(current_object) != none and html_navigable_parent(dom_node_navigable(current_object) else trap("unreachable")) != none:
            # Otherwise, if currentObject is a Document whose node navigable's parent is non-null, then set currentObject to currentObject's node navigable's parent.
            let container = html_navigable_container(dom_node_navigable(current_object) else trap("unreachable")) else trap("VERIFY: a child navigable has a container")
            current_object = container.dom_node()
        else:
            # Otherwise, break.
            break

    # 4. Return output.
    return output

# mark: Focusing and unfocusing =================================================================

## Ported from Focus.cpp:209 Web::HTML::run_focusing_steps.
# https://html.spec.whatwg.org/multipage/interaction.html#focusing-steps
# FIXME: This should accept more types.
pub func html_run_focusing_steps(new_focus_target: DomNode*?, fallback_target: DomNode*? = none, focus_trigger: HtmlFocusTrigger = HtmlFocusTrigger.other):
    # FIXME: 1. If new focus target is not a focusable area, then set new focus target to the result of getting the focusable
    #    area for new focus target, given focus trigger if it was passed.

    # 2. If new focus target is null, then:
    var target = new_focus_target
    if target == none:
        # 1. If no fallback target was specified, then return.
        if fallback_target == none:
            return

        # 2. Otherwise, set new focus target to the fallback target.
        target = fallback_target
    var new_target = target else trap("unreachable")

    # 3. If new focus target is a navigable container with non-null content navigable, then set new focus target to the content navigable's active document.
    if let navigable_container = as_if_html_navigable_container(new_target):
        if let content_navigable = html_navigable_container_content_navigable(navigable_container):
            let active_document = html_navigable_active_document(content_navigable) else trap("VERIFY: GC::Ptr<Document>::operator* on null")
            new_target = active_document.dom_node()

    # 4. If new focus target is a focusable area and its DOM anchor is inert, then return.
    if dom_node_is_inert(new_target):
        return

    # 5. If new focus target is the currently focused area of a top-level browsing context, then return.
    let browsing_context = dom_document_browsing_context(dom_node_document(new_target)) else return
    let top_level_traversable = html_browsing_context_top_level_traversable(browsing_context)
    if html_traversable_navigable_currently_focused_area(top_level_traversable) == new_target:
        return

    # 6. Let old chain be the current focus chain of the top-level browsing context in which
    #    new focus target finds itself.
    let old_chain = html_focus_chain(html_traversable_navigable_currently_focused_area(top_level_traversable))

    # 7. Let new chain be the focus chain of new focus target.
    let new_chain = html_focus_chain(new_target)

    # AD-HOC: Remember last focus trigger for :focus-visible / focus indication.
    dom_document_set_last_focus_trigger(dom_node_document(new_target), focus_trigger)

    # 8. Run the focus update steps with old chain, new chain, and new focus target respectively.
    html_run_focus_update_steps(old_chain, new_chain, new_target)

## `[](DOM::Node* node) { return is<DOM::Element>(node) && static_cast<DOM::Element*>(node)->is_shadow_host(); }`.
func html_run_unfocusing_steps_is_shadow_host(node: DomNode*?) -> bool:
    let present = node else return false
    let element = as_if_dom_element(present) else return false
    return dom_element_is_shadow_host(element)

## Ported from Focus.cpp:256 Web::HTML::run_unfocusing_steps.
# https://html.spec.whatwg.org/multipage/interaction.html#unfocusing-steps
pub func html_run_unfocusing_steps(old_focus_target: DomNode*?):
    # NOTE: The unfocusing steps do not always result in the focus changing, even when applied to the currently focused
    # area of a top-level browsing context. For example, if the currently focused area of a top-level browsing context
    # is a viewport, then it will usually keep its focus regardless until another focusable area is explicitly focused
    # with the focusing steps.

    var old_target = old_focus_target

    # 1. If old focus target is a shadow host whose shadow root's delegates focus is true, and old focus target's
    #    shadow root is a shadow-including inclusive ancestor of the currently focused area of a top-level browsing
    #    context's DOM anchor, then set old focus target to that currently focused area of a top-level browsing
    #    context.
    if html_run_unfocusing_steps_is_shadow_host(old_target):
        let host = as_dom_element(old_target else trap("unreachable"))
        let shadow_root = dom_element_shadow_root(host) else trap("VERIFY: a shadow host has a shadow root")
        if dom_shadow_root_delegates_focus(shadow_root):
            let browsing_context = dom_document_browsing_context(dom_element_document(host)) else trap("VERIFY: GC::Ptr<BrowsingContext>::operator-> on null")
            let top_level_traversable = html_browsing_context_top_level_traversable(browsing_context)
            if let currently_focused_area = html_traversable_navigable_currently_focused_area(top_level_traversable):
                if dom_node_is_shadow_including_ancestor_of(shadow_root.dom_node(), currently_focused_area):
                    old_target = currently_focused_area

    let target = old_target else trap("VERIFY: run_unfocusing_steps given null")

    # 2. If old focus target is inert, then return.
    if dom_node_is_inert(target):
        return

    # FIXME: 3. If old focus target is an area element and one of its shapes is the currently focused area of a
    #    top-level browsing context, or, if old focus target is an element with one or more scrollable regions, and one
    #    of them is the currently focused area of a top-level browsing context, then let old focus target be that
    #    currently focused area of a top-level browsing context.

    # NOTE: HTMLAreaElement is currently missing the shapes property

    # 4. Let old chain be the current focus chain of the top-level browsing context in which old focus target finds itself.
    let browsing_context = dom_document_browsing_context(dom_node_document(target)) else trap("VERIFY: GC::Ptr<BrowsingContext>::operator-> on null")
    let top_level_traversable = html_browsing_context_top_level_traversable(browsing_context)
    var old_chain = html_focus_chain(html_traversable_navigable_currently_focused_area(top_level_traversable))

    # 5. If old focus target is not one of the entries in old chain, then return.
    var found = false
    for node in ak.vector_span(&old_chain):
        if target == node:
            found = true
            break
    if not found:
        return

    # 6. If old focus target is not a focusable area, then return.
    if not dom_event_target_is_focusable(target.dom_event_target()):
        return

    # 7. Let topDocument be old chain's last entry.
    let top_document = as_dom_document(*ak.vector_last(&old_chain))

    # 8. If topDocument's node navigable has system focus, then run the focusing steps for topDocument's viewport.
    let top_navigable = dom_document_navigable(top_document) else trap("VERIFY: GC::Ptr<Navigable>::operator-> on null")
    let traversable = html_navigable_traversable_navigable(top_navigable) else trap("VERIFY: GC::Ptr<TraversableNavigable>::operator-> on null")
    if html_navigable_is_focused(traversable.html_navigable()):
        # AD-HOC: Remove top_document from old_chain so step 1 in run_focus_update_steps doesn't cancel the blur.
        var without_viewport_surrogate = ak.vector_clone(&old_chain)
        _ = ak.vector_take_last(&without_viewport_surrogate)

        let with_viewport_surrogate = html_focus_chain(top_document.dom_node())

        html_run_focus_update_steps(without_viewport_surrogate, with_viewport_surrogate, top_document.dom_node())
    else:
        # FIXME: Otherwise, apply any relevant platform-specific conventions for removing system focus from topDocument's
        # browsing context, and run the focus update steps with old chain, an empty list, and null respectively.

        var no_chain: ak.Vector[DomNode*]
        html_run_focus_update_steps(old_chain, no_chain, none)

    # NOTE: The unfocusing steps do not always result in the focus changing, even when applied to the currently focused
    #       area of a top-level traversable. For example, if the currently focused area of a top-level traversable is a
    #       viewport, then it will usually keep its focus regardless until another focusable area is explicitly focused
    #       with the focusing steps.