HTMLInputElement.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Adam Hodgen <ant1441@gmail.com>
  4. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/Event.h>
  10. #include <LibWeb/DOM/ShadowRoot.h>
  11. #include <LibWeb/DOM/Text.h>
  12. #include <LibWeb/HTML/BrowsingContext.h>
  13. #include <LibWeb/HTML/EventNames.h>
  14. #include <LibWeb/HTML/HTMLFormElement.h>
  15. #include <LibWeb/HTML/HTMLInputElement.h>
  16. #include <LibWeb/HTML/Scripting/Environments.h>
  17. #include <LibWeb/Infra/CharacterTypes.h>
  18. #include <LibWeb/Layout/BlockContainer.h>
  19. #include <LibWeb/Layout/ButtonBox.h>
  20. #include <LibWeb/Layout/CheckBox.h>
  21. #include <LibWeb/Layout/RadioButton.h>
  22. #include <LibWeb/WebIDL/DOMException.h>
  23. #include <LibWeb/WebIDL/ExceptionOr.h>
  24. namespace Web::HTML {
  25. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  26. : HTMLElement(document, move(qualified_name))
  27. , m_value(DeprecatedString::empty())
  28. {
  29. activation_behavior = [this](auto&) {
  30. // The activation behavior for input elements are these steps:
  31. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  32. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  33. run_input_activation_behavior().release_value_but_fixme_should_propagate_errors();
  34. };
  35. }
  36. HTMLInputElement::~HTMLInputElement() = default;
  37. JS::ThrowCompletionOr<void> HTMLInputElement::initialize(JS::Realm& realm)
  38. {
  39. MUST_OR_THROW_OOM(Base::initialize(realm));
  40. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLInputElementPrototype>(realm, "HTMLInputElement"));
  41. return {};
  42. }
  43. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  44. {
  45. Base::visit_edges(visitor);
  46. visitor.visit(m_text_node.ptr());
  47. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group.ptr());
  48. visitor.visit(m_selected_files);
  49. }
  50. JS::GCPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  51. {
  52. if (type_state() == TypeAttributeState::Hidden)
  53. return nullptr;
  54. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton || type_state() == TypeAttributeState::FileUpload)
  55. return heap().allocate_without_realm<Layout::ButtonBox>(document(), *this, move(style));
  56. if (type_state() == TypeAttributeState::Checkbox)
  57. return heap().allocate_without_realm<Layout::CheckBox>(document(), *this, move(style));
  58. if (type_state() == TypeAttributeState::RadioButton)
  59. return heap().allocate_without_realm<Layout::RadioButton>(document(), *this, move(style));
  60. return heap().allocate_without_realm<Layout::BlockContainer>(document(), this, move(style));
  61. }
  62. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  63. {
  64. if (m_checked == checked)
  65. return;
  66. // The dirty checkedness flag must be initially set to false when the element is created,
  67. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  68. if (change_source == ChangeSource::User)
  69. m_dirty_checkedness = true;
  70. m_checked = checked;
  71. // This element's :checked pseudo-class could be used in a sibling's sibling-selector,
  72. // so we need to invalidate the style of all siblings.
  73. if (parent()) {
  74. parent()->for_each_child([&](auto& child) {
  75. child.invalidate_style();
  76. });
  77. }
  78. }
  79. void HTMLInputElement::set_checked_binding(bool checked)
  80. {
  81. if (type_state() == TypeAttributeState::RadioButton) {
  82. if (checked)
  83. set_checked_within_group();
  84. else
  85. set_checked(false, ChangeSource::Programmatic);
  86. } else {
  87. set_checked(checked, ChangeSource::Programmatic);
  88. }
  89. }
  90. // https://html.spec.whatwg.org/multipage/input.html#dom-input-indeterminate
  91. void HTMLInputElement::set_indeterminate(bool value)
  92. {
  93. // On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.
  94. m_indeterminate = value;
  95. }
  96. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  97. JS::GCPtr<FileAPI::FileList> HTMLInputElement::files()
  98. {
  99. // On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
  100. // The same object must be returned until the list of selected files changes.
  101. // If the IDL attribute does not apply, then it must instead return null.
  102. if (m_type != TypeAttributeState::FileUpload)
  103. return nullptr;
  104. if (!m_selected_files)
  105. m_selected_files = FileAPI::FileList::create(realm(), {}).release_value_but_fixme_should_propagate_errors();
  106. return m_selected_files;
  107. }
  108. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  109. void HTMLInputElement::set_files(JS::GCPtr<FileAPI::FileList> files)
  110. {
  111. // 1. If the IDL attribute does not apply or the given value is null, then return.
  112. if (m_type != TypeAttributeState::FileUpload || files == nullptr)
  113. return;
  114. // 2. Replace the element's selected files with the given value.
  115. m_selected_files = files;
  116. }
  117. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  118. void HTMLInputElement::update_the_file_selection(JS::NonnullGCPtr<FileAPI::FileList> files)
  119. {
  120. // 1. Queue an element task on the user interaction task source given element and the following steps:
  121. queue_an_element_task(Task::Source::UserInteraction, [this, files] {
  122. // 1. Update element's selected files so that it represents the user's selection.
  123. this->set_files(files.ptr());
  124. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  125. auto input_event = DOM::Event::create(this->realm(), EventNames::input, { .bubbles = true, .composed = true }).release_value_but_fixme_should_propagate_errors();
  126. this->dispatch_event(input_event);
  127. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  128. auto change_event = DOM::Event::create(this->realm(), EventNames::change, { .bubbles = true }).release_value_but_fixme_should_propagate_errors();
  129. this->dispatch_event(change_event);
  130. });
  131. }
  132. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  133. static void show_the_picker_if_applicable(HTMLInputElement& element)
  134. {
  135. // To show the picker, if applicable for an input element element:
  136. // 1. If element's relevant global object does not have transient activation, then return.
  137. auto& global_object = relevant_global_object(element);
  138. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation())
  139. return;
  140. // FIXME: 2. If element is not mutable, then return.
  141. // 3. If element's type attribute is in the File Upload state, then run these steps in parallel:
  142. if (element.type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
  143. // NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
  144. // 1. Optionally, wait until any prior execution of this algorithm has terminated.
  145. // 2. Display a prompt to the user requesting that the user specify some files.
  146. // If the multiple attribute is not set on element, there must be no more than one file selected; otherwise, any number may be selected.
  147. // Files can be from the filesystem or created on the fly, e.g., a picture taken from a camera connected to the user's device.
  148. // 3. Wait for the user to have made their selection.
  149. // 4. If the user dismissed the prompt without changing their selection,
  150. // then queue an element task on the user interaction task source given element to fire an event named cancel at element,
  151. // with the bubbles attribute initialized to true.
  152. // 5. Otherwise, update the file selection for element.
  153. bool const multiple = element.has_attribute(HTML::AttributeNames::multiple);
  154. auto weak_element = element.make_weak_ptr<DOM::EventTarget>();
  155. // FIXME: Pass along accept attribute information https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
  156. // The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.
  157. element.document().browsing_context()->top_level_browsing_context().page()->client().page_did_request_file_picker(weak_element, multiple);
  158. return;
  159. }
  160. // FIXME: show "any relevant user interface" for other type attribute states "in the way [the user agent] normally would"
  161. // 4. Otherwise, the user agent should show any relevant user interface for selecting a value for element,
  162. // in the way it normally would when the user interacts with the control. (If no such UI applies to element, then this step does nothing.)
  163. // If such a user interface is shown, it must respect the requirements stated in the relevant parts of the specification for how element
  164. // behaves given its type attribute state. (For example, various sections describe restrictions on the resulting value string.)
  165. // This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
  166. // (If this closes a file selection picker, then per the above that will lead to firing either input and change events, or a cancel event.)
  167. }
  168. // https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
  169. WebIDL::ExceptionOr<void> HTMLInputElement::show_picker()
  170. {
  171. // The showPicker() method steps are:
  172. // FIXME: 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
  173. // 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
  174. // and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
  175. // NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
  176. // and has never been guarded by an origin check.
  177. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(*this).top_level_origin)
  178. && m_type != TypeAttributeState::FileUpload && m_type != TypeAttributeState::Color) {
  179. return WebIDL::SecurityError::create(realm(), "Cross origin pickers are not allowed"sv);
  180. }
  181. // 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
  182. // FIXME: The global object we get here should probably not need casted to Window to check for transient activation
  183. auto& global_object = relevant_global_object(*this);
  184. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation()) {
  185. return WebIDL::NotAllowedError::create(realm(), "Too long since user activation to show picker"sv);
  186. }
  187. // 4. Show the picker, if applicable, for this.
  188. show_the_picker_if_applicable(*this);
  189. return {};
  190. }
  191. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  192. ErrorOr<void> HTMLInputElement::run_input_activation_behavior()
  193. {
  194. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  195. // 1. If the element is not connected, then return.
  196. if (!is_connected())
  197. return {};
  198. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  199. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input).release_value_but_fixme_should_propagate_errors();
  200. input_event->set_bubbles(true);
  201. input_event->set_composed(true);
  202. dispatch_event(input_event);
  203. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  204. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change).release_value_but_fixme_should_propagate_errors();
  205. change_event->set_bubbles(true);
  206. dispatch_event(*change_event);
  207. } else if (type_state() == TypeAttributeState::SubmitButton) {
  208. JS::GCPtr<HTMLFormElement> form;
  209. // 1. If the element does not have a form owner, then return.
  210. if (!(form = this->form()))
  211. return {};
  212. // 2. If the element's node document is not fully active, then return.
  213. if (!document().is_fully_active())
  214. return {};
  215. // 3. Submit the form owner from the element.
  216. TRY(form->submit_form(this));
  217. } else if (type_state() == TypeAttributeState::FileUpload) {
  218. show_the_picker_if_applicable(*this);
  219. } else {
  220. dispatch_event(DOM::Event::create(realm(), EventNames::change).release_value_but_fixme_should_propagate_errors());
  221. }
  222. return {};
  223. }
  224. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  225. {
  226. // An input element's dirty value flag must be set to true whenever the user interacts with the control in a way that changes the value.
  227. m_value = value_sanitization_algorithm(m_text_node->data());
  228. m_dirty_value = true;
  229. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  230. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  231. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  232. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input).release_value_but_fixme_should_propagate_errors();
  233. input_event->set_bubbles(true);
  234. input_event->set_composed(true);
  235. dispatch_event(*input_event);
  236. // FIXME: This should only fire when the input is "committed", whatever that means.
  237. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change).release_value_but_fixme_should_propagate_errors();
  238. change_event->set_bubbles(true);
  239. dispatch_event(change_event);
  240. });
  241. }
  242. DeprecatedString HTMLInputElement::value() const
  243. {
  244. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  245. if (type_state() == TypeAttributeState::FileUpload) {
  246. // NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
  247. // NOTE: Since path components are not permitted in filenames in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.
  248. if (m_selected_files && m_selected_files->item(0))
  249. return DeprecatedString::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name());
  250. return "C:\\fakepath\\"sv;
  251. }
  252. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  253. // Return the current value of the element.
  254. return m_value;
  255. }
  256. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(DeprecatedString value)
  257. {
  258. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  259. if (type_state() == TypeAttributeState::FileUpload) {
  260. // On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.
  261. if (value != DeprecatedString::empty())
  262. return WebIDL::InvalidStateError::create(realm(), "Setting value of input type file to non-empty string"sv);
  263. m_selected_files = nullptr;
  264. return {};
  265. }
  266. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  267. // 1. Let oldValue be the element's value.
  268. auto old_value = move(m_value);
  269. // 2. Set the element's value to the new value.
  270. // NOTE: This is done as part of step 4 below.
  271. // 3. Set the element's dirty value flag to true.
  272. m_dirty_value = true;
  273. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  274. m_value = value_sanitization_algorithm(move(value));
  275. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  276. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  277. // text control, unselecting any selected text and resetting the selection direction to "none".
  278. if (m_text_node && (m_value != old_value))
  279. m_text_node->set_data(m_value);
  280. return {};
  281. }
  282. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  283. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  284. {
  285. switch (state) {
  286. case HTML::HTMLInputElement::TypeAttributeState::Text:
  287. case HTML::HTMLInputElement::TypeAttributeState::Search:
  288. case HTML::HTMLInputElement::TypeAttributeState::URL:
  289. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  290. case HTML::HTMLInputElement::TypeAttributeState::Email:
  291. case HTML::HTMLInputElement::TypeAttributeState::Password:
  292. case HTML::HTMLInputElement::TypeAttributeState::Number:
  293. return true;
  294. default:
  295. return false;
  296. }
  297. }
  298. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  299. Optional<DeprecatedString> HTMLInputElement::placeholder_value() const
  300. {
  301. if (!m_text_node || !m_text_node->data().is_empty())
  302. return {};
  303. if (!is_allowed_to_have_placeholder(type_state()))
  304. return {};
  305. if (!has_attribute(HTML::AttributeNames::placeholder))
  306. return {};
  307. auto placeholder = attribute(HTML::AttributeNames::placeholder);
  308. if (placeholder.contains('\r') || placeholder.contains('\n')) {
  309. StringBuilder builder;
  310. for (auto ch : placeholder) {
  311. if (ch != '\r' && ch != '\n')
  312. builder.append(ch);
  313. }
  314. placeholder = builder.to_deprecated_string();
  315. }
  316. return placeholder;
  317. }
  318. void HTMLInputElement::create_shadow_tree_if_needed()
  319. {
  320. if (shadow_root_internal())
  321. return;
  322. // FIXME: This could be better factored. Everything except the below types becomes a text input.
  323. switch (type_state()) {
  324. case TypeAttributeState::RadioButton:
  325. case TypeAttributeState::Checkbox:
  326. case TypeAttributeState::Button:
  327. case TypeAttributeState::SubmitButton:
  328. case TypeAttributeState::ResetButton:
  329. case TypeAttributeState::ImageButton:
  330. return;
  331. default:
  332. break;
  333. }
  334. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed).release_allocated_value_but_fixme_should_propagate_errors();
  335. auto initial_value = m_value;
  336. if (initial_value.is_null())
  337. initial_value = DeprecatedString::empty();
  338. auto element = document().create_element(HTML::TagNames::div).release_value();
  339. MUST(element->set_attribute(HTML::AttributeNames::style, "white-space: pre; padding-top: 1px; padding-bottom: 1px; padding-left: 2px; padding-right: 2px; height: 1lh;"));
  340. m_text_node = heap().allocate<DOM::Text>(realm(), document(), initial_value).release_allocated_value_but_fixme_should_propagate_errors();
  341. m_text_node->set_always_editable(m_type != TypeAttributeState::FileUpload);
  342. m_text_node->set_owner_input_element({}, *this);
  343. if (m_type == TypeAttributeState::Password)
  344. m_text_node->set_is_password_input({}, true);
  345. MUST(element->append_child(*m_text_node));
  346. MUST(shadow_root->append_child(element));
  347. set_shadow_root(shadow_root);
  348. }
  349. void HTMLInputElement::did_receive_focus()
  350. {
  351. auto* browsing_context = document().browsing_context();
  352. if (!browsing_context)
  353. return;
  354. if (!m_text_node)
  355. return;
  356. browsing_context->set_cursor_position(DOM::Position { *m_text_node, 0 });
  357. }
  358. void HTMLInputElement::parse_attribute(DeprecatedFlyString const& name, DeprecatedString const& value)
  359. {
  360. HTMLElement::parse_attribute(name, value);
  361. if (name == HTML::AttributeNames::checked) {
  362. // When the checked content attribute is added, if the control does not have dirty checkedness,
  363. // the user agent must set the checkedness of the element to true
  364. if (!m_dirty_checkedness)
  365. set_checked(true, ChangeSource::Programmatic);
  366. } else if (name == HTML::AttributeNames::type) {
  367. m_type = parse_type_attribute(value);
  368. } else if (name == HTML::AttributeNames::value) {
  369. if (!m_dirty_value)
  370. m_value = value_sanitization_algorithm(value);
  371. }
  372. }
  373. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  374. {
  375. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  376. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  377. return HTMLInputElement::TypeAttributeState::state;
  378. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  379. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  380. // The missing value default and the invalid value default are the Text state.
  381. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  382. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  383. return HTMLInputElement::TypeAttributeState::Text;
  384. }
  385. void HTMLInputElement::did_remove_attribute(DeprecatedFlyString const& name)
  386. {
  387. HTMLElement::did_remove_attribute(name);
  388. if (name == HTML::AttributeNames::checked) {
  389. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  390. // the user agent must set the checkedness of the element to false.
  391. if (!m_dirty_checkedness)
  392. set_checked(false, ChangeSource::Programmatic);
  393. } else if (name == HTML::AttributeNames::value) {
  394. if (!m_dirty_value)
  395. m_value = DeprecatedString::empty();
  396. }
  397. }
  398. DeprecatedString HTMLInputElement::type() const
  399. {
  400. switch (m_type) {
  401. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  402. case TypeAttributeState::state: \
  403. return #keyword##sv;
  404. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  405. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  406. }
  407. VERIFY_NOT_REACHED();
  408. }
  409. void HTMLInputElement::set_type(DeprecatedString const& type)
  410. {
  411. MUST(set_attribute(HTML::AttributeNames::type, type));
  412. }
  413. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  414. static bool is_valid_simple_color(DeprecatedString const& value)
  415. {
  416. // if it is exactly seven characters long,
  417. if (value.length() != 7)
  418. return false;
  419. // and the first character is a U+0023 NUMBER SIGN character (#),
  420. if (!value.starts_with('#'))
  421. return false;
  422. // and the remaining six characters are all ASCII hex digits
  423. for (size_t i = 1; i < value.length(); i++)
  424. if (!is_ascii_hex_digit(value[i]))
  425. return false;
  426. return true;
  427. }
  428. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  429. static bool is_valid_time_string(DeprecatedString const& value)
  430. {
  431. // A string is a valid time string representing an hour hour, a minute minute, and a second second if it consists of the following components in the given order:
  432. // 1. Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23
  433. // 2. A U+003A COLON character (:)
  434. // 3. Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59
  435. // 4. If second is nonzero, or optionally if second is zero:
  436. // 1. A U+003A COLON character (:)
  437. // 2. Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59
  438. // 3. If second is not an integer, or optionally if second is an integer:
  439. // 1. A U+002E FULL STOP character (.)
  440. // 2. One, two, or three ASCII digits, representing the fractional part of second
  441. auto parts = value.split(':');
  442. if (parts.size() != 2 || parts.size() != 3)
  443. return false;
  444. if (parts[0].length() != 2)
  445. return false;
  446. auto hour = (parse_ascii_digit(parts[0][0]) * 10) + parse_ascii_digit(parts[0][1]);
  447. if (hour > 23)
  448. return false;
  449. if (parts[1].length() != 2)
  450. return false;
  451. auto minute = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  452. if (minute > 59)
  453. return false;
  454. if (parts.size() == 2)
  455. return true;
  456. if (parts[2].length() < 2)
  457. return false;
  458. auto second = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  459. if (second > 59)
  460. return false;
  461. if (parts[2].length() == 2)
  462. return true;
  463. auto second_parts = parts[2].split('.');
  464. if (second_parts.size() != 2)
  465. return false;
  466. if (second_parts[1].length() < 1 || second_parts[1].length() > 3)
  467. return false;
  468. for (auto digit : second_parts[1])
  469. if (!is_ascii_digit(digit))
  470. return false;
  471. return true;
  472. }
  473. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#week-number-of-the-last-day
  474. static u32 week_number_of_the_last_day(u64)
  475. {
  476. // FIXME: sometimes return 53 (!)
  477. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#weeks
  478. return 52;
  479. }
  480. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-week-string
  481. static bool is_valid_week_string(DeprecatedString const& value)
  482. {
  483. // A string is a valid week string representing a week-year year and week week if it consists of the following components in the given order:
  484. // 1. Four or more ASCII digits, representing year, where year > 0
  485. // 2. A U+002D HYPHEN-MINUS character (-)
  486. // 3. A U+0057 LATIN CAPITAL LETTER W character (W)
  487. // 4. Two ASCII digits, representing the week week, in the range 1 ≤ week ≤ maxweek, where maxweek is the week number of the last day of week-year year
  488. auto parts = value.split('-');
  489. if (parts.size() != 2)
  490. return false;
  491. if (parts[0].length() < 4)
  492. return false;
  493. for (auto digit : parts[0])
  494. if (!is_ascii_digit(digit))
  495. return false;
  496. if (parts[1].length() != 3)
  497. return false;
  498. if (!parts[1].starts_with('W'))
  499. return false;
  500. if (!is_ascii_digit(parts[1][1]))
  501. return false;
  502. if (!is_ascii_digit(parts[1][2]))
  503. return false;
  504. u64 year = 0;
  505. for (auto d : parts[0]) {
  506. year *= 10;
  507. year += parse_ascii_digit(d);
  508. }
  509. auto week = (parse_ascii_digit(parts[1][1]) * 10) + parse_ascii_digit(parts[1][2]);
  510. return week >= 1 && week <= week_number_of_the_last_day(year);
  511. }
  512. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string
  513. static bool is_valid_month_string(DeprecatedString const& value)
  514. {
  515. // A string is a valid month string representing a year year and month month if it consists of the following components in the given order:
  516. // 1. Four or more ASCII digits, representing year, where year > 0
  517. // 2. A U+002D HYPHEN-MINUS character (-)
  518. // 3. Two ASCII digits, representing the month month, in the range 1 ≤ month ≤ 12
  519. auto parts = value.split('-');
  520. if (parts.size() != 2)
  521. return false;
  522. if (parts[0].length() < 4)
  523. return false;
  524. for (auto digit : parts[0])
  525. if (!is_ascii_digit(digit))
  526. return false;
  527. if (parts[1].length() != 2)
  528. return false;
  529. if (!is_ascii_digit(parts[1][0]))
  530. return false;
  531. if (!is_ascii_digit(parts[1][1]))
  532. return false;
  533. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  534. return month >= 1 && month <= 12;
  535. }
  536. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  537. static bool is_valid_date_string(DeprecatedString const& value)
  538. {
  539. // A string is a valid date string representing a year year, month month, and day day if it consists of the following components in the given order:
  540. // 1. A valid month string, representing year and month
  541. // 2. A U+002D HYPHEN-MINUS character (-)
  542. // 3. Two ASCII digits, representing day, in the range 1 ≤ day ≤ maxday where maxday is the number of days in the month month and year year
  543. auto parts = value.split('-');
  544. if (parts.size() != 3)
  545. return false;
  546. if (!is_valid_month_string(DeprecatedString::formatted("{}-{}", parts[0], parts[1])))
  547. return false;
  548. if (parts[2].length() != 2)
  549. return false;
  550. i64 year = 0;
  551. for (auto d : parts[0]) {
  552. year *= 10;
  553. year += parse_ascii_digit(d);
  554. }
  555. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  556. i64 day = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  557. return day >= 1 && day <= AK::days_in_month(year, month);
  558. }
  559. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-local-date-and-time-string
  560. static bool is_valid_local_date_and_time_string(DeprecatedString const& value)
  561. {
  562. auto parts_split_by_T = value.split('T');
  563. if (parts_split_by_T.size() == 2)
  564. return is_valid_date_string(parts_split_by_T[0]) && is_valid_time_string(parts_split_by_T[1]);
  565. auto parts_split_by_space = value.split(' ');
  566. if (parts_split_by_space.size() == 2)
  567. return is_valid_date_string(parts_split_by_space[0]) && is_valid_time_string(parts_split_by_space[1]);
  568. return false;
  569. }
  570. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-normalised-local-date-and-time-string
  571. static DeprecatedString normalize_local_date_and_time_string(DeprecatedString const& value)
  572. {
  573. VERIFY(value.count(" "sv) == 1);
  574. return value.replace(" "sv, "T"sv, ReplaceMode::FirstOnly);
  575. }
  576. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  577. DeprecatedString HTMLInputElement::value_sanitization_algorithm(DeprecatedString value) const
  578. {
  579. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  580. // Strip newlines from the value.
  581. if (value.contains('\r') || value.contains('\n')) {
  582. StringBuilder builder;
  583. for (auto c : value) {
  584. if (!(c == '\r' || c == '\n'))
  585. builder.append(c);
  586. }
  587. return builder.to_deprecated_string();
  588. }
  589. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  590. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  591. if (value.contains('\r') || value.contains('\n')) {
  592. StringBuilder builder;
  593. for (auto c : value) {
  594. if (!(c == '\r' || c == '\n'))
  595. builder.append(c);
  596. }
  597. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  598. }
  599. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  600. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  601. // FIXME: handle the `multiple` attribute
  602. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  603. if (value.contains('\r') || value.contains('\n')) {
  604. StringBuilder builder;
  605. for (auto c : value) {
  606. if (!(c == '\r' || c == '\n'))
  607. builder.append(c);
  608. }
  609. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  610. }
  611. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  612. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  613. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values
  614. // 6. Skip ASCII whitespace within input given position.
  615. auto maybe_double = value.to_double(TrimWhitespace::Yes);
  616. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  617. return "";
  618. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  619. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  620. if (!is_valid_date_string(value))
  621. return "";
  622. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  623. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  624. if (!is_valid_month_string(value))
  625. return "";
  626. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  627. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  628. if (!is_valid_week_string(value))
  629. return "";
  630. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  631. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  632. if (!is_valid_time_string(value))
  633. return "";
  634. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  635. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  636. if (is_valid_local_date_and_time_string(value))
  637. return normalize_local_date_and_time_string(value);
  638. return "";
  639. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  640. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  641. auto maybe_double = value.to_double(TrimWhitespace::Yes);
  642. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  643. return JS::number_to_deprecated_string(maybe_double.value_or(0));
  644. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  645. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  646. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  647. if (is_valid_simple_color(value))
  648. return value.to_lowercase();
  649. // otherwise, set it to the string "#000000".
  650. return "#000000";
  651. }
  652. return value;
  653. }
  654. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  655. void HTMLInputElement::reset_algorithm()
  656. {
  657. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  658. m_dirty_value = false;
  659. m_dirty_checkedness = false;
  660. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  661. m_value = has_attribute(AttributeNames::value) ? get_attribute(AttributeNames::value) : DeprecatedString::empty();
  662. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  663. m_checked = has_attribute(AttributeNames::checked);
  664. // empty the list of selected files,
  665. m_selected_files = FileAPI::FileList::create(realm(), {}).release_value_but_fixme_should_propagate_errors();
  666. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  667. m_value = value_sanitization_algorithm(m_value);
  668. if (m_text_node)
  669. m_text_node->set_data(m_value);
  670. }
  671. void HTMLInputElement::form_associated_element_was_inserted()
  672. {
  673. create_shadow_tree_if_needed();
  674. }
  675. void HTMLInputElement::set_checked_within_group()
  676. {
  677. if (checked())
  678. return;
  679. set_checked(true, ChangeSource::User);
  680. DeprecatedString name = this->name();
  681. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  682. if (element.checked() && &element != this && element.name() == name)
  683. element.set_checked(false, ChangeSource::User);
  684. return IterationDecision::Continue;
  685. });
  686. }
  687. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  688. void HTMLInputElement::legacy_pre_activation_behavior()
  689. {
  690. m_before_legacy_pre_activation_behavior_checked = checked();
  691. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  692. // 1. If this element's type attribute is in the Checkbox state, then set
  693. // this element's checkedness to its opposite value (i.e. true if it is
  694. // false, false if it is true) and set this element's indeterminate IDL
  695. // attribute to false.
  696. if (type_state() == TypeAttributeState::Checkbox) {
  697. set_checked(!checked(), ChangeSource::User);
  698. set_indeterminate(false);
  699. }
  700. // 2. If this element's type attribute is in the Radio Button state, then
  701. // get a reference to the element in this element's radio button group that
  702. // has its checkedness set to true, if any, and then set this element's
  703. // checkedness to true.
  704. if (type_state() == TypeAttributeState::RadioButton) {
  705. DeprecatedString name = this->name();
  706. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  707. if (element.checked() && element.name() == name) {
  708. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  709. return IterationDecision::Break;
  710. }
  711. return IterationDecision::Continue;
  712. });
  713. set_checked_within_group();
  714. }
  715. }
  716. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  717. void HTMLInputElement::legacy_cancelled_activation_behavior()
  718. {
  719. // 1. If the element's type attribute is in the Checkbox state, then set the
  720. // element's checkedness and the element's indeterminate IDL attribute back
  721. // to the values they had before the legacy-pre-activation behavior was run.
  722. if (type_state() == TypeAttributeState::Checkbox) {
  723. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  724. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  725. }
  726. // 2. If this element 's type attribute is in the Radio Button state, then
  727. // if the element to which a reference was obtained in the
  728. // legacy-pre-activation behavior, if any, is still in what is now this
  729. // element' s radio button group, if it still has one, and if so, setting
  730. // that element 's checkedness to true; or else, if there was no such
  731. // element, or that element is no longer in this element' s radio button
  732. // group, or if this element no longer has a radio button group, setting
  733. // this element's checkedness to false.
  734. if (type_state() == TypeAttributeState::RadioButton) {
  735. DeprecatedString name = this->name();
  736. bool did_reselect_previous_element = false;
  737. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  738. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  739. if (name == element_in_group.name()) {
  740. element_in_group.set_checked_within_group();
  741. did_reselect_previous_element = true;
  742. }
  743. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  744. }
  745. if (!did_reselect_previous_element)
  746. set_checked(false, ChangeSource::User);
  747. }
  748. }
  749. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  750. {
  751. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  752. }
  753. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  754. i32 HTMLInputElement::default_tab_index_value() const
  755. {
  756. // See the base function for the spec comments.
  757. return 0;
  758. }
  759. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  760. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  761. {
  762. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  763. return true;
  764. }
  765. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  766. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  767. {
  768. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  769. return true;
  770. }
  771. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  772. void HTMLInputElement::set_custom_validity(DeprecatedString const& error)
  773. {
  774. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  775. return;
  776. }
  777. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  778. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  779. {
  780. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  781. return {};
  782. }
  783. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  784. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, DeprecatedString const& direction)
  785. {
  786. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  787. return {};
  788. }
  789. Optional<ARIA::Role> HTMLInputElement::default_role() const
  790. {
  791. // https://www.w3.org/TR/html-aria/#el-input-button
  792. if (type_state() == TypeAttributeState::Button)
  793. return ARIA::Role::button;
  794. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  795. if (type_state() == TypeAttributeState::Checkbox)
  796. return ARIA::Role::checkbox;
  797. // https://www.w3.org/TR/html-aria/#el-input-email
  798. if (type_state() == TypeAttributeState::Email && attribute("list").is_null())
  799. return ARIA::Role::textbox;
  800. // https://www.w3.org/TR/html-aria/#el-input-image
  801. if (type_state() == TypeAttributeState::ImageButton)
  802. return ARIA::Role::button;
  803. // https://www.w3.org/TR/html-aria/#el-input-number
  804. if (type_state() == TypeAttributeState::Number)
  805. return ARIA::Role::spinbutton;
  806. // https://www.w3.org/TR/html-aria/#el-input-radio
  807. if (type_state() == TypeAttributeState::RadioButton)
  808. return ARIA::Role::radio;
  809. // https://www.w3.org/TR/html-aria/#el-input-range
  810. if (type_state() == TypeAttributeState::Range)
  811. return ARIA::Role::slider;
  812. // https://www.w3.org/TR/html-aria/#el-input-reset
  813. if (type_state() == TypeAttributeState::ResetButton)
  814. return ARIA::Role::button;
  815. // https://www.w3.org/TR/html-aria/#el-input-text-list
  816. if ((type_state() == TypeAttributeState::Text
  817. || type_state() == TypeAttributeState::Search
  818. || type_state() == TypeAttributeState::Telephone
  819. || type_state() == TypeAttributeState::URL
  820. || type_state() == TypeAttributeState::Email)
  821. && !attribute("list").is_null())
  822. return ARIA::Role::combobox;
  823. // https://www.w3.org/TR/html-aria/#el-input-search
  824. if (type_state() == TypeAttributeState::Search && attribute("list").is_null())
  825. return ARIA::Role::textbox;
  826. // https://www.w3.org/TR/html-aria/#el-input-submit
  827. if (type_state() == TypeAttributeState::SubmitButton)
  828. return ARIA::Role::button;
  829. // https://www.w3.org/TR/html-aria/#el-input-tel
  830. if (type_state() == TypeAttributeState::Telephone)
  831. return ARIA::Role::textbox;
  832. // https://www.w3.org/TR/html-aria/#el-input-text
  833. if (type_state() == TypeAttributeState::Text && attribute("list").is_null())
  834. return ARIA::Role::textbox;
  835. // https://www.w3.org/TR/html-aria/#el-input-url
  836. if (type_state() == TypeAttributeState::URL && attribute("list").is_null())
  837. return ARIA::Role::textbox;
  838. // https://www.w3.org/TR/html-aria/#el-input-color
  839. // https://www.w3.org/TR/html-aria/#el-input-date
  840. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  841. // https://www.w3.org/TR/html-aria/#el-input-file
  842. // https://www.w3.org/TR/html-aria/#el-input-hidden
  843. // https://www.w3.org/TR/html-aria/#el-input-month
  844. // https://www.w3.org/TR/html-aria/#el-input-password
  845. // https://www.w3.org/TR/html-aria/#el-input-time
  846. // https://www.w3.org/TR/html-aria/#el-input-week
  847. return {};
  848. }
  849. }