HTMLFormElement.cpp 38 KB

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