Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.0

0.6.0 / src / web / html / html_input_element_1.lucb

#==============================================================================================
#
#   html_input_element_1 - HTML::HTMLInputElement: construction, layout, checkedness, pickers
#
#   DESCRIPTION:
#       Port of LibWeb/HTML/HTMLInputElement.cpp (lines 1-480): is_integral_multiple, the
#       constructor (which moves the mixin tables to HTMLInputElement's, as C++'s vptrs move),
#       initialize, visit_edges, set_being_activated, the layout node, the adjusted computed
#       style, checkedness and indeterminate, the list attribute's suggestions source element,
#       the compiled pattern regular expression, the selected files and the accept attribute,
#       updating the file selection, showing the picker and showPicker(). The rest of the file
#       follows in html_input_element_2 to html_input_element_7; the inline functions of
#       HTMLInputElement.h are in html_input_element_7.
#
#       Copyright (c) 2018-2025, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2022, Adam Hodgen <ant1441@gmail.com>
#       Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
#       Copyright (c) 2023-2026, Shannon Booth <shannon@serenityos.org>
#       Copyright (c) 2023, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
#       Copyright (c) 2024-2026, Jelle Raaijmakers <jelle@ladybird.org>
#       Copyright (c) 2024, Fernando Kiotheka <fer@k6a.dev>
#       Copyright (c) 2025, Felipe Muñoz Mazur <felipe.munoz.mazur@protonmail.com>
#       Copyright (c) 2025, Glenn Skrzypczak <glenn.skrzypczak@gmail.com>
#       Copyright (c) 2026, Michiel Nijenhuis <michielmitsjol@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Helpers =================================================================================

## The input element of its FormAssociatedElement base (C++'s `this` adjustment).
func html_input_element_from_form_associated_element(base: HtmlFormAssociatedElement*) -> HtmlInputElement*:
    return (HtmlInputElement*)((u8*)base - memory.offset_of(HtmlElement, form_associated_element))

## The input element of its FormAssociatedTextControlElement base.
func html_input_element_from_text_control(base: HtmlFormAssociatedTextControlElement*) -> HtmlInputElement*:
    return (HtmlInputElement*)((u8*)base - memory.offset_of(HtmlInputElement, form_associated_text_control_element))

## The input element of its InputEventsTarget base (the first field of the text control).
func html_input_element_from_input_events_target(base: InputEventsTarget*) -> HtmlInputElement*:
    return (HtmlInputElement*)((u8*)base - memory.offset_of(HtmlInputElement, form_associated_text_control_element))

## The input element of its Layout::ImageProvider base.
func html_input_element_from_image_provider(base: LayoutImageProvider*) -> HtmlInputElement*:
    return (HtmlInputElement*)((u8*)base - memory.offset_of(HtmlInputElement, image_provider))

## The input element of its AutocompleteElement base.
func html_input_element_from_autocomplete_element(base: HtmlAutocompleteElement*) -> HtmlInputElement*:
    return (HtmlInputElement*)((u8*)base - memory.offset_of(HtmlInputElement, autocomplete_element))

## The FormAssociatedElement base of an input element.
func html_input_element_form_associated(this: HtmlInputElement*) -> HtmlFormAssociatedElement*:
    return &this.html_element_base.form_associated_element

## The FormAssociatedTextControlElement base of an input element.
func html_input_element_text_control(this: HtmlInputElement*) -> HtmlFormAssociatedTextControlElement*:
    return &this.form_associated_text_control_element

## `realm()` of an input element.
func html_input_element_realm(this: HtmlInputElement*) -> Realm*:
    return html_element_realm(this.html_element())

## `document()` of an input element.
func html_input_element_document(this: HtmlInputElement*) -> DomDocument*:
    return dom_node_document(this.dom_node())

## `form()` of an input element: its form owner.
func html_input_element_form(this: HtmlInputElement*) -> HtmlFormElement*?:
    return html_form_associated_element_form(html_input_element_form_associated(this))

## `has_attribute(name)` of an input element.
func html_input_element_has_attribute(this: HtmlInputElement*, name: ak.FlyString) -> bool:
    return dom_element_has_attribute(this.dom_element(), name)

## `get_attribute(name)` of an input element.
func html_input_element_get_attribute(this: HtmlInputElement*, name: ak.FlyString) -> ak.String?:
    return dom_element_get_attribute(this.dom_element(), name)

