Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_form_element_3.lucb

#==============================================================================================
#
#   html_form_element_3 - HTML::HTMLFormElement: the submission algorithms and
#                         the named properties
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLFormElement.cpp (lines 801-1237) and the inline functions of
#       HTMLFormElement.h: the mutate / entity body / get / mailto submission algorithms,
#       planning a navigation, the indexed and named properties (with the past names map), the
#       default button and the fields that block implicit submission.
#
#==============================================================================================

# mark: The submission algorithms ===============================================================

## Ported from HTMLFormElement.cpp:802 Web::HTML::HTMLFormElement::mutate_action_url.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mutate-action
pub func html_form_element_mutate_action_url(this: HtmlFormElement*, parsed_action: web_url.Url, entry_list: ak.Vector[XhrFormDataEntry], encoding: ak.String, target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement) -> !:
    var action = parsed_action

    # 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
    let pairs = try html_convert_to_list_of_name_value_pairs(entry_list)

    # 2. Let query be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
    let query = domurl_url_encode(&pairs, ak.string_bytes_as_string_view(&encoding))

    # 3. Set parsed action's query component to query.
    web_url.url_set_query(&action, query)

    # 4. Plan to navigate to parsed action.
    html_form_element_plan_to_navigate_to(this, action, EmptyOrStringOrHtmlPostResource.empty, entry_list, target_navigable, history_handling, user_involvement)

## Ported from HTMLFormElement.cpp:819 Web::HTML::HTMLFormElement::submit_as_entity_body.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-body
pub func html_form_element_submit_as_entity_body(this: HtmlFormElement*, parsed_action: web_url.Url, entry_list: ak.Vector[XhrFormDataEntry], encoding_type: HtmlFormElementEncodingTypeAttributeState, encoding: ak.String, target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement) -> !:
    # 1. Assert: method is POST.

    var mime_type = HtmlPostResourceRequestContentType.application_xwww_form_urlencoded
    var mime_type_directives: ak.Vector[HtmlPostResourceDirective]
    var body = ak.ByteBuffer()

    # 2. Switch on enctype:
    match encoding_type:
        .form_url_encoded:
            # -> application/x-www-form-urlencoded
            # 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
            let pairs = try html_convert_to_list_of_name_value_pairs(entry_list)

            # 2. Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
            let query = domurl_url_encode(&pairs, ak.string_bytes_as_string_view(&encoding))
            body = try ak.byte_buffer_copy_span_u8(ak.string_base_bytes(&query.string_base))

            # 3. Set body to the result of encoding body.
            # NOTE: `encoding` refers to `UTF-8 encode`, which body already is encoded as because it uses AK::String.

            # 4. Let mimeType be `application/x-www-form-urlencoded`.
            mime_type = HtmlPostResourceRequestContentType.application_xwww_form_urlencoded
        .form_data:
            # -> multipart/form-data
            # 1. Let body be the result of running the multipart/form-data encoding algorithm with entry list and encoding.
            let body_and_mime_type = try html_serialize_to_multipart_form_data(entry_list)
            body = body_and_mime_type.serialized_data

            # 2. Let mimeType be the isomorphic encoding of the concatenation of "multipart/form-data; boundary=" and the multipart/form-data
            #    boundary string generated by the multipart/form-data encoding algorithm.
            mime_type = HtmlPostResourceRequestContentType.multipart_form_data
            ak.vector_append_t(&mime_type_directives, HtmlPostResourceDirective(type_ = ak.sv("boundary"), value = body_and_mime_type.boundary))
        .plain_text:
            # -> text/plain
            # 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
            let pairs = try html_convert_to_list_of_name_value_pairs(entry_list)

            # 2. Let body be the result of running the text/plain encoding algorithm with pairs.
            let serialized_body = try html_plain_text_encode(pairs)
            body = try ak.byte_buffer_copy_span_u8(ak.string_base_bytes(&serialized_body.string_base))

            # FIXME: 3. Set body to the result of encoding body using encoding.

            # 4. Let mimeType be `text/plain`.
            mime_type = HtmlPostResourceRequestContentType.text_plain
        _:
            trap("VERIFY_NOT_REACHED")

    # 3. Plan to navigate to parsed action given a POST resource whose request body is body and request content-type is mimeType.
    html_form_element_plan_to_navigate_to(this, parsed_action, EmptyOrStringOrHtmlPostResource.html_post_resource(HtmlPostResource(request_body = body, request_content_type = mime_type, request_content_type_directives = mime_type_directives)), entry_list, target_navigable, history_handling, user_involvement)

