HTMLFormElement.cpp 52 KB

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