Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / dom / element_6.lucb

#==============================================================================================
#
#   element_6 - DOM::Element: fragment parsing, outerHTML, insertAdjacent*, fullscreen
#
#   DESCRIPTION:
#       Port of LibWeb/DOM/Element.cpp (lines 2349-2703): the fragment parsing algorithm
#       steps, the outerHTML getter and setter, insertAdjacentHTML, requestFullscreen and the
#       fullscreen removing steps and checks, the onfullscreen* event handler attributes,
#       insert adjacent, insertAdjacentElement and insertAdjacentText.
#
#==============================================================================================

# mark: Fragment parsing and outerHTML ==========================================================

## Ported from Element.cpp:2350 Web::DOM::Element::parse_fragment.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#fragment-parsing-algorithm-steps
pub func dom_element_parse_fragment(this: DomElement*, markup: ak.StringView, scripting_mode: HtmlParserScriptingMode = HtmlParserScriptingMode.inert) -> DomDocumentFragment*!:
    # 1. Assert: scriptingMode is either Inert or Fragment.
    assert(scripting_mode == HtmlParserScriptingMode.inert or scripting_mode == HtmlParserScriptingMode.fragment)

    # 2. Let newChildren be null.
    var new_children: ak.Vector[DomNode*?]

    # 3. If context's node document is an XML document, then set newChildren to the result of invoking the XML fragment parsing algorithm given context and markup.
    if dom_document_is_xml_document(dom_element_document(this)):
        new_children = try xml_fragment_parser_parse_xml_fragment(this, markup)
    # 4. Otherwise, set newChildren to the result of invoking the HTML fragment parsing algorithm given context, markup, false, and scriptingMode.
    else:
        new_children = try html_parser_parse_html_fragment(this, markup, HtmlParserAllowDeclarativeShadowRoots.no, scripting_mode)

    # 5. Let fragment be a new DocumentFragment whose node document is context's node document.
    let fragment = realm_create_dom_document_fragment(dom_element_realm(this), dom_element_document(this))

    # 6. For each node of newChildren, in tree order: append node to fragment.
    for child in ak.vector_span(&new_children):
        _ = try dom_node_append_child(fragment.dom_node(), child else trap("null GC::Root<Node>"))

    # 7. Return fragment.
    return fragment

## Ported from Element.cpp:2379 Web::DOM::Element::outer_html.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-outerhtml
pub func dom_element_outer_html(this: DomElement*) -> TrustedTypesTrustedHtmlOrString!:
    return .utf16_string(try dom_node_serialize_fragment(this.dom_node(), HtmlRequireWellFormed.yes, DomFragmentSerializationMode.outer))

## Ported from Element.cpp:2385 Web::DOM::Element::set_outer_html.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-element-outerhtml
pub func dom_element_set_outer_html(this: DomElement*, value: TrustedTypesTrustedHtmlOrString) -> !:
    # 1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with
    #    TrustedHTML, this's relevant global object, the given value, "Element outerHTML", and "script".
    # (TrustedTypes::Script.to_string() is "'script'".)
    let compliant_string = try trusted_types_get_trusted_type_compliant_string(TrustedTypesTrustedTypeName.trusted_html, html_relevant_global_object((JsObject*)this), dom_element_trusted_html_or_string_as_trusted_type(value), TrustedTypesInjectionSink.element_outer_html, ak.string_from_str("'script'"))

    # 2. Let parent be this's parent.
    var parent = tree_node_parent(this.dom_node())

    # 3. If parent is null, return. There would be no way to obtain a reference to the nodes created even if the remaining steps were run.
    let parent_node = parent else return

    # 4. If parent is a Document, throw a "NoModificationAllowedError" DOMException.
    if dom_node_is_document(parent_node):
        try idl_throw(.idl_dom_exception(idl_no_modification_allowed_error_create(dom_element_realm(this), ak.utf16_string_from_str("Cannot set outer HTML on document"))))

    # 5. If parent is a DocumentFragment, set parent to the result of creating an element given this's node document, "body", and the HTML namespace.
    if dom_node_is_document_fragment(parent_node):
        parent = (try dom_create_element(dom_element_document(this), html_tag_names_body, namespace_html)).dom_node()

    # 6. Let fragment be the result of invoking the fragment parsing algorithm steps given parent and compliantString.
    let compliant_utf8 = ak.utf16_string_base_to_utf8_but_should_be_ported_to_utf16(&compliant_string.utf16_string_base)
    let fragment = try dom_element_parse_fragment(as_dom_element(parent else trap("unreachable")), ak.string_bytes_as_string_view(&compliant_utf8))

    # 6. Replace this with fragment within this's parent.
    _ = try dom_node_replace_child(parent else trap("unreachable"), fragment.dom_node(), this.dom_node())