## `dispatch_event(event)` at an input element.
func html_input_element_dispatch_event(this: HtmlInputElement*, event: DomEvent*) -> bool:
    return dom_event_target_dispatch_event(this.dom_event_target(), event)

## `Utf16String::is_empty()`.
func html_utf16_is_empty(string: const ak.Utf16String*) -> bool:
    return ak.utf16_string_base_is_empty(&string.utf16_string_base)

## `Utf16String == Utf16String`.
func html_utf16_equals(a: const ak.Utf16String*, b: const ak.Utf16String*) -> bool:
    return ak.utf16_string_base_eq_utf16_string_base(&a.utf16_string_base, &b.utf16_string_base)

# mark: is_integral_multiple ====================================================================

## Ported from HTMLInputElement.cpp:70 (anonymous)::is_integral_multiple.
func is_integral_multiple(value: f64, step: f64) -> bool:
    assert(step > 0.0)

    # The step is so small, that the integral multiple closest to the value cannot be accurately expressed as a double
    if math.abs(value) / math.scalbn(1.0, 53) > step:
        return true

    let division_remainder = math.abs(math.remainder(value, step))
    # NOTE: There is no spec for the integral multiple. However, chromium uses tolerance so we comply here.
    #       https://github.com/chromium/chromium/blob/18aeefb6d0fe94e267c08e1aaeaf2632937f4ce2/third_party/blink/renderer/core/html/forms/step_range.cc#L67
    let acceptable_error = 0.0 if math.round(step) == step else step / f64(1 << 24)
    return division_remainder <= acceptable_error or division_remainder >= (step - acceptable_error)

# mark: Construction ============================================================================

## Ported from HTMLInputElement.cpp:91 Web::HTML::HTMLInputElement::HTMLInputElement.
pub func html_input_element_construct(this: HtmlInputElement*, document: DomDocument*, qualified_name: DomQualifiedName):
    html_element_construct(this.html_element(), document, qualified_name)
    html_input_element_init_fields(this)
    # The FormAssociatedTextControlElement, Layout::ImageProvider and AutocompleteElement bases get
    # their tables, then the vptrs of the mixin bases move to HTMLInputElement's tables.
    html_form_associated_text_control_element_init_fields(&this.form_associated_text_control_element)
    this.form_associated_text_control_element.input_events_target_base.vtable = (const InputEventsTargetVTable*)&html_input_element_form_associated_text_control_element_vtable
    this.form_associated_text_control_element.input_events_target_base.class_id = this.cell().class_id
    this.image_provider.vtable = &html_input_element_image_provider_vtable
    this.image_provider.class_id = this.cell().class_id
    this.autocomplete_element.vtable = &html_input_element_autocomplete_element_vtable
    this.autocomplete_element.class_id = this.cell().class_id
    let element = this.html_element()
    element.element.slottable_mixin.vtable = &html_input_element_slottable_mixin_vtable
    element.element.aria_mixin.vtable = &html_input_element_aria_mixin_vtable
    element.element.animatable.vtable = &html_input_element_animatable_vtable
    element.global_event_handlers.vtable = &html_input_element_global_event_handlers_vtable
    element.form_associated_element.vtable = &html_input_element_form_associated_element_vtable

## Ported from HTMLInputElement.cpp:98 Web::HTML::HTMLInputElement::initialize (override).
pub func html_input_element_initialize_impl(base: JsCell*, realm: Realm*):
    web_set_prototype_for_interface(base, realm, BindInterfaceName.html_input_element)
    html_element_initialize_impl(base, realm)

