HTMLFormElement.cpp 38 KB

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