Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / html / html_input_element_4.lucb

#==============================================================================================
#
#   html_input_element_4 - HTML::HTMLInputElement: focus, attribute changes, the type, values
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLInputElement.cpp (lines 1495-2056): receiving and losing
#       focus, the attribute change steps of the form-associated element, the type change
#       steps, signalling a type change (radio button groups), the src attribute of image
#       buttons, the type attribute's states and keywords, valid simple colors, the value
#       sanitization algorithm of every type, the reset and clear algorithms, the insertion
#       steps and the return key.
#
#==============================================================================================

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

## Ported from HTMLInputElement.cpp:1495 Web::HTML::HTMLInputElement::did_receive_focus (override).
pub func html_input_element_did_receive_focus_impl(base: DomElement*):
    let this = (HtmlInputElement*)base
    let text_node = this.m_text_node else return
    dom_node_set_needs_repaint(text_node.dom_node())

    if let placeholder_text_node = this.m_placeholder_text_node:
        dom_node_set_needs_repaint(placeholder_text_node.dom_node())

    if html_input_element_has_selectable_text(this):
        let document = html_input_element_document(this)
        if dom_document_last_focus_trigger(document) == HtmlFocusTrigger.key:
            html_form_associated_text_control_element_select(html_input_element_text_control(this)) else trap("MUST: select")
        else:
            selection_selection_remove_all_ranges(dom_document_get_selection(document) else trap("VERIFY: GC::Ptr<Selection>::operator-> on null"))

## Ported from HTMLInputElement.cpp:1512 Web::HTML::HTMLInputElement::did_lose_focus (override).
pub func html_input_element_did_lose_focus_impl(base: DomElement*):
    let this = (HtmlInputElement*)base
    if let text_node = this.m_text_node:
        dom_node_set_needs_repaint(text_node.dom_node())

    if let placeholder_text_node = this.m_placeholder_text_node:
        dom_node_set_needs_repaint(placeholder_text_node.dom_node())

    html_input_element_commit_pending_changes(this)

# mark: Attribute changes and the type ==========================================================

## Ported from HTMLInputElement.cpp:1523 Web::HTML::HTMLInputElement::form_associated_element_attribute_changed (override).
pub func html_input_element_form_associated_element_attribute_changed_impl(base: HtmlFormAssociatedElement*, name: ak.FlyString, old_value: ak.String?, value: ak.String?, namespace_: ak.FlyString?):
    let this = html_input_element_from_form_associated_element(base)
    html_popover_target_attributes_associated_attribute_changed(&this.popover_target_attributes, name, value, namespace_)

    if ak.fly_string_eq_fly_string(&name, &html_attribute_names_checked):
        # https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-input-checked-dirty-2
        # When the checked content attribute is added, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to true;
        # when the checked content attribute is removed, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to false.
        if not this.m_dirty_checkedness:
            html_input_element_set_checked(this, value != none)
            # set_checked() sets the dirty checkedness flag. We reset it here sinceit shouldn't be set when updating the attribute value
            this.m_dirty_checkedness = false
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_type):
        let type_value = value else ak.string_new()
        let new_type_attribute_state = html_input_element_parse_type_attribute(ak.string_bytes_as_string_view(&type_value))
        html_input_element_type_attribute_changed(this, this.m_type, new_type_attribute_state)

        # https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):the-input-element-4
        # the input element's type attribute is changed back to the Image Button state, and the src attribute is present,
        # and its value has changed since the last time the type attribute was in the Image Button state
        if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.image_button:
            if let src = dom_element_attribute(this.dom_element(), html_attribute_names_src):
                if not ak.string_equals(&src, &this.m_last_src_value):
                    html_input_element_handle_src_attribute(this, src) else trap("FIXME: should propagate errors")
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_value):
        if not this.m_dirty_value:
            let old_value_of_element = this.m_value

            if let new_value = value:
                this.m_value = html_input_element_value_sanitization_algorithm(this, ak.utf16_string_from_utf8_string(&new_value))
            else:
                this.m_value = ak.utf16_string_new()

            if not html_utf16_equals(&this.m_value, &old_value_of_element):
                html_form_associated_text_control_element_relevant_value_was_changed(html_input_element_text_control(this))

            html_input_element_update_shadow_tree(this)
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_placeholder):
        if let placeholder_text_node = this.m_placeholder_text_node:
            let placeholder = html_input_element_placeholder(this)
            dom_character_data_set_data(placeholder_text_node.dom_character_data(), ak.utf16_string_from_utf8_string(&placeholder))
            html_input_element_update_placeholder_visibility(this)
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_src):
        html_input_element_handle_src_attribute(this, value else ak.string_new()) else trap("FIXME: should propagate errors")
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_alt):
        if dom_element_unsafe_layout_node(this.dom_element()) != none and html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.image_button:
            let layout_node = dom_element_unsafe_layout_node(this.dom_element()) else trap("unreachable")
            layout_image_provider_did_update_alt_text(as_layout_image_box(layout_node))
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_maxlength):
        html_input_element_handle_maxlength_attribute(this)
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_multiple):
        if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.email and (old_value != none) != (value != none):
            this.m_value = html_input_element_value_sanitization_algorithm(this, this.m_value)
        html_input_element_update_shadow_tree(this)
    elif ak.fly_string_eq_fly_string(&name, &html_attribute_names_min) or ak.fly_string_eq_fly_string(&name, &html_attribute_names_max) or ak.fly_string_eq_fly_string(&name, &html_attribute_names_step):
        if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.range:
            this.m_value = html_input_element_value_sanitization_algorithm(this, this.m_value)
            html_input_element_update_shadow_tree(this)