## Ported from HTMLInputElement.cpp:104 Web::HTML::HTMLInputElement::visit_edges (override).
pub func html_input_element_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (HtmlInputElement*)base
    html_element_visit_edges_impl(base, visitor)
    layout_image_provider_image_provider_visit_edges(&this.image_provider, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_inner_text_element)
    gc.cell_visitor_visit_t(visitor, this.m_text_node)
    gc.cell_visitor_visit_t(visitor, this.m_placeholder_element)
    gc.cell_visitor_visit_t(visitor, this.m_placeholder_text_node)
    gc.cell_visitor_visit_t(visitor, this.m_up_button_element)
    gc.cell_visitor_visit_t(visitor, this.m_down_button_element)
    gc.cell_visitor_visit_t(visitor, this.m_color_well_element)
    gc.cell_visitor_visit_t(visitor, this.m_file_button)
    gc.cell_visitor_visit_t(visitor, this.m_file_label)
    gc.cell_visitor_visit_t(visitor, this.m_legacy_pre_activation_behavior_checked_element_in_group)
    # (FileAPI::FileList is opaque until phase 2; it is a cell.)
    gc.cell_visitor_visit_cell(visitor, (gc.Cell*?)this.m_selected_files)
    gc.cell_visitor_visit_t(visitor, this.m_slider_runnable_track)
    gc.cell_visitor_visit_t(visitor, this.m_slider_progress_element)
    gc.cell_visitor_visit_t(visitor, this.m_slider_thumb)
    gc.cell_visitor_visit_t(visitor, this.m_resource_request)
    # (PopoverTargetAttributes::visit_edges: HTMLInputElement's C++ does not call it.)

## Ported from HTMLInputElement.cpp:125 Web::HTML::HTMLInputElement::set_being_activated (override).
pub func html_input_element_set_being_activated_impl(base: DomElement*, activated: bool):
    let this = (HtmlInputElement*)base
    dom_element_set_being_activated_impl(base, activated)
    if this.m_type == HtmlInputElementTypeAttributeState.checkbox or this.m_type == HtmlInputElementTypeAttributeState.radio_button:
        dom_node_set_needs_repaint(this.dom_node())

# mark: Layout ==================================================================================

## Ported from HTMLInputElement.cpp:132 Web::HTML::HTMLInputElement::create_layout_node (override).
pub func html_input_element_create_layout_node_impl(base: DomElement*, style: CssComputedProperties*) -> LayoutNode*?:
    let this = (HtmlInputElement*)base
    let document = html_input_element_document(this)
    let realm = html_input_element_realm(this)
    if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.hidden:
        return none

    # NOTE: Image inputs are `appearance: none` per the default UA style,
    #       but we still need to create an ImageBox for them, or no image will get loaded.
    if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.image_button:
        return realm_create_layout_image_box(realm, document, base, style, &this.image_provider).layout_node()

    # https://drafts.csswg.org/css-ui/#appearance-switching
    # This specification introduces the appearance property to provide some control over this behavior.
    # In particular, using appearance: none allows authors to suppress the native appearance of widgets,
    # giving them a primitive appearance where CSS can be used to restyle them.
    if css_computed_properties_appearance(style) == css_data.Appearance.none_:
        return (LayoutNode*?)dom_element_create_layout_node_for_display_type(document, css_computed_properties_display(style), style, base)

    match html_input_element_type_state(this):
        .submit_button, .button, .reset_button:
            return realm_create_layout_block_container_css_computed_properties(realm, document, this.dom_node(), style).layout_node()
        .checkbox:
            return realm_create_layout_check_box(realm, document, this, style).layout_node()
        .radio_button:
            return realm_create_layout_radio_button(realm, document, this, style).layout_node()
        .text, .search, .url, .telephone, .email, .password, .number:
            # FIXME: text padding issues
            return realm_create_layout_text_input_box(realm, document, base, style).layout_node()
        _:
            return (LayoutNode*?)dom_element_create_layout_node_for_display_type(document, css_computed_properties_display(style), style, base)

## Ported from HTMLInputElement.cpp:175 Web::HTML::HTMLInputElement::adjust_computed_style (override).
pub func html_input_element_adjust_computed_style_impl(base: DomElement*, style: CssComputedProperties*):
    let this = (HtmlInputElement*)base
    let type_state = html_input_element_type_state(this)
    if type_state == HtmlInputElementTypeAttributeState.hidden or type_state == HtmlInputElementTypeAttributeState.submit_button or type_state == HtmlInputElementTypeAttributeState.button or type_state == HtmlInputElementTypeAttributeState.reset_button or type_state == HtmlInputElementTypeAttributeState.image_button or type_state == HtmlInputElementTypeAttributeState.checkbox or type_state == HtmlInputElementTypeAttributeState.radio_button:
        return

    # https://drafts.csswg.org/css-display-3/#unbox
    let display = css_computed_properties_display(style)
    if css_display_is_contents(&display):
        css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.none_)).css_style_value())

    # AD-HOC: We rewrite `display: inline` to `display: inline-block`.
    #         This is required for the internal shadow tree to work correctly in layout.
    let display_now = css_computed_properties_display(style)
    if css_display_is_inline_outside(&display_now) and css_display_is_flow_inside(&display_now):
        css_computed_properties_set_property(style, css_data.PropertyId.display, css_display_style_value_create(css_display_from_short(CssDisplayShort.inline_block)).css_style_value())

    # NOTE: Other browsers apply a minimum height of a single line's line-height to single-line input elements.
    if html_input_element_is_single_line(this) and css_style_value_has_auto(css_computed_properties_property(style, css_data.PropertyId.height)):
        let current_line_height = css_computed_properties_line_height(style).to_double()
        let font = css_computed_properties_first_available_computed_font(style, dom_document_font_computer(html_input_element_document(this)))
        let minimum_line_height = f64(web_fonts.font_pixel_size(font)) * css_computed_properties_normal_line_height_scale

        # FIXME: Instead of overriding line-height, we should set height here instead.
        if current_line_height < minimum_line_height:
            css_computed_properties_set_property(style, css_data.PropertyId.line_height, css_keyword_style_value_create(css_data.Keyword.normal).css_style_value())

