Coverage Report

Created: 2026-11-13 08:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibWeb/HTML/HTMLFormElement.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
3
 * Copyright (c) 2023, Kenneth Myhra <kennethmyhra@serenityos.org>
4
 * Copyright (c) 2023, Luke Wilde <lukew@serenityos.org>
5
 *
6
 * SPDX-License-Identifier: BSD-2-Clause
7
 */
8
9
#include <AK/QuickSort.h>
10
#include <AK/StringBuilder.h>
11
#include <LibTextCodec/Decoder.h>
12
#include <LibWeb/Bindings/ExceptionOrUtils.h>
13
#include <LibWeb/Bindings/HTMLFormElementPrototype.h>
14
#include <LibWeb/DOM/DOMTokenList.h>
15
#include <LibWeb/DOM/Document.h>
16
#include <LibWeb/DOM/Event.h>
17
#include <LibWeb/DOMURL/DOMURL.h>
18
#include <LibWeb/HTML/BrowsingContext.h>
19
#include <LibWeb/HTML/EventNames.h>
20
#include <LibWeb/HTML/FormControlInfrastructure.h>
21
#include <LibWeb/HTML/HTMLButtonElement.h>
22
#include <LibWeb/HTML/HTMLDialogElement.h>
23
#include <LibWeb/HTML/HTMLFieldSetElement.h>
24
#include <LibWeb/HTML/HTMLFormControlsCollection.h>
25
#include <LibWeb/HTML/HTMLFormElement.h>
26
#include <LibWeb/HTML/HTMLImageElement.h>
27
#include <LibWeb/HTML/HTMLInputElement.h>
28
#include <LibWeb/HTML/HTMLObjectElement.h>
29
#include <LibWeb/HTML/HTMLOutputElement.h>
30
#include <LibWeb/HTML/HTMLSelectElement.h>
31
#include <LibWeb/HTML/HTMLTextAreaElement.h>
32
#include <LibWeb/HTML/RadioNodeList.h>
33
#include <LibWeb/HTML/SubmitEvent.h>
34
#include <LibWeb/Infra/CharacterTypes.h>
35
#include <LibWeb/Infra/Strings.h>
36
#include <LibWeb/Page/Page.h>
37
38
namespace Web::HTML {
39
40
JS_DEFINE_ALLOCATOR(HTMLFormElement);
41
42
HTMLFormElement::HTMLFormElement(DOM::Document& document, DOM::QualifiedName qualified_name)
43
0
    : HTMLElement(document, move(qualified_name))
44
0
{
45
0
    m_legacy_platform_object_flags = LegacyPlatformObjectFlags {
46
0
        .supports_indexed_properties = true,
47
0
        .supports_named_properties = true,
48
0
        .has_legacy_unenumerable_named_properties_interface_extended_attribute = true,
49
0
        .has_legacy_override_built_ins_interface_extended_attribute = true,
50
0
    };
51
0
}
52
53
0
HTMLFormElement::~HTMLFormElement() = default;
54
55
void HTMLFormElement::initialize(JS::Realm& realm)
56
0
{
57
0
    Base::initialize(realm);
58
0
    WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLFormElement);
59
0
}
60
61
void HTMLFormElement::visit_edges(Cell::Visitor& visitor)
62
0
{
63
0
    Base::visit_edges(visitor);
64
0
    visitor.visit(m_elements);
65
0
    visitor.visit(m_associated_elements);
66
0
    visitor.visit(m_planned_navigation);
67
0
    visitor.visit(m_rel_list);
68
0
}
69
70
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission
71
WebIDL::ExceptionOr<void> HTMLFormElement::implicitly_submit_form()
72
0
{
73
    // If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the
74
    // "enter" key while a text control is focused implicitly submits the form), then doing so for a form, whose default
75
    // button has activation behavior and is not disabled, must cause the user agent to fire a click event at that
76
    // default button.
77
0
    if (auto* default_button = this->default_button()) {
78
0
        auto& default_button_element = default_button->form_associated_element_to_html_element();
79
80
0
        if (default_button_element.has_activation_behavior() && default_button->enabled())
81
0
            default_button_element.click();
82
83
0
        return {};
84
0
    }
85
86
    // If the form has no submit button, then the implicit submission mechanism must perform the following steps:
87
88
    // 1. If the form has more than one field that blocks implicit submission, then return.
89
0
    if (number_of_fields_blocking_implicit_submission() > 1)
90
0
        return {};
91
92
    // 2. Submit the form element from the form element itself with userInvolvement set to "activation".
93
0
    TRY(submit_form(*this, { .user_involvement = UserNavigationInvolvement::Activation }));
94
95
0
    return {};
96
0
}
97
98
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-form-submit
99
WebIDL::ExceptionOr<void> HTMLFormElement::submit_form(JS::NonnullGCPtr<HTMLElement> submitter, SubmitFormOptions options)
100
0
{
101
0
    auto& vm = this->vm();
102
0
    auto& realm = this->realm();
103
104
    // 1. If form cannot navigate, then return.
105
0
    if (cannot_navigate())
106
0
        return {};
107
108
    // 2. If form's constructing entry list is true, then return.
109
0
    if (m_constructing_entry_list)
110
0
        return {};
111
112
    // 3. Let form document be form's node document.
113
0
    JS::NonnullGCPtr<DOM::Document> form_document = this->document();
114
115
    // 4. If form document's active sandboxing flag set has its sandboxed forms browsing context flag set, then return.
116
0
    if (has_flag(form_document->active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedForms))
117
0
        return {};
118
119
    // 5. If the submitted from submit() method flag is not set, then:
120
0
    if (!options.from_submit_binding) {
121
        // 1. If form's firing submission events is true, then return.
122
0
        if (m_firing_submission_events)
123
0
            return {};
124
125
        // 2. Set form's firing submission events to true.
126
0
        m_firing_submission_events = true;
127
128
        // FIXME: 3. If the submitter element's no-validate state is false, then interactively validate the constraints
129
        //           of form and examine the result. If the result is negative (i.e., the constraint validation concluded
130
        //           that there were invalid fields and probably informed the user of this), then:
131
        //           1. Set form's firing submission events to false.
132
        //           2. Return.
133
134
        // 4. Let submitterButton be null if submitter is form. Otherwise, let submitterButton be submitter.
135
0
        JS::GCPtr<HTMLElement> submitter_button;
136
0
        if (submitter != this)
137
0
            submitter_button = submitter;
138
139
        // 5. Let shouldContinue be the result of firing an event named submit at form using SubmitEvent, with the
140
        //    submitter attribute initialized to submitterButton, the bubbles attribute initialized to true, and the
141
        //    cancelable attribute initialized to true.
142
0
        SubmitEventInit event_init {};
143
0
        event_init.submitter = submitter_button;
144
0
        auto submit_event = SubmitEvent::create(realm, EventNames::submit, event_init);
145
0
        submit_event->set_bubbles(true);
146
0
        submit_event->set_cancelable(true);
147
0
        bool should_continue = dispatch_event(*submit_event);
148
149
        // 6. Set form's firing submission events to false.
150
0
        m_firing_submission_events = false;
151
152
        // 7. If shouldContinue is false, then return.
153
0
        if (!should_continue)
154
0
            return {};
155
156
        // 8. If form cannot navigate, then return.
157
        // Spec Note: Cannot navigate is run again as dispatching the submit event could have changed the outcome.
158
0
        if (cannot_navigate())
159
0
            return {};
160
0
    }
161
162
    // 6. Let encoding be the result of picking an encoding for the form.
163
0
    auto encoding = TRY_OR_THROW_OOM(vm, pick_an_encoding());
164
165
    // 7. Let entry list be the result of constructing the entry list with form, submitter, and encoding.
166
0
    auto entry_list_or_null = TRY(construct_entry_list(realm, *this, submitter, encoding));
167
168
    // 8. Assert: entry list is not null.
169
0
    VERIFY(entry_list_or_null.has_value());
170
0
    auto entry_list = entry_list_or_null.release_value();
171
172
    // 9. If form cannot navigate, then return.
173
    // Spec Note: Cannot navigate is run again as dispatching the formdata event in constructing the entry list could
174
    //            have changed the outcome.
175
0
    if (cannot_navigate())
176
0
        return {};
177
178
    // 10. Let method be the submitter element's method.
179
0
    auto method = method_state_from_form_element(submitter);
180
181
    // 11. If method is dialog, then:
182
0
    if (method == MethodAttributeState::Dialog) {
183
        // 1. If form does not have an ancestor dialog element, then return.
184
        // 2. Let subject be form's nearest ancestor dialog element.
185
0
        auto* subject = first_ancestor_of_type<HTMLDialogElement>();
186
0
        if (!subject)
187
0
            return {};
188
189
        // 3. Let result be null.
190
0
        Optional<String> result;
191
192
        // 4. If submitter is an input element whose type attribute is in the Image Button state, then:
193
0
        if (is<HTMLInputElement>(*submitter)) {
194
0
            auto const& input_element = static_cast<HTMLInputElement const&>(*submitter);
195
196
0
            if (input_element.type_state() == HTMLInputElement::TypeAttributeState::ImageButton) {
197
                // 1. Let (x, y) be the selected coordinate.
198
0
                auto [x, y] = input_element.selected_coordinate();
199
200
                // 2. Set result to the concatenation of x, ",", and y.
201
0
                result = MUST(String::formatted("{},{}", x, y));
202
0
            }
203
0
        }
204
205
        // 5. Otherwise, if submitter has a value, then set result to that value.
206
0
        if (!result.has_value())
207
0
            result = submitter->get_attribute_value(AttributeNames::value);
208
209
        // 6. Close the dialog subject with result.
210
0
        subject->close(move(result));
211
212
        // 7. Return.
213
0
        return {};
214
0
    }
215
216
    // 12. Let action be the submitter element's action.
217
0
    auto action = action_from_form_element(submitter);
218
219
    // 13. If action is the empty string, let action be the URL of the form document.
220
0
    if (action.is_empty())
221
0
        action = form_document->url_string();
222
223
    // 14. Parse a URL given action, relative to the submitter element's node document. If this fails, return.
224
    // 15. Let parsed action be the resulting URL record.
225
0
    auto parsed_action = document().parse_url(action);
226
0
    if (!parsed_action.is_valid()) {
227
0
        dbgln("Failed to submit form: Invalid URL: {}", action);
228
0
        return {};
229
0
    }
230
231
    // 16. Let scheme be the scheme of parsed action.
232
0
    auto const& scheme = parsed_action.scheme();
233
234
    // 17. Let enctype be the submitter element's enctype.
235
0
    auto encoding_type = encoding_type_state_from_form_element(submitter);
236
237
    // 18. Let target be the submitter element's formtarget attribute value, if the element is a submit button and has
238
    //     such an attribute. Otherwise, let it be the result of getting an element's target given submitter's form
239
    //     owner.
240
0
    auto target = submitter->attribute(AttributeNames::formtarget).value_or(get_an_elements_target());
241
242
    // 19. Let noopener be the result of getting an element's noopener with form and target.
243
0
    auto no_opener = get_an_elements_noopener(target);
244
245
    // 20. Let targetNavigable be the first return value of applying the rules for choosing a navigable given target, form's node navigable, and noopener.
246
0
    auto target_navigable = form_document->navigable()->choose_a_navigable(target, no_opener).navigable;
247
248
    // 21. If targetNavigable is null, then return.
249
0
    if (!target_navigable) {
250
0
        dbgln("Failed to submit form: choose_a_browsing_context returning a null browsing context");
251
0
        return {};
252
0
    }
253
254
    // 22. Let historyHandling be "auto".
255
0
    auto history_handling = Bindings::NavigationHistoryBehavior::Auto;
256
257
    // 23. If form document has not yet completely loaded, then set historyHandling to "replace".
258
0
    if (!form_document->is_completely_loaded())
259
0
        history_handling = Bindings::NavigationHistoryBehavior::Replace;
260
261
    // 24. Select the appropriate row in the table below based on scheme as given by the first cell of each row.
262
    //     Then, select the appropriate cell on that row based on method as given in the first cell of each column.
263
    //     Then, jump to the steps named in that cell and defined below the table.
264
265
    //            | GET               | POST
266
    // ------------------------------------------------------
267
    // http       | Mutate action URL | Submit as entity body
268
    // https      | Mutate action URL | Submit as entity body
269
    // ftp        | Get action URL    | Get action URL
270
    // javascript | Get action URL    | Get action URL
271
    // data       | Mutate action URL | Get action URL
272
    // mailto     | Mail with headers | Mail as body
273
274
    // If scheme is not one of those listed in this table, then the behavior is not defined by this specification.
275
    // User agents should, in the absence of another specification defining this, act in a manner analogous to that defined
276
    // in this specification for similar schemes.
277
278
    // AD-HOC: In accordance with the above paragraph, we implement file:// submission URLs the same as data: URLs.
279
280
    // This should have been handled above.
281
0
    VERIFY(method != MethodAttributeState::Dialog);
282
283
0
    if (scheme.is_one_of("http"sv, "https"sv)) {
284
0
        if (method == MethodAttributeState::GET)
285
0
            TRY_OR_THROW_OOM(vm, mutate_action_url(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling, options.user_involvement));
286
0
        else
287
0
            TRY_OR_THROW_OOM(vm, submit_as_entity_body(move(parsed_action), move(entry_list), encoding_type, move(encoding), *target_navigable, history_handling, options.user_involvement));
288
0
    } else if (scheme.is_one_of("ftp"sv, "javascript"sv)) {
289
0
        get_action_url(move(parsed_action), *target_navigable, history_handling, options.user_involvement);
290
0
    } else if (scheme.is_one_of("data"sv, "file"sv)) {
291
0
        if (method == MethodAttributeState::GET)
292
0
            TRY_OR_THROW_OOM(vm, mutate_action_url(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling, options.user_involvement));
293
0
        else
294
0
            get_action_url(move(parsed_action), *target_navigable, history_handling, options.user_involvement);
295
0
    } else if (scheme == "mailto"sv) {
296
0
        if (method == MethodAttributeState::GET)
297
0
            TRY_OR_THROW_OOM(vm, mail_with_headers(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling, options.user_involvement));
298
0
        else
299
0
            TRY_OR_THROW_OOM(vm, mail_as_body(move(parsed_action), move(entry_list), encoding_type, move(encoding), *target_navigable, history_handling, options.user_involvement));
300
0
    } else {
301
0
        dbgln("Failed to submit form: Unknown scheme: {}", scheme);
302
0
        return {};
303
0
    }
304
305
0
    return {};
306
0
}
307
308
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#resetting-a-form
309
void HTMLFormElement::reset_form()
310
0
{
311
    // 1. Let reset be the result of firing an event named reset at form, with the bubbles and cancelable attributes initialized to true.
312
0
    auto reset_event = DOM::Event::create(realm(), HTML::EventNames::reset);
313
0
    reset_event->set_bubbles(true);
314
0
    reset_event->set_cancelable(true);
315
316
0
    bool reset = dispatch_event(reset_event);
317
318
    // 2. If reset is true, then invoke the reset algorithm of each resettable element whose form owner is form.
319
0
    if (reset) {
320
0
        for (auto element : m_associated_elements) {
321
0
            VERIFY(is<FormAssociatedElement>(*element));
322
0
            auto& form_associated_element = dynamic_cast<FormAssociatedElement&>(*element);
323
0
            if (form_associated_element.is_resettable())
324
0
                form_associated_element.reset_algorithm();
325
0
        }
326
0
    }
327
0
}
328
329
WebIDL::ExceptionOr<void> HTMLFormElement::submit()
330
0
{
331
0
    return submit_form(*this, { .from_submit_binding = true });
332
0
}
333
334
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-requestsubmit
335
WebIDL::ExceptionOr<void> HTMLFormElement::request_submit(JS::GCPtr<Element> submitter)
336
0
{
337
    // 1. If submitter is not null, then:
338
0
    if (submitter) {
339
        // 1. If submitter is not a submit button, then throw a TypeError.
340
0
        auto* form_associated_element = dynamic_cast<FormAssociatedElement*>(submitter.ptr());
341
0
        if (!(form_associated_element && form_associated_element->is_submit_button()))
342
0
            return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "The submitter is not a submit button"sv };
343
344
        // 2. If submitter's form owner is not this form element, then throw a "NotFoundError" DOMException.
345
0
        if (form_associated_element->form() != this)
346
0
            return WebIDL::NotFoundError::create(realm(), "The submitter is not owned by this form element"_string);
347
0
    }