# mark: insertAdjacentHTML ======================================================================

## `String::equals_ignoring_ascii_case("text"sv)`.
func dom_element_string_equals_ignoring_ascii_case(string: const ak.String*, text: str) -> bool:
    return ak.string_equals_ignoring_ascii_case_string_view(string, ak.sv(text))

## Ported from Element.cpp:2421 Web::DOM::Element::insert_adjacent_html.
# https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#the-insertadjacenthtml()-method
pub func dom_element_insert_adjacent_html(this: DomElement*, position: ak.String, string: TrustedTypesTrustedHtmlOrString) -> !:
    # 1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with
    #    TrustedHTML, this's relevant global object, string, "Element insertAdjacentHTML", and "script".
    # (TrustedTypes::Script.to_string() is "'script'".)
    let compliant_string = try trusted_types_get_trusted_type_compliant_string(TrustedTypesTrustedTypeName.trusted_html, html_relevant_global_object((JsObject*)this), dom_element_trusted_html_or_string_as_trusted_type(string), TrustedTypesInjectionSink.element_insert_adjacent_html, ak.string_from_str("'script'"))

    # 2. Let context be null.
    var context: DomNode*? = none

    # 3. Use the first matching item from this list:
    # - If position is an ASCII case-insensitive match for the string "beforebegin"
    # - If position is an ASCII case-insensitive match for the string "afterend"
    if dom_element_string_equals_ignoring_ascii_case(&position, "beforebegin") or dom_element_string_equals_ignoring_ascii_case(&position, "afterend"):
        # 1. Set context to this's parent.
        context = tree_node_parent(this.dom_node())

        # 2. If context is null or a Document, throw a "NoModificationAllowedError" DOMException.
        if context == none or dom_node_is_document(context else trap("unreachable")):
            try idl_throw(.idl_dom_exception(idl_no_modification_allowed_error_create(dom_element_realm(this), ak.utf16_string_from_str("insertAdjacentHTML: context is null or a Document"))))
    # - If position is an ASCII case-insensitive match for the string "afterbegin"
    # - If position is an ASCII case-insensitive match for the string "beforeend"
    elif dom_element_string_equals_ignoring_ascii_case(&position, "afterbegin") or dom_element_string_equals_ignoring_ascii_case(&position, "beforeend"):
        # Set context to this.
        context = this.dom_node()
    # Otherwise
    else:
        # Throw a "SyntaxError" DOMException.
        try idl_throw(.idl_dom_exception(idl_syntax_error_create(dom_element_realm(this), ak.utf16_string_from_str("insertAdjacentHTML: invalid position argument"))))

    # 4. If context is not an Element or the following are all true:
    #    - context's node document is an HTML document,
    #    - context's local name is "html", and
    #    - context's namespace is the HTML namespace;
    let context_node = context else trap("unreachable")
    var replace_context = true
    if let context_element = as_if_dom_element(context_node):
        let local_name = dom_element_local_name(context_element)
        replace_context = dom_document_document_type(dom_node_document(context_node)) == DocumentDomDocumentType.html and ak.fly_string_eq_string_view(&local_name, ak.sv("html")) and dom_node_optional_fly_string_is(dom_element_namespace_uri(context_element), namespace_html)
    if replace_context:
        # then set context to the result of creating an element given this's node document, "body", and the HTML namespace.
        context = (try dom_create_element(dom_element_document(this), html_tag_names_body, namespace_html)).dom_node()

    # 5. Let fragment be the result of invoking the fragment parsing algorithm steps with context and compliantString.
    let compliant_utf8 = ak.utf16_string_base_to_utf8_but_should_be_ported_to_utf16(&compliant_string.utf16_string_base)
    let fragment = try dom_element_parse_fragment(as_dom_element(context else trap("unreachable")), ak.string_bytes_as_string_view(&compliant_utf8))

    # 6. Use the first matching item from this list:

    # - If position is an ASCII case-insensitive match for the string "beforebegin"
    if dom_element_string_equals_ignoring_ascii_case(&position, "beforebegin"):
        # Insert fragment into this's parent before this.
        dom_node_insert_before(tree_node_parent(this.dom_node()) else trap("unreachable"), fragment.dom_node(), this.dom_node())

    # - If position is an ASCII case-insensitive match for the string "afterbegin"
    elif dom_element_string_equals_ignoring_ascii_case(&position, "afterbegin"):
        # Insert fragment into this before its first child.
        dom_node_insert_before(this.dom_node(), fragment.dom_node(), tree_node_first_child(this.dom_node()))

    # - If position is an ASCII case-insensitive match for the string "beforeend"
    elif dom_element_string_equals_ignoring_ascii_case(&position, "beforeend"):
        # Append fragment to this.
        _ = try dom_node_append_child(this.dom_node(), fragment.dom_node())

    # - If position is an ASCII case-insensitive match for the string "afterend"
    elif dom_element_string_equals_ignoring_ascii_case(&position, "afterend"):
        # Insert fragment into this's parent before this's next sibling.
        dom_node_insert_before(tree_node_parent(this.dom_node()) else trap("unreachable"), fragment.dom_node(), tree_node_next_sibling(this.dom_node()))

