HTMLInputElement.cpp 50 KB

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