348
    // 2. Otherwise, set submitter to this form element.
349
0
    else {
350
0
        submitter = this;
351
0
    }
352
353
    // 3. Submit this form element, from submitter.
354
0
    return submit_form(static_cast<HTMLElement&>(*submitter), {});
355
0
}
356
357
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-reset
358
void HTMLFormElement::reset()
359
0
{
360
    // 1. If the form element is marked as locked for reset, then return.
361
0
    if (m_locked_for_reset)
362
0
        return;
363
364
    // 2. Mark the form element as locked for reset.
365
0
    m_locked_for_reset = true;
366
367
    // 3. Reset the form element.
368
0
    reset_form();
369
370
    // 4. Unmark the form element as locked for reset.
371
0
    m_locked_for_reset = false;
372
0
}
373
374
void HTMLFormElement::add_associated_element(Badge<FormAssociatedElement>, HTMLElement& element)
375
0
{
376
0
    m_associated_elements.append(element);
377
0
}
378
379
void HTMLFormElement::remove_associated_element(Badge<FormAssociatedElement>, HTMLElement& element)
380
0
{
381
0
    m_associated_elements.remove_first_matching([&](auto& entry) { return entry.ptr() == &element; });
382
383
    // If an element listed in a form element's past names map changes form owner, then its entries must be removed from that map.
384
0
    m_past_names_map.remove_all_matching([&](auto&, auto const& entry) { return entry.node == &element; });
385
0
}
386
387
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-action
388
String HTMLFormElement::action_from_form_element(JS::NonnullGCPtr<HTMLElement> element) const
389
0
{
390
    // The action of an element is the value of the element's formaction attribute, if the element is a submit button
391
    // and has such an attribute, or the value of its form owner's action attribute, if it has one, or else the empty
392
    // string.
393
0
    if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
394
0
        form_associated_element && form_associated_element->is_submit_button()) {
395
0
        if (auto maybe_attribute = element->attribute(AttributeNames::formaction); maybe_attribute.has_value())
396
0
            return maybe_attribute.release_value();
397
0
    }