# mark: Fullscreen ==============================================================================

## Ported from Element.cpp:2504 Web::DOM::Element::request_fullscreen.
# https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
pub func dom_element_request_fullscreen(this: DomElement*, fullscreen_requester: DomElementFullscreenRequester = DomElementFullscreenRequester.bindings) -> JsPromiseCapability*:
    let realm = dom_element_realm(this)

    # 1. Let pendingDoc be this’s node document.
    let pending_doc = this.parent_node.node.m_document else trap("an element has a node document")

    # 2. Let promise be a new promise.
    let promise = idl_create_promise(realm)

    # 3. If pendingDoc is not fully active, then reject promise with a TypeError exception and return promise.
    if not dom_document_is_fully_active(pending_doc):
        idl_reject_promise(realm, promise, js_type_error_create(realm, ak.string_from_str("Document not fully active.")))
        return promise

    # 4. Let error be false.
    # 5. If any of conditions are false, set error to true
    let error_ = dom_element_is_element_allowed_to_enter_fullscreen(this, fullscreen_requester)

    # 6. If error is false, then consume user activation given pendingDoc’s relevant global object.
    if error_ == DomRequestFullscreenError.false_:
        let relevant_global = as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)pending_doc))
        html_window_consume_user_activation(relevant_global)

    # 7. Return promise, and run the remaining steps in parallel.
    page_enqueue_fullscreen_enter(dom_document_page(pending_doc), this, pending_doc, error_, promise)

    return promise

## Element::exit_fullscreen_on_element_removal's lambda, run on each shadow-including inclusive
## descendant of the removed node; the context is the node document.
func dom_element_exit_fullscreen_on_element_removal_steps(context: void*?, node: DomNode*) -> TraversalDecision:
    let document = (DomDocument*)(context else trap("no document"))
    let element = as_if_dom_element(node) else return TraversalDecision.continue_

    if not dom_element_is_fullscreen_element(element):
        return TraversalDecision.continue_

    # 1. If node is document’s fullscreen element, exit fullscreen document.
    if dom_document_fullscreen_element(document) == element:
        _ = dom_document_exit_fullscreen(document)
    # 2. Otherwise, unfullscreen node.
    else:
        dom_document_unfullscreen_element(document, element)

    # 3. If document’s top layer contains node, remove from the top layer immediately given node
    if dom_element_in_top_layer(element):
        dom_document_remove_an_element_from_the_top_layer_immediately(document, element)

    return TraversalDecision.continue_