## Ported from HTMLFormElement.cpp:882 Web::HTML::HTMLFormElement::get_action_url.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-get-action
pub func html_form_element_get_action_url(this: HtmlFormElement*, parsed_action: web_url.Url, entry_list: ak.Vector[XhrFormDataEntry], target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement):
    # 1. Plan to navigate to parsed action.
    # Spec Note: entry list is discarded.
    html_form_element_plan_to_navigate_to(this, parsed_action, EmptyOrStringOrHtmlPostResource.empty, entry_list, target_navigable, history_handling, user_involvement)

## Ported from HTMLFormElement.cpp:890 Web::HTML::HTMLFormElement::mail_with_headers.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mailto-headers
pub func html_form_element_mail_with_headers(this: HtmlFormElement*, parsed_action: web_url.Url, entry_list: ak.Vector[XhrFormDataEntry], encoding: ak.String, target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement) -> !:
    var action = parsed_action

    # 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
    let pairs = try html_convert_to_list_of_name_value_pairs(entry_list)

    # 2. Let headers be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
    let headers = domurl_url_encode(&pairs, ak.string_bytes_as_string_view(&encoding))

    # 3. Replace occurrences of U+002B PLUS SIGN characters (+) in headers with the string "%20".
    # donor quirk: String::replace returns the new string, and the C++ discards it (headers keep their pluses).
    _ = try ak.string_replace(&headers, ak.sv("+"), ak.sv("%20"), ak.ReplaceMode.all)

    # 4. Set parsed action's query to headers.
    web_url.url_set_query(&action, headers)

    # 5. Plan to navigate to parsed action.
    html_form_element_plan_to_navigate_to(this, action, EmptyOrStringOrHtmlPostResource.empty, entry_list, target_navigable, history_handling, user_involvement)

## Ported from HTMLFormElement.cpp:909 Web::HTML::HTMLFormElement::mail_as_body.
pub func html_form_element_mail_as_body(this: HtmlFormElement*, parsed_action: web_url.Url, entry_list: ak.Vector[XhrFormDataEntry], encoding_type: HtmlFormElementEncodingTypeAttributeState, encoding: ak.String, target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement) -> !:
    var action = parsed_action

    # 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
    let pairs = try html_convert_to_list_of_name_value_pairs(entry_list)

    var body = ak.string_new()

    # 2. Switch on enctype:
    match encoding_type:
        .plain_text:
            # -> text/plain
            # 1. Let body be the result of running the text/plain encoding algorithm with pairs.
            body = try html_plain_text_encode(pairs)

            # 2. Set body to the result of running UTF-8 percent-encode on body using the default encode set. [URL]
            # NOTE: body is already UTF-8 encoded due to using AK::String, so we only have to do the percent encoding.
            # NOTE: "default encode set" links to "path percent-encode-set": https://url.spec.whatwg.org/#default-encode-set
            body = web_url.percent_encode(ak.string_bytes_as_string_view(&body), web_url.PercentEncodeSet.path)
        _:
            # -> Otherwise
            # Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
            body = domurl_url_encode(&pairs, ak.string_bytes_as_string_view(&encoding))

    # 3. If parsed action's query is null, then set it to the empty string.
    if web_url.url_query(&action) == none:
        web_url.url_set_query(&action, ak.string_new())

    var query_builder = ak.string_builder_new()

    let query = web_url.url_query(&action) else trap("Optional::operator* of an empty value")
    ak.string_builder_append_string_view(&query_builder, ak.string_bytes_as_string_view(&query))

    # 4. If parsed action's query is not the empty string, then append a single U+0026 AMPERSAND character (&) to it.
    if not ak.string_is_empty(&query):
        try ak.string_builder_try_append_u8(&query_builder, '&')

    # 5. Append "body=" to parsed action's query.
    try ak.string_builder_try_append_string_view(&query_builder, ak.sv("body="))

    # 6. Append body to parsed action's query.
    try ak.string_builder_try_append_string_view(&query_builder, ak.string_bytes_as_string_view(&body))

    web_url.url_set_query(&action, ak.string_builder_to_string(&query_builder) else trap("MUST: StringBuilder::to_string"))

    # 7. Plan to navigate to parsed action.
    html_form_element_plan_to_navigate_to(this, action, EmptyOrStringOrHtmlPostResource.empty, entry_list, target_navigable, history_handling, user_involvement)

