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