## Ported from Element.cpp:2537 Web::DOM::Element::exit_fullscreen_on_element_removal.
# https://fullscreen.spec.whatwg.org/#removing-steps
func dom_element_exit_fullscreen_on_element_removal(this: DomElement*):
    # 1. Let document be removedNode’s node document.
    let document = dom_element_document(this)

    # 2. Let nodes be removedNode’s shadow-including inclusive descendants that have their fullscreen flag set, in
    #    shadow-including tree order.
    # 3. For each node in nodes:
    _ = dom_node_for_each_shadow_including_inclusive_descendant(this.dom_node(), ak.Function1[DomNode*, TraversalDecision](call = dom_element_exit_fullscreen_on_element_removal_steps, context = document))

## Ported from Element.cpp:2570 Web::DOM::Element::is_element_allowed_to_enter_fullscreen.
# https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
# 5. If any of conditions are false, set error to true
pub func dom_element_is_element_allowed_to_enter_fullscreen(this: DomElement*, fullscreen_requester: DomElementFullscreenRequester) -> DomRequestFullscreenError:
    # * This’s namespace is the HTML namespace or this is an SVG svg or MathML math element. [SVG] [MATHML]
    # FIXME: This likely wants to use is<MathML::MathMLMathElement> instead.
    let tag_name = dom_element_tag_name(this)
    if not (dom_node_optional_fly_string_is(dom_element_namespace_uri(this), namespace_html) or dom_node_is_svg_svg_element(this.dom_node()) or (is_math_ml_math_ml_element(this) and ak.fly_string_eq_fly_string(&tag_name, &math_ml_tag_names_math))):
        return DomRequestFullscreenError.unsupported_element

    # * This is not a dialog element
    if is_html_dialog_element(this):
        return DomRequestFullscreenError.unsupported_element

    # * The fullscreen element ready check for this returns true.
    if not dom_element_is_element_ready_for_fullscreen(this):
        return DomRequestFullscreenError.element_ready_check_failed

    # FIXME: * Fullscreen is supported.

    # * This’s relevant global object has transient activation or the algorithm is triggered by a user generated
    #   orientation change.
    # FIXME: Handle user generated orientation changes.
    # FIXME: Spec issue: We don't require transient activations for WebDriver.
    #        https://github.com/w3c/webdriver/issues/1888
    if fullscreen_requester != DomElementFullscreenRequester.web_driver:
        let window = as_html_window((gc.Cell*)html_relevant_global_object((JsObject*)this))
        if not html_window_has_transient_activation(window):
            return DomRequestFullscreenError.no_transient_user_activation

    return DomRequestFullscreenError.false_

## Ported from Element.cpp:2602 Web::DOM::Element::is_element_ready_for_fullscreen.
# https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check
pub func dom_element_is_element_ready_for_fullscreen(this: DomElement*) -> bool:
    # A fullscreen element ready check for an element element returns true if all of the following are true, and false otherwise:

    # * element is connected.
    if not dom_node_is_connected(this.dom_node()):
        return false

    # * element’s node document is allowed to use the "fullscreen" feature.
    let document = this.parent_node.node.m_document else trap("an element has a node document")
    if not dom_document_is_allowed_to_use_feature(document, DomPolicyControlledFeature.fullscreen):
        return false

    # * element namespace is not the HTML namespace or element’s popover visibility state is hidden.
    if not dom_node_optional_fly_string_is(dom_element_namespace_uri(this), namespace_html):
        return true

    let html_element = as_if_html_element(this) else return false
    return html_element_popover_visibility_state(html_element) == HtmlElementPopoverVisibilityState.hidden

## Ported from Element.cpp:2622 Web::DOM::Element::onfullscreenchange.
pub func dom_element_onfullscreenchange(this: DomElement*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenchange)

## Ported from Element.cpp:2627 Web::DOM::Element::set_onfullscreenchange.
pub func dom_element_set_onfullscreenchange(this: DomElement*, event_handler: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenchange, event_handler)