# mark: Planning a navigation ===================================================================

## The captures of the navigation task plan_to_navigate_to queues.
struct HtmlFormElementPlanToNavigateToTask:
    var this: HtmlFormElement*
    var url: web_url.Url
    var post_resource: EmptyOrStringOrHtmlPostResource
    var entry_list: ak.Vector[XhrFormDataEntry]
    var target_navigable: HtmlNavigable*
    var history_handling: BindNavigationHistoryBehavior
    var referrer_policy: ReferrerPolicyReferrerPolicy
    var user_involvement: HtmlUserNavigationInvolvement

    ## The task's steps.
    static func run(context: void*?):
        let captures = (HtmlFormElementPlanToNavigateToTask*)(context else trap("plan to navigate: no captures"))
        let this = captures.this

        # 1. Set the form's planned navigation to null.
        this.m_planned_navigation = none

        # 2. Navigate targetNavigable to url using the form element's node document, with historyHandling set to historyHandling,
        #    referrerPolicy set to referrerPolicy, documentResource set to postResource, and formDataEntryList set to entry list.
        html_navigable_navigate(captures.target_navigable, HtmlNavigableNavigateParams(url = captures.url, source_document = dom_node_document(this.dom_node()), document_resource = captures.post_resource, response = none, exceptions_enabled = false, history_handling = captures.history_handling, form_data_entry_list = captures.entry_list, referrer_policy = captures.referrer_policy, user_involvement = captures.user_involvement)) else trap("MUST: Navigable::navigate")

## The `[this](Task const& task)` filter of plan_to_navigate_to: the planned navigation.
func html_form_element_is_planned_navigation(context: void*?, task: HtmlTask*) -> bool:
    let this = (HtmlFormElement*)(context else trap("no form"))
    return this.m_planned_navigation == task