## Ported from HTMLInputElement.cpp:1588 Web::HTML::HTMLInputElement::type_attribute_changed.
# https://html.spec.whatwg.org/multipage/input.html#input-type-change
func html_input_element_type_attribute_changed(this: HtmlInputElement*, old_state: HtmlInputElementTypeAttributeState, new_state: HtmlInputElementTypeAttributeState):
    let new_value_attribute_mode = html_input_element_value_attribute_mode_for_type_state(new_state)
    let old_value_attribute_mode = html_input_element_value_attribute_mode_for_type_state(old_state)

    if html_input_element_checked_applies_html_input_element_type_attrib(old_state) != html_input_element_checked_applies_html_input_element_type_attrib(new_state):
        css_invalidation_invalidate_style_after_checked_state_change(this.dom_element(), DomStyleInvalidationReason.html_input_element_set_type)

    # 1. If the previous state of the element's type attribute put the value IDL attribute in the value mode, and the element's
    #    value is not the empty string, and the new state of the element's type attribute puts the value IDL attribute in either
    #    the default mode or the default/on mode, then set the element's value content attribute to the element's value.
    if old_value_attribute_mode == HtmlInputElementValueAttributeMode.value and not html_utf16_is_empty(&this.m_value) and (new_value_attribute_mode == HtmlInputElementValueAttributeMode.default or new_value_attribute_mode == HtmlInputElementValueAttributeMode.default_on):
        dom_element_set_attribute_value(this.dom_element(), html_attribute_names_value, ak.utf16_string_base_to_utf8_but_should_be_ported_to_utf16(&this.m_value.utf16_string_base))

    # 2. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other
    #    than the value mode, and the new state of the element's type attribute puts the value IDL attribute in the value mode,
    #    then set the value of the element to the value of the value content attribute, if there is one, or the empty string
    #    otherwise, and then set the control's dirty value flag to false.
    elif old_value_attribute_mode != HtmlInputElementValueAttributeMode.value and new_value_attribute_mode == HtmlInputElementValueAttributeMode.value:
        let value_attribute = dom_element_attribute(this.dom_element(), html_attribute_names_value) else ak.string_new()
        this.m_value = ak.utf16_string_from_utf8_string(&value_attribute)
        this.m_dirty_value = false

    # 3. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other
    #    than the filename mode, and the new state of the element's type attribute puts the value IDL attribute in the filename mode,
    #    then set the value of the element to the empty string.
    elif old_value_attribute_mode != HtmlInputElementValueAttributeMode.filename and new_value_attribute_mode == HtmlInputElementValueAttributeMode.filename:
        this.m_value = ak.utf16_string_new()

    # 4. Update the element's rendering and behavior to the new state's.
    this.m_type = new_state
    dom_element_set_shadow_root(this.dom_element(), none)
    html_input_element_create_shadow_tree_if_needed(this)

    # 5. Signal a type change for the element. (The Radio Button state uses this, in particular.)
    html_input_element_signal_a_type_change(this)

    # 6. Invoke the value sanitization algorithm, if one is defined for the type attribute's new state.
    this.m_value = html_input_element_value_sanitization_algorithm(this, this.m_value)

    # 7. Let previouslySelectable be true if setRangeText() previously applied to the element, and false otherwise.
    let previously_selectable = html_input_element_selection_or_range_applies_for_type_state(old_state)

    # 8. Let nowSelectable be true if setRangeText() now applies to the element, and false otherwise.
    let now_selectable = html_input_element_selection_or_range_applies_for_type_state(new_state)

    # 9. If previouslySelectable is false and nowSelectable is true, set the element's text entry cursor position to the
    #    beginning of the text control, and set its selection direction to "none".
    if not previously_selectable and now_selectable:
        html_form_associated_text_control_element_set_the_selection_range(html_input_element_text_control(this), 0, 0)
        html_form_associated_text_control_element_set_selection_direction(html_input_element_text_control(this), none)