## Ported from Element.cpp:2632 Web::DOM::Element::onfullscreenerror.
pub func dom_element_onfullscreenerror(this: DomElement*) -> IdlCallbackType*?:
    return dom_event_target_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenerror)

## Ported from Element.cpp:2637 Web::DOM::Element::set_onfullscreenerror.
pub func dom_element_set_onfullscreenerror(this: DomElement*, event_handler: IdlCallbackType*?):
    dom_event_target_set_event_handler_attribute(this.dom_event_target(), html_event_names_fullscreenerror, event_handler)

# mark: Insert adjacent =========================================================================

## Ported from Element.cpp:2643 Web::DOM::Element::insert_adjacent.
# https://dom.spec.whatwg.org/#insert-adjacent
func dom_element_insert_adjacent(this: DomElement*, where: ak.StringView, node: DomNode*) -> DomNode*?!:
    # To insert adjacent, given an element element, string where, and a node node, run the steps associated with the first ASCII case-insensitive match for where:
    if ak.string_view_equals_ignoring_ascii_case(&where, ak.sv("beforebegin")):
        # -> "beforebegin"
        # If element’s parent is null, return null.
        let parent = tree_node_parent(this.dom_node()) else return none

        # Return the result of pre-inserting node into element’s parent before element.
        return try dom_node_pre_insert(parent, node, this.dom_node())

    if ak.string_view_equals_ignoring_ascii_case(&where, ak.sv("afterbegin")):
        # -> "afterbegin"
        # Return the result of pre-inserting node into element before element’s first child.
        return try dom_node_pre_insert(this.dom_node(), node, tree_node_first_child(this.dom_node()))

    if ak.string_view_equals_ignoring_ascii_case(&where, ak.sv("beforeend")):
        # -> "beforeend"
        # Return the result of pre-inserting node into element before null.
        return try dom_node_pre_insert(this.dom_node(), node, none)

    if ak.string_view_equals_ignoring_ascii_case(&where, ak.sv("afterend")):
        # -> "afterend"
        # If element’s parent is null, return null.
        let parent = tree_node_parent(this.dom_node()) else return none

        # Return the result of pre-inserting node into element’s parent before element’s next sibling.
        return try dom_node_pre_insert(parent, node, tree_node_next_sibling(this.dom_node()))

    # -> Otherwise
    # Throw a "SyntaxError" DOMException.
    var builder = ak.string_builder_new_mode(ak.StringBuilderMode.utf16)
    ak.string_builder_append_string_view(&builder, ak.sv("Unknown position '"))
    ak.string_builder_append_string_view(&builder, where)
    ak.string_builder_append_string_view(&builder, ak.sv("'. Must be one of 'beforebegin', 'afterbegin', 'beforeend' or 'afterend'"))
    return try idl_throw(.idl_dom_exception(idl_syntax_error_create(dom_element_realm(this), ak.string_builder_to_utf16_string(&builder))))

## Ported from Element.cpp:2684 Web::DOM::Element::insert_adjacent_element.
# https://dom.spec.whatwg.org/#dom-element-insertadjacentelement
pub func dom_element_insert_adjacent_element(this: DomElement*, where: ak.String, element: DomElement*) -> DomElement*?!:
    # The insertAdjacentElement(where, element) method steps are to return the result of running insert adjacent, give this, where, and element.
    let returned_node = try dom_element_insert_adjacent(this, ak.string_bytes_as_string_view(&where), element.dom_node())
    let node = returned_node else return none
    return as_dom_element(node)

## Ported from Element.cpp:2694 Web::DOM::Element::insert_adjacent_text.
# https://dom.spec.whatwg.org/#dom-element-insertadjacenttext
pub func dom_element_insert_adjacent_text(this: DomElement*, where: ak.String, data: ak.Utf16String) -> !:
    # 1. Let text be a new Text node whose data is data and node document is this’s node document.
    let text = realm_create_dom_text_utf16_string(dom_element_realm(this), dom_element_document(this), data)

    # 2. Run insert adjacent, given this, where, and text.
    # Spec Note: This method returns nothing because it existed before we had a chance to design it.
    _ = try dom_element_insert_adjacent(this, ak.string_bytes_as_string_view(&where), text.dom_node())