# mark: Checkedness =============================================================================

## Ported from HTMLInputElement.cpp:200 Web::HTML::HTMLInputElement::set_checked.
pub func html_input_element_set_checked(this: HtmlInputElement*, checked: bool):
    # The dirty checkedness flag must be initially set to false when the element is created,
    # and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
    this.m_dirty_checkedness = true
    if this.m_checked == checked:
        return

    this.m_checked = checked

    css_invalidation_invalidate_style_after_checked_state_change(this.dom_element(), DomStyleInvalidationReason.html_input_element_set_checked)

    dom_node_set_needs_repaint(this.dom_node())

## Ported from HTMLInputElement.cpp:215 Web::HTML::HTMLInputElement::set_checked_binding.
pub func html_input_element_set_checked_binding(this: HtmlInputElement*, checked: bool):
    if html_input_element_type_state(this) == HtmlInputElementTypeAttributeState.radio_button:
        if checked:
            html_input_element_set_checked_within_group(this)
        else:
            html_input_element_set_checked(this, false)
    else:
        html_input_element_set_checked(this, checked)

## Ported from HTMLInputElement.cpp:228 Web::HTML::HTMLInputElement::set_indeterminate.
# https://html.spec.whatwg.org/multipage/input.html#dom-input-indeterminate
pub func html_input_element_set_indeterminate(this: HtmlInputElement*, value: bool):
    # On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.
    this.m_indeterminate = value

# mark: The list attribute ======================================================================

## Ported from HTMLInputElement.cpp:235 Web::HTML::HTMLInputElement::list.
# https://html.spec.whatwg.org/multipage/input.html#dom-input-list
pub func html_input_element_list(this: HtmlInputElement*) -> HtmlDataListElement*?:
    # The list IDL attribute must return the current suggestions source element, if any, or null otherwise.
    if let data_list_element = html_input_element_suggestions_source_element(this):
        return data_list_element

    return none

## Ported from HTMLInputElement.cpp:245 Web::HTML::HTMLInputElement::suggestions_source_element.
# https://html.spec.whatwg.org/multipage/input.html#concept-input-list
func html_input_element_suggestions_source_element(this: HtmlInputElement*) -> HtmlDataListElement*?:
    # The suggestions source element is the first element in the tree in tree order to have an ID equal to the value of the list attribute,
    # if that element is a datalist element. If there is no list attribute, or if there is no element with that ID,
    # or if the first element with that ID is not a datalist element, then there is no suggestions source element.
    var result: HtmlDataListElement*? = none
    if let list_attribute_value = html_input_element_get_attribute(this, html_attribute_names_list):
        for node in dom_node_inclusive_subtree(tree_node_root(this.dom_node())):
            let element = as_if_dom_element(node) else continue
            if let id = dom_element_id(element):
                if ak.string_eq_fly_string(&list_attribute_value, &id):
                    if let data_list_element = as_if_html_data_list_element(element):
                        result = data_list_element

                    break

    return result

# mark: The pattern attribute ===================================================================