## Ported from HTMLFormElement.cpp:962 Web::HTML::HTMLFormElement::plan_to_navigate_to.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plan-to-navigate
pub func html_form_element_plan_to_navigate_to(this: HtmlFormElement*, url: web_url.Url, post_resource: EmptyOrStringOrHtmlPostResource, entry_list: ak.Vector[XhrFormDataEntry], target_navigable: HtmlNavigable*, history_handling: BindNavigationHistoryBehavior, user_involvement: HtmlUserNavigationInvolvement):
    # 1. Let referrerPolicy be the empty string.
    var referrer_policy = ReferrerPolicyReferrerPolicy.empty_string

    # 2. If the form element's link types include the noreferrer keyword, then set referrerPolicy to "no-referrer".
    let rel_value = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_rel)
    let rel = web_unicode.string_to_lowercase(&rel_value) else trap("MUST: String::to_lowercase")
    let rel_view = ak.string_bytes_as_string_view(&rel)
    let predicate = ak.CharPredicateFunction(function = web_infra.is_ascii_whitespace)
    var link_types = ak.string_view_split_view_if(&rel_view, &predicate)
    for link_type in ak.vector_span(&link_types):
        if ak.string_view_eq_string_view(&link_type, ak.sv("noreferrer")):
            referrer_policy = ReferrerPolicyReferrerPolicy.no_referrer
            break

    # 3. If the form has a non-null planned navigation, remove it from its task queue.
    if this.m_planned_navigation != none:
        html_task_queue_remove_tasks_matching(html_event_loop_task_queue(html_main_thread_event_loop()), ak.Function1[HtmlTask*, bool](call = html_form_element_is_planned_navigation, context = this))

    # 4. Queue an element task on the DOM manipulation task source given the form element and the following steps:
    # NOTE: `this`, `actual_resource` and `target_navigable` are protected by GC::HeapFunction.
    let captures = new HtmlFormElementPlanToNavigateToTask(this = this, url = url, post_resource = post_resource, entry_list = entry_list, target_navigable = target_navigable, history_handling = history_handling, referrer_policy = referrer_policy, user_involvement = user_involvement) else trap("out of memory")
    _ = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.dom_manipulation, ak.Function0[unit](call = HtmlFormElementPlanToNavigateToTask.run, context = captures))

    # 5. Set the form's planned navigation to the just-queued task.
    this.m_planned_navigation = html_task_queue_last_added_task(html_event_loop_task_queue(html_main_thread_event_loop()))
    assert(this.m_planned_navigation != none)

# mark: Indexed and named properties ============================================================

## Ported from HTMLFormElement.cpp:1005 Web::HTML::HTMLFormElement::item_value (override).
# https://html.spec.whatwg.org/multipage/forms.html#dom-form-item
pub func html_form_element_item_value_impl(base: BindPlatformObject*, index: usize) -> JsValue?:
    let this = (HtmlFormElement*)base
    # To determine the value of an indexed property for a form element, the user agent must return the value returned by
    # the item method on the elements collection, when invoked with the given index as its argument.
    if let value = dom_html_collection_item(&html_form_element_elements(this).html_collection, index):
        return js_value_from_object((JsObject*?)value)
    return none

## `first_is_one_of(name, candidate->id(), candidate->name())`.
func html_form_element_candidate_has_name(candidate: HtmlElement*, name: ak.FlyString) -> bool:
    return dom_node_optional_fly_string_is(dom_element_id(candidate.dom_element()), name) or dom_node_optional_fly_string_is(dom_element_name(candidate.dom_element()), name)

## Ported from HTMLFormElement.cpp:1014 Web::HTML::HTMLFormElement::is_supported_property_name (override).
pub func html_form_element_is_supported_property_name_impl(base: BindPlatformObject*, name: ak.FlyString) -> bool:
    let this = (HtmlFormElement*)base
    # NB: This is a simplified version of ::supported_property_names() that does not require sorting or allocations.
    for candidate in ak.vector_span(&this.m_associated_elements):
        if html_is_form_control(candidate.dom_element(), this) or is_html_image_element(candidate):
            if html_form_element_candidate_has_name(candidate, name):
                return true

    return ak.hash_map_contains_k(&this.m_past_names_map, name)

## SourcedName::Source (the local enum of supported_property_names).
enum HtmlFormElementSourcedNameSource as i32:
    id = 0
    name = 1
    past = 2

## SourcedName (the local struct of supported_property_names).
struct HtmlFormElementSourcedName:
    var name: ak.FlyString
    var element: DomElement*?
    var source: HtmlFormElementSourcedNameSource
    var age: ak.Duration

## The quick_sort comparator of supported_property_names: tree order of the elements, then the
## source, then the age.
func html_form_element_sourced_name_less_than(context: void*?, lhs: const HtmlFormElementSourcedName*, rhs: const HtmlFormElementSourcedName*) -> bool:
    if lhs.element != rhs.element:
        let lhs_element = lhs.element else trap("null element")
        let rhs_element = rhs.element else trap("null element")
        return tree_node_is_before(lhs_element.dom_node(), rhs_element.dom_node())
    if lhs.source != rhs.source:
        return (i32)lhs.source < (i32)rhs.source
    return ak.duration_cmp(&lhs.age, rhs.age) < 0

