HTMLFormElement.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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/StringBuilder.h>
  9. #include <LibTextCodec/Decoder.h>
  10. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOM/Event.h>
  13. #include <LibWeb/DOM/HTMLFormControlsCollection.h>
  14. #include <LibWeb/HTML/BrowsingContext.h>
  15. #include <LibWeb/HTML/EventNames.h>
  16. #include <LibWeb/HTML/FormControlInfrastructure.h>
  17. #include <LibWeb/HTML/HTMLButtonElement.h>
  18. #include <LibWeb/HTML/HTMLFieldSetElement.h>
  19. #include <LibWeb/HTML/HTMLFormElement.h>
  20. #include <LibWeb/HTML/HTMLInputElement.h>
  21. #include <LibWeb/HTML/HTMLObjectElement.h>
  22. #include <LibWeb/HTML/HTMLOutputElement.h>
  23. #include <LibWeb/HTML/HTMLSelectElement.h>
  24. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  25. #include <LibWeb/HTML/SubmitEvent.h>
  26. #include <LibWeb/Infra/CharacterTypes.h>
  27. #include <LibWeb/Infra/Strings.h>
  28. #include <LibWeb/Page/Page.h>
  29. #include <LibWeb/URL/URL.h>
  30. namespace Web::HTML {
  31. JS_DEFINE_ALLOCATOR(HTMLFormElement);
  32. HTMLFormElement::HTMLFormElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  33. : HTMLElement(document, move(qualified_name))
  34. {
  35. }
  36. HTMLFormElement::~HTMLFormElement() = default;
  37. void HTMLFormElement::initialize(JS::Realm& realm)
  38. {
  39. Base::initialize(realm);
  40. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLFormElementPrototype>(realm, "HTMLFormElement"_fly_string));
  41. }
  42. void HTMLFormElement::visit_edges(Cell::Visitor& visitor)
  43. {
  44. Base::visit_edges(visitor);
  45. visitor.visit(m_elements);
  46. for (auto& element : m_associated_elements)
  47. visitor.visit(element);
  48. }
  49. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-form-submit
  50. WebIDL::ExceptionOr<void> HTMLFormElement::submit_form(JS::NonnullGCPtr<HTMLElement> submitter, bool from_submit_binding)
  51. {
  52. auto& vm = this->vm();
  53. auto& realm = this->realm();
  54. // 1. If form cannot navigate, then return.
  55. if (cannot_navigate())
  56. return {};
  57. // 2. If form's constructing entry list is true, then return.
  58. if (m_constructing_entry_list)
  59. return {};
  60. // 3. Let form document be form's node document.
  61. JS::NonnullGCPtr<DOM::Document> form_document = this->document();
  62. // 4. If form document's active sandboxing flag set has its sandboxed forms browsing context flag set, then return.
  63. if (has_flag(form_document->active_sandboxing_flag_set(), HTML::SandboxingFlagSet::SandboxedForms))
  64. return {};
  65. // 5. If the submitted from submit() method flag is not set, then:
  66. if (!from_submit_binding) {
  67. // 1. If form's firing submission events is true, then return.
  68. if (m_firing_submission_events)
  69. return {};
  70. // 2. Set form's firing submission events to true.
  71. m_firing_submission_events = true;
  72. // FIXME: 3. If the submitter element's no-validate state is false, then interactively validate the constraints
  73. // of form and examine the result. If the result is negative (i.e., the constraint validation concluded
  74. // that there were invalid fields and probably informed the user of this), then:
  75. // 1. Set form's firing submission events to false.
  76. // 2. Return.
  77. // 4. Let submitterButton be null if submitter is form. Otherwise, let submitterButton be submitter.
  78. JS::GCPtr<HTMLElement> submitter_button;
  79. if (submitter != this)
  80. submitter_button = submitter;
  81. // 5. Let shouldContinue be the result of firing an event named submit at form using SubmitEvent, with the
  82. // submitter attribute initialized to submitterButton, the bubbles attribute initialized to true, and the
  83. // cancelable attribute initialized to true.
  84. SubmitEventInit event_init {};
  85. event_init.submitter = submitter_button;
  86. auto submit_event = SubmitEvent::create(realm, EventNames::submit, event_init);
  87. submit_event->set_bubbles(true);
  88. submit_event->set_cancelable(true);
  89. bool should_continue = dispatch_event(*submit_event);
  90. // 6. Set form's firing submission events to false.
  91. m_firing_submission_events = false;
  92. // 7. If shouldContinue is false, then return.
  93. if (!should_continue)
  94. return {};
  95. // 8. If form cannot navigate, then return.
  96. // Spec Note: Cannot navigate is run again as dispatching the submit event could have changed the outcome.
  97. if (cannot_navigate())
  98. return {};
  99. }
  100. // 6. Let encoding be the result of picking an encoding for the form.
  101. auto encoding = TRY_OR_THROW_OOM(vm, pick_an_encoding());
  102. if (encoding != "UTF-8"sv) {
  103. dbgln("FIXME: Support encodings other than UTF-8 in form submission. Returning from form submission.");
  104. return {};
  105. }
  106. // 7. Let entry list be the result of constructing the entry list with form, submitter, and encoding.
  107. auto entry_list_or_null = TRY(construct_entry_list(realm, *this, submitter, encoding));
  108. // 8. Assert: entry list is not null.
  109. VERIFY(entry_list_or_null.has_value());
  110. auto entry_list = entry_list_or_null.release_value();
  111. // 9. If form cannot navigate, then return.
  112. // Spec Note: Cannot navigate is run again as dispatching the formdata event in constructing the entry list could
  113. // have changed the outcome.
  114. if (cannot_navigate())
  115. return {};
  116. // 10. Let method be the submitter element's method.
  117. auto method = method_state_from_form_element(submitter);
  118. // 11. If method is dialog, then:
  119. if (method == MethodAttributeState::Dialog) {
  120. // FIXME: 1. If form does not have an ancestor dialog element, then return.
  121. // FIXME: 2. Let subject be form's nearest ancestor dialog element.
  122. // FIXME: 3. Let result be null.
  123. // FIXME: 4. If submitter is an input element whose type attribute is in the Image Button state, then:
  124. // 1. Let (x, y) be the selected coordinate.
  125. // 2. Set result to the concatenation of x, ",", and y.
  126. // FIXME: 5. Otherwise, if submitter has a value, then set result to that value.
  127. // FIXME: 6. Close the dialog subject with result.
  128. // FIXME: 7. Return.
  129. dbgln("FIXME: Implement form submission with `dialog` action. Returning from form submission.");
  130. return {};
  131. }
  132. // 12. Let action be the submitter element's action.
  133. auto action = action_from_form_element(submitter);
  134. // 13. If action is the empty string, let action be the URL of the form document.
  135. if (action.is_empty())
  136. action = form_document->url_string();
  137. // 14. Parse a URL given action, relative to the submitter element's node document. If this fails, return.
  138. // 15. Let parsed action be the resulting URL record.
  139. auto parsed_action = document().parse_url(action);
  140. if (!parsed_action.is_valid()) {
  141. dbgln("Failed to submit form: Invalid URL: {}", action);
  142. return {};
  143. }
  144. // 16. Let scheme be the scheme of parsed action.
  145. auto const& scheme = parsed_action.scheme();
  146. // 17. Let enctype be the submitter element's enctype.
  147. auto encoding_type = encoding_type_state_from_form_element(submitter);
  148. // 18. Let target be the submitter element's formtarget attribute value, if the element is a submit button and has
  149. // such an attribute. Otherwise, let it be the result of getting an element's target given submitter's form
  150. // owner.
  151. auto target = submitter->attribute(AttributeNames::formtarget).value_or(get_an_elements_target());
  152. // 19. Let noopener be the result of getting an element's noopener with form and target.
  153. auto no_opener = get_an_elements_noopener(target);
  154. // 20. Let targetNavigable be the first return value of applying the rules for choosing a navigable given target, form's node navigable, and noopener.
  155. auto target_navigable = form_document->navigable()->choose_a_navigable(target, no_opener).navigable;
  156. // 21. If targetNavigable is null, then return.
  157. if (!target_navigable) {
  158. dbgln("Failed to submit form: choose_a_browsing_context returning a null browsing context");
  159. return {};
  160. }
  161. // 22. Let historyHandling be "push".
  162. // NOTE: This is `Default` in the old spec.
  163. auto history_handling = HistoryHandlingBehavior::Default;
  164. // 23. If form document has not yet completely loaded, then set historyHandling to "replace".
  165. if (!form_document->is_completely_loaded())
  166. history_handling = HistoryHandlingBehavior::Replace;
  167. // 24. Select the appropriate row in the table below based on scheme as given by the first cell of each row.
  168. // Then, select the appropriate cell on that row based on method as given in the first cell of each column.
  169. // Then, jump to the steps named in that cell and defined below the table.
  170. // | GET | POST
  171. // ------------------------------------------------------
  172. // http | Mutate action URL | Submit as entity body
  173. // https | Mutate action URL | Submit as entity body
  174. // ftp | Get action URL | Get action URL
  175. // javascript | Get action URL | Get action URL
  176. // data | Mutate action URL | Get action URL
  177. // mailto | Mail with headers | Mail as body
  178. // If scheme is not one of those listed in this table, then the behavior is not defined by this specification.
  179. // User agents should, in the absence of another specification defining this, act in a manner analogous to that defined
  180. // in this specification for similar schemes.
  181. // This should have been handled above.
  182. VERIFY(method != MethodAttributeState::Dialog);
  183. if (scheme.is_one_of("http"sv, "https"sv)) {
  184. if (method == MethodAttributeState::GET)
  185. TRY_OR_THROW_OOM(vm, mutate_action_url(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling));
  186. else
  187. TRY_OR_THROW_OOM(vm, submit_as_entity_body(move(parsed_action), move(entry_list), encoding_type, move(encoding), *target_navigable, history_handling));
  188. } else if (scheme.is_one_of("ftp"sv, "javascript"sv)) {
  189. get_action_url(move(parsed_action), *target_navigable, history_handling);
  190. } else if (scheme == "data"sv) {
  191. if (method == MethodAttributeState::GET)
  192. TRY_OR_THROW_OOM(vm, mutate_action_url(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling));
  193. else
  194. get_action_url(move(parsed_action), *target_navigable, history_handling);
  195. } else if (scheme == "mailto"sv) {
  196. if (method == MethodAttributeState::GET)
  197. TRY_OR_THROW_OOM(vm, mail_with_headers(move(parsed_action), move(entry_list), move(encoding), *target_navigable, history_handling));
  198. else
  199. TRY_OR_THROW_OOM(vm, mail_as_body(move(parsed_action), move(entry_list), encoding_type, move(encoding), *target_navigable, history_handling));
  200. } else {
  201. dbgln("Failed to submit form: Unknown scheme: {}", scheme);
  202. return {};
  203. }
  204. return {};
  205. }
  206. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#resetting-a-form
  207. void HTMLFormElement::reset_form()
  208. {
  209. // 1. Let reset be the result of firing an event named reset at form, with the bubbles and cancelable attributes initialized to true.
  210. auto reset_event = DOM::Event::create(realm(), HTML::EventNames::reset);
  211. reset_event->set_bubbles(true);
  212. reset_event->set_cancelable(true);
  213. bool reset = dispatch_event(reset_event);
  214. // 2. If reset is true, then invoke the reset algorithm of each resettable element whose form owner is form.
  215. if (reset) {
  216. for (auto element : m_associated_elements) {
  217. VERIFY(is<FormAssociatedElement>(*element));
  218. auto& form_associated_element = dynamic_cast<FormAssociatedElement&>(*element);
  219. if (form_associated_element.is_resettable())
  220. form_associated_element.reset_algorithm();
  221. }
  222. }
  223. }
  224. WebIDL::ExceptionOr<void> HTMLFormElement::submit()
  225. {
  226. return submit_form(*this, true);
  227. }
  228. // https://html.spec.whatwg.org/multipage/forms.html#dom-form-reset
  229. void HTMLFormElement::reset()
  230. {
  231. // 1. If the form element is marked as locked for reset, then return.
  232. if (m_locked_for_reset)
  233. return;
  234. // 2. Mark the form element as locked for reset.
  235. m_locked_for_reset = true;
  236. // 3. Reset the form element.
  237. reset_form();
  238. // 4. Unmark the form element as locked for reset.
  239. m_locked_for_reset = false;
  240. }
  241. void HTMLFormElement::add_associated_element(Badge<FormAssociatedElement>, HTMLElement& element)
  242. {
  243. m_associated_elements.append(element);
  244. }
  245. void HTMLFormElement::remove_associated_element(Badge<FormAssociatedElement>, HTMLElement& element)
  246. {
  247. m_associated_elements.remove_first_matching([&](auto& entry) { return entry.ptr() == &element; });
  248. }
  249. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-action
  250. String HTMLFormElement::action_from_form_element(JS::NonnullGCPtr<HTMLElement> element) const
  251. {
  252. // The action of an element is the value of the element's formaction attribute, if the element is a submit button
  253. // and has such an attribute, or the value of its form owner's action attribute, if it has one, or else the empty
  254. // string.
  255. if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
  256. form_associated_element && form_associated_element->is_submit_button()) {
  257. if (auto maybe_attribute = element->attribute(AttributeNames::formaction); maybe_attribute.has_value())
  258. return maybe_attribute.release_value();
  259. }
  260. if (auto maybe_attribute = attribute(AttributeNames::action); maybe_attribute.has_value())
  261. return maybe_attribute.release_value();
  262. return String {};
  263. }
  264. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-attributes:attr-fs-method-2
  265. static HTMLFormElement::MethodAttributeState method_attribute_to_method_state(StringView method)
  266. {
  267. #define __ENUMERATE_FORM_METHOD_ATTRIBUTE(keyword, state) \
  268. if (Infra::is_ascii_case_insensitive_match(#keyword##sv, method)) \
  269. return HTMLFormElement::MethodAttributeState::state;
  270. ENUMERATE_FORM_METHOD_ATTRIBUTES
  271. #undef __ENUMERATE_FORM_METHOD_ATTRIBUTE
  272. // The method attribute's invalid value default and missing value default are both the GET state.
  273. return HTMLFormElement::MethodAttributeState::GET;
  274. }
  275. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-method
  276. HTMLFormElement::MethodAttributeState HTMLFormElement::method_state_from_form_element(JS::NonnullGCPtr<HTMLElement const> element) const
  277. {
  278. // If the element is a submit button and has a formmethod attribute, then the element's method is that attribute's state;
  279. // otherwise, it is the form owner's method attribute's state.
  280. if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
  281. form_associated_element && form_associated_element->is_submit_button() && element->has_attribute(AttributeNames::formmethod)) {
  282. // NOTE: `formmethod` is the same as `method`, except that it has no missing value default.
  283. // This is handled by not calling `method_attribute_to_method_state` in the first place if there is no `formmethod` attribute.
  284. return method_attribute_to_method_state(element->deprecated_attribute(AttributeNames::formmethod));
  285. }
  286. if (!this->has_attribute(AttributeNames::method))
  287. return MethodAttributeState::GET;
  288. return method_attribute_to_method_state(this->deprecated_attribute(AttributeNames::method));
  289. }
  290. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-submission-attributes:attr-fs-enctype-2
  291. static HTMLFormElement::EncodingTypeAttributeState encoding_type_attribute_to_encoding_type_state(StringView encoding_type)
  292. {
  293. #define __ENUMERATE_FORM_METHOD_ENCODING_TYPE(keyword, state) \
  294. if (Infra::is_ascii_case_insensitive_match(keyword##sv, encoding_type)) \
  295. return HTMLFormElement::EncodingTypeAttributeState::state;
  296. ENUMERATE_FORM_METHOD_ENCODING_TYPES
  297. #undef __ENUMERATE_FORM_METHOD_ENCODING_TYPE
  298. // The enctype attribute's invalid value default and missing value default are both the application/x-www-form-urlencoded state.
  299. return HTMLFormElement::EncodingTypeAttributeState::FormUrlEncoded;
  300. }
  301. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-fs-enctype
  302. HTMLFormElement::EncodingTypeAttributeState HTMLFormElement::encoding_type_state_from_form_element(JS::NonnullGCPtr<HTMLElement> element) const
  303. {
  304. // If the element is a submit button and has a formenctype attribute, then the element's enctype is that attribute's state;
  305. // otherwise, it is the form owner's enctype attribute's state.
  306. if (auto const* form_associated_element = dynamic_cast<FormAssociatedElement const*>(element.ptr());
  307. form_associated_element && form_associated_element->is_submit_button() && element->has_attribute(AttributeNames::formenctype)) {
  308. // NOTE: `formenctype` is the same as `enctype`, except that it has no missing value default.
  309. // This is handled by not calling `encoding_type_attribute_to_encoding_type_state` in the first place if there is no
  310. // `formenctype` attribute.
  311. return encoding_type_attribute_to_encoding_type_state(element->deprecated_attribute(AttributeNames::formenctype));
  312. }
  313. if (!this->has_attribute(AttributeNames::enctype))
  314. return EncodingTypeAttributeState::FormUrlEncoded;
  315. return encoding_type_attribute_to_encoding_type_state(this->deprecated_attribute(AttributeNames::enctype));
  316. }
  317. static bool is_form_control(DOM::Element const& element)
  318. {
  319. if (is<HTMLButtonElement>(element)
  320. || is<HTMLFieldSetElement>(element)
  321. || is<HTMLObjectElement>(element)
  322. || is<HTMLOutputElement>(element)
  323. || is<HTMLSelectElement>(element)
  324. || is<HTMLTextAreaElement>(element)) {
  325. return true;
  326. }
  327. if (is<HTMLInputElement>(element)
  328. && !element.deprecated_get_attribute(HTML::AttributeNames::type).equals_ignoring_ascii_case("image"sv)) {
  329. return true;
  330. }
  331. // FIXME: Form-associated custom elements return also true
  332. return false;
  333. }
  334. // https://html.spec.whatwg.org/multipage/forms.html#dom-form-elements
  335. JS::NonnullGCPtr<DOM::HTMLFormControlsCollection> HTMLFormElement::elements() const
  336. {
  337. if (!m_elements) {
  338. m_elements = DOM::HTMLFormControlsCollection::create(const_cast<HTMLFormElement&>(*this), DOM::HTMLCollection::Scope::Descendants, [](Element const& element) {
  339. return is_form_control(element);
  340. });
  341. }
  342. return *m_elements;
  343. }
  344. // https://html.spec.whatwg.org/multipage/forms.html#dom-form-length
  345. unsigned HTMLFormElement::length() const
  346. {
  347. // The length IDL attribute must return the number of nodes represented by the elements collection.
  348. return elements()->length();
  349. }
  350. // https://html.spec.whatwg.org/multipage/forms.html#dom-form-checkvalidity
  351. WebIDL::ExceptionOr<bool> HTMLFormElement::check_validity()
  352. {
  353. dbgln("(STUBBED) HTMLFormElement::check_validity(). Called on: {}", debug_description());
  354. return true;
  355. }
  356. // https://html.spec.whatwg.org/multipage/forms.html#dom-form-reportvalidity
  357. WebIDL::ExceptionOr<bool> HTMLFormElement::report_validity()
  358. {
  359. dbgln("(STUBBED) HTMLFormElement::report_validity(). Called on: {}", debug_description());
  360. return true;
  361. }
  362. // https://html.spec.whatwg.org/multipage/forms.html#category-submit
  363. ErrorOr<Vector<JS::NonnullGCPtr<DOM::Element>>> HTMLFormElement::get_submittable_elements()
  364. {
  365. Vector<JS::NonnullGCPtr<DOM::Element>> submittable_elements = {};
  366. for (size_t i = 0; i < elements()->length(); i++) {
  367. auto* element = elements()->item(i);
  368. TRY(populate_vector_with_submittable_elements_in_tree_order(*element, submittable_elements));
  369. }
  370. return submittable_elements;
  371. }
  372. ErrorOr<void> HTMLFormElement::populate_vector_with_submittable_elements_in_tree_order(JS::NonnullGCPtr<DOM::Element> element, Vector<JS::NonnullGCPtr<DOM::Element>>& elements)
  373. {
  374. if (auto* form_associated_element = dynamic_cast<HTML::FormAssociatedElement*>(element.ptr())) {
  375. if (form_associated_element->is_submittable())
  376. TRY(elements.try_append(element));
  377. }
  378. for (size_t i = 0; i < element->children()->length(); i++) {
  379. auto* child = element->children()->item(i);
  380. TRY(populate_vector_with_submittable_elements_in_tree_order(*child, elements));
  381. }
  382. return {};
  383. }
  384. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-method
  385. StringView HTMLFormElement::method() const
  386. {
  387. // The method and enctype IDL attributes must reflect the respective content attributes of the same name, limited to only known values.
  388. // FIXME: This should probably be `Reflect` in the IDL.
  389. auto method_state = method_state_from_form_element(*this);
  390. switch (method_state) {
  391. case MethodAttributeState::GET:
  392. return "get"sv;
  393. case MethodAttributeState::POST:
  394. return "post"sv;
  395. case MethodAttributeState::Dialog:
  396. return "dialog"sv;
  397. }
  398. VERIFY_NOT_REACHED();
  399. }
  400. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-method
  401. WebIDL::ExceptionOr<void> HTMLFormElement::set_method(String const& method)
  402. {
  403. // The method and enctype IDL attributes must reflect the respective content attributes of the same name, limited to only known values.
  404. return set_attribute(AttributeNames::method, method);
  405. }
  406. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-action
  407. String HTMLFormElement::action() const
  408. {
  409. // The action IDL attribute must reflect the content attribute of the same name, except that on getting, when the
  410. // content attribute is missing or its value is the empty string, the element's node document's URL must be returned
  411. // instead.
  412. if (!has_attribute(AttributeNames::action))
  413. return MUST(document().url().to_string());
  414. auto action_attribute = attribute(AttributeNames::action);
  415. if (!action_attribute.has_value() || action_attribute->is_empty())
  416. return MUST(document().url().to_string());
  417. return action_attribute.value();
  418. }
  419. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-action
  420. WebIDL::ExceptionOr<void> HTMLFormElement::set_action(String const& value)
  421. {
  422. return set_attribute(AttributeNames::action, value);
  423. }
  424. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#picking-an-encoding-for-the-form
  425. ErrorOr<String> HTMLFormElement::pick_an_encoding() const
  426. {
  427. // 1. Let encoding be the document's character encoding.
  428. auto encoding = document().encoding_or_default();
  429. // 2. If the form element has an accept-charset attribute, set encoding to the return value of running these substeps:
  430. if (has_attribute(AttributeNames::accept_charset)) {
  431. // 1. Let input be the value of the form element's accept-charset attribute.
  432. auto input = deprecated_attribute(AttributeNames::accept_charset);
  433. // 2. Let candidate encoding labels be the result of splitting input on ASCII whitespace.
  434. auto candidate_encoding_labels = input.split_view(Infra::is_ascii_whitespace);
  435. // 3. Let candidate encodings be an empty list of character encodings.
  436. Vector<StringView> candidate_encodings;
  437. // 4. For each token in candidate encoding labels in turn (in the order in which they were found in input),
  438. // get an encoding for the token and, if this does not result in failure, append the encoding to candidate
  439. // encodings.
  440. for (auto const& token : candidate_encoding_labels) {
  441. auto candidate_encoding = TextCodec::get_standardized_encoding(token);
  442. if (candidate_encoding.has_value())
  443. TRY(candidate_encodings.try_append(candidate_encoding.value()));
  444. }
  445. // 5. If candidate encodings is empty, return UTF-8.
  446. if (candidate_encodings.is_empty())
  447. return "UTF-8"_string;
  448. // 6. Return the first encoding in candidate encodings.
  449. return String::from_utf8(candidate_encodings.first());
  450. }
  451. // 3. Return the result of getting an output encoding from encoding.
  452. return MUST(String::from_utf8(TextCodec::get_output_encoding(encoding)));
  453. }
  454. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#convert-to-a-list-of-name-value-pairs
  455. static ErrorOr<Vector<URL::QueryParam>> convert_to_list_of_name_value_pairs(Vector<XHR::FormDataEntry> const& entry_list)
  456. {
  457. // 1. Let list be an empty list of name-value pairs.
  458. Vector<URL::QueryParam> list;
  459. // 2. For each entry of entry list:
  460. for (auto const& entry : entry_list) {
  461. // 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)
  462. // not preceded by U+000D (CR), replaced by a string consisting of U+000D (CR) and U+000A (LF).
  463. auto name = TRY(normalize_line_breaks(entry.name));
  464. // 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.
  465. String value;
  466. entry.value.visit(
  467. [&value](JS::Handle<FileAPI::File> const& file) {
  468. value = file->name();
  469. },
  470. [&value](String const& string) {
  471. value = string;
  472. });
  473. // 3. Replace every occurrence of U+000D (CR) not followed by U+000A (LF), and every occurrence of
  474. // U+000A (LF) not preceded by U+000D (CR), in value, by a string consisting of U+000D (CR) and U+000A (LF).
  475. auto normalized_value = TRY(normalize_line_breaks(value));
  476. // 4. Append to list a new name-value pair whose name is name and whose value is value.
  477. TRY(list.try_append(URL::QueryParam { .name = move(name), .value = move(normalized_value) }));
  478. }
  479. // 3. Return list.
  480. return list;
  481. }
  482. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#text/plain-encoding-algorithm
  483. static ErrorOr<String> plain_text_encode(Vector<URL::QueryParam> const& pairs)
  484. {
  485. // 1. Let result be the empty string.
  486. StringBuilder result;
  487. // 2. For each pair in pairs:
  488. for (auto const& pair : pairs) {
  489. // 1. Append pair's name to result.
  490. TRY(result.try_append(pair.name));
  491. // 2. Append a single U+003D EQUALS SIGN character (=) to result.
  492. TRY(result.try_append('='));
  493. // 3. Append pair's value to result.
  494. TRY(result.try_append(pair.value));
  495. // 4. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) character pair to result.
  496. TRY(result.try_append("\r\n"sv));
  497. }
  498. // 3. Return result.
  499. return result.to_string();
  500. }
  501. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mutate-action
  502. ErrorOr<void> HTMLFormElement::mutate_action_url(AK::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, String encoding, JS::NonnullGCPtr<Navigable> target_navigable, HistoryHandlingBehavior history_handling)
  503. {
  504. // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
  505. auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
  506. // 2. Let query be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
  507. auto query = TRY(url_encode(pairs, encoding));
  508. // 3. Set parsed action's query component to query.
  509. parsed_action.set_query(query);
  510. // 4. Plan to navigate to parsed action.
  511. plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling);
  512. return {};
  513. }
  514. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-body
  515. ErrorOr<void> HTMLFormElement::submit_as_entity_body(AK::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, EncodingTypeAttributeState encoding_type, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, HistoryHandlingBehavior history_handling)
  516. {
  517. // 1. Assert: method is POST.
  518. POSTResource::RequestContentType mime_type {};
  519. ByteBuffer body;
  520. // 2. Switch on enctype:
  521. switch (encoding_type) {
  522. case EncodingTypeAttributeState::FormUrlEncoded: {
  523. // -> application/x-www-form-urlencoded
  524. // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
  525. auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
  526. // 2. Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
  527. body = TRY(ByteBuffer::copy(TRY(url_encode(pairs, encoding)).bytes()));
  528. // 3. Set body to the result of encoding body.
  529. // NOTE: `encoding` refers to `UTF-8 encode`, which body already is encoded as because it uses AK::String.
  530. // 4. Let mimeType be `application/x-www-form-urlencoded`.
  531. mime_type = POSTResource::RequestContentType::ApplicationXWWWFormUrlencoded;
  532. break;
  533. }
  534. case EncodingTypeAttributeState::FormData: {
  535. // -> multipart/form-data
  536. // 1. Let body be the result of running the multipart/form-data encoding algorithm with entry list and encoding.
  537. auto body_and_mime_type = TRY(serialize_to_multipart_form_data(entry_list));
  538. body = move(body_and_mime_type.serialized_data);
  539. // 2. Let mimeType be the isomorphic encoding of the concatenation of "multipart/form-data; boundary=" and the multipart/form-data
  540. // boundary string generated by the multipart/form-data encoding algorithm.
  541. mime_type = POSTResource::RequestContentType::MultipartFormData;
  542. return {};
  543. }
  544. case EncodingTypeAttributeState::PlainText: {
  545. // -> text/plain
  546. // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
  547. auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
  548. // 2. Let body be the result of running the text/plain encoding algorithm with pairs.
  549. body = TRY(ByteBuffer::copy(TRY(plain_text_encode(pairs)).bytes()));
  550. // FIXME: 3. Set body to the result of encoding body using encoding.
  551. // 4. Let mimeType be `text/plain`.
  552. mime_type = POSTResource::RequestContentType::TextPlain;
  553. break;
  554. }
  555. default:
  556. VERIFY_NOT_REACHED();
  557. }
  558. // 3. Plan to navigate to parsed action given a POST resource whose request body is body and request content-type is mimeType.
  559. plan_to_navigate_to(parsed_action, POSTResource { .request_body = move(body), .request_content_type = mime_type }, target_navigable, history_handling);
  560. return {};
  561. }
  562. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-get-action
  563. void HTMLFormElement::get_action_url(AK::URL parsed_action, JS::NonnullGCPtr<Navigable> target_navigable, Web::HTML::HistoryHandlingBehavior history_handling)
  564. {
  565. // 1. Plan to navigate to parsed action.
  566. // Spec Note: entry list is discarded.
  567. plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling);
  568. }
  569. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#submit-mailto-headers
  570. ErrorOr<void> HTMLFormElement::mail_with_headers(AK::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, HistoryHandlingBehavior history_handling)
  571. {
  572. // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
  573. auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
  574. // 2. Let headers be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
  575. auto headers = TRY(url_encode(pairs, encoding));
  576. // 3. Replace occurrences of U+002B PLUS SIGN characters (+) in headers with the string "%20".
  577. TRY(headers.replace("+"sv, "%20"sv, ReplaceMode::All));
  578. // 4. Set parsed action's query to headers.
  579. parsed_action.set_query(headers);
  580. // 5. Plan to navigate to parsed action.
  581. plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling);
  582. return {};
  583. }
  584. ErrorOr<void> HTMLFormElement::mail_as_body(AK::URL parsed_action, Vector<XHR::FormDataEntry> entry_list, EncodingTypeAttributeState encoding_type, [[maybe_unused]] String encoding, JS::NonnullGCPtr<Navigable> target_navigable, HistoryHandlingBehavior history_handling)
  585. {
  586. // 1. Let pairs be the result of converting to a list of name-value pairs with entry list.
  587. auto pairs = TRY(convert_to_list_of_name_value_pairs(entry_list));
  588. String body;
  589. // 2. Switch on enctype:
  590. switch (encoding_type) {
  591. case EncodingTypeAttributeState::PlainText: {
  592. // -> text/plain
  593. // 1. Let body be the result of running the text/plain encoding algorithm with pairs.
  594. body = TRY(plain_text_encode(pairs));
  595. // 2. Set body to the result of running UTF-8 percent-encode on body using the default encode set. [URL]
  596. // NOTE: body is already UTF-8 encoded due to using AK::String, so we only have to do the percent encoding.
  597. // NOTE: "default encode set" links to "path percent-encode-set": https://url.spec.whatwg.org/#default-encode-set
  598. auto percent_encoded_body = AK::URL::percent_encode(body, AK::URL::PercentEncodeSet::Path);
  599. body = TRY(String::from_utf8(percent_encoded_body.view()));
  600. break;
  601. }
  602. default:
  603. // -> Otherwise
  604. // Let body be the result of running the application/x-www-form-urlencoded serializer with pairs and encoding.
  605. body = TRY(url_encode(pairs, encoding));
  606. break;
  607. }
  608. // 3. If parsed action's query is null, then set it to the empty string.
  609. if (!parsed_action.query().has_value())
  610. parsed_action.set_query(String {});
  611. StringBuilder query_builder;
  612. query_builder.append(*parsed_action.query());
  613. // 4. If parsed action's query is not the empty string, then append a single U+0026 AMPERSAND character (&) to it.
  614. if (!parsed_action.query()->is_empty())
  615. TRY(query_builder.try_append('&'));
  616. // 5. Append "body=" to parsed action's query.
  617. TRY(query_builder.try_append("body="sv));
  618. // 6. Append body to parsed action's query.
  619. TRY(query_builder.try_append(body));
  620. parsed_action.set_query(MUST(query_builder.to_string()));
  621. // 7. Plan to navigate to parsed action.
  622. plan_to_navigate_to(move(parsed_action), Empty {}, target_navigable, history_handling);
  623. return {};
  624. }
  625. // FIXME:
  626. static Bindings::NavigationHistoryBehavior to_navigation_history_behavior(HistoryHandlingBehavior b)
  627. {
  628. switch (b) {
  629. case HistoryHandlingBehavior::Push:
  630. return Bindings::NavigationHistoryBehavior::Push;
  631. case HistoryHandlingBehavior::Replace:
  632. return Bindings::NavigationHistoryBehavior::Replace;
  633. default:
  634. return Bindings::NavigationHistoryBehavior::Auto;
  635. }
  636. }
  637. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#plan-to-navigate
  638. void HTMLFormElement::plan_to_navigate_to(AK::URL url, Variant<Empty, String, POSTResource> post_resource, JS::NonnullGCPtr<Navigable> target_navigable, HistoryHandlingBehavior history_handling)
  639. {
  640. // 1. Let referrerPolicy be the empty string.
  641. ReferrerPolicy::ReferrerPolicy referrer_policy = ReferrerPolicy::ReferrerPolicy::EmptyString;
  642. // 2. If the form element's link types include the noreferrer keyword, then set referrerPolicy to "no-referrer".
  643. auto rel = deprecated_attribute(HTML::AttributeNames::rel).to_lowercase();
  644. auto link_types = rel.view().split_view_if(Infra::is_ascii_whitespace);
  645. if (link_types.contains_slow("noreferrer"sv))
  646. referrer_policy = ReferrerPolicy::ReferrerPolicy::NoReferrer;
  647. // 3. If the form has a non-null planned navigation, remove it from its task queue.
  648. if (m_planned_navigation) {
  649. HTML::main_thread_event_loop().task_queue().remove_tasks_matching([this](Task const& task) {
  650. return &task == m_planned_navigation;
  651. });
  652. }
  653. // 4. Queue an element task on the DOM manipulation task source given the form element and the following steps:
  654. // NOTE: `this`, `actual_resource` and `target_navigable` are protected by JS::SafeFunction.
  655. queue_an_element_task(Task::Source::DOMManipulation, [this, url, post_resource, target_navigable, history_handling, referrer_policy]() {
  656. // 1. Set the form's planned navigation to null.
  657. m_planned_navigation = nullptr;
  658. // 2. Navigate targetNavigable to url using the form element's node document, with historyHandling set to historyHandling,
  659. // referrerPolicy set to referrerPolicy, documentResource set to postResource, and cspNavigationType set to "form-submission".
  660. MUST(target_navigable->navigate({ .url = url,
  661. .source_document = this->document(),
  662. .document_resource = post_resource,
  663. .response = nullptr,
  664. .exceptions_enabled = false,
  665. .history_handling = to_navigation_history_behavior(history_handling),
  666. .referrer_policy = referrer_policy }));
  667. });
  668. // 5. Set the form's planned navigation to the just-queued task.
  669. m_planned_navigation = HTML::main_thread_event_loop().task_queue().last_added_task();
  670. VERIFY(m_planned_navigation);
  671. }
  672. }