HTMLFormElement.cpp 51 KB

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