HTMLInputElement.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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. set_prototype(&Bindings::cached_web_prototype(realm(), "HTMLInputElement"));
  30. activation_behavior = [this](auto&) {
  31. // The activation behavior for input elements are these steps:
  32. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  33. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  34. run_input_activation_behavior();
  35. };
  36. }
  37. HTMLInputElement::~HTMLInputElement() = default;
  38. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  39. {
  40. Base::visit_edges(visitor);
  41. visitor.visit(m_text_node.ptr());
  42. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group.ptr());
  43. visitor.visit(m_selected_files);
  44. }
  45. JS::GCPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  46. {
  47. if (type_state() == TypeAttributeState::Hidden)
  48. return nullptr;
  49. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton || type_state() == TypeAttributeState::FileUpload)
  50. return heap().allocate_without_realm<Layout::ButtonBox>(document(), *this, move(style));
  51. if (type_state() == TypeAttributeState::Checkbox)
  52. return heap().allocate_without_realm<Layout::CheckBox>(document(), *this, move(style));
  53. if (type_state() == TypeAttributeState::RadioButton)
  54. return heap().allocate_without_realm<Layout::RadioButton>(document(), *this, move(style));
  55. return heap().allocate_without_realm<Layout::BlockContainer>(document(), this, move(style));
  56. }
  57. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  58. {
  59. if (m_checked == checked)
  60. return;
  61. // The dirty checkedness flag must be initially set to false when the element is created,
  62. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  63. if (change_source == ChangeSource::User)
  64. m_dirty_checkedness = true;
  65. m_checked = checked;
  66. set_needs_style_update(true);
  67. }
  68. void HTMLInputElement::set_checked_binding(bool checked)
  69. {
  70. if (type_state() == TypeAttributeState::RadioButton) {
  71. if (checked)
  72. set_checked_within_group();
  73. else
  74. set_checked(false, ChangeSource::Programmatic);
  75. } else {
  76. set_checked(checked, ChangeSource::Programmatic);
  77. }
  78. }
  79. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  80. JS::GCPtr<FileAPI::FileList> HTMLInputElement::files()
  81. {
  82. // On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
  83. // The same object must be returned until the list of selected files changes.
  84. // If the IDL attribute does not apply, then it must instead return null.
  85. if (m_type != TypeAttributeState::FileUpload)
  86. return nullptr;
  87. if (!m_selected_files)
  88. m_selected_files = FileAPI::FileList::create(realm(), {});
  89. return m_selected_files;
  90. }
  91. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  92. void HTMLInputElement::set_files(JS::GCPtr<FileAPI::FileList> files)
  93. {
  94. // 1. If the IDL attribute does not apply or the given value is null, then return.
  95. if (m_type != TypeAttributeState::FileUpload || files == nullptr)
  96. return;
  97. // 2. Replace the element's selected files with the given value.
  98. m_selected_files = files;
  99. }
  100. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  101. void HTMLInputElement::update_the_file_selection(JS::NonnullGCPtr<FileAPI::FileList> files)
  102. {
  103. // 1. Queue an element task on the user interaction task source given element and the following steps:
  104. queue_an_element_task(Task::Source::UserInteraction, [this, files] {
  105. // 1. Update element's selected files so that it represents the user's selection.
  106. this->set_files(files.ptr());
  107. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  108. auto input_event = DOM::Event::create(this->realm(), EventNames::input, { .bubbles = true, .composed = true });
  109. this->dispatch_event(*input_event);
  110. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  111. auto change_event = DOM::Event::create(this->realm(), EventNames::change, { .bubbles = true });
  112. this->dispatch_event(*change_event);
  113. });
  114. }
  115. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  116. static void show_the_picker_if_applicable(HTMLInputElement& element)
  117. {
  118. // To show the picker, if applicable for an input element element:
  119. // 1. If element's relevant global object does not have transient activation, then return.
  120. auto& global_object = relevant_global_object(element);
  121. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation())
  122. return;
  123. // FIXME: 2. If element is not mutable, then return.
  124. // 3. If element's type attribute is in the File Upload state, then run these steps in parallel:
  125. if (element.type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
  126. // NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
  127. // 1. Optionally, wait until any prior execution of this algorithm has terminated.
  128. // 2. Display a prompt to the user requesting that the user specify some files.
  129. // If the multiple attribute is not set on element, there must be no more than one file selected; otherwise, any number may be selected.
  130. // 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.
  131. // 3. Wait for the user to have made their selection.
  132. // 4. If the user dismissed the prompt without changing their selection,
  133. // then queue an element task on the user interaction task source given element to fire an event named cancel at element,
  134. // with the bubbles attribute initialized to true.
  135. // 5. Otherwise, update the file selection for element.
  136. bool const multiple = element.has_attribute(HTML::AttributeNames::multiple);
  137. auto weak_element = element.make_weak_ptr<DOM::EventTarget>();
  138. // FIXME: Pass along accept attribute information https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
  139. // The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.
  140. element.document().browsing_context()->top_level_browsing_context().page()->client().page_did_request_file_picker(weak_element, multiple);
  141. return;
  142. }
  143. // FIXME: show "any relevant user interface" for other type attribute states "in the way [the user agent] normally would"
  144. // 4. Otherwise, the user agent should show any relevant user interface for selecting a value for element,
  145. // 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.)
  146. // If such a user interface is shown, it must respect the requirements stated in the relevant parts of the specification for how element
  147. // behaves given its type attribute state. (For example, various sections describe restrictions on the resulting value string.)
  148. // This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
  149. // (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.)
  150. }
  151. // https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
  152. WebIDL::ExceptionOr<void> HTMLInputElement::show_picker()
  153. {
  154. // The showPicker() method steps are:
  155. // FIXME: 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
  156. // 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
  157. // and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
  158. // NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
  159. // and has never been guarded by an origin check.
  160. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(*this).top_level_origin)
  161. && m_type != TypeAttributeState::FileUpload && m_type != TypeAttributeState::Color) {
  162. return WebIDL::SecurityError::create(realm(), "Cross origin pickers are not allowed"sv);
  163. }
  164. // 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
  165. // FIXME: The global object we get here should probably not need casted to Window to check for transient activation
  166. auto& global_object = relevant_global_object(*this);
  167. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation()) {
  168. return WebIDL::NotAllowedError::create(realm(), "Too long since user activation to show picker"sv);
  169. }
  170. // 4. Show the picker, if applicable, for this.
  171. show_the_picker_if_applicable(*this);
  172. return {};
  173. }
  174. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  175. void HTMLInputElement::run_input_activation_behavior()
  176. {
  177. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  178. // 1. If the element is not connected, then return.
  179. if (!is_connected())
  180. return;
  181. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  182. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  183. input_event->set_bubbles(true);
  184. input_event->set_composed(true);
  185. dispatch_event(*input_event);
  186. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  187. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  188. change_event->set_bubbles(true);
  189. dispatch_event(*change_event);
  190. } else if (type_state() == TypeAttributeState::SubmitButton) {
  191. JS::GCPtr<HTMLFormElement> form;
  192. // 1. If the element does not have a form owner, then return.
  193. if (!(form = this->form()))
  194. return;
  195. // 2. If the element's node document is not fully active, then return.
  196. if (!document().is_fully_active())
  197. return;
  198. // 3. Submit the form owner from the element.
  199. form->submit_form(this);
  200. } else if (type_state() == TypeAttributeState::FileUpload) {
  201. show_the_picker_if_applicable(*this);
  202. } else {
  203. dispatch_event(*DOM::Event::create(realm(), EventNames::change));
  204. }
  205. }
  206. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  207. {
  208. // 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.
  209. m_value = value_sanitization_algorithm(m_text_node->data());
  210. m_dirty_value = true;
  211. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  212. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  213. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  214. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  215. input_event->set_bubbles(true);
  216. input_event->set_composed(true);
  217. dispatch_event(*input_event);
  218. // FIXME: This should only fire when the input is "committed", whatever that means.
  219. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  220. change_event->set_bubbles(true);
  221. dispatch_event(*change_event);
  222. });
  223. }
  224. DeprecatedString HTMLInputElement::value() const
  225. {
  226. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  227. if (type_state() == TypeAttributeState::FileUpload) {
  228. // NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
  229. // NOTE: Since path components are not permitted in filenames in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.
  230. if (m_selected_files && m_selected_files->item(0))
  231. return DeprecatedString::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name());
  232. return "C:\\fakepath\\"sv;
  233. }
  234. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  235. // Return the current value of the element.
  236. return m_value;
  237. }
  238. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(DeprecatedString value)
  239. {
  240. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  241. if (type_state() == TypeAttributeState::FileUpload) {
  242. // On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.
  243. if (value != DeprecatedString::empty())
  244. return WebIDL::InvalidStateError::create(realm(), "Setting value of input type file to non-empty string"sv);
  245. m_selected_files = nullptr;
  246. return {};
  247. }
  248. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  249. // 1. Let oldValue be the element's value.
  250. auto old_value = move(m_value);
  251. // 2. Set the element's value to the new value.
  252. // NOTE: This is done as part of step 4 below.
  253. // 3. Set the element's dirty value flag to true.
  254. m_dirty_value = true;
  255. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  256. m_value = value_sanitization_algorithm(move(value));
  257. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  258. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  259. // text control, unselecting any selected text and resetting the selection direction to "none".
  260. if (m_text_node && (m_value != old_value))
  261. m_text_node->set_data(m_value);
  262. return {};
  263. }
  264. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  265. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  266. {
  267. switch (state) {
  268. case HTML::HTMLInputElement::TypeAttributeState::Text:
  269. case HTML::HTMLInputElement::TypeAttributeState::Search:
  270. case HTML::HTMLInputElement::TypeAttributeState::URL:
  271. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  272. case HTML::HTMLInputElement::TypeAttributeState::Email:
  273. case HTML::HTMLInputElement::TypeAttributeState::Password:
  274. case HTML::HTMLInputElement::TypeAttributeState::Number:
  275. return true;
  276. default:
  277. return false;
  278. }
  279. }
  280. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  281. Optional<DeprecatedString> HTMLInputElement::placeholder_value() const
  282. {
  283. if (!m_text_node || !m_text_node->data().is_empty())
  284. return {};
  285. if (!is_allowed_to_have_placeholder(type_state()))
  286. return {};
  287. if (!has_attribute(HTML::AttributeNames::placeholder))
  288. return {};
  289. auto placeholder = attribute(HTML::AttributeNames::placeholder);
  290. if (placeholder.contains('\r') || placeholder.contains('\n')) {
  291. StringBuilder builder;
  292. for (auto ch : placeholder) {
  293. if (ch != '\r' && ch != '\n')
  294. builder.append(ch);
  295. }
  296. placeholder = builder.to_deprecated_string();
  297. }
  298. return placeholder;
  299. }
  300. void HTMLInputElement::create_shadow_tree_if_needed()
  301. {
  302. if (shadow_root())
  303. return;
  304. // FIXME: This could be better factored. Everything except the below types becomes a text input.
  305. switch (type_state()) {
  306. case TypeAttributeState::RadioButton:
  307. case TypeAttributeState::Checkbox:
  308. case TypeAttributeState::Button:
  309. case TypeAttributeState::SubmitButton:
  310. case TypeAttributeState::ResetButton:
  311. case TypeAttributeState::ImageButton:
  312. return;
  313. default:
  314. break;
  315. }
  316. auto* shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this);
  317. auto initial_value = m_value;
  318. if (initial_value.is_null())
  319. initial_value = DeprecatedString::empty();
  320. auto element = document().create_element(HTML::TagNames::div).release_value();
  321. MUST(element->set_attribute(HTML::AttributeNames::style, "white-space: pre; padding-top: 1px; padding-bottom: 1px; padding-left: 2px; padding-right: 2px"));
  322. m_text_node = heap().allocate<DOM::Text>(realm(), document(), initial_value);
  323. m_text_node->set_always_editable(m_type != TypeAttributeState::FileUpload);
  324. m_text_node->set_owner_input_element({}, *this);
  325. if (m_type == TypeAttributeState::Password)
  326. m_text_node->set_is_password_input({}, true);
  327. MUST(element->append_child(*m_text_node));
  328. MUST(shadow_root->append_child(move(element)));
  329. set_shadow_root(move(shadow_root));
  330. }
  331. void HTMLInputElement::did_receive_focus()
  332. {
  333. auto* browsing_context = document().browsing_context();
  334. if (!browsing_context)
  335. return;
  336. if (!m_text_node)
  337. return;
  338. browsing_context->set_cursor_position(DOM::Position { *m_text_node, 0 });
  339. }
  340. void HTMLInputElement::parse_attribute(FlyString const& name, DeprecatedString const& value)
  341. {
  342. HTMLElement::parse_attribute(name, value);
  343. if (name == HTML::AttributeNames::checked) {
  344. // When the checked content attribute is added, if the control does not have dirty checkedness,
  345. // the user agent must set the checkedness of the element to true
  346. if (!m_dirty_checkedness)
  347. set_checked(true, ChangeSource::Programmatic);
  348. } else if (name == HTML::AttributeNames::type) {
  349. m_type = parse_type_attribute(value);
  350. } else if (name == HTML::AttributeNames::value) {
  351. if (!m_dirty_value)
  352. m_value = value_sanitization_algorithm(value);
  353. }
  354. }
  355. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  356. {
  357. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  358. if (type.equals_ignoring_case(#keyword##sv)) \
  359. return HTMLInputElement::TypeAttributeState::state;
  360. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  361. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  362. // The missing value default and the invalid value default are the Text state.
  363. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  364. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  365. return HTMLInputElement::TypeAttributeState::Text;
  366. }
  367. void HTMLInputElement::did_remove_attribute(FlyString const& name)
  368. {
  369. HTMLElement::did_remove_attribute(name);
  370. if (name == HTML::AttributeNames::checked) {
  371. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  372. // the user agent must set the checkedness of the element to false.
  373. if (!m_dirty_checkedness)
  374. set_checked(false, ChangeSource::Programmatic);
  375. } else if (name == HTML::AttributeNames::value) {
  376. if (!m_dirty_value)
  377. m_value = DeprecatedString::empty();
  378. }
  379. }
  380. DeprecatedString HTMLInputElement::type() const
  381. {
  382. switch (m_type) {
  383. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  384. case TypeAttributeState::state: \
  385. return #keyword##sv;
  386. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  387. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  388. }
  389. VERIFY_NOT_REACHED();
  390. }
  391. void HTMLInputElement::set_type(DeprecatedString const& type)
  392. {
  393. MUST(set_attribute(HTML::AttributeNames::type, type));
  394. }
  395. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  396. static bool is_valid_simple_color(DeprecatedString const& value)
  397. {
  398. // if it is exactly seven characters long,
  399. if (value.length() != 7)
  400. return false;
  401. // and the first character is a U+0023 NUMBER SIGN character (#),
  402. if (!value.starts_with('#'))
  403. return false;
  404. // and the remaining six characters are all ASCII hex digits
  405. for (size_t i = 1; i < value.length(); i++)
  406. if (!is_ascii_hex_digit(value[i]))
  407. return false;
  408. return true;
  409. }
  410. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string
  411. static bool is_valid_month_string(DeprecatedString const& value)
  412. {
  413. // 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:
  414. // 1. Four or more ASCII digits, representing year, where year > 0
  415. // 2. A U+002D HYPHEN-MINUS character (-)
  416. // 3. Two ASCII digits, representing the month month, in the range 1 ≤ month ≤ 12
  417. auto parts = value.split('-');
  418. if (parts.size() != 2)
  419. return false;
  420. if (parts[0].length() < 4)
  421. return false;
  422. for (auto digit : parts[0])
  423. if (!is_ascii_digit(digit))
  424. return false;
  425. if (parts[1].length() != 2)
  426. return false;
  427. if (!is_ascii_digit(parts[1][0]))
  428. return false;
  429. if (!is_ascii_digit(parts[1][1]))
  430. return false;
  431. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  432. return month >= 1 && month <= 12;
  433. }
  434. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  435. static bool is_valid_date_string(DeprecatedString const& value)
  436. {
  437. // 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:
  438. // 1. A valid month string, representing year and month
  439. // 2. A U+002D HYPHEN-MINUS character (-)
  440. // 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
  441. auto parts = value.split('-');
  442. if (parts.size() != 3)
  443. return false;
  444. if (!is_valid_month_string(DeprecatedString::formatted("{}-{}", parts[0], parts[1])))
  445. return false;
  446. if (parts[2].length() != 2)
  447. return false;
  448. i64 year = 0;
  449. for (auto d : parts[0]) {
  450. year *= 10;
  451. year += parse_ascii_digit(d);
  452. }
  453. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  454. i64 day = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  455. return day >= 1 && day <= AK::days_in_month(year, month);
  456. }
  457. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  458. DeprecatedString HTMLInputElement::value_sanitization_algorithm(DeprecatedString value) const
  459. {
  460. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  461. // Strip newlines from the value.
  462. if (value.contains('\r') || value.contains('\n')) {
  463. StringBuilder builder;
  464. for (auto c : value) {
  465. if (!(c == '\r' || c == '\n'))
  466. builder.append(c);
  467. }
  468. return builder.to_deprecated_string();
  469. }
  470. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  471. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  472. if (value.contains('\r') || value.contains('\n')) {
  473. StringBuilder builder;
  474. for (auto c : value) {
  475. if (!(c == '\r' || c == '\n'))
  476. builder.append(c);
  477. }
  478. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  479. }
  480. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  481. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  482. // FIXME: handle the `multiple` attribute
  483. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  484. if (value.contains('\r') || value.contains('\n')) {
  485. StringBuilder builder;
  486. for (auto c : value) {
  487. if (!(c == '\r' || c == '\n'))
  488. builder.append(c);
  489. }
  490. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  491. }
  492. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  493. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  494. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values
  495. // 6. Skip ASCII whitespace within input given position.
  496. auto maybe_double = value.to_double(TrimWhitespace::Yes);
  497. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  498. return "";
  499. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  500. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  501. if (!is_valid_date_string(value))
  502. return "";
  503. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  504. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  505. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  506. if (is_valid_simple_color(value))
  507. return value.to_lowercase();
  508. // otherwise, set it to the string "#000000".
  509. return "#000000";
  510. }
  511. // FIXME: Implement remaining value sanitation algorithms
  512. return value;
  513. }
  514. void HTMLInputElement::form_associated_element_was_inserted()
  515. {
  516. create_shadow_tree_if_needed();
  517. }
  518. void HTMLInputElement::set_checked_within_group()
  519. {
  520. if (checked())
  521. return;
  522. set_checked(true, ChangeSource::User);
  523. DeprecatedString name = this->name();
  524. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  525. if (element.checked() && &element != this && element.name() == name)
  526. element.set_checked(false, ChangeSource::User);
  527. return IterationDecision::Continue;
  528. });
  529. }
  530. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  531. void HTMLInputElement::legacy_pre_activation_behavior()
  532. {
  533. m_before_legacy_pre_activation_behavior_checked = checked();
  534. // 1. If this element's type attribute is in the Checkbox state, then set
  535. // this element's checkedness to its opposite value (i.e. true if it is
  536. // false, false if it is true) and set this element's indeterminate IDL
  537. // attribute to false.
  538. // FIXME: Set indeterminate to false when that exists.
  539. if (type_state() == TypeAttributeState::Checkbox) {
  540. set_checked(!checked(), ChangeSource::User);
  541. }
  542. // 2. If this element's type attribute is in the Radio Button state, then
  543. // get a reference to the element in this element's radio button group that
  544. // has its checkedness set to true, if any, and then set this element's
  545. // checkedness to true.
  546. if (type_state() == TypeAttributeState::RadioButton) {
  547. DeprecatedString name = this->name();
  548. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  549. if (element.checked() && element.name() == name) {
  550. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  551. return IterationDecision::Break;
  552. }
  553. return IterationDecision::Continue;
  554. });
  555. set_checked_within_group();
  556. }
  557. }
  558. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  559. void HTMLInputElement::legacy_cancelled_activation_behavior()
  560. {
  561. // 1. If the element's type attribute is in the Checkbox state, then set the
  562. // element's checkedness and the element's indeterminate IDL attribute back
  563. // to the values they had before the legacy-pre-activation behavior was run.
  564. if (type_state() == TypeAttributeState::Checkbox) {
  565. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  566. }
  567. // 2. If this element 's type attribute is in the Radio Button state, then
  568. // if the element to which a reference was obtained in the
  569. // legacy-pre-activation behavior, if any, is still in what is now this
  570. // element' s radio button group, if it still has one, and if so, setting
  571. // that element 's checkedness to true; or else, if there was no such
  572. // element, or that element is no longer in this element' s radio button
  573. // group, or if this element no longer has a radio button group, setting
  574. // this element's checkedness to false.
  575. if (type_state() == TypeAttributeState::RadioButton) {
  576. DeprecatedString name = this->name();
  577. bool did_reselect_previous_element = false;
  578. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  579. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  580. if (name == element_in_group.name()) {
  581. element_in_group.set_checked_within_group();
  582. did_reselect_previous_element = true;
  583. }
  584. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  585. }
  586. if (!did_reselect_previous_element)
  587. set_checked(false, ChangeSource::User);
  588. }
  589. }
  590. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  591. {
  592. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  593. }
  594. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  595. i32 HTMLInputElement::default_tab_index_value() const
  596. {
  597. // See the base function for the spec comments.
  598. return 0;
  599. }
  600. }