HTMLInputElement.cpp 42 KB

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