HTMLFormElement.cpp 48 KB

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