## Ported from HTMLInputElement.cpp:268 Web::HTML::HTMLInputElement::compiled_pattern_regular_expression.
## (C++ answers the regex by value; regex::ECMAScriptRegex::compile answers a pointer here.)
# https://html.spec.whatwg.org/multipage/input.html#compiled-pattern-regular-expression
func html_input_element_compiled_pattern_regular_expression(this: HtmlInputElement*) -> web_url.RegexEcmaScriptRegex*?:
    # 1. If the element does not have a pattern attribute specified, then return nothing. The element has no compiled pattern regular expression.
    let maybe_pattern = html_input_element_get_attribute(this, html_attribute_names_pattern)
    if maybe_pattern == none:
        return none

    # 2. Let pattern be the value of the pattern attribute of the element.
    let pattern = maybe_pattern else trap("unreachable")

    # 3. Let regexpCompletion be RegExpCreate(pattern, "v").
    var compile_flags = web_url.RegexEcmaScriptCompileFlags()
    compile_flags.unicode_sets = true
    let regexp_completion = web_url.regex_ecma_script_regex_compile(ak.string_bytes_as_string_view(&pattern), compile_flags) catch:
        # 4. If regexpCompletion is an abrupt completion, then return nothing. The element has no compiled pattern regular expression.
        return none
    _ = regexp_completion

    # 5. Let anchoredPattern be the string "^(?:", followed by pattern, followed by ")$".
    var builder = ak.string_builder_new()
    ak.string_builder_append_string_view(&builder, ak.sv("^(?:"))
    ak.string_builder_append_string_view(&builder, ak.string_bytes_as_string_view(&pattern))
    ak.string_builder_append_string_view(&builder, ak.sv(")$"))
    let anchored_pattern = ak.string_from_string_builder(&builder) else trap("MUST: String::formatted")

    # 6. Return ! RegExpCreate(anchoredPattern, "v").
    let anchored = web_url.regex_ecma_script_regex_compile(ak.string_bytes_as_string_view(&anchored_pattern), compile_flags) catch:
        return none
    return anchored

# mark: Files ===================================================================================

## Ported from HTMLInputElement.cpp:298 Web::HTML::HTMLInputElement::files.
# https://html.spec.whatwg.org/multipage/input.html#dom-input-files
pub func html_input_element_files(this: HtmlInputElement*) -> FileApiFileList*?:
    # On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
    #  The same object must be returned until the list of selected files changes.
    # If the IDL attribute does not apply, then it must instead return null.
    if this.m_type != HtmlInputElementTypeAttributeState.file_upload:
        return none

    if this.m_selected_files == none:
        this.m_selected_files = file_api_file_list_create(html_input_element_realm(this))
    return this.m_selected_files

## Ported from HTMLInputElement.cpp:312 Web::HTML::HTMLInputElement::set_files.
# https://html.spec.whatwg.org/multipage/input.html#dom-input-files
pub func html_input_element_set_files(this: HtmlInputElement*, files: FileApiFileList*?):
    # 1. If the IDL attribute does not apply or the given value is null, then return.
    if this.m_type != HtmlInputElementTypeAttributeState.file_upload or files == none:
        return

    # 2. Replace the element's selected files with the given value.
    this.m_selected_files = files

## Ported from HTMLInputElement.cpp:323 Web::HTML::HTMLInputElement::parse_accept_attribute.
# https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
pub func html_input_element_parse_accept_attribute(this: HtmlInputElement*) -> HtmlFileFilter:
    var filter = HtmlFileFilter(filters = ak.Vector[HtmlFileFilterFilterType]())

    # If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII
    # case-insensitive match for one of the following:
    let accept = dom_element_get_attribute_value(this.dom_element(), html_attribute_names_accept)

    let accept_view = ak.string_bytes_as_string_view(&accept)
    var values = ak.string_view_split_view_u8(&accept_view, ',', ak.SplitBehavior.nothing)
    for value in ak.vector_span(&values):
        # The string "audio/*"
        #     Indicates that sound files are accepted.
        if ak.string_view_equals_ignoring_ascii_case(&value, ak.sv("audio/*")):
            html_file_filter_add_filter(&filter, .file_type(HtmlFileFilterFileType.audio))

        # The string "video/*"
        #     Indicates that video files are accepted.
        elif ak.string_view_equals_ignoring_ascii_case(&value, ak.sv("video/*")):
            html_file_filter_add_filter(&filter, .file_type(HtmlFileFilterFileType.video))

        # The string "image/*"
        #     Indicates that image files are accepted.
        elif ak.string_view_equals_ignoring_ascii_case(&value, ak.sv("image/*")):
            html_file_filter_add_filter(&filter, .file_type(HtmlFileFilterFileType.image))

        # A valid MIME type string with no parameters
        #     Indicates that files of the specified type are accepted.
        elif html_input_element_accept_token_is_mime_type_without_parameters(value):
            let mime_type = mime_type_parse(value) else trap("unreachable")
            html_file_filter_add_filter(&filter, .mime_type(HtmlFileFilterMimeType(value = mime_type_essence(&mime_type))))

        # A string whose first character is a U+002E FULL STOP character (.)
        #     Indicates that files with the specified file extension are accepted.
        elif ak.string_view_starts_with_u8(&value, '.'):
            let extension = ak.string_view_substring_view(&value, 1)
            html_file_filter_add_filter(&filter, .extension(HtmlFileFilterExtension(value = ak.string_from_utf8(extension) else trap("MUST: String::from_utf8"))))

    return filter