398
399
0
    if (auto maybe_attribute = attribute(AttributeNames::action); maybe_attribute.has_value())
400
0
        return maybe_attribute.release_value();
401
402
0
    return String {};
403
0
}
404
405
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-attributes:attr-fs-method-2
406
static HTMLFormElement::MethodAttributeState method_attribute_to_method_state(StringView method)
407
0
{
408
0
#define __ENUMERATE_FORM_METHOD_ATTRIBUTE(keyword, state)             \
409
0
    if (Infra::is_ascii_case_insensitive_match(#keyword##sv, method)) \
410
0
        return HTMLFormElement::MethodAttributeState::state;
411
0
    ENUMERATE_FORM_METHOD_ATTRIBUTES
412
0
#undef __ENUMERATE_FORM_METHOD_ATTRIBUTE
413
414
    // The method attribute's invalid value default and missing value default are both the GET state.
415
0
    return HTMLFormElement::MethodAttributeState::GET;
416
0
}
417
418
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-method
419
HTMLFormElement::MethodAttributeState HTMLFormElement::method_state_from_form_element(JS::NonnullGCPtr<HTMLElement const> element) const
420
0
{
421
    // If the element is a submit button and has a formmethod attribute, then the element's method is that attribute's state;
422
    // otherwise, it is the form owner's method attribute's state.
423
0
    if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
424
0
        form_associated_element && form_associated_element->is_submit_button()) {
425
426
0
        if (auto maybe_formmethod = element->attribute(AttributeNames::formmethod); maybe_formmethod.has_value()) {
427
            // NOTE: `formmethod` is the same as `method`, except that it has no missing value default.
428
            //       This is handled by not calling `method_attribute_to_method_state` in the first place if there is no `formmethod` attribute.
429
0
            return method_attribute_to_method_state(maybe_formmethod.value());
430
0
        }
431
0
    }
432
433
0
    if (auto maybe_method = attribute(AttributeNames::method); maybe_method.has_value()) {
434
0
        return method_attribute_to_method_state(maybe_method.value());
435
0
    }
436
437
0
    return MethodAttributeState::GET;
438
0
}
439
440
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-attributes:attr-fs-enctype-2
441
static HTMLFormElement::EncodingTypeAttributeState encoding_type_attribute_to_encoding_type_state(StringView encoding_type)
442
0
{
443
0
#define __ENUMERATE_FORM_METHOD_ENCODING_TYPE(keyword, state)               \
444
0
    if (Infra::is_ascii_case_insensitive_match(keyword##sv, encoding_type)) \
445
0
        return HTMLFormElement::EncodingTypeAttributeState::state;
446
0
    ENUMERATE_FORM_METHOD_ENCODING_TYPES
447
0
#undef __ENUMERATE_FORM_METHOD_ENCODING_TYPE
448
449
    // The enctype attribute's invalid value default and missing value default are both the application/x-www-form-urlencoded state.
450
0
    return HTMLFormElement::EncodingTypeAttributeState::FormUrlEncoded;
451
0
}
452
453
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-enctype
454
HTMLFormElement::EncodingTypeAttributeState HTMLFormElement::encoding_type_state_from_form_element(JS::NonnullGCPtr<HTMLElement> element) const
455
0
{
456
    // If the element is a submit button and has a formenctype attribute, then the element's enctype is that attribute's state;
457
    // otherwise, it is the form owner's enctype attribute's state.
458
0
    if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
459
0
        form_associated_element && form_associated_element->is_submit_button()) {
460
0
        if (auto formenctype = element->attribute(AttributeNames::formenctype); formenctype.has_value()) {
461
            // NOTE: `formenctype` is the same as `enctype`, except that it has nomissing value default.
462
            //       This is handled by not calling `encoding_type_attribute_to_encoding_type_state` in the first place if there is no
463
            //       `formenctype` attribute.
464
0
            return encoding_type_attribute_to_encoding_type_state(formenctype.value());
465
0
        }
466
0
    }
467
468
0
    if (auto maybe_enctype = attribute(AttributeNames::enctype); maybe_enctype.has_value())
469
0
        return encoding_type_attribute_to_encoding_type_state(maybe_enctype.value());
470
471
0
    return EncodingTypeAttributeState::FormUrlEncoded;
472
0
}
473
474
// https://html.spec.whatwg.org/multipage/forms.html#category-listed
475
static bool is_listed_element(DOM::Element const& element)
476
0
{
477
    // Denotes elements that are listed in the form.elements and fieldset.elements APIs.
478
    // These elements also have a form content attribute, and a matching form IDL attribute,
479
    // that allow authors to specify an explicit form owner.
480
    // => button, fieldset, input, object, output, select, textarea, form-associated custom elements
481
482
0
    if (is<HTMLButtonElement>(element)
483
0
        || is<HTMLFieldSetElement>(element)
484
0
        || is<HTMLInputElement>(element)
485
0
        || is<HTMLObjectElement>(element)
486
0
        || is<HTMLOutputElement>(element)
487
0
        || is<HTMLSelectElement>(element)
488
0
        || is<HTMLTextAreaElement>(element)) {
489
0
        return true;
490
0
    }
491
492
    // FIXME: Form-associated custom elements return also true
493
494
0
    return false;
495
0
}
496
497
static bool is_form_control(DOM::Element const& element, HTMLFormElement const& form)
498
0
{
499
    // The elements IDL attribute must return an HTMLFormControlsCollection rooted at the form element's root,
500
    // whose filter matches listed elements whose form owner is the form element,
501
    // with the exception of input elements whose type attribute is in the Image Button state, which must,
502
    // for historical reasons, be excluded from this particular collection.
503
504
0
    if (!is_listed_element(element))
505
0
        return false;
506
507
0
    if (is<HTMLInputElement>(element)
508
0
        && static_cast<HTMLInputElement const&>(element).type_state() == HTMLInputElement::TypeAttributeState::ImageButton) {
509
0
        return false;
510
0
    }
511
512
0
    auto const& form_associated_element = dynamic_cast<FormAssociatedElement const&>(element);
513
0
    if (form_associated_element.form() != &form)
514
0
        return false;
515
516
0
    return true;
517
0
}
518
519
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-elements
520
JS::NonnullGCPtr<HTMLFormControlsCollection> HTMLFormElement::elements() const
521
0
{
522
0
    if (!m_elements) {
523
0
        auto& root = verify_cast<ParentNode>(const_cast<HTMLFormElement*>(this)->root());
524
0
        m_elements = HTMLFormControlsCollection::create(root, DOM::HTMLCollection::Scope::Descendants, [this](Element const& element) {
525
0
            return is_form_control(element, *this);
526
0
        });
527
0
    }
528
0
    return *m_elements;
529
0
}
530
531
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-length
532
unsigned HTMLFormElement::length() const
533
0
{
534
    // The length IDL attribute must return the number of nodes represented by the elements collection.
535
0
    return elements()->length();
536
0
}
537
538
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-checkvalidity
539
WebIDL::ExceptionOr<bool> HTMLFormElement::check_validity()
540
0
{
541
0
    dbgln("(STUBBED) HTMLFormElement::check_validity(). Called on: {}", debug_description());
542
0
    return true;
543
0
}
544
545
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-reportvalidity
546
WebIDL::ExceptionOr<bool> HTMLFormElement::report_validity()
547
0
{
548
0
    dbgln("(STUBBED) HTMLFormElement::report_validity(). Called on: {}", debug_description());
549
0
    return true;
550
0
}
551
552
// https://html.spec.whatwg.org/multipage/forms.html#category-submit
553
Vector<JS::NonnullGCPtr<DOM::Element>> HTMLFormElement::get_submittable_elements()
554
0
{
555
0
    Vector<JS::NonnullGCPtr<DOM::Element>> submittable_elements;
556
557
0
    root().for_each_in_subtree([&](auto& node) {
558
0
        if (auto* form_associated_element = dynamic_cast<FormAssociatedElement*>(&node)) {
559
0
            if (form_associated_element->is_submittable() && form_associated_element->form() == this)
560
0
                submittable_elements.append(form_associated_element->form_associated_element_to_html_element());
561
0
        }
562
563
0
        return TraversalDecision::Continue;
564
0
    });
565
566
0
    return submittable_elements;
567
0
}
568
569
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-rellist
570
JS::NonnullGCPtr<DOM::DOMTokenList> HTMLFormElement::rel_list()
571
0
{
572
    // The relList IDL attribute must reflect the rel content attribute.
573
0
    if (!m_rel_list)
574
0
        m_rel_list = DOM::DOMTokenList::create(*this, HTML::AttributeNames::rel);
575
0
    return *m_rel_list;
576
0
}
577
578
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-method
579
WebIDL::ExceptionOr<void> HTMLFormElement::set_method(String const& method)
580
0
{
581
    // The method and enctype IDL attributes must reflect the respective content attributes of the same name, limited to only known values.
582
0
    return set_attribute(AttributeNames::method, method);
583
0
}
584
585
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-action
586
String HTMLFormElement::action() const
587
0
{
588
    // The action IDL attribute must reflect the content attribute of the same name, except that on getting, when the
589
    // content attribute is missing or its value is the empty string, the element's node document's URL must be returned
590
    // instead.
591
0
    auto form_action_attribute = attribute(AttributeNames::action);
592
0
    if (!form_action_attribute.has_value() || form_action_attribute.value().is_empty()) {
593
0
        return document().url_string();
594
0
    }
595
596
0
    return MUST(document().base_url().complete_url(form_action_attribute.value()).to_string());
597
0
}
598
599
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-action
600
WebIDL::ExceptionOr<void> HTMLFormElement::set_action(String const& value)
601
0
{
602
0
    return set_attribute(AttributeNames::action, value);
603
0
}
604
605
void HTMLFormElement::attribute_changed(FlyString const& name, Optional<String> const& old_value, Optional<String> const& value)
606
0
{
607
0
    HTMLElement::attribute_changed(name, old_value, value);
608
0
    if (name == HTML::AttributeNames::rel) {
609
0
        if (m_rel_list)
610
0
            m_rel_list->associated_attribute_changed(value.value_or(String {}));
611
0
    }
612
0
}
613
614
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#picking-an-encoding-for-the-form
615
ErrorOr<String> HTMLFormElement::pick_an_encoding() const
616
0
{
617
    // 1. Let encoding be the document's character encoding.
618
0
    auto encoding = document().encoding_or_default();
619
620
    // 2. If the form element has an accept-charset attribute, set encoding to the return value of running these substeps:
621
0
    if (auto maybe_input = attribute(AttributeNames::accept_charset); maybe_input.has_value()) {
622
        // 1. Let input be the value of the form element's accept-charset attribute.
623
0
        auto input = maybe_input.release_value();
624
625
        // 2. Let candidate encoding labels be the result of splitting input on ASCII whitespace.
626
0
        auto candidate_encoding_labels = input.bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
627
628
        // 3. Let candidate encodings be an empty list of character encodings.
629
0
        Vector<StringView> candidate_encodings;
630
631
        // 4. For each token in candidate encoding labels in turn (in the order in which they were found in input),
632
        //    get an encoding for the token and, if this does not result in failure, append the encoding to candidate
633
        //    encodings.
634
0
        for (auto const& token : candidate_encoding_labels) {
635
0
            auto candidate_encoding = TextCodec::get_standardized_encoding(token);
636
0
            if (candidate_encoding.has_value())
637
0
                TRY(candidate_encodings.try_append(candidate_encoding.value()));
638
0
        }
639
640
        // 5. If candidate encodings is empty, return UTF-8.
641
0
        if (candidate_encodings.is_empty())
642
0
            return "UTF-8"_string;
643
644
        // 6. Return the first encoding in candidate encodings.
645
0
        return String::from_utf8(candidate_encodings.first());
646
0
    }
647
648
    // 3. Return the result of getting an output encoding from encoding.
649
0
    return MUST(String::from_utf8(TextCodec::get_output_encoding(encoding)));
650
0
}
651
652
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#convert-to-a-list-of-name-value-pairs
653
static ErrorOr<Vector<DOMURL::QueryParam>> convert_to_list_of_name_value_pairs(Vector<XHR::FormDataEntry> const& entry_list)
654
0
{
655
    // 1. Let list be an empty list of name-value pairs.
656
0
    Vector<DOMURL::QueryParam> list;
657
658
    // 2. For each entry of entry list:
659
0
    for (auto const& entry : entry_list) {
660
        // 1. Let name be entry's name, with every occurrence of U+000D (CR) not followed by U+000A (LF), and every occurrence of U+000A (LF)
661
        //    not preceded by U+000D (CR), replaced by a string consisting of U+000D (CR) and U+000A (LF).
662
0
        auto name = TRY(normalize_line_breaks(entry.name));
663
664
        // 2. If entry's value is a File object, then let value be entry's value's name. Otherwise, let value be entry's value.
665
0
        String value;
666
0
        entry.value.visit(
667
0
            [&value](JS::Handle<FileAPI::File> const& file) {
668
0
                value = file->name();
669
0
            },
670
0
            [&value](String const& string) {
671
0
                value = string;
672
0
            });
673
674
        // 3. Replace every occurrence of U+000D (CR) not followed by U+000A (LF), and every occurrence of
675
        //    U+000A (LF) not preceded by U+000D (CR), in value, by a string consisting of U+000D (CR) and U+000A (LF).
676
0
        auto normalized_value = TRY(normalize_line_breaks(value));
677
678
        // 4. Append to list a new name-value pair whose name is name and whose value is value.
679
0
        TRY(list.try_append(DOMURL::QueryParam { .name = move(name), .value = move(normalized_value) }));
680
0
    }
681
682
    // 3. Return list.
683
0
    return list;
684
0
}
685
686
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#text/plain-encoding-algorithm
687
static ErrorOr<String> plain_text_encode(Vector<DOMURL::QueryParam> const& pairs)
688
0
{
689
    // 1. Let result be the empty string.
690
0
    StringBuilder result;
691
692
    // 2. For each pair in pairs:
693
0
    for (auto const& pair : pairs) {
694
        // 1. Append pair's name to result.
695
0
        TRY(result.try_append(pair.name));
696
697
        // 2. Append a single U+003D EQUALS SIGN character (=) to result.
698
0
        TRY(result.try_append('='));
699
700
        // 3. Append pair's value to result.
701
0
        TRY(result.try_append(pair.value));
702
703
        // 4. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) character pair to result.
704
0
        TRY(result.try_append("\r\n"sv));
705
0
    }
706
707
    // 3. Return result.
708
0
    return result.to_string();
709
0
}
710
711
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mutate-action
712
ErrorOr<void> HTMLFormElement::mutate_action_url(URL::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, String encoding, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
713
0
{
714
    // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
715
0
    auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
716
717
    // 2. Let query be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
718
0
    auto query = url_encode(pairs, encoding);
719
720
    // 3. Set parsed action's query component to query.
721
0
    parsed_action.set_query(query);
722
723
    // 4. Plan to navigate to parsed action.
724
0
    plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling, user_involvement);
725
0
    return {};
726
0
}
727
728
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-body
729
ErrorOr<void> HTMLFormElement::submit_as_entity_body(URL::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, EncodingTypeAttributeState encoding_type, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
730
0
{
731
    // 1. Assert: method is POST.
732
733
0
    POSTResource::RequestContentType mime_type {};
734
0
    Vector<POSTResource::Directive> mime_type_directives;
735
0
    ByteBuffer body;
736
737
    // 2. Switch on enctype:
738
0
    switch (encoding_type) {
739
0
    case EncodingTypeAttributeState::FormUrlEncoded: {
740
        // -> application/x-www-form-urlencoded
741
        // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
742
0
        auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
743
744
        // 2. Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
745
0
        body = TRY(ByteBuffer::copy(url_encode(pairs, encoding).bytes()));
746
747
        // 3. Set body to the result of encoding body.
748
        // NOTE: `encoding` refers to `UTF-8 encode`, which body already is encoded as because it uses AK::String.
749
750
        // 4. Let mimeType be `application/x-www-form-urlencoded`.
751
0
        mime_type = POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded;
752
0
        break;
753
0
    }
754
0
    case EncodingTypeAttributeState::FormData: {
755
        // -> multipart/form-data
756
        // 1. Let body be the result of running the multipart/form-data encoding algorithm with entry list and encoding.
757
0
        auto body_and_mime_type = TRY(serialize_to_multipart_form_data(entry_list));
758
0
        body = move(body_and_mime_type.serialized_data);
759
760
        // 2. Let mimeType be the isomorphic encoding of the concatenation of "multipart/form-data; boundary=" and the multipart/form-data
761
        //    boundary string generated by the multipart/form-data encoding algorithm.
762
0
        mime_type = POSTResource::RequestContentType::MultipartFormData;
763
0
        mime_type_directives.empend("boundary"sv, move(body_and_mime_type.boundary));
764
0
        break;
765
0
    }
766
0
    case EncodingTypeAttributeState::PlainText: {
767
        // -> text/plain
768
        // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
769
0
        auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
770
771
        // 2. Let body be the result of running the text/plain encoding algorithm with pairs.
772
0
        body = TRY(ByteBuffer::copy(TRY(plain_text_encode(pairs)).bytes()));
773
774
        // FIXME: 3. Set body to the result of encoding body using encoding.
775
776
        // 4. Let mimeType be `text/plain`.
777
0
        mime_type = POSTResource::RequestContentType::TextPlain;
778
0
        break;
779
0
    }
780
0
    default:
781
0
        VERIFY_NOT_REACHED();
782
0
    }
783
784
    // 3. Plan to navigate to parsed action given a POST resource whose request body is body and request content-type is mimeType.
785
0
    plan_to_navigate_to(parsed_action, POSTResource { .request_body = move(body), .request_content_type = mime_type, .request_content_type_directives = move(mime_type_directives) }, target_navigable, history_handling, user_involvement);
786
0
    return {};
787
0
}
788
789
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-get-action
790
void HTMLFormElement::get_action_url(URL::URL parsed_action, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
791
0
{
792
    // 1. Plan to navigate to parsed action.
793
    // Spec Note: entry list is discarded.
794
0
    plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling, user_involvement);
795
0
}
796
797
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mailto-headers
798
ErrorOr<void> HTMLFormElement::mail_with_headers(URL::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
799
0
{
800
    // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
801
0
    auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
802
803
    // 2. Let headers be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
804
0
    auto headers = url_encode(pairs, encoding);
805
806
    // 3. Replace occurrences of U+002B PLUS SIGN characters (+) in headers with the string "%20".
807
0
    TRY(headers.replace("+"sv, "%20"sv, ReplaceMode::All));
808
809
    // 4. Set parsed action's query to headers.
810
0
    parsed_action.set_query(headers);
811
812
    // 5. Plan to navigate to parsed action.
813
0
    plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling, user_involvement);
814
0
    return {};
815
0
}
816
817
ErrorOr<void> HTMLFormElement::mail_as_body(URL::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, EncodingTypeAttributeState encoding_type, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
818
0
{
819
    // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
820
0
    auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
821
822
0
    String body;
823
824
    // 2. Switch on enctype:
825
0
    switch (encoding_type) {
826
0
    case EncodingTypeAttributeState::PlainText: {
827
        // -> text/plain
828
        // 1. Let body be the result of running the text/plain encoding algorithm with pairs.
829
0
        body = TRY(plain_text_encode(pairs));
830
831
        // 2. Set body to the result of running UTF-8 percent-encode on body using the default encode set. [URL]
832
        // NOTE: body is already UTF-8 encoded due to using AK::String, so we only have to do the percent encoding.
833
        // NOTE: "default encode set" links to "path percent-encode-set": https://url.spec.whatwg.org/#default-encode-set
834
0
        body = URL::percent_encode(body, URL::PercentEncodeSet::Path);
835
0
        break;
836
0
    }
837
0
    default:
838
        // -> Otherwise
839
        // Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
840
0
        body = url_encode(pairs, encoding);
841
0
        break;
842
0
    }
843
844
    // 3. If parsed action's query is null, then set it to the empty string.
845
0
    if (!parsed_action.query().has_value())
846
0
        parsed_action.set_query(String {});
847
848
0
    StringBuilder query_builder;
849
850
0
    query_builder.append(*parsed_action.query());
851
852
    // 4. If parsed action's query is not the empty string, then append a single U+0026 AMPERSAND character (&) to it.
853
0
    if (!parsed_action.query()->is_empty())
854
0
        TRY(query_builder.try_append('&'));
855
856
    // 5. Append "body=" to parsed action's query.
857
0
    TRY(query_builder.try_append("body="sv));
858
859
    // 6. Append body to parsed action's query.
860
0
    TRY(query_builder.try_append(body));
861
862
0
    parsed_action.set_query(MUST(query_builder.to_string()));
863
864
    // 7. Plan to navigate to parsed action.
865
0
    plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling, user_involvement);
866
0
    return {};
867
0
}
868
869
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plan-to-navigate
870
void HTMLFormElement::plan_to_navigate_to(URL::URL url, Variant<Empty, String, POSTResource> post_resource, JS::NonnullGCPtr<Navigable> target_navigable, Bindings::NavigationHistoryBehavior history_handling, UserNavigationInvolvement user_involvement)
871
0
{
872
    // 1. Let referrerPolicy be the empty string.
873
0
    ReferrerPolicy::ReferrerPolicy referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString;
874
875
    // 2. If the form element's link types include the noreferrer keyword, then set referrerPolicy to "no-referrer".
876
0
    auto rel = MUST(get_attribute_value(HTML::AttributeNames::rel).to_lowercase());
877
0
    auto link_types = rel.bytes_as_string_view().split_view_if(Infra::is_ascii_whitespace);
878
0
    if (link_types.contains_slow("noreferrer"sv))
879
0
        referrer_policy = ReferrerPolicy::ReferrerPolicy::NoReferrer;
880
881
    // 3. If the form has a non-null planned navigation, remove it from its task queue.
882
0
    if (m_planned_navigation) {
883
0
        HTML::main_thread_event_loop().task_queue().remove_tasks_matching([this](Task const& task) {
884
0
            return &task == m_planned_navigation;
885
0
        });
886
0
    }
887
888
    // 4. Queue an element task on the DOM manipulation task source given the form element and the following steps:
889
    // NOTE: `this`, `actual_resource` and `target_navigable` are protected by JS::SafeFunction.
890
0
    queue_an_element_task(Task::Source::DOMManipulation, [this, url, post_resource, target_navigable, history_handling, referrer_policy, user_involvement]() {
891
        // 1. Set the form's planned navigation to null.
892
0
        m_planned_navigation = {};
893
894
        // 2. Navigate targetNavigable to url using the form element's node document, with historyHandling set to historyHandling,
895
        //    referrerPolicy set to referrerPolicy, documentResource set to postResource, and cspNavigationType set to "form-submission".
896
0
        MUST(target_navigable->navigate({ .url = url,
897
0
            .source_document = this->document(),
898
0
            .document_resource = post_resource,
899
0
            .response = nullptr,
900
0
            .exceptions_enabled = false,
901
0
            .history_handling = history_handling,
902
0
            .referrer_policy = referrer_policy,
903
0
            .user_involvement = user_involvement }));
904
0
    });
905
906
    // 5. Set the form's planned navigation to the just-queued task.
907
0
    m_planned_navigation = HTML::main_thread_event_loop().task_queue().last_added_task();
908
0
    VERIFY(m_planned_navigation);
909
0
}
910
911
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-item
912
Optional<JS::Value> HTMLFormElement::item_value(size_t index) const
913
0
{
914
    // To determine the value of an indexed property for a form element, the user agent must return the value returned by
915
    // the item method on the elements collection, when invoked with the given index as its argument.
916
0
    if (auto value = elements()->item(index))
917
0
        return value;
918
0
    return {};
919
0
}
920
921
// https://html.spec.whatwg.org/multipage/forms.html#the-form-element:supported-property-names
922
Vector<FlyString> HTMLFormElement::supported_property_names() const
923
0
{
924
    // The supported property names consist of the names obtained from the following algorithm, in the order obtained from this algorithm:
925
926
    // 1. Let sourced names be an initially empty ordered list of tuples consisting of a string, an element, a source,
927
    //    where the source is either id, name, or past, and, if the source is past, an age.
928
0
    struct SourcedName {
929
0
        FlyString name;
930
0
        JS::GCPtr<DOM::Element const> element;
931
0
        enum class Source {
932
0
            Id,
933
0
            Name,
934
0
            Past,
935
0
        } source;
936
0
        AK::Duration age;
937
0
    };
938
0
    Vector<SourcedName> sourced_names;
939
940
    // 2. For each listed element candidate whose form owner is the form element, with the exception of any
941
    //    input elements whose type attribute is in the Image Button state:
942
0
    for (auto const& candidate : m_associated_elements) {
943
0
        if (!is_form_control(*candidate, *this))
944
0
            continue;
945
946
        // 1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the
947
        //    string, candidate as the element, and id as the source.
948
0
        if (candidate->id().has_value())
949
0
            sourced_names.append(SourcedName { candidate->id().value(), candidate, SourcedName::Source::Id, {} });
950
951
        // 2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the
952
        //    string, candidate as the element, and name as the source.
953
0
        if (candidate->name().has_value())
954
0
            sourced_names.append(SourcedName { candidate->name().value(), candidate, SourcedName::Source::Name, {} });
955
0
    }
956
957
    // 3. For each img element candidate whose form owner is the form element:
958
0
    for (auto const& candidate : m_associated_elements) {
959
0
        if (!is<HTMLImageElement>(*candidate))
960
0
            continue;
961
962
        // Every element in m_associated_elements has this as the form owner.
963
964
        // 1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the
965
        //    string, candidate as the element, and id as the source.
966
0
        if (candidate->id().has_value())
967
0
            sourced_names.append(SourcedName { candidate->id().value(), candidate, SourcedName::Source::Id, {} });
968
969
        // 2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the
970
        //    string, candidate as the element, and name as the source.
971
0
        if (candidate->name().has_value())
972
0
            sourced_names.append(SourcedName { candidate->name().value(), candidate, SourcedName::Source::Name, {} });
973
0
    }
974
975
    // 4. For each entry past entry in the past names map add an entry to sourced names with the past entry's name as
976
    //    the string, past entry's element as the element, past as the source, and the length of time past entry has
977
    //    been in the past names map as the age.
978
0
    auto const now = MonotonicTime::now();
979
0
    for (auto const& entry : m_past_names_map)
980
0
        sourced_names.append(SourcedName { entry.key, static_cast<DOM::Element const*>(entry.value.node.ptr()), SourcedName::Source::Past, now - entry.value.insertion_time });
981
982
    // 5. Sort sourced names by tree order of the element entry of each tuple, sorting entries with the same element by
983
    //    putting entries whose source is id first, then entries whose source is name, and finally entries whose source
984
    //    is past, and sorting entries with the same element and source by their age, oldest first.
985
    // FIXME: Require less const casts here by changing the signature of DOM::Node::compare_document_position
986
0
    quick_sort(sourced_names, [](auto const& lhs, auto const& rhs) -> bool {
987
0
        if (lhs.element != rhs.element)
988
0
            return const_cast<DOM::Element*>(lhs.element.ptr())->compare_document_position(const_cast<DOM::Element*>(rhs.element.ptr())) & DOM::Node::DOCUMENT_POSITION_FOLLOWING;
989
0
        if (lhs.source != rhs.source)
990
0
            return lhs.source < rhs.source;
991
0
        return lhs.age < rhs.age;
992
0
    });
993
994
    // FIXME: Surely there's a more efficient way to do this without so many FlyStrings and collections?
995
    // 6. Remove any entries in sourced names that have the empty string as their name.
996
    // 7. Remove any entries in sourced names that have the same name as an earlier entry in the map.
997
    // 8. Return the list of names from sourced names, maintaining their relative order.
998
0
    OrderedHashTable<FlyString> names;
999
0
    names.ensure_capacity(sourced_names.size());
1000
0
    for (auto const& entry : sourced_names) {
1001
0
        if (entry.name.is_empty())
1002
0
            continue;
1003
0
        names.set(entry.name, AK::HashSetExistingEntryBehavior::Keep);
1004
0
    }
1005
1006
0
    Vector<FlyString> result;
1007
0
    result.ensure_capacity(names.size());
1008
0
    for (auto const& name : names)
1009
0
        result.unchecked_append(name);
1010
1011
0
    return result;
1012
0
}
1013
1014
// https://html.spec.whatwg.org/multipage/forms.html#dom-form-nameditem
1015
JS::Value HTMLFormElement::named_item_value(FlyString const& name) const
1016
0
{
1017
0
    auto& realm = this->realm();
1018
0
    auto& root = verify_cast<ParentNode>(this->root());
1019
1020
    // To determine the value of a named property name for a form element, the user agent must run the following steps:
1021
1022
    // 1. Let candidates be a live RadioNodeList object containing all the listed elements, whose form owner is the form
1023
    //    element, that have either an id attribute or a name attribute equal to name, with the exception of input
1024
    //    elements whose type attribute is in the Image Button state, in tree order.
1025
0
    auto candidates = RadioNodeList::create(realm, root, DOM::LiveNodeList::Scope::Descendants, [this, name](auto& node) -> bool {
1026
0
        if (!is<DOM::Element>(node))
1027
0
            return false;
1028
0
        auto const& element = static_cast<DOM::Element const&>(node);
1029
1030
        // Form controls are defined as listed elements, with the exception of input elements in the Image Button state,
1031
        // whose form owner is the form element.
1032
0
        if (!is_form_control(element, *this))
1033
0
            return false;
1034
1035
0
        return name == element.id() || name == element.name();
1036
0
    });
1037
1038
    // 2. If candidates is empty, let candidates be a live RadioNodeList object containing all the img elements,
1039
    //    whose form owner is the form element, that have either an id attribute or a name attribute equal to name,
1040
    //    in tree order.
1041
0
    if (candidates->length() == 0) {
1042
0
        candidates = RadioNodeList::create(realm, root, DOM::LiveNodeList::Scope::Descendants, [this, name](auto& node) -> bool {
1043
0
            if (!is<HTMLImageElement>(node))
1044
0
                return false;
1045
1046
0
            auto const& element = static_cast<HTMLImageElement const&>(node);
1047
0
            if (element.form() != this)
1048
0
                return false;
1049
1050
0
            return name == element.id() || name == element.name();
1051
0
        });
1052
0
    }
1053
1054
0
    auto length = candidates->length();
1055
1056
    // 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.
1057
0
    if (length == 0) {
1058
0
        auto it = m_past_names_map.find(name);
1059
0
        if (it != m_past_names_map.end())
1060
0
            return it->value.node;
1061
0
    }
1062
1063
    // 4. If candidates contains more than one node, return candidates.
1064
0
    if (length > 1)
1065
0
        return candidates;
1066
1067
    // 5. Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the form
1068
    //    element's past names map, replacing the previous entry with the same name, if any.
1069
0
    auto const* node = candidates->item(0);
1070
0
    m_past_names_map.set(name, HTMLFormElement::PastNameEntry { .node = node, .insertion_time = MonotonicTime::now() });
1071
1072
    // 6. Return the node in candidates.
1073
0
    return node;
1074
0
}
1075
1076
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#default-button
1077
FormAssociatedElement* HTMLFormElement::default_button()
1078
0
{
1079
    // A form element's default button is the first submit button in tree order whose form owner is that form element.
1080
0
    FormAssociatedElement* default_button = nullptr;
1081
1082
0
    root().for_each_in_subtree([&](auto& node) {
1083
0
        auto* form_associated_element = dynamic_cast<FormAssociatedElement*>(&node);
1084
0
        if (!form_associated_element)
1085
0
            return TraversalDecision::Continue;
1086
1087
0
        if (form_associated_element->form() == this && form_associated_element->is_submit_button()) {
1088
0
            default_button = form_associated_element;
1089
0
            return TraversalDecision::Break;
1090
0
        }
1091
1092
0
        return TraversalDecision::Continue;
1093
0
    });
1094
1095
0
    return default_button;
1096
0
}
1097
1098
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#field-that-blocks-implicit-submission
1099
size_t HTMLFormElement::number_of_fields_blocking_implicit_submission() const
1100
0
{
1101
    // For the purpose of the previous paragraph, an element is a field that blocks implicit submission of a form
1102
    // element if it is an input element whose form owner is that form element and whose type attribute is in one of
1103
    // the following states: Text, Search, Telephone, URL, Email, Password, Date, Month, Week, Time,
1104
    // Local Date and Time, Number.
1105
0
    size_t count = 0;
1106
1107
0
    for (auto element : m_associated_elements) {
1108
0
        if (!is<HTMLInputElement>(*element))
1109
0
            continue;
1110
1111
0
        auto const& input = static_cast<HTMLInputElement&>(*element);
1112
0
        using enum HTMLInputElement::TypeAttributeState;
1113
1114
0
        switch (input.type_state()) {
1115
0
        case Text:
1116
0
        case Search:
1117
0
        case Telephone:
1118
0
        case URL:
1119
0
        case Email:
1120
0
        case Password:
1121
0
        case Date:
1122
0
        case Month:
1123
0
        case Week:
1124
0
        case Time:
1125
0
        case LocalDateAndTime:
1126
0
        case Number:
1127
0
            ++count;
1128
0
            break;
1129
1130
0
        default:
1131
0
            break;
1132
0
        }
1133
0
    };
1134
1135
0
    return count;
1136
0
}
1137
1138
}