## Ported from HTMLFormElement.cpp:1028 Web::HTML::HTMLFormElement::supported_property_names (override).
# https://html.spec.whatwg.org/multipage/forms.html#the-form-element:supported-property-names
pub func html_form_element_supported_property_names_impl(base: BindPlatformObject*) -> ak.Vector[ak.FlyString]:
    let this = (HtmlFormElement*)base
    # The supported property names consist of the names obtained from the following algorithm, in the order obtained from this algorithm:

    # 1. Let sourced names be an initially empty ordered list of tuples consisting of a string, an element, a source,
    #    where the source is either id, name, or past, and, if the source is past, an age.
    var sourced_names: ak.Vector[HtmlFormElementSourcedName]

    # 2. For each listed element candidate whose form owner is the form element, with the exception of any
    #    input elements whose type attribute is in the Image Button state:
    for candidate in ak.vector_span(&this.m_associated_elements):
        if not html_is_form_control(candidate.dom_element(), this):
            continue

        # 1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the
        #    string, candidate as the element, and id as the source.
        if let id = dom_element_id(candidate.dom_element()):
            ak.vector_append_t(&sourced_names, HtmlFormElementSourcedName(name = id, element = candidate.dom_element(), source = HtmlFormElementSourcedNameSource.id, age = ak.Duration()))

        # 2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the
        #    string, candidate as the element, and name as the source.
        if let candidate_name = dom_element_name(candidate.dom_element()):
            ak.vector_append_t(&sourced_names, HtmlFormElementSourcedName(name = candidate_name, element = candidate.dom_element(), source = HtmlFormElementSourcedNameSource.name, age = ak.Duration()))

    # 3. For each img element candidate whose form owner is the form element:
    for candidate in ak.vector_span(&this.m_associated_elements):
        if not is_html_image_element(candidate):
            continue

        # Every element in m_associated_elements has this as the form owner.

        # 1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the
        #    string, candidate as the element, and id as the source.
        if let id = dom_element_id(candidate.dom_element()):
            ak.vector_append_t(&sourced_names, HtmlFormElementSourcedName(name = id, element = candidate.dom_element(), source = HtmlFormElementSourcedNameSource.id, age = ak.Duration()))

        # 2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the
        #    string, candidate as the element, and name as the source.
        if let candidate_name = dom_element_name(candidate.dom_element()):
            ak.vector_append_t(&sourced_names, HtmlFormElementSourcedName(name = candidate_name, element = candidate.dom_element(), source = HtmlFormElementSourcedNameSource.name, age = ak.Duration()))

    # 4. For each entry past entry in the past names map add an entry to sourced names with the past entry's name as
    #    the string, past entry's element as the element, past as the source, and the length of time past entry has
    #    been in the past names map as the age.
    let now = ak.monotonic_time_now()
    for entry in ak.hash_map_begin(&this.m_past_names_map):
        ak.vector_append_t(&sourced_names, HtmlFormElementSourcedName(name = entry.key, element = (DomElement*?)entry.value.node, source = HtmlFormElementSourcedNameSource.past, age = ak.monotonic_time_sub_monotonic_time(&now, entry.value.insertion_time)))

    # 5. Sort sourced names by tree order of the element entry of each tuple, sorting entries with the same element by
    #    putting entries whose source is id first, then entries whose source is name, and finally entries whose source
    #    is past, and sorting entries with the same element and source by their age, oldest first.
    ak.quick_sort_t_collection_t_less_than(ak.vector_span(&sourced_names), ak.Function2[const HtmlFormElementSourcedName*, const HtmlFormElementSourcedName*, bool](call = html_form_element_sourced_name_less_than, context = none))

    # FIXME: Surely there's a more efficient way to do this without so many FlyStrings and collections?
    # 6. Remove any entries in sourced names that have the empty string as their name.
    # 7. Remove any entries in sourced names that have the same name as an earlier entry in the map.
    # 8. Return the list of names from sourced names, maintaining their relative order.
    var names: ak.OrderedHashTable[ak.FlyString, ak.FlyStringTraits]
    ak.ordered_hash_table_ensure_capacity(&names, ak.vector_size(&sourced_names))
    for entry in ak.vector_span(&sourced_names):
        if ak.fly_string_is_empty(&entry.name):
            continue
        _ = ak.ordered_hash_table_set(&names, entry.name, ak.HashSetExistingEntryBehavior.keep)

    # names.values()
    var values: ak.Vector[ak.FlyString]
    ak.vector_ensure_capacity(&values, ak.ordered_hash_table_size(&names))
    for name in ak.ordered_hash_table_begin(&names):
        ak.vector_append_t(&values, *name)
    return values