## `auto mime_type = MimeSniff::MimeType::parse(value); mime_type.has_value() && mime_type->parameters().is_empty()`.
func html_input_element_accept_token_is_mime_type_without_parameters(value: ak.StringView) -> bool:
    let mime_type = mime_type_parse(value) else return false
    return ak.ordered_hash_map_is_empty(mime_type_parameters(&mime_type))

## The captures of update_the_file_selection's element task: `[this, files]`.
struct HtmlInputElementUpdateTheFileSelectionTask:
    var this: HtmlInputElement*
    var files: FileApiFileList*

## update_the_file_selection's element task.
func html_input_element_update_the_file_selection_task(context: void*?):
    let captures = (HtmlInputElementUpdateTheFileSelectionTask*)(context else trap("no captures"))
    let this = captures.this
    let realm = html_input_element_realm(this)
    # 1. Update element's selected files so that it represents the user's selection.
    html_input_element_set_files(this, captures.files)

    # 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
    let input_event = dom_event_create(realm, html_event_names_input, DomEventInit(bubbles = true, composed = true))
    _ = html_input_element_dispatch_event(this, input_event)

    # 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
    let change_event = dom_event_create(realm, html_event_names_change, DomEventInit(bubbles = true))
    _ = html_input_element_dispatch_event(this, change_event)

## Ported from HTMLInputElement.cpp:362 Web::HTML::HTMLInputElement::update_the_file_selection.
# https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
pub func html_input_element_update_the_file_selection(this: HtmlInputElement*, files: FileApiFileList*):
    # 1. Queue an element task on the user interaction task source given element and the following steps:
    let captures = new HtmlInputElementUpdateTheFileSelectionTask(this = this, files = files) else trap("out of memory")
    _ = dom_element_queue_an_element_task(this.dom_element(), HtmlTaskSource.user_interaction, ak.Function0[unit](call = html_input_element_update_the_file_selection_task, context = captures))

# mark: Pickers =================================================================================

