HTMLFormElement.cpp 53 KB

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