HTMLFormElement.cpp 47 KB

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