HTMLInputElement.cpp 41 KB

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