## Ported from HTMLInputElement.cpp:380 Web::HTML::show_the_picker_if_applicable.
# https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
func html_show_the_picker_if_applicable(element: HtmlInputElement*):
    # To show the picker, if applicable for an input element element:

    # 1. If element's relevant global object does not have transient activation, then return.
    let global_object = html_relevant_global_object((JsObject*)element)
    let relevant_global_object = as_if_html_window((gc.Cell*)global_object) else return
    if not html_window_has_transient_activation(relevant_global_object):
        return

    # 2. If element is not mutable, then return.
    if not html_input_element_is_mutable_impl(html_input_element_form_associated(element)):
        return

    # 3. Consume user activation given element's relevant global object.
    html_window_consume_user_activation(relevant_global_object)

    # 4. If element does not support a picker, then return.
    if not html_input_element_supports_a_picker(element):
        return

    # 5. If element is an input element and element's type attribute is in the File Upload state, then run these steps in parallel:
    if html_input_element_type_state(element) == HtmlInputElementTypeAttributeState.file_upload:
        # NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
        #       See: ViewImplementation::on_request_file_picker, Page::did_request_file_picker(), Page::file_picker_closed()

        # 1. Optionally, wait until any prior execution of this algorithm has terminated.
        # FIXME: 2. Let dismissed be the result of WebDriver BiDi file dialog opened with element.
        let dismissed = false
        # 3. If dismissed is false:
        if not dismissed:
            # 1. Display a prompt to the user requesting that the user specify some files.
            #    If the multiple attribute is not set on element, there must be no more than one file selected;
            #    otherwise, any number may be selected.
            #    Files can be from the filesystem or created on the fly, e.g., a picture taken from a camera connected
            #    to the user's device.
            # 2. Wait for the user to have made their selection.
            let accepted_file_types = html_input_element_parse_accept_attribute(element)
            let allow_multiple_files = HtmlAllowMultipleFiles.yes if html_input_element_has_attribute(element, html_attribute_names_multiple) else HtmlAllowMultipleFiles.no
            let weak_element = gc.make_weak(element)

            html_input_element_set_is_open(element, true)
            page_did_request_file_picker(html_input_element_top_level_page(element), weak_element, accepted_file_types, allow_multiple_files)
        # 4. If dismissed is true or if the user dismissed the prompt without changing their selection,
        #    then queue an element task on the user interaction task source given element to fire an event named cancel at element,
        #    with the bubbles attribute initialized to true.
        else:
            # FIXME: Handle the "dismissed is true" case here.
            return
        # 5. Otherwise, update the file selection for element.

    # 6. Otherwise, the user agent should show the relevant user interface for selecting a value for element, in the
    #    way it normally would when the user interacts with the control.
    #    When showing such a user interface, it must respect the requirements stated in the relevant parts of the
    #    specification for how element behaves given its type attribute state. (For example, various sections describe
    #    restrictions on the resulting value string.)
    #    This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
    #    (If this closes a file selection picker, then per the above that will lead to firing either input and change
    #    events, or a cancel event.)
    else:
        if html_input_element_type_state(element) == HtmlInputElementTypeAttributeState.color:
            let weak_element = gc.make_weak(element)
            html_input_element_set_is_open(element, true)
            let value = html_input_element_value(element)
            let current_color = gfx.color_from_utf16_string(ak.utf16_string_base_utf16_view(&value.utf16_string_base)) else gfx.Color(m_value = 0xff000000)
            page_did_request_color_picker(html_input_element_top_level_page(element), weak_element, current_color)

## `element.document().browsing_context()->top_level_browsing_context()->page()`.
func html_input_element_top_level_page(element: HtmlInputElement*) -> Page*:
    let browsing_context = dom_document_browsing_context(html_input_element_document(element)) else trap("VERIFY: GC::Ptr<BrowsingContext>::operator-> on null")
    let top_level_browsing_context = html_browsing_context_top_level_browsing_context(browsing_context) else trap("VERIFY: GC::Ptr<BrowsingContext>::operator-> on null")
    return html_browsing_context_page(top_level_browsing_context)

## Ported from HTMLInputElement.cpp:453 Web::HTML::HTMLInputElement::show_picker.
# https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
pub func html_input_element_show_picker(this: HtmlInputElement*) -> !:
    let realm = html_input_element_realm(this)
    # The showPicker() method steps are:

    # 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
    if not html_input_element_is_mutable_impl(html_input_element_form_associated(this)):
        try idl_throw(.idl_dom_exception(idl_invalid_state_error_create(realm, ak.utf16_string_from_str("Element is not mutable"))))

    # 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
    # and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
    # NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
    #       and has never been guarded by an origin check.
    let settings = html_relevant_settings_object_dom_node(this.dom_node())
    let origin = html_environment_settings_object_origin(settings)
    let top_level_origin = settings.environment.top_level_origin else trap("VERIFY: Optional::value() on an empty optional")
    if not web_url.origin_is_same_origin(&origin, top_level_origin) and this.m_type != HtmlInputElementTypeAttributeState.file_upload and this.m_type != HtmlInputElementTypeAttributeState.color:
        try idl_throw(.idl_dom_exception(idl_security_error_create(realm, ak.utf16_string_from_str("Cross origin pickers are not allowed"))))

    # 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
    # FIXME: The global object we get here should probably not need casted to Window to check for transient activation
    let global_object = html_relevant_global_object((JsObject*)this)
    let window = as_if_html_window((gc.Cell*)global_object)
    if window == none or not html_window_has_transient_activation(window else trap("unreachable")):
        try idl_throw(.idl_dom_exception(idl_not_allowed_error_create(realm, ak.utf16_string_from_str("Too long since user activation to show picker"))))

    # 4. Show the picker, if applicable, for this.
    html_show_the_picker_if_applicable(this)