## The `[this, name](auto& node)` filters of named_item_value: the form and the name.
struct HtmlFormElementNamedItemFilter:
    var this: HtmlFormElement*
    var name: ak.FlyString

    ## Listed form controls (no Image Button inputs) whose form owner is the form, with the id or name.
    static func form_controls(context: void*?, node: DomNode*) -> bool:
        let captures = (HtmlFormElementNamedItemFilter*)(context else trap("named item filter: no captures"))
        if not is_dom_element(node):
            return false
        let element = as_dom_element(node)

        # Form controls are defined as listed elements, with the exception of input elements in the Image Button state,
        # whose form owner is the form element.
        if not html_is_form_control(element, captures.this):
            return false

        return dom_node_optional_fly_string_is(dom_element_id(element), captures.name) or dom_node_optional_fly_string_is(dom_element_name(element), captures.name)

    ## img elements whose form owner is the form, with the id or name.
    static func images(context: void*?, node: DomNode*) -> bool:
        let captures = (HtmlFormElementNamedItemFilter*)(context else trap("named item filter: no captures"))
        if not is_html_image_element(node):
            return false

        let element = as_html_image_element(node)
        if html_form_associated_element_form(&element.html_element().form_associated_element) != captures.this:
            return false

        return dom_node_optional_fly_string_is(dom_element_id(element.dom_element()), captures.name) or dom_node_optional_fly_string_is(dom_element_name(element.dom_element()), captures.name)

## Ported from HTMLFormElement.cpp:1114 Web::HTML::HTMLFormElement::named_item_value (override).
# https://html.spec.whatwg.org/multipage/forms.html#dom-form-nameditem
pub func html_form_element_named_item_value_impl(base: BindPlatformObject*, name: ak.FlyString) -> JsValue:
    let this = (HtmlFormElement*)base
    let realm = html_element_realm(this.html_element())
    let root = as_dom_parent_node(tree_node_root(this.dom_node()))

    # To determine the value of a named property name for a form element, the user agent must run the following steps:

    # 1. Let candidates be a live RadioNodeList object containing all the listed elements, whose form owner is the form
    #    element, that have either an id attribute or a name attribute equal to name, with the exception of input
    #    elements whose type attribute is in the Image Button state, in tree order.
    let captures = new HtmlFormElementNamedItemFilter(this = this, name = name) else trap("out of memory")
    var candidates = html_radio_node_list_create(realm, root.dom_node(), DomLiveNodeListScope.descendants, ak.Function1[DomNode*, bool](call = HtmlFormElementNamedItemFilter.form_controls, context = captures))

    # 2. If candidates is empty, let candidates be a live RadioNodeList object containing all the img elements,
    #    whose form owner is the form element, that have either an id attribute or a name attribute equal to name,
    #    in tree order.
    # (RadioNodeList derives from DOM::NodeList through LiveNodeList, first; opaque until phase 3.)
    if dom_node_list_length((DomNodeList*)candidates) == 0:
        candidates = html_radio_node_list_create(realm, root.dom_node(), DomLiveNodeListScope.descendants, ak.Function1[DomNode*, bool](call = HtmlFormElementNamedItemFilter.images, context = captures))

    let length = dom_node_list_length((DomNodeList*)candidates)

    # 3. If candidates is empty, name is the name of one of the entries in the form element's past names map: return the object associated with name in that map.
    if length == 0:
        if let entry = ak.hash_map_get_k(&this.m_past_names_map, name):
            return js_value_from_object((JsObject*?)entry.node)

    # 4. If candidates contains more than one node, return candidates.
    if length > 1:
        return js_value_from_object((JsObject*?)candidates)

    # 5. Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the form
    #    element's past names map, replacing the previous entry with the same name, if any.
    let node = dom_node_list_item((DomNodeList*)candidates, 0)
    _ = ak.hash_map_set(&this.m_past_names_map, name, HtmlFormElementPastNameEntry(node = node, insertion_time = ak.monotonic_time_now()))

    # 6. Return the node in candidates.
    return js_value_from_object((JsObject*?)node)