## Ported from HTMLInputElement.cpp:1645 Web::HTML::HTMLInputElement::computed_properties_changed (override).
pub func html_input_element_computed_properties_changed_impl(base: DomElement*):
    let this = (HtmlInputElement*)base
    html_input_element_create_shadow_tree_if_needed(this)
    html_input_element_update_shadow_tree(this)

## Unchecks every other checked input element in the same radio button group as `this`
## (`root().for_each_in_inclusive_subtree_of_type<HTMLInputElement>(...)`, three places).
func html_input_element_uncheck_others_in_radio_button_group(this: HtmlInputElement*):
    for node in dom_node_inclusive_subtree(tree_node_root(this.dom_node())):
        let element = as_if_html_input_element(node) else continue
        if html_input_element_checked(element) and element != this and html_is_in_same_radio_button_group(this, element):
            html_input_element_set_checked(element, false)

## Ported from HTMLInputElement.cpp:1652 Web::HTML::HTMLInputElement::signal_a_type_change.
# https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio):signal-a-type-change
func html_input_element_signal_a_type_change(this: HtmlInputElement*):
    # https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
    # When any of the following phenomena occur, if the element's checkedness state is true after the occurrence,
    # the checkedness state of all the other elements in the same radio button group must be set to false:
    # ...
    # - A type change is signalled for the element.
    if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.radio_button and html_input_element_checked(this):
        html_input_element_uncheck_others_in_radio_button_group(this)

# mark: The src attribute =======================================================================

## The captures of handle_src_attribute's tasks: `[this, &realm]`.
struct HtmlInputElementHandleSrcAttributeTask:
    var this: HtmlInputElement*
    var realm: Realm*

## The load event task of handle_src_attribute.
func html_input_element_handle_src_attribute_load_task(context: void*?):
    let captures = (HtmlInputElementHandleSrcAttributeTask*)(context else trap("no captures"))
    _ = html_input_element_dispatch_event(captures.this, dom_event_create(captures.realm, html_event_names_load))

## The error event task of handle_src_attribute.
func html_input_element_handle_src_attribute_error_task(context: void*?):
    let captures = (HtmlInputElementHandleSrcAttributeTask*)(context else trap("no captures"))
    _ = html_input_element_dispatch_event(captures.this, dom_event_create(captures.realm, html_event_names_error))

## `m_load_event_delayer.clear()`: destroys a held delayer.
func html_input_element_clear_load_event_delayer(this: HtmlInputElement*):
    if let delayer = this.m_load_event_delayer:
        var released = delayer
        dom_document_load_event_delayer_destruct(&released)
    this.m_load_event_delayer = none

