Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / dom / document_11.lucb

#==============================================================================================
#
#   document_11 - DOM::Document: named elements, design mode, hit tests
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Document.cpp (lines 6199-6605; the animation timelines and events,
#       lines 5994-6198, are in document_animations): the potentially named elements kept in
#       tree order, the id and name bookkeeping, anchor names, form-associated elements with a
#       form attribute, design mode, elementFromPoint() and elementsFromPoint(),
#       scrollingElement, and the named properties of the document (supported names and
#       namedItem).
#
#==============================================================================================

# mark: Potentially named elements ==============================================================

## Ported from Document.cpp:6200 Web::DOM::is_potentially_named_element.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
func dom_is_potentially_named_element(element: DomElement*) -> bool:
    return is_html_embed_element(element) or is_html_form_element(element) or is_html_htmli_frame_element(element) or is_html_image_element(element) or is_html_object_element(element)

## Ported from Document.cpp:6206 Web::DOM::is_potentially_named_element_by_id.
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem-filter
func dom_is_potentially_named_element_by_id(element: DomElement*) -> bool:
    return is_html_object_element(element) or is_html_image_element(element)

## The captures of insert_in_tree_order's predicate: `[&]` (the element).
struct DomInsertInTreeOrderPredicate:
    var element: DomElement*

## insert_in_tree_order's predicate: an existing element that the new element follows.
func dom_insert_in_tree_order_follows(context: void*?, existing_element: const (DomElement*)*) -> bool:
    let captures = (DomInsertInTreeOrderPredicate*)(context else trap("no captures"))
    return (dom_node_compare_document_position((*existing_element).dom_node(), captures.element.dom_node()) & (u16)DomNodeDocumentPosition.document_position_following) != 0

## Ported from Document.cpp:6211 Web::DOM::insert_in_tree_order.
func dom_insert_in_tree_order(elements: ak.Vector[DomElement*]*, element: DomElement*):
    for el in ak.vector_span(elements):
        if el == element:
            return

    var captures = DomInsertInTreeOrderPredicate(element = element)
    let index = ak.vector_find_first_index_if(elements, ak.Function1[const (DomElement*)*, bool](call = dom_insert_in_tree_order_follows, context = &captures))
    if let found = index:
        ak.vector_insert(elements, found, element)
    else:
        ak.vector_append_t(elements, element)

## The captures of `remove_first_matching([element](auto& e) { return e == element; })`.
struct DomDocumentIsElement:
    var element: DomElement*

## The predicate `e == element`.
func dom_document_is_element(context: void*?, e: const (DomElement*)*) -> bool:
    let captures = (DomDocumentIsElement*)(context else trap("no captures"))
    return *e == captures.element

## `m_potentially_named_elements.remove_first_matching([element](auto& e) { return e == element; })`.
func dom_document_remove_potentially_named_element(this: DomDocument*, element: DomElement*):
    var captures = DomDocumentIsElement(element = element)
    _ = ak.vector_remove_first_matching(&this.m_potentially_named_elements, ak.Function1[const (DomElement*)*, bool](call = dom_document_is_element, context = &captures))

## Ported from Document.cpp:6227 Web::DOM::Document::element_id_changed.
pub func dom_document_element_id_changed(this: DomDocument*, element: DomElement*, old_id: ak.FlyString?):
    for form_associated_element in ak.vector_span(&this.m_form_associated_elements_with_form_attribute):
        html_form_associated_element_element_id_changed(form_associated_element else trap("a null form-associated element"))

    if dom_element_id(element) != none:
        dom_insert_in_tree_order(&this.m_potentially_named_elements, element)
    elif dom_element_name(element) == none:
        dom_document_remove_potentially_named_element(this, element)

    let new_id = dom_element_id(element)
    if let old = old_id:
        dom_element_by_id_map_remove(dom_element_document_or_shadow_root_element_by_id_map(element), old, element)
    if let new_value = new_id:
        dom_element_by_id_map_add(dom_element_document_or_shadow_root_element_by_id_map(element), new_value, element)

## Ported from Document.cpp:6246 Web::DOM::Document::element_with_id_was_added.
pub func dom_document_element_with_id_was_added(this: DomDocument*, element: DomElement*):
    for form_associated_element in ak.vector_span(&this.m_form_associated_elements_with_form_attribute):
        html_form_associated_element_element_with_id_was_added_or_removed(form_associated_element else trap("a null form-associated element"))

    if dom_is_potentially_named_element_by_id(element):
        dom_insert_in_tree_order(&this.m_potentially_named_elements, element)

    if let id = dom_element_id(element):
        dom_element_by_id_map_add(dom_element_document_or_shadow_root_element_by_id_map(element), id, element)

## Ported from Document.cpp:6259 Web::DOM::Document::element_with_id_was_removed.
pub func dom_document_element_with_id_was_removed(this: DomDocument*, element: DomElement*):
    for form_associated_element in ak.vector_span(&this.m_form_associated_elements_with_form_attribute):
        html_form_associated_element_element_with_id_was_added_or_removed(form_associated_element else trap("a null form-associated element"))

    if dom_is_potentially_named_element_by_id(element):
        dom_document_remove_potentially_named_element(this, element)

    if let id = dom_element_id(element):
        dom_element_by_id_map_remove(dom_element_document_or_shadow_root_element_by_id_map(element), id, element)

## Ported from Document.cpp:6272 Web::DOM::Document::element_name_changed.
pub func dom_document_element_name_changed(this: DomDocument*, element: DomElement*):
    if dom_element_name(element) != none:
        dom_insert_in_tree_order(&this.m_potentially_named_elements, element)
    else:
        if dom_is_potentially_named_element_by_id(element) and dom_element_id(element) != none:
            return
        dom_document_remove_potentially_named_element(this, element)

## Ported from Document.cpp:6283 Web::DOM::Document::element_with_name_was_added.
pub func dom_document_element_with_name_was_added(this: DomDocument*, element: DomElement*):
    if dom_is_potentially_named_element(element):
        dom_insert_in_tree_order(&this.m_potentially_named_elements, element)

## Ported from Document.cpp:6289 Web::DOM::Document::element_with_name_was_removed.
pub func dom_document_element_with_name_was_removed(this: DomDocument*, element: DomElement*):
    if dom_is_potentially_named_element(element):
        if dom_is_potentially_named_element_by_id(element) and dom_element_id(element) != none:
            return
        dom_document_remove_potentially_named_element(this, element)

## Ported from Document.cpp:6298 Web::DOM::Document::element_by_anchor_name.
pub func dom_document_element_by_anchor_name(this: DomDocument*, name: ak.FlyString, querying_node: DomNode*) -> DomElement*?:
    # https://drafts.csswg.org/css-shadow-1/#tree-scoped-name
    # If a tree-scoped name is global (such as @font-face names), then when a tree-scoped reference is dereferenced to
    # find it, first search only the tree-scoped names associated with the same root as the tree-scoped reference. If
    # no relevant tree-scoped name is found, and the root is a shadow root, then repeat this search in the root's
    # host's node tree (recursively).
    var node = querying_node
    while let shadow_root = as_if_dom_shadow_root(tree_node_root(node)):
        if let element = dom_anchor_name_map_element_by_name(dom_shadow_root_anchor_name_map(shadow_root), name):
            return element
        let host = dom_document_fragment_host(shadow_root.dom_document_fragment()) else return none
        node = host.dom_node()
    return dom_anchor_name_map_element_by_name(&this.m_anchor_name_map, name)

## Ported from Document.cpp:6316 Web::DOM::Document::add_form_associated_element_with_form_attribute.
pub func dom_document_add_form_associated_element_with_form_attribute(this: DomDocument*, form_associated_element: HtmlFormAssociatedElement*):
    ak.vector_append_t(&this.m_form_associated_elements_with_form_attribute, form_associated_element)

## The captures of remove_form_associated_element_with_form_attribute's predicate.
struct DomDocumentIsFormAssociatedElement:
    var form_associated_element: HtmlFormAssociatedElement*

## The predicate `element == &form_associated_element`.
func dom_document_is_form_associated_element(context: void*?, element: const (HtmlFormAssociatedElement*?)*) -> bool:
    let captures = (DomDocumentIsFormAssociatedElement*)(context else trap("no captures"))
    return *element == captures.form_associated_element

## Ported from Document.cpp:6321 Web::DOM::Document::remove_form_associated_element_with_form_attribute.
pub func dom_document_remove_form_associated_element_with_form_attribute(this: DomDocument*, form_associated_element: HtmlFormAssociatedElement*):
    var captures = DomDocumentIsFormAssociatedElement(form_associated_element = form_associated_element)
    _ = ak.vector_remove_all_matching(&this.m_form_associated_elements_with_form_attribute, ak.Function1[const (HtmlFormAssociatedElement*?)*, bool](call = dom_document_is_form_associated_element, context = &captures))

# mark: Design mode =============================================================================

## Ported from Document.cpp:6328 Web::DOM::Document::set_design_mode_enabled_state.
pub func dom_document_set_design_mode_enabled_state(this: DomDocument*, design_mode_enabled: bool):
    this.m_design_mode_enabled = design_mode_enabled
    dom_document_set_editable(this, design_mode_enabled)
    for node in dom_node_inclusive_subtree(this.dom_node()):
        dom_node_recompute_editable_subtree_flag(node)

## Ported from Document.cpp:6339 Web::DOM::Document::design_mode.
# https://html.spec.whatwg.org/multipage/interaction.html#making-entire-documents-editable:-the-designmode-idl-attribute
pub func dom_document_design_mode(this: DomDocument*) -> ak.String:
    # The designMode getter steps are to return "on" if this's design mode enabled is true; otherwise "off".
    return ak.string_from_str("on") if dom_document_design_mode_enabled_state(this) else ak.string_from_str("off")

## Ported from Document.cpp:6345 Web::DOM::Document::set_design_mode.
pub func dom_document_set_design_mode(this: DomDocument*, design_mode: ak.String) -> !:
    # 1. Let value be the given value, converted to ASCII lowercase.
    let value = web_unicode.string_to_lowercase(&design_mode) else trap("MUST: String::to_lowercase")

    # 2. If value is "on" and this's design mode enabled is false, then:
    if ak.string_eq_string_view(&value, ak.sv("on")) and not this.m_design_mode_enabled:
        # 1. Set this's design mode enabled to true.
        dom_document_set_design_mode_enabled_state(this, true)
        # 2. Reset this's active range's start and end boundary points to be at the start of this.
        if let selection = dom_document_get_selection(this):
            try selection_selection_collapse(selection, this.dom_node(), 0)
            dom_document_update_layout(this, DomUpdateLayoutReason.document_set_design_mode)
        # 3. Run the focusing steps for this's document element, if non-null.
        if let document_element = dom_document_document_element(this):
            html_run_focusing_steps(document_element.dom_node())
    # 3. If value is "off", then set this's design mode enabled to false.
    elif ak.string_eq_string_view(&value, ak.sv("off")):
        dom_document_set_design_mode_enabled_state(this, false)

# mark: Hit testing =============================================================================

## Ported from Document.cpp:6370 Web::DOM::retarget_from_ua_internal_shadow_root.
func dom_retarget_from_ua_internal_shadow_root(element: DomElement*) -> DomElement*:
    var result = element
    while let shadow_root = dom_node_containing_shadow_root(result.dom_node()):
        if not dom_shadow_root_is_user_agent_internal(shadow_root):
            break
        result = dom_document_fragment_host(shadow_root.dom_document_fragment()) else trap("a shadow root has a host")
    return result

## The point (x, y) when it lies within the viewport (elementFromPoint's step 1 test).
func dom_document_point_in_viewport(this: DomDocument*, x: f64, y: f64) -> gfx.CssPixelPoint?:
    let viewport_rect = dom_document_viewport_rect(this)
    let position = gfx.CssPixelPoint(m_x = gfx.css_pixels_from_f64(x), m_y = gfx.css_pixels_from_f64(y))
    # FIXME: This should account for the size of the scroll bar.
    if x < 0.0 or y < 0.0 or position.m_x.gt(gfx.css_pixel_rect_width(&viewport_rect)) or position.m_y.gt(gfx.css_pixel_rect_height(&viewport_rect)):
        return none
    return position

## The captures of elementFromPoint's hit test callback: `[&]` (the hit element).
struct DomDocumentElementFromPointHit:
    var hit_element: DomElement*?

## elementFromPoint's hit test callback: the first element hit.
func dom_document_element_from_point_hit(context: void*?, result: PaintHitTestResult) -> TraversalDecision:
    let captures = (DomDocumentElementFromPointHit*)(context else trap("no captures"))
    var hit_result = result
    if let node = paint_hit_test_result_dom_node(&hit_result):
        if let element = as_if_dom_element(node):
            captures.hit_element = element
            return TraversalDecision.break_
    return TraversalDecision.continue_

## Ported from Document.cpp:6382 Web::DOM::Document::element_from_point.
# https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
pub func dom_document_element_from_point(this: DomDocument*, x: f64, y: f64) -> DomElement*?:
    # 1. If either argument is negative, x is greater than the viewport width excluding the size of a rendered scroll
    #    bar (if any), or y is greater than the viewport height excluding the size of a rendered scroll bar (if any), or
    #    there is no viewport associated with the document, return null and terminate these steps.
    let position = dom_document_point_in_viewport(this, x, y) else return none

    # Ensure the layout tree exists prior to hit testing.
    dom_document_update_layout(this, DomUpdateLayoutReason.document_element_from_point)

    # 2. If there is a box in the viewport that would be a target for hit testing at coordinates x,y, when applying the transforms
    #    that apply to the descendants of the viewport, return the associated element and terminate these steps.
    var captures = DomDocumentElementFromPointHit(hit_element = none)
    if let paintable_box = dom_node_paintable_box(this.dom_node()):
        _ = paint_paintable_hit_test(paintable_box.paint_paintable(), position, PaintHitTestType.exact, ak.Function1[PaintHitTestResult, TraversalDecision](call = dom_document_element_from_point_hit, context = &captures))
    if let hit_element = captures.hit_element:
        # AD-HOC: If element is inside a UA internal shadow root, retarget to the host.
        return dom_retarget_from_ua_internal_shadow_root(hit_element)

    # 3. If the document has a root element, return the root element and terminate these steps.
    if let root_element = dom_document_document_element(this):
        return root_element

    # 4. Return null.
    return none

## The captures of elementsFromPoint's hit test callback: `[&]` (the sequence).
struct DomDocumentElementsFromPointHits:
    var sequence: ak.Vector[DomElement*]*

## elementsFromPoint's hit test callback: append every element hit, retargeted, without repeats.
func dom_document_elements_from_point_hit(context: void*?, result: PaintHitTestResult) -> TraversalDecision:
    let captures = (DomDocumentElementsFromPointHits*)(context else trap("no captures"))
    var hit_result = result
    if let node = paint_hit_test_result_dom_node(&hit_result):
        if let hit_element = as_if_dom_element(node):
            # AD-HOC: If element is inside a UA internal shadow root, retarget to the host.
            let element = dom_retarget_from_ua_internal_shadow_root(hit_element)
            # AD-HOC: Avoid adding duplicates when multiple internal elements retarget to the same host.
            if ak.vector_is_empty(captures.sequence) or *ak.vector_last(captures.sequence) != element:
                ak.vector_append_t(captures.sequence, element)
    return TraversalDecision.continue_

## Ported from Document.cpp:6422 Web::DOM::Document::elements_from_point.
# https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint
pub func dom_document_elements_from_point(this: DomDocument*, x: f64, y: f64) -> ak.Vector[DomElement*]:
    # 1. Let sequence be a new empty sequence.
    var sequence: ak.Vector[DomElement*]

    # 2. If either argument is negative, x is greater than the viewport width excluding the size of a rendered scroll bar (if any),
    #    or y is greater than the viewport height excluding the size of a rendered scroll bar (if any),
    #    or there is no viewport associated with the document, return sequence and terminate these steps.
    let position = dom_document_point_in_viewport(this, x, y) else return sequence

    # Ensure the layout tree exists prior to hit testing.
    dom_document_update_layout(this, DomUpdateLayoutReason.document_elements_from_point)

    # 3. For each box in the viewport, in paint order, starting with the topmost box, that would be a target for
    #    hit testing at coordinates x,y even if nothing would be overlapping it, when applying the transforms that
    #    apply to the descendants of the viewport, append the associated element to sequence.
    var captures = DomDocumentElementsFromPointHits(sequence = &sequence)
    if let paintable_box = dom_node_paintable_box(this.dom_node()):
        _ = paint_paintable_hit_test(paintable_box.paint_paintable(), position, PaintHitTestType.exact, ak.Function1[PaintHitTestResult, TraversalDecision](call = dom_document_elements_from_point_hit, context = &captures))

    # 4. If the document has a root element, and the last item in sequence is not the root element,
    #    append the root element to sequence.
    if let root_element = dom_document_document_element(this):
        if ak.vector_is_empty(&sequence) or *ak.vector_last(&sequence) != root_element:
            ak.vector_append_t(&sequence, root_element)

    # 5. Return sequence.
    return sequence

## Ported from Document.cpp:6465 Web::DOM::Document::scrolling_element.
# https://drafts.csswg.org/cssom-view/#dom-document-scrollingelement
pub func dom_document_scrolling_element(this: DomDocument*) -> DomElement*?:
    # 1. If the Document is in quirks mode, follow these substeps:
    if dom_document_in_quirks_mode(this):
        # 1. If the body element exists, and it is not potentially scrollable, return the body element and abort these steps.
        #    For this purpose, a value of overflow:clip on the the body element’s parent element must be treated as overflow:hidden.
        if let body_element = dom_document_body(this):
            if not dom_element_is_potentially_scrollable(body_element.dom_element(), DomElementTreatOverflowClipOnBodyParentAsOverflowHidden.yes):
                return body_element.dom_element()

        # 2. Return null and abort these steps.
        return none

    # 2. If there is a root element, return the root element and abort these steps.
    if let root_element = dom_document_document_element(this):
        return root_element

    # 3. Return null.
    return none

# mark: Named properties ========================================================================

## Ported from Document.cpp:6487 Web::DOM::is_exposed.
# https://html.spec.whatwg.org/multipage/dom.html#exposed
func dom_is_exposed(element: DomElement*) -> bool:
    assert(is_html_embed_element(element) or is_html_object_element(element))

    # FIXME: An embed or object element is said to be exposed if it has no exposed object ancestor, and,
    #        for object elements, is additionally either not showing its fallback content or has no object or embed descendants.
    return true

## Ported from Document.cpp:6497 Web::DOM::Document::supported_property_names (override).
# https://html.spec.whatwg.org/multipage/dom.html#dom-tree-accessors:supported-property-names
pub func dom_document_supported_property_names_impl(base: BindPlatformObject*) -> ak.Vector[ak.FlyString]:
    let this = (DomDocument*)base
    # The supported property names of a Document object document at any moment consist of the following,
    # in tree order according to the element that contributed them, ignoring later duplicates,
    # and with values from id attributes coming before values from name attributes when the same element contributes both:
    var names: ak.OrderedHashTable[ak.FlyString, ak.FlyStringTraits]

    for element in ak.vector_span(&this.m_potentially_named_elements):
        # - the value of the name content attribute for all exposed embed, form, iframe, img, and exposed object elements
        #   that have a non-empty name content attribute and are in a document tree with document as their root;
        if (is_html_embed_element(element) and dom_is_exposed(element)) or is_html_form_element(element) or is_html_htmli_frame_element(element) or is_html_image_element(element) or (is_html_object_element(element) and dom_is_exposed(element)):
            if let name = dom_element_name(element):
                _ = ak.ordered_hash_table_set(&names, name)

        # - the value of the id content attribute for all exposed object elements that have a non-empty id content attribute
        #   and are in a document tree with document as their root; and
        if is_html_object_element(element) and dom_is_exposed(element):
            if let id = dom_element_id(element):
                _ = ak.ordered_hash_table_set(&names, id)

        # - the value of the id content attribute for all img elements that have both a non-empty id content attribute
        #   and a non-empty name content attribute, and are in a document tree with document as their root.
        if is_html_image_element(element):
            if let id = dom_element_id(element):
                if dom_element_name(element) != none:
                    _ = ak.ordered_hash_table_set(&names, id)

    return ak.ordered_hash_table_values(&names)

## `Optional<FlyString> == FlyString`.
func dom_document_optional_fly_string_is(a: ak.FlyString?, b: ak.FlyString) -> bool:
    let a_value = a else return false
    return ak.fly_string_eq_fly_string(&a_value, &b)

## Ported from Document.cpp:6537 Web::DOM::is_named_element_with_name.
func dom_is_named_element_with_name(element: DomElement*, name: ak.FlyString) -> bool:
    # Named elements with the name name, for the purposes of the above algorithm, are those that are either:

    # - Exposed embed, form, iframe, img, or exposed object elements that have a name content attribute whose value
    #   is name, or
    if (is_html_embed_element(element) and dom_is_exposed(element)) or is_html_form_element(element) or is_html_htmli_frame_element(element) or is_html_image_element(element) or (is_html_object_element(element) and dom_is_exposed(element)):
        if dom_document_optional_fly_string_is(dom_element_name(element), name):
            return true

    # - Exposed object elements that have an id content attribute whose value is name, or
    if is_html_object_element(element) and dom_is_exposed(element):
        if dom_document_optional_fly_string_is(dom_element_id(element), name):
            return true

    # - img elements that have an id content attribute whose value is name, and that have a non-empty name content
    #   attribute present also.
    if is_html_image_element(element):
        if dom_document_optional_fly_string_is(dom_element_id(element), name) and dom_element_name(element) != none:
            return true

    return false

## Ported from Document.cpp:6568 Web::DOM::named_elements_with_name.
func dom_named_elements_with_name(document: DomDocument*, name: ak.FlyString) -> ak.Vector[DomElement*]:
    var named_elements: ak.Vector[DomElement*]

    for element in ak.vector_span(&document.m_potentially_named_elements):
        if dom_is_named_element_with_name(element, name):
            ak.vector_append_t(&named_elements, element)

    return named_elements

## The captures of namedItem's collection filter: `[name]`.
struct DomDocumentNamedItemFilter:
    var name: ak.FlyString

## namedItem's collection filter: named elements with the name.
func dom_document_named_item_filter(context: void*?, element: DomElement*) -> bool:
    let captures = (DomDocumentNamedItemFilter*)(context else trap("no captures"))
    return dom_is_named_element_with_name(element, captures.name)

## Ported from Document.cpp:6581 Web::DOM::Document::named_item_value (override).
# https://html.spec.whatwg.org/multipage/dom.html#dom-document-nameditem
pub func dom_document_named_item_value_impl(base: BindPlatformObject*, name: ak.FlyString) -> JsValue:
    let this = (DomDocument*)base
    # 1. Let elements be the list of named elements with the name name that are in a document tree with the Document as their root.
    # NOTE: There will be at least one such element, since the algorithm would otherwise not have been invoked by Web IDL.
    var elements = dom_named_elements_with_name(this, name)

    # 2. If elements has only one element, and that element is an iframe element, and that iframe element's content navigable is not null,
    #    then return the active WindowProxy of the element's content navigable.
    if ak.vector_size(&elements) == 1 and is_html_htmli_frame_element(*ak.vector_first(&elements)):
        let iframe_element = as_html_navigable_container(*ak.vector_first(&elements))
        if let content_navigable = html_navigable_container_content_navigable(iframe_element):
            return js_value_from_object((JsObject*?)html_navigable_active_window_proxy(content_navigable))

    # 3. Otherwise, if elements has only one element, return that element.
    if ak.vector_size(&elements) == 1:
        return js_value_from_object((JsObject*)*ak.vector_first(&elements))

    # 4. Otherwise return an HTMLCollection rooted at the Document node, whose filter matches only named elements with the name name.
    let captures = new DomDocumentNamedItemFilter(name = name) else trap("out of memory")
    return js_value_from_object((JsObject*)dom_html_collection_create(this.dom_parent_node(), DomHtmlCollectionScope.descendants, ak.Function1[DomElement*, bool](call = dom_document_named_item_filter, context = captures), ak.Function2[DomElement*, DomElement*, bool]()))