# mark: The default button and implicit submission ==============================================

## Ported from HTMLFormElement.cpp:1176 Web::HTML::HTMLFormElement::default_button.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#default-button
pub func html_form_element_default_button(this: HtmlFormElement*) -> HtmlFormAssociatedElement*?:
    # A form element's default button is the first submit button in tree order whose form owner is that form element.
    var default_button: HtmlFormAssociatedElement*? = none

    for node in dom_node_subtree(tree_node_root(this.dom_node())):
        let form_associated_element = as_if_form_associated_element(node) else continue

        if html_form_associated_element_form(form_associated_element) == this and html_form_associated_element_is_submit_button(form_associated_element):
            default_button = form_associated_element
            break

    return default_button

## Ported from HTMLFormElement.cpp:1198 Web::HTML::HTMLFormElement::number_of_fields_blocking_implicit_submission.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#field-that-blocks-implicit-submission
func html_form_element_number_of_fields_blocking_implicit_submission(this: HtmlFormElement*) -> usize:
    # For the purpose of the previous paragraph, an element is a field that blocks implicit submission of a form
    # element if it is an input element whose form owner is that form element and whose type attribute is in one of
    # the following states: Text, Search, Telephone, URL, Email, Password, Date, Month, Week, Time,
    # Local Date and Time, Number.
    var count: usize = 0

    for element in ak.vector_span(&this.m_associated_elements):
        if not is_html_input_element(element):
            continue

        let input = as_html_input_element(element)

        match html_input_element_type_state(input):
            .text, .search, .telephone, .url, .email, .password, .date, .month, .week, .time, .local_date_and_time, .number:
                count += 1
            _:
                continue

    return count

# mark: Inline functions of HTMLFormElement.h ===================================================

## Ported from HTMLFormElement.h:93 Web::HTML::HTMLFormElement::default_role (override).
# https://www.w3.org/TR/html-aria/#el-form
pub func html_form_element_default_role_impl(base: AriaMixin*) -> AriaRole?:
    return AriaRole.form

## Ported from HTMLFormElement.h:96 Web::HTML::HTMLFormElement::constructing_entry_list.
# https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#constructing-entry-list
pub func html_form_element_constructing_entry_list(this: HtmlFormElement*) -> bool:
    return this.m_constructing_entry_list

## Ported from HTMLFormElement.h:97 Web::HTML::HTMLFormElement::set_constructing_entry_list.
pub func html_form_element_set_constructing_entry_list(this: HtmlFormElement*, value: bool):
    this.m_constructing_entry_list = value

## Ported from HTMLFormElement.h:111 Web::HTML::HTMLFormElement::is_html_form_element (override).
pub func html_form_element_is_html_form_element_impl(base: DomNode*) -> bool:
    return true