HTMLFormElement.cpp 37 KB

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