## The resource request's on-finish callback of handle_src_attribute.
func html_input_element_handle_src_attribute_on_finish(context: void*?):
    let captures = (HtmlInputElementHandleSrcAttributeTask*)(context else trap("no captures"))
    let this = captures.this
    # 1. If the download was successful and the image is available, queue an element task on the user interaction
    #    task source given the input element to fire an event named load at the input element.
    _ = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.user_interaction, ak.Function0[unit](call = html_input_element_handle_src_attribute_load_task, context = captures))

    html_input_element_clear_load_event_delayer(this)
    dom_node_set_needs_layout_tree_update(this.dom_node(), true, DomSetNeedsLayoutTreeUpdateReason.html_input_element_src_attribute)

## The resource request's on-fail callback of handle_src_attribute.
func html_input_element_handle_src_attribute_on_fail(context: void*?):
    let captures = (HtmlInputElementHandleSrcAttributeTask*)(context else trap("no captures"))
    let this = captures.this
    # 2. Otherwise, if the fetching process fails without a response from the remote server, or completes but the
    #    image is not a valid or supported image, then queue an element task on the user interaction task source
    #    given the input element to fire an event named error on the input element.
    _ = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.user_interaction, ak.Function0[unit](call = html_input_element_handle_src_attribute_error_task, context = captures))

    html_input_element_clear_load_event_delayer(this)

## Ported from HTMLInputElement.cpp:1669 Web::HTML::HTMLInputElement::handle_src_attribute.
# https://html.spec.whatwg.org/multipage/input.html#attr-input-src
func html_input_element_handle_src_attribute(this: HtmlInputElement*, value: ak.String) -> !:
    let realm = html_input_element_realm(this)
    let vm = realm_vm(realm)
    let document = html_input_element_document(this)

    if html_input_element_type_state(this) != HtmlInputElementTypeAttributeState.image_button:
        return

    this.m_last_src_value = value

    # 1. Let url be the result of encoding-parsing a URL given the src attribute's value, relative to the element's
    #    node document.
    let url = dom_document_encoding_parse_url(document, ak.string_bytes_as_string_view(&value))

    # 2. If url is failure, then return.
    if url == none:
        return

    # 3. Let request be a new request whose URL is url, client is the element's node document's relevant settings
    #    object, destination is "image", initiator type is "input", credentials mode is "include", and whose
    #    use-URL-credentials flag is set.
    let request = fetch_request_create(vm)
    fetch_request_set_url(request, url else trap("unreachable"))
    fetch_request_set_client(request, dom_document_relevant_settings_object(document))
    fetch_request_set_destination(request, FetchRequestDestination.image)
    fetch_request_set_initiator_type(request, FetchRequestInitiatorType.input)
    fetch_request_set_credentials_mode(request, FetchRequestCredentialsMode.include)
    fetch_request_set_use_url_credentials(request, true)

    # 4. Fetch request, with processResponseEndOfBody set to the following steps given response response:
    let resource_request = html_shared_resource_request_get_or_create(realm, dom_document_page(document), fetch_request_url(request))
    this.m_resource_request = resource_request
    let captures = new HtmlInputElementHandleSrcAttributeTask(this = this, realm = realm) else trap("out of memory")
    html_shared_resource_request_add_callbacks(resource_request, ak.Function0[unit](call = html_input_element_handle_src_attribute_on_finish, context = captures), ak.Function0[unit](call = html_input_element_handle_src_attribute_on_fail, context = captures))

    if html_shared_resource_request_needs_fetching(resource_request):
        html_shared_resource_request_fetch_resource(resource_request, realm, request)

    # Fetching the image must delay the load event of the element's node document until the task that is queued by the
    # networking task source once the resource has been fetched (defined below) has been run.
    html_input_element_clear_load_event_delayer(this)
    var delayer: DomDocumentLoadEventDelayer = ---
    dom_document_load_event_delayer_construct(&delayer, document)
    this.m_load_event_delayer = delayer

# mark: The type attribute ======================================================================

## The keywords and states of ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES, in order.
let html_input_element_type_keywords: str[22] = ["hidden", "text", "search", "tel", "url", "email", "password", "date", "month", "week", "time", "datetime-local", "number", "range", "color", "checkbox", "radio", "file", "submit", "image", "reset", "button"]

## Ported from HTMLInputElement.cpp:1733 Web::HTML::HTMLInputElement::parse_type_attribute.
func html_input_element_parse_type_attribute(type_: ak.StringView) -> HtmlInputElementTypeAttributeState:
    for (index, keyword) in html_input_element_type_keywords.indexed():
        if ak.string_view_equals_ignoring_ascii_case(&type_, ak.sv(keyword)):
            return (HtmlInputElementTypeAttributeState)(i32)index

    # The missing value default and the invalid value default are the Text state.
    # https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
    # https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
    return HtmlInputElementTypeAttributeState.text

## Ported from HTMLInputElement.cpp:1747 Web::HTML::HTMLInputElement::type.
pub func html_input_element_type(this: HtmlInputElement*) -> ak.StringView:
    # FIXME: This should probably be `Reflect` in the IDL.
    let index = (usize)(i32)this.m_type
    if index < html_input_element_type_keywords.length:
        return ak.sv(html_input_element_type_keywords[index])

    trap("VERIFY_NOT_REACHED")

## Ported from HTMLInputElement.cpp:1761 Web::HTML::HTMLInputElement::set_type.
pub func html_input_element_set_type(this: HtmlInputElement*, type_: ak.String):
    dom_element_set_attribute_value(this.dom_element(), html_attribute_names_type, type_)

## Ported from HTMLInputElement.cpp:1766 Web::HTML::HTMLInputElement::can_have_text_editing_cursor.
pub func html_input_element_can_have_text_editing_cursor(this: HtmlInputElement*) -> bool:
    let type_state = html_input_element_type_state(this)
    if type_state == HtmlInputElementTypeAttributeState.submit_button or type_state == HtmlInputElementTypeAttributeState.reset_button or type_state == HtmlInputElementTypeAttributeState.button:
        return false

    return true

# mark: Value sanitization ======================================================================

## Ported from HTMLInputElement.cpp:1775 Web::HTML::is_valid_simple_color.
# https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
func html_is_valid_simple_color(value: ak.Utf16View) -> bool:
    # if it is exactly seven characters long,
    if ak.utf16_view_length_in_code_units(&value) != 7:
        return false
    # and the first character is a U+0023 NUMBER SIGN character (#),
    if not ak.utf16_view_starts_with_u16(&value, (u16)'#'):
        return false
    # and the remaining six characters are all ASCII hex digits
    for i in 1..<ak.utf16_view_length_in_code_units(&value):
        if not ak.is_ascii_hex_digit((u32)ak.utf16_view_code_unit_at(&value, i)):
            return false

    return true

## `strip_newlines` of the value sanitization algorithm.
func html_input_element_strip_newlines(value: ak.Utf16String) -> ak.Utf16String:
    if not ak.utf16_string_base_contains_u16(&value.utf16_string_base, (u16)'\r') and not ak.utf16_string_base_contains_u16(&value.utf16_string_base, (u16)'\n'):
        return value

    var builder = ak.string_builder_new_mode(ak.StringBuilderMode.utf16)

    for i in 0..<ak.utf16_string_base_length_in_code_units(&value.utf16_string_base):
        let code_unit = ak.utf16_string_base_code_unit_at(&value.utf16_string_base, i)
        if code_unit != (u16)'\r' and code_unit != (u16)'\n':
            ak.string_builder_append_code_unit(&builder, code_unit)

    return ak.string_builder_to_utf16_string(&builder)

## `strip_newlines_and_trim` of the value sanitization algorithm.
func html_input_element_strip_newlines_and_trim(value: ak.Utf16String) -> ak.Utf16String:
    let stripped = html_input_element_strip_newlines(value)
    return ak.utf16_string_trim(&stripped, ak.utf16_view_from_ascii(web_infra.ascii_whitespace.bytes))

## The value of a range input: the value, or the default value when it is not a valid floating-point number.
func html_input_element_range_number_value(this: HtmlInputElement*, value: ak.Utf16String, minimum: f64, maximum: f64) -> f64:
    # If the value of the element is not a valid floating-point number, then set it to the best representation,
    # as a floating-point number, of the default value.
    let maybe_value = html_parse_floating_point_number_utf16_string(value)
    # (Or) AD-HOC: Use the default value if the value has not been set.
    # (Or) AD-HOC: The spec doesn't require these checks - but other engines do them.
    if not html_is_valid_floating_point_number_utf16_string(value) or (not this.m_dirty_value and not html_input_element_has_attribute(this, html_attribute_names_value)) or maybe_value == none or not math.is_finite(maybe_value else 0.0):
        # The default value is the minimum plus half the difference between the minimum and the maximum, unless
        # the maximum is less than the minimum, in which case the default value is the minimum.
        if maximum < minimum:
            return minimum
        return minimum + ((maximum - minimum) / 2.0)
    return maybe_value else trap("unreachable")

## Ported from HTMLInputElement.cpp:1792 Web::HTML::HTMLInputElement::value_sanitization_algorithm.
# https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
func html_input_element_value_sanitization_algorithm(this: HtmlInputElement*, value: ak.Utf16String) -> ak.Utf16String:
    let type_state = html_input_element_type_state(this)

    # https://html.spec.whatwg.org/multipage/input.html#text-(type=text)-state-and-search-state-(type=search):value-sanitization-algorithm
    # https://html.spec.whatwg.org/multipage/input.html#telephone-state-(type=tel):value-sanitization-algorithm
    # https://html.spec.whatwg.org/multipage/input.html#password-state-(type=password):value-sanitization-algorithm
    if type_state == HtmlInputElementTypeAttributeState.text or type_state == HtmlInputElementTypeAttributeState.search or type_state == HtmlInputElementTypeAttributeState.telephone or type_state == HtmlInputElementTypeAttributeState.password:
        # Strip newlines from the value.
        return html_input_element_strip_newlines(value)

    # https://html.spec.whatwg.org/multipage/input.html#url-state-(type=url):value-sanitization-algorithm
    if type_state == HtmlInputElementTypeAttributeState.url:
        # Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
        return html_input_element_strip_newlines_and_trim(value)

    # https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
    # https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm-2
    if type_state == HtmlInputElementTypeAttributeState.email:
        if not html_input_element_has_attribute(this, html_attribute_names_multiple):
            # Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
            return html_input_element_strip_newlines_and_trim(value)

        # 1. Split on commas the element's value, strip leading and trailing ASCII whitespace from each resulting token,
        #    if any, and let the element's values be the (possibly empty) resulting list of (possibly empty) tokens,
        #    maintaining the original order.
        var values = ak.utf16_string_base_split_view_u16(&value.utf16_string_base, (u16)',', ak.SplitBehavior.keep_empty)

        for token in &ak.vector_span(&values):
            *token = ak.utf16_view_trim(token, ak.utf16_view_from_ascii(web_infra.ascii_whitespace.bytes))

        # 2. Set the element's value to the result of concatenating the element's values, separating each value from
        #    the next by a single U+002C COMMA character (,), maintaining the list's order.
        return ak.utf16_string_join_utf16_view(ak.utf16_view_from_ascii(",".bytes), ak.vector_span_const(&values))

    # https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):value-sanitization-algorithm
    if type_state == HtmlInputElementTypeAttributeState.number:
        # If the value of the element is not a valid floating-point number, then set it to the empty string instead.
        if not html_is_valid_floating_point_number_utf16_string(value):
            return ak.utf16_string_new()

        # AD-HOC: The spec doesn't require these checks - but other engines do them, and there's a WPT case which tests
        # that the value is less than Number.MAX_VALUE.
        let maybe_value = html_parse_floating_point_number_utf16_string(value)
        if maybe_value == none or not math.is_finite(maybe_value else 0.0):
            return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.date:
        # If the value of the element is not a valid date string, then set it to the empty string instead.
        if not html_is_valid_date_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.month:
        # If the value of the element is not a valid month string, then set it to the empty string instead.
        if not html_is_valid_month_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.week:
        if not html_is_valid_week_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.time:
        # If the value of the element is not a valid week string, then set it to the empty string instead.
        if not html_is_valid_time_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.local_date_and_time:
        # If the value of the element is a valid local date and time string, then set it to a valid normalized local
        # date and time string representing the same date and time; otherwise, set it to the empty string instead.
        if html_is_valid_local_date_and_time_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return html_normalize_local_date_and_time_string(value)
        return ak.utf16_string_new()
    # https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.range:
        let minimum = html_input_element_min(this) else trap("VERIFY: Optional::operator*")
        let maximum = html_input_element_max(this) else trap("VERIFY: Optional::operator*")
        var number_value = html_input_element_range_number_value(this, value, minimum, maximum)

        # When the element is suffering from an overflow, if the maximum is not less than the minimum, the user agent
        # must set the element's value to a valid floating-point number that represents the maximum.
        if html_input_element_is_number_overflowing(this, number_value):
            number_value = html_input_element_max(this) else trap("VERIFY: Optional::value() on an empty optional")

        # When the element is suffering from an underflow, the user agent must set the element's value to the best
        # representation, as a floating-point number, of the minimum.
        if html_input_element_is_number_underflowing(this, number_value):
            number_value = html_input_element_min(this) else trap("VERIFY: Optional::value() on an empty optional")

        # When the element is suffering from a step mismatch, the user agent must round the element's value to the
        # nearest number for which the element would not suffer from a step mismatch, and which is greater than or
        # equal to the minimum, and, if the maximum is not less than the minimum, which is less than or equal to the
        # maximum, if there is a number that matches these constraints. If two numbers match these constraints, then
        # user agents must use the one nearest to positive infinity.
        if html_input_element_is_number_mismatching_step(this, number_value):
            let allowed_step = html_input_element_allowed_value_step(this) else trap("VERIFY: Optional::value() on an empty optional")
            let step_minimum = html_input_element_min(this) else trap("VERIFY: Optional::value() on an empty optional")
            let step_maximum = html_input_element_max(this) else trap("VERIFY: Optional::value() on an empty optional")
            let step_mismatch = ((number_value - html_input_element_step_base(this)) / allowed_step) - math.floor((number_value - html_input_element_step_base(this)) / allowed_step)
            if step_mismatch >= 0.5:
                let nearest_number = html_input_element_step_base(this) + (allowed_step * math.ceil((number_value - html_input_element_step_base(this)) / allowed_step))
                if nearest_number >= step_minimum and (step_maximum <= step_minimum or nearest_number <= step_maximum):
                    return js_number_to_utf16_string(nearest_number)
            if step_mismatch <= 0.5:
                let nearest_number = html_input_element_step_base(this) + (allowed_step * math.floor((number_value - html_input_element_step_base(this)) / allowed_step))
                if nearest_number >= step_minimum and (step_maximum <= step_minimum or nearest_number <= step_maximum):
                    return js_number_to_utf16_string(nearest_number)

        return js_number_to_utf16_string(number_value)
    # https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
    elif type_state == HtmlInputElementTypeAttributeState.color:
        # If the value of the element is a valid simple color, then set it to the value of the element converted to
        # ASCII lowercase; otherwise, set it to the string "#000000".
        if html_is_valid_simple_color(ak.utf16_string_base_utf16_view(&value.utf16_string_base)):
            return ak.utf16_string_to_ascii_lowercase(&value)
        return ak.utf16_string_from_str("#000000")

    return value

# mark: Reset, clear, insertion and the return key ==============================================

## Ported from HTMLInputElement.cpp:1961 Web::HTML::HTMLInputElement::reset_algorithm (override).
# https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
pub func html_input_element_reset_algorithm_impl(base: HtmlFormAssociatedElement*):
    let this = html_input_element_from_form_associated_element(base)
    # The reset algorithm for input elements is to set its user validity, dirty value flag, and dirty checkedness flag back to false,
    this.m_user_validity = false
    this.m_dirty_value = false
    this.m_dirty_checkedness = false

    # set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
    let old_value = this.m_value
    let value_attribute = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_value)
    this.m_value = ak.utf16_string_from_utf8_string(&value_attribute)

    # set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
    this.m_checked = html_input_element_has_attribute(this, html_attribute_names_checked)

    # empty the list of selected files,
    if this.m_selected_files != none:
        this.m_selected_files = file_api_file_list_create(html_input_element_realm(this))

    # and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
    this.m_value = html_input_element_value_sanitization_algorithm(this, this.m_value)

    if not html_utf16_equals(&this.m_value, &old_value):
        html_form_associated_text_control_element_relevant_value_was_changed(html_input_element_text_control(this))

    if let text_node = this.m_text_node:
        dom_character_data_set_data(text_node.dom_character_data(), this.m_value)
        html_input_element_update_placeholder_visibility(this)

    html_input_element_update_shadow_tree(this)

## Ported from HTMLInputElement.cpp:1994 Web::HTML::HTMLInputElement::clear_algorithm (override).
# https://w3c.github.io/webdriver/#dfn-clear-algorithm
pub func html_input_element_clear_algorithm_impl(base: HtmlFormAssociatedElement*):
    let this = html_input_element_from_form_associated_element(base)
    # The clear algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
    this.m_dirty_value = false
    this.m_dirty_checkedness = false

    # set the value of the element to an empty string,
    let old_value = this.m_value
    this.m_value = ak.utf16_string_new()

    # set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
    this.m_checked = html_input_element_has_attribute(this, html_attribute_names_checked)

    # empty the list of selected files,
    if this.m_selected_files != none:
        this.m_selected_files = file_api_file_list_create(html_input_element_realm(this))

    # and then invoke the value sanitization algorithm iff the type attribute's current state defines one.
    this.m_value = html_input_element_value_sanitization_algorithm(this, this.m_value)

    # Unlike their associated reset algorithms, changes made to form controls as part of these algorithms do count as
    # changes caused by the user (and thus, e.g. do cause input events to fire).
    html_input_element_user_interaction_did_change_input_value(this)

    if not html_utf16_equals(&this.m_value, &old_value):
        html_form_associated_text_control_element_relevant_value_was_changed(html_input_element_text_control(this))

    if let text_node = this.m_text_node:
        dom_character_data_set_data(text_node.dom_character_data(), this.m_value)
        html_input_element_update_placeholder_visibility(this)

    html_input_element_update_shadow_tree(this)

## Ported from HTMLInputElement.cpp:2029 Web::HTML::HTMLInputElement::form_associated_element_was_inserted (override).
pub func html_input_element_form_associated_element_was_inserted_impl(base: HtmlFormAssociatedElement*):
    let this = html_input_element_from_form_associated_element(base)
    html_input_element_create_shadow_tree_if_needed(this)

    if dom_node_is_connected(this.dom_node()):
        # https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
        # When any of the following phenomena occur, if the element's checkedness state is true after the occurrence,
        # the checkedness state of all the other elements in the same radio button group must be set to false:
        # ...
        # - The element becomes connected.
        if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.radio_button and html_input_element_checked(this):
            html_input_element_uncheck_others_in_radio_button_group(this)

## Ported from HTMLInputElement.cpp:2049 Web::HTML::HTMLInputElement::handle_return_key (override).
pub func html_input_element_handle_return_key_impl(base: InputEventsTarget*, ui_input_type: ak.FlyString) -> EventResult:
    _ = ui_input_type
    let this = html_input_element_from_input_events_target(base)
    if let form = html_input_element_form(this):
        html_form_element_implicitly_submit_form(form) else trap("FIXME: should propagate errors")
    else:
        html_input_element_commit_pending_changes(this)
    return EventResult.handled