HTMLFormElement.cpp 37 KB

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