HTMLFormElement.cpp 52 KB

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