HTMLInputElement.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569
  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. * Copyright (c) 2023, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include <LibJS/Runtime/NativeFunction.h>
  11. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  12. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  13. #include <LibWeb/DOM/Document.h>
  14. #include <LibWeb/DOM/ElementFactory.h>
  15. #include <LibWeb/DOM/Event.h>
  16. #include <LibWeb/DOM/IDLEventListener.h>
  17. #include <LibWeb/DOM/ShadowRoot.h>
  18. #include <LibWeb/HTML/BrowsingContext.h>
  19. #include <LibWeb/HTML/Dates.h>
  20. #include <LibWeb/HTML/EventNames.h>
  21. #include <LibWeb/HTML/HTMLDivElement.h>
  22. #include <LibWeb/HTML/HTMLFormElement.h>
  23. #include <LibWeb/HTML/HTMLInputElement.h>
  24. #include <LibWeb/HTML/Numbers.h>
  25. #include <LibWeb/HTML/Scripting/Environments.h>
  26. #include <LibWeb/HTML/Window.h>
  27. #include <LibWeb/Infra/CharacterTypes.h>
  28. #include <LibWeb/Infra/Strings.h>
  29. #include <LibWeb/Layout/BlockContainer.h>
  30. #include <LibWeb/Layout/ButtonBox.h>
  31. #include <LibWeb/Layout/CheckBox.h>
  32. #include <LibWeb/Layout/RadioButton.h>
  33. #include <LibWeb/Namespace.h>
  34. #include <LibWeb/Page/Page.h>
  35. #include <LibWeb/WebIDL/DOMException.h>
  36. #include <LibWeb/WebIDL/ExceptionOr.h>
  37. namespace Web::HTML {
  38. JS_DEFINE_ALLOCATOR(HTMLInputElement);
  39. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  40. : HTMLElement(document, move(qualified_name))
  41. {
  42. }
  43. HTMLInputElement::~HTMLInputElement() = default;
  44. void HTMLInputElement::initialize(JS::Realm& realm)
  45. {
  46. Base::initialize(realm);
  47. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLInputElementPrototype>(realm, "HTMLInputElement"_fly_string));
  48. }
  49. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  50. {
  51. Base::visit_edges(visitor);
  52. visitor.visit(m_inner_text_element);
  53. visitor.visit(m_text_node);
  54. visitor.visit(m_placeholder_element);
  55. visitor.visit(m_placeholder_text_node);
  56. visitor.visit(m_color_well_element);
  57. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group);
  58. visitor.visit(m_selected_files);
  59. visitor.visit(m_slider_thumb);
  60. }
  61. JS::GCPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  62. {
  63. if (type_state() == TypeAttributeState::Hidden)
  64. return nullptr;
  65. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton || type_state() == TypeAttributeState::FileUpload)
  66. return heap().allocate_without_realm<Layout::ButtonBox>(document(), *this, move(style));
  67. if (type_state() == TypeAttributeState::Checkbox)
  68. return heap().allocate_without_realm<Layout::CheckBox>(document(), *this, move(style));
  69. if (type_state() == TypeAttributeState::RadioButton)
  70. return heap().allocate_without_realm<Layout::RadioButton>(document(), *this, move(style));
  71. // AD-HOC: We rewrite `display: inline` to `display: inline-block`.
  72. // This is required for the internal shadow tree to work correctly in layout.
  73. if (style->display().is_inline_outside() && style->display().is_flow_inside())
  74. style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::InlineBlock)));
  75. return Element::create_layout_node_for_display_type(document(), style->display(), style, this);
  76. }
  77. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  78. {
  79. if (m_checked == checked)
  80. return;
  81. // The dirty checkedness flag must be initially set to false when the element is created,
  82. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  83. if (change_source == ChangeSource::User)
  84. m_dirty_checkedness = true;
  85. m_checked = checked;
  86. // This element's :checked pseudo-class could be used in a sibling's sibling-selector,
  87. // so we need to invalidate the style of all siblings.
  88. if (parent()) {
  89. parent()->for_each_child([&](auto& child) {
  90. child.invalidate_style();
  91. });
  92. }
  93. }
  94. void HTMLInputElement::set_checked_binding(bool checked)
  95. {
  96. if (type_state() == TypeAttributeState::RadioButton) {
  97. if (checked)
  98. set_checked_within_group();
  99. else
  100. set_checked(false, ChangeSource::Programmatic);
  101. } else {
  102. set_checked(checked, ChangeSource::Programmatic);
  103. }
  104. }
  105. // https://html.spec.whatwg.org/multipage/input.html#dom-input-indeterminate
  106. void HTMLInputElement::set_indeterminate(bool value)
  107. {
  108. // On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.
  109. m_indeterminate = value;
  110. }
  111. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  112. JS::GCPtr<FileAPI::FileList> HTMLInputElement::files()
  113. {
  114. // On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
  115. // The same object must be returned until the list of selected files changes.
  116. // If the IDL attribute does not apply, then it must instead return null.
  117. if (m_type != TypeAttributeState::FileUpload)
  118. return nullptr;
  119. if (!m_selected_files)
  120. m_selected_files = FileAPI::FileList::create(realm(), {});
  121. return m_selected_files;
  122. }
  123. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  124. void HTMLInputElement::set_files(JS::GCPtr<FileAPI::FileList> files)
  125. {
  126. // 1. If the IDL attribute does not apply or the given value is null, then return.
  127. if (m_type != TypeAttributeState::FileUpload || files == nullptr)
  128. return;
  129. // 2. Replace the element's selected files with the given value.
  130. m_selected_files = files;
  131. }
  132. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  133. void HTMLInputElement::update_the_file_selection(JS::NonnullGCPtr<FileAPI::FileList> files)
  134. {
  135. // 1. Queue an element task on the user interaction task source given element and the following steps:
  136. queue_an_element_task(Task::Source::UserInteraction, [this, files] {
  137. // 1. Update element's selected files so that it represents the user's selection.
  138. this->set_files(files.ptr());
  139. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  140. auto input_event = DOM::Event::create(this->realm(), EventNames::input, { .bubbles = true, .composed = true });
  141. this->dispatch_event(input_event);
  142. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  143. auto change_event = DOM::Event::create(this->realm(), EventNames::change, { .bubbles = true });
  144. this->dispatch_event(change_event);
  145. });
  146. }
  147. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  148. static void show_the_picker_if_applicable(HTMLInputElement& element)
  149. {
  150. // To show the picker, if applicable for an input element element:
  151. // 1. If element's relevant global object does not have transient activation, then return.
  152. auto& global_object = relevant_global_object(element);
  153. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation())
  154. return;
  155. // 2. If element is not mutable, then return.
  156. if (!element.is_mutable())
  157. return;
  158. // 3. If element's type attribute is in the File Upload state, then run these steps in parallel:
  159. if (element.type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
  160. // NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
  161. // 1. Optionally, wait until any prior execution of this algorithm has terminated.
  162. // 2. Display a prompt to the user requesting that the user specify some files.
  163. // If the multiple attribute is not set on element, there must be no more than one file selected; otherwise, any number may be selected.
  164. // 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.
  165. // 3. Wait for the user to have made their selection.
  166. // 4. If the user dismissed the prompt without changing their selection,
  167. // then queue an element task on the user interaction task source given element to fire an event named cancel at element,
  168. // with the bubbles attribute initialized to true.
  169. // 5. Otherwise, update the file selection for element.
  170. bool const multiple = element.has_attribute(HTML::AttributeNames::multiple);
  171. auto weak_element = element.make_weak_ptr<DOM::EventTarget>();
  172. // FIXME: Pass along accept attribute information https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
  173. // The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.
  174. element.document().browsing_context()->top_level_browsing_context()->page().client().page_did_request_file_picker(weak_element, multiple);
  175. return;
  176. }
  177. // 4. Otherwise, the user agent should show any relevant user interface for selecting a value for element,
  178. // 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.)
  179. // If such a user interface is shown, it must respect the requirements stated in the relevant parts of the specification for how element
  180. // behaves given its type attribute state. (For example, various sections describe restrictions on the resulting value string.)
  181. // This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
  182. // (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.)
  183. if (element.type_state() == HTMLInputElement::TypeAttributeState::Color) {
  184. auto weak_element = element.make_weak_ptr<HTMLInputElement>();
  185. element.document().browsing_context()->top_level_browsing_context()->page().did_request_color_picker(weak_element, Color::from_string(element.value()).value_or(Color(0, 0, 0)));
  186. }
  187. }
  188. // https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
  189. WebIDL::ExceptionOr<void> HTMLInputElement::show_picker()
  190. {
  191. // The showPicker() method steps are:
  192. // 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
  193. if (!m_is_mutable)
  194. return WebIDL::InvalidStateError::create(realm(), "Element is not mutable"_fly_string);
  195. // 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
  196. // and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
  197. // NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
  198. // and has never been guarded by an origin check.
  199. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(*this).top_level_origin)
  200. && m_type != TypeAttributeState::FileUpload && m_type != TypeAttributeState::Color) {
  201. return WebIDL::SecurityError::create(realm(), "Cross origin pickers are not allowed"_fly_string);
  202. }
  203. // 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
  204. // FIXME: The global object we get here should probably not need casted to Window to check for transient activation
  205. auto& global_object = relevant_global_object(*this);
  206. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation()) {
  207. return WebIDL::NotAllowedError::create(realm(), "Too long since user activation to show picker"_fly_string);
  208. }
  209. // 4. Show the picker, if applicable, for this.
  210. show_the_picker_if_applicable(*this);
  211. return {};
  212. }
  213. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  214. WebIDL::ExceptionOr<void> HTMLInputElement::run_input_activation_behavior()
  215. {
  216. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  217. // 1. If the element is not connected, then return.
  218. if (!is_connected())
  219. return {};
  220. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  221. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  222. input_event->set_bubbles(true);
  223. input_event->set_composed(true);
  224. dispatch_event(input_event);
  225. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  226. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  227. change_event->set_bubbles(true);
  228. dispatch_event(*change_event);
  229. } else if (type_state() == TypeAttributeState::SubmitButton) {
  230. JS::GCPtr<HTMLFormElement> form;
  231. // 1. If the element does not have a form owner, then return.
  232. if (!(form = this->form()))
  233. return {};
  234. // 2. If the element's node document is not fully active, then return.
  235. if (!document().is_fully_active())
  236. return {};
  237. // 3. Submit the form owner from the element.
  238. TRY(form->submit_form(*this));
  239. } else if (type_state() == TypeAttributeState::FileUpload || type_state() == TypeAttributeState::Color) {
  240. show_the_picker_if_applicable(*this);
  241. }
  242. return {};
  243. }
  244. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  245. {
  246. // 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.
  247. m_value = value_sanitization_algorithm(m_text_node->data());
  248. m_dirty_value = true;
  249. m_has_uncommitted_changes = true;
  250. update_placeholder_visibility();
  251. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  252. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  253. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  254. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  255. input_event->set_bubbles(true);
  256. input_event->set_composed(true);
  257. dispatch_event(*input_event);
  258. });
  259. }
  260. void HTMLInputElement::did_pick_color(Optional<Color> picked_color)
  261. {
  262. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  263. // For input elements without a defined input activation behavior, but to which these events apply
  264. // and for which the user interface involves both interactive manipulation and an explicit commit action
  265. if (type_state() == TypeAttributeState::Color && picked_color.has_value()) {
  266. // then when the user changes the element's value
  267. m_value = value_sanitization_algorithm(picked_color.value().to_string_without_alpha());
  268. m_dirty_value = true;
  269. if (m_color_well_element)
  270. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  271. // the user agent must queue an element task on the user interaction task source
  272. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  273. // given the input element to fire an event named input at the input element, with the bubbles and composed attributes initialized to true
  274. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  275. input_event->set_bubbles(true);
  276. input_event->set_composed(true);
  277. dispatch_event(*input_event);
  278. });
  279. // and any time the user commits the change, the user agent must queue an element task on the user interaction task source
  280. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  281. // given the input element
  282. // FIXME: to set its user interacted to true
  283. // and fire an event named change at the input element, with the bubbles attribute initialized to true.
  284. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  285. change_event->set_bubbles(true);
  286. dispatch_event(*change_event);
  287. });
  288. }
  289. }
  290. String HTMLInputElement::value() const
  291. {
  292. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  293. if (type_state() == TypeAttributeState::FileUpload) {
  294. // NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
  295. // NOTE: Since path components are not permitted in filenames in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.
  296. // 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.
  297. if (m_selected_files && m_selected_files->item(0))
  298. return MUST(String::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name()));
  299. return String {};
  300. }
  301. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
  302. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  303. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the string "on".
  304. return get_attribute(AttributeNames::value).value_or("on"_string);
  305. }
  306. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
  307. if (type_state() == TypeAttributeState::Hidden
  308. || type_state() == TypeAttributeState::SubmitButton
  309. || type_state() == TypeAttributeState::ImageButton
  310. || type_state() == TypeAttributeState::ResetButton
  311. || type_state() == TypeAttributeState::Button) {
  312. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the empty string.
  313. return get_attribute(AttributeNames::value).value_or(String {});
  314. }
  315. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  316. // Return the current value of the element.
  317. return m_value;
  318. }
  319. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(String const& value)
  320. {
  321. auto& realm = this->realm();
  322. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  323. if (type_state() == TypeAttributeState::FileUpload) {
  324. // On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.
  325. if (!value.is_empty())
  326. return WebIDL::InvalidStateError::create(realm, "Setting value of input type file to non-empty string"_fly_string);
  327. m_selected_files = nullptr;
  328. return {};
  329. }
  330. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  331. // 1. Let oldValue be the element's value.
  332. auto old_value = move(m_value);
  333. // 2. Set the element's value to the new value.
  334. // NOTE: For the TextNode this is done as part of step 4 below.
  335. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  336. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  337. // 3. Set the element's dirty value flag to true.
  338. m_dirty_value = true;
  339. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  340. m_value = value_sanitization_algorithm(value);
  341. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  342. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  343. // text control, unselecting any selected text and resetting the selection direction to "none".
  344. if (m_text_node && (m_value != old_value)) {
  345. m_text_node->set_data(m_value);
  346. update_placeholder_visibility();
  347. if (auto* browsing_context = document().browsing_context())
  348. browsing_context->set_cursor_position(DOM::Position::create(realm, *m_text_node, m_text_node->data().bytes().size()));
  349. }
  350. return {};
  351. }
  352. void HTMLInputElement::commit_pending_changes()
  353. {
  354. // The change event fires when the value is committed, if that makes sense for the control,
  355. // or else when the control loses focus
  356. switch (type_state()) {
  357. case TypeAttributeState::Email:
  358. case TypeAttributeState::Password:
  359. case TypeAttributeState::Search:
  360. case TypeAttributeState::Telephone:
  361. case TypeAttributeState::Text:
  362. case TypeAttributeState::URL:
  363. if (!m_has_uncommitted_changes)
  364. return;
  365. break;
  366. default:
  367. break;
  368. }
  369. m_has_uncommitted_changes = false;
  370. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true });
  371. dispatch_event(change_event);
  372. }
  373. void HTMLInputElement::update_placeholder_visibility()
  374. {
  375. if (!m_placeholder_element)
  376. return;
  377. auto placeholder_text = this->placeholder_value();
  378. if (placeholder_text.has_value()) {
  379. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  380. } else {
  381. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  382. }
  383. }
  384. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  385. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  386. {
  387. switch (state) {
  388. case HTML::HTMLInputElement::TypeAttributeState::Text:
  389. case HTML::HTMLInputElement::TypeAttributeState::Search:
  390. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  391. case HTML::HTMLInputElement::TypeAttributeState::URL:
  392. case HTML::HTMLInputElement::TypeAttributeState::Email:
  393. case HTML::HTMLInputElement::TypeAttributeState::Password:
  394. case HTML::HTMLInputElement::TypeAttributeState::Date:
  395. case HTML::HTMLInputElement::TypeAttributeState::Month:
  396. case HTML::HTMLInputElement::TypeAttributeState::Week:
  397. case HTML::HTMLInputElement::TypeAttributeState::Time:
  398. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  399. case HTML::HTMLInputElement::TypeAttributeState::Number:
  400. return true;
  401. default:
  402. return false;
  403. }
  404. }
  405. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  406. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  407. {
  408. // The readonly attribute is a boolean attribute that controls whether or not the user can edit the form control. When specified, the element is not mutable.
  409. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  410. if (m_text_node)
  411. m_text_node->set_always_editable(m_is_mutable);
  412. }
  413. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  414. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  415. {
  416. switch (state) {
  417. case HTML::HTMLInputElement::TypeAttributeState::Text:
  418. case HTML::HTMLInputElement::TypeAttributeState::Search:
  419. case HTML::HTMLInputElement::TypeAttributeState::URL:
  420. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  421. case HTML::HTMLInputElement::TypeAttributeState::Email:
  422. case HTML::HTMLInputElement::TypeAttributeState::Password:
  423. case HTML::HTMLInputElement::TypeAttributeState::Number:
  424. return true;
  425. default:
  426. return false;
  427. }
  428. }
  429. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  430. String HTMLInputElement::placeholder() const
  431. {
  432. auto maybe_placeholder = get_attribute(HTML::AttributeNames::placeholder);
  433. if (!maybe_placeholder.has_value())
  434. return String {};
  435. auto placeholder = *maybe_placeholder;
  436. // The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
  437. StringBuilder builder;
  438. for (auto c : placeholder.bytes_as_string_view()) {
  439. if (c != '\r' && c != '\n')
  440. builder.append(c);
  441. }
  442. return MUST(builder.to_string());
  443. }
  444. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  445. Optional<ByteString> HTMLInputElement::placeholder_value() const
  446. {
  447. if (!m_text_node || !m_text_node->data().is_empty())
  448. return {};
  449. if (!is_allowed_to_have_placeholder(type_state()))
  450. return {};
  451. if (!has_attribute(HTML::AttributeNames::placeholder))
  452. return {};
  453. return placeholder().to_byte_string();
  454. }
  455. void HTMLInputElement::create_shadow_tree_if_needed()
  456. {
  457. if (shadow_root_internal())
  458. return;
  459. switch (type_state()) {
  460. case TypeAttributeState::Hidden:
  461. case TypeAttributeState::RadioButton:
  462. case TypeAttributeState::Checkbox:
  463. case TypeAttributeState::Button:
  464. case TypeAttributeState::SubmitButton:
  465. case TypeAttributeState::ResetButton:
  466. case TypeAttributeState::ImageButton:
  467. break;
  468. case TypeAttributeState::Color:
  469. create_color_input_shadow_tree();
  470. break;
  471. case TypeAttributeState::Range:
  472. create_range_input_shadow_tree();
  473. break;
  474. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  475. default:
  476. create_text_input_shadow_tree();
  477. break;
  478. }
  479. }
  480. void HTMLInputElement::create_text_input_shadow_tree()
  481. {
  482. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  483. set_shadow_root(shadow_root);
  484. auto initial_value = m_value;
  485. auto element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  486. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  487. display: flex;
  488. height: 100%;
  489. align-items: center;
  490. white-space: pre;
  491. border: none;
  492. padding: 1px 2px;
  493. )~~~"_string));
  494. MUST(shadow_root->append_child(element));
  495. m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  496. m_placeholder_element->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::Placeholder);
  497. MUST(m_placeholder_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  498. flex: 1;
  499. height: 1lh;
  500. )~~~"_string));
  501. MUST(element->append_child(*m_placeholder_element));
  502. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), String {});
  503. m_placeholder_text_node->set_data(placeholder());
  504. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  505. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  506. m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  507. MUST(m_inner_text_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  508. flex: 1;
  509. height: 1lh;
  510. )~~~"_string));
  511. MUST(element->append_child(*m_inner_text_element));
  512. m_text_node = heap().allocate<DOM::Text>(realm(), document(), move(initial_value));
  513. if (type_state() == TypeAttributeState::FileUpload) {
  514. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  515. m_text_node->set_always_editable(false);
  516. } else {
  517. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  518. }
  519. m_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  520. if (type_state() == TypeAttributeState::Password)
  521. m_text_node->set_is_password_input({}, true);
  522. MUST(m_inner_text_element->append_child(*m_text_node));
  523. update_placeholder_visibility();
  524. if (type_state() == TypeAttributeState::Number) {
  525. // Up button
  526. auto up_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  527. // FIXME: This cursor property doesn't work
  528. MUST(up_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  529. padding: 0;
  530. cursor: default;
  531. )~~~"_string));
  532. MUST(up_button->set_inner_html("<svg style=\"width: 1em; height: 1em;\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"currentColor\" d=\"M7.41,15.41L12,10.83L16.59,15.41L18,14L12,8L6,14L7.41,15.41Z\" /></svg>"sv));
  533. MUST(element->append_child(up_button));
  534. auto up_callback_function = JS::NativeFunction::create(
  535. realm(), [this](JS::VM&) {
  536. (void)step_up();
  537. return JS::js_undefined();
  538. },
  539. 0, "", &realm());
  540. auto up_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*up_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  541. up_button->add_event_listener_without_options("click"_fly_string, DOM::IDLEventListener::create(realm(), up_callback));
  542. // Down button
  543. auto down_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  544. MUST(down_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  545. padding: 0;
  546. cursor: default;
  547. )~~~"_string));
  548. MUST(down_button->set_inner_html("<svg style=\"width: 1em; height: 1em;\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path fill=\"currentColor\" d=\"M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z\" /></svg>"sv));
  549. MUST(element->append_child(down_button));
  550. auto down_callback_function = JS::NativeFunction::create(
  551. realm(), [this](JS::VM&) {
  552. (void)step_down();
  553. return JS::js_undefined();
  554. },
  555. 0, "", &realm());
  556. auto down_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*down_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  557. down_button->add_event_listener_without_options("click"_fly_string, DOM::IDLEventListener::create(realm(), down_callback));
  558. }
  559. }
  560. void HTMLInputElement::create_color_input_shadow_tree()
  561. {
  562. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  563. auto color = value_sanitization_algorithm(m_value);
  564. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  565. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  566. width: fit-content;
  567. height: fit-content;
  568. padding: 4px;
  569. border: 1px solid ButtonBorder;
  570. background-color: ButtonFace;
  571. )~~~"_string));
  572. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  573. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  574. width: 24px;
  575. height: 24px;
  576. border: 1px solid ButtonBorder;
  577. box-sizing: border-box;
  578. )~~~"_string));
  579. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  580. MUST(border->append_child(*m_color_well_element));
  581. MUST(shadow_root->append_child(border));
  582. set_shadow_root(shadow_root);
  583. }
  584. void HTMLInputElement::create_range_input_shadow_tree()
  585. {
  586. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  587. set_shadow_root(shadow_root);
  588. auto slider_runnable_track = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  589. slider_runnable_track->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderRunnableTrack);
  590. MUST(shadow_root->append_child(slider_runnable_track));
  591. m_slider_thumb = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  592. m_slider_thumb->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderThumb);
  593. MUST(slider_runnable_track->append_child(*m_slider_thumb));
  594. update_slider_thumb_element();
  595. }
  596. void HTMLInputElement::update_slider_thumb_element()
  597. {
  598. double minimum = *min();
  599. double maximum = *max();
  600. double default_value = minimum + (maximum - minimum) / 2;
  601. if (maximum < minimum)
  602. default_value = minimum;
  603. double value = MUST(value_as_number());
  604. if (!isfinite(value))
  605. value = default_value;
  606. double position = (value - minimum) / (maximum - minimum) * 100;
  607. MUST(m_slider_thumb->style_for_bindings()->set_property(CSS::PropertyID::MarginLeft, MUST(String::formatted("{}%", position))));
  608. }
  609. void HTMLInputElement::did_receive_focus()
  610. {
  611. auto* browsing_context = document().browsing_context();
  612. if (!browsing_context)
  613. return;
  614. if (!m_text_node)
  615. return;
  616. browsing_context->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  617. }
  618. void HTMLInputElement::did_lose_focus()
  619. {
  620. commit_pending_changes();
  621. }
  622. void HTMLInputElement::attribute_changed(FlyString const& name, Optional<String> const& value)
  623. {
  624. HTMLElement::attribute_changed(name, value);
  625. if (name == HTML::AttributeNames::checked) {
  626. if (!value.has_value()) {
  627. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  628. // the user agent must set the checkedness of the element to false.
  629. if (!m_dirty_checkedness)
  630. set_checked(false, ChangeSource::Programmatic);
  631. } else {
  632. // When the checked content attribute is added, if the control does not have dirty checkedness,
  633. // the user agent must set the checkedness of the element to true
  634. if (!m_dirty_checkedness)
  635. set_checked(true, ChangeSource::Programmatic);
  636. }
  637. } else if (name == HTML::AttributeNames::type) {
  638. m_type = parse_type_attribute(value.value_or(String {}));
  639. } else if (name == HTML::AttributeNames::value) {
  640. if (!value.has_value()) {
  641. if (!m_dirty_value) {
  642. m_value = String {};
  643. update_placeholder_visibility();
  644. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  645. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  646. if (type_state() == TypeAttributeState::Range && m_slider_thumb)
  647. update_slider_thumb_element();
  648. }
  649. } else {
  650. if (!m_dirty_value) {
  651. m_value = value_sanitization_algorithm(*value);
  652. update_placeholder_visibility();
  653. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  654. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  655. if (type_state() == TypeAttributeState::Range && m_slider_thumb)
  656. update_slider_thumb_element();
  657. }
  658. }
  659. } else if (name == HTML::AttributeNames::placeholder) {
  660. if (m_placeholder_text_node)
  661. m_placeholder_text_node->set_data(placeholder());
  662. } else if (name == HTML::AttributeNames::readonly) {
  663. handle_readonly_attribute(value);
  664. }
  665. }
  666. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  667. {
  668. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  669. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  670. return HTMLInputElement::TypeAttributeState::state;
  671. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  672. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  673. // The missing value default and the invalid value default are the Text state.
  674. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  675. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  676. return HTMLInputElement::TypeAttributeState::Text;
  677. }
  678. StringView HTMLInputElement::type() const
  679. {
  680. // FIXME: This should probably be `Reflect` in the IDL.
  681. switch (m_type) {
  682. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  683. case TypeAttributeState::state: \
  684. return #keyword##sv;
  685. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  686. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  687. }
  688. VERIFY_NOT_REACHED();
  689. }
  690. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  691. {
  692. return set_attribute(HTML::AttributeNames::type, type);
  693. }
  694. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  695. static bool is_valid_simple_color(StringView value)
  696. {
  697. // if it is exactly seven characters long,
  698. if (value.length() != 7)
  699. return false;
  700. // and the first character is a U+0023 NUMBER SIGN character (#),
  701. if (!value.starts_with('#'))
  702. return false;
  703. // and the remaining six characters are all ASCII hex digits
  704. for (size_t i = 1; i < value.length(); i++)
  705. if (!is_ascii_hex_digit(value[i]))
  706. return false;
  707. return true;
  708. }
  709. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  710. String HTMLInputElement::value_sanitization_algorithm(String const& value) const
  711. {
  712. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  713. // Strip newlines from the value.
  714. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  715. StringBuilder builder;
  716. for (auto c : value.bytes_as_string_view()) {
  717. if (c != '\r' && c != '\n')
  718. builder.append(c);
  719. }
  720. return MUST(builder.to_string());
  721. }
  722. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  723. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  724. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  725. StringBuilder builder;
  726. for (auto c : value.bytes_as_string_view()) {
  727. if (c != '\r' && c != '\n')
  728. builder.append(c);
  729. }
  730. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  731. }
  732. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  733. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  734. // FIXME: handle the `multiple` attribute
  735. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  736. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  737. StringBuilder builder;
  738. for (auto c : value.bytes_as_string_view()) {
  739. if (c != '\r' && c != '\n')
  740. builder.append(c);
  741. }
  742. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  743. }
  744. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  745. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  746. auto maybe_value = parse_floating_point_number(value);
  747. if (!maybe_value.has_value() || !isfinite(maybe_value.value()))
  748. return String {};
  749. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  750. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  751. if (!is_valid_date_string(value))
  752. return String {};
  753. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  754. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  755. if (!is_valid_month_string(value))
  756. return String {};
  757. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  758. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  759. if (!is_valid_week_string(value))
  760. return String {};
  761. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  762. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  763. if (!is_valid_time_string(value))
  764. return String {};
  765. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  766. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  767. if (is_valid_local_date_and_time_string(value))
  768. return normalize_local_date_and_time_string(value);
  769. return String {};
  770. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  771. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  772. // If the value of the element is not a valid floating-point number, then set it to the best representation, as a floating-point number, of the default value.
  773. auto maybe_value = parse_floating_point_number(value);
  774. if (!maybe_value.has_value() || !isfinite(maybe_value.value())) {
  775. // The default value is the minimum plus half the difference between the minimum and the maximum, unless the maximum is less than the minimum, in which case the default value is the minimum.
  776. auto min = parse_floating_point_number(get_attribute(HTML::AttributeNames::min).value_or("0"_string)).value_or(0);
  777. auto max = parse_floating_point_number(get_attribute(HTML::AttributeNames::max).value_or("1"_string)).value_or(1);
  778. if (max > min)
  779. return JS::number_to_string(min);
  780. return JS::number_to_string(min + (max - min) / 2);
  781. }
  782. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  783. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  784. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  785. if (is_valid_simple_color(value))
  786. return MUST(Infra::to_ascii_lowercase(value));
  787. // otherwise, set it to the string "#000000".
  788. return "#000000"_string;
  789. }
  790. return value;
  791. }
  792. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  793. void HTMLInputElement::reset_algorithm()
  794. {
  795. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  796. m_dirty_value = false;
  797. m_dirty_checkedness = false;
  798. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  799. m_value = get_attribute(AttributeNames::value).value_or(String {});
  800. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  801. m_checked = has_attribute(AttributeNames::checked);
  802. // empty the list of selected files,
  803. m_selected_files = FileAPI::FileList::create(realm(), {});
  804. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  805. m_value = value_sanitization_algorithm(m_value);
  806. if (m_text_node) {
  807. m_text_node->set_data(m_value);
  808. update_placeholder_visibility();
  809. }
  810. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  811. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  812. }
  813. void HTMLInputElement::form_associated_element_was_inserted()
  814. {
  815. create_shadow_tree_if_needed();
  816. }
  817. void HTMLInputElement::form_associated_element_was_removed(DOM::Node*)
  818. {
  819. set_shadow_root(nullptr);
  820. }
  821. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  822. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  823. {
  824. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  825. return !value_a.is_empty() && value_a == value_b;
  826. };
  827. // The radio button group that contains an input element a also contains all the
  828. // other input elements b that fulfill all of the following conditions:
  829. return (
  830. // - Both a and b are in the same tree.
  831. // - The input element b's type attribute is in the Radio Button state.
  832. a.type_state() == b.type_state()
  833. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  834. // - Either a and b have the same form owner, or they both have no form owner.
  835. && a.form() == b.form()
  836. // - They both have a name attribute, their name attributes are not empty, and the
  837. // value of a's name attribute equals the value of b's name attribute.
  838. && a.has_attribute(HTML::AttributeNames::name)
  839. && b.has_attribute(HTML::AttributeNames::name)
  840. && non_empty_equals(a.name(), b.name()));
  841. }
  842. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  843. void HTMLInputElement::set_checked_within_group()
  844. {
  845. if (checked())
  846. return;
  847. set_checked(true, ChangeSource::User);
  848. // No point iterating the tree if we have an empty name.
  849. auto name = this->name();
  850. if (name.is_empty())
  851. return;
  852. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  853. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  854. element.set_checked(false, ChangeSource::User);
  855. return IterationDecision::Continue;
  856. });
  857. }
  858. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  859. void HTMLInputElement::legacy_pre_activation_behavior()
  860. {
  861. m_before_legacy_pre_activation_behavior_checked = checked();
  862. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  863. // 1. If this element's type attribute is in the Checkbox state, then set
  864. // this element's checkedness to its opposite value (i.e. true if it is
  865. // false, false if it is true) and set this element's indeterminate IDL
  866. // attribute to false.
  867. if (type_state() == TypeAttributeState::Checkbox) {
  868. set_checked(!checked(), ChangeSource::User);
  869. set_indeterminate(false);
  870. }
  871. // 2. If this element's type attribute is in the Radio Button state, then
  872. // get a reference to the element in this element's radio button group that
  873. // has its checkedness set to true, if any, and then set this element's
  874. // checkedness to true.
  875. if (type_state() == TypeAttributeState::RadioButton) {
  876. ByteString name = this->name();
  877. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  878. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  879. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  880. return IterationDecision::Break;
  881. }
  882. return IterationDecision::Continue;
  883. });
  884. set_checked_within_group();
  885. }
  886. }
  887. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  888. void HTMLInputElement::legacy_cancelled_activation_behavior()
  889. {
  890. // 1. If the element's type attribute is in the Checkbox state, then set the
  891. // element's checkedness and the element's indeterminate IDL attribute back
  892. // to the values they had before the legacy-pre-activation behavior was run.
  893. if (type_state() == TypeAttributeState::Checkbox) {
  894. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  895. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  896. }
  897. // 2. If this element 's type attribute is in the Radio Button state, then
  898. // if the element to which a reference was obtained in the
  899. // legacy-pre-activation behavior, if any, is still in what is now this
  900. // element' s radio button group, if it still has one, and if so, setting
  901. // that element 's checkedness to true; or else, if there was no such
  902. // element, or that element is no longer in this element' s radio button
  903. // group, or if this element no longer has a radio button group, setting
  904. // this element's checkedness to false.
  905. if (type_state() == TypeAttributeState::RadioButton) {
  906. bool did_reselect_previous_element = false;
  907. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  908. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  909. if (is_in_same_radio_button_group(*this, element_in_group)) {
  910. element_in_group.set_checked_within_group();
  911. did_reselect_previous_element = true;
  912. }
  913. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  914. }
  915. if (!did_reselect_previous_element)
  916. set_checked(false, ChangeSource::User);
  917. }
  918. }
  919. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  920. {
  921. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  922. }
  923. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  924. i32 HTMLInputElement::default_tab_index_value() const
  925. {
  926. // See the base function for the spec comments.
  927. return 0;
  928. }
  929. // https://html.spec.whatwg.org/multipage/input.html#the-size-attribute
  930. unsigned HTMLInputElement::size() const
  931. {
  932. // The size IDL attribute is limited to only positive numbers and has a default value of 20.
  933. if (auto size_string = get_attribute(HTML::AttributeNames::size); size_string.has_value()) {
  934. if (auto size = parse_non_negative_integer(*size_string); size.has_value())
  935. return *size;
  936. }
  937. return 20;
  938. }
  939. WebIDL::ExceptionOr<void> HTMLInputElement::set_size(unsigned value)
  940. {
  941. return set_attribute(HTML::AttributeNames::size, MUST(String::number(value)));
  942. }
  943. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  944. Optional<double> HTMLInputElement::convert_string_to_number(StringView input) const
  945. {
  946. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-string-number
  947. if (type_state() == TypeAttributeState::Number)
  948. return parse_floating_point_number(input);
  949. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-string-number
  950. if (type_state() == TypeAttributeState::Range)
  951. return parse_floating_point_number(input);
  952. dbgln("HTMLInputElement::convert_string_to_number() not implemented for input type {}", type());
  953. return {};
  954. }
  955. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  956. String HTMLInputElement::covert_number_to_string(double input) const
  957. {
  958. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-number-string
  959. if (type_state() == TypeAttributeState::Number)
  960. return MUST(String::number(input));
  961. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-number-string
  962. if (type_state() == TypeAttributeState::Range)
  963. return MUST(String::number(input));
  964. dbgln("HTMLInputElement::covert_number_to_string() not implemented for input type {}", type());
  965. return {};
  966. }
  967. // https://html.spec.whatwg.org/multipage/input.html#attr-input-min
  968. Optional<double> HTMLInputElement::min() const
  969. {
  970. // If the element has a min attribute, and the result of applying the algorithm to convert a string to a number to
  971. // the value of the min attribute is a number, then that number is the element's minimum; otherwise, if the type
  972. // attribute's current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.
  973. if (auto min_string = get_attribute(HTML::AttributeNames::min); min_string.has_value()) {
  974. if (auto min = convert_string_to_number(*min_string); min.has_value())
  975. return *min;
  976. }
  977. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-min-default
  978. if (type_state() == TypeAttributeState::Range)
  979. return 0;
  980. return {};
  981. }
  982. // https://html.spec.whatwg.org/multipage/input.html#attr-input-max
  983. Optional<double> HTMLInputElement::max() const
  984. {
  985. // If the element has a max attribute, and the result of applying the algorithm to convert a string to a number to the
  986. // value of the max attribute is a number, then that number is the element's maximum; otherwise, if the type attribute's
  987. // current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.
  988. if (auto max_string = get_attribute(HTML::AttributeNames::max); max_string.has_value()) {
  989. if (auto max = convert_string_to_number(*max_string); max.has_value())
  990. return *max;
  991. }
  992. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-max-default
  993. if (type_state() == TypeAttributeState::Range)
  994. return 100;
  995. return {};
  996. }
  997. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default
  998. double HTMLInputElement::default_step() const
  999. {
  1000. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-default
  1001. if (type_state() == TypeAttributeState::Number)
  1002. return 1;
  1003. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-default
  1004. if (type_state() == TypeAttributeState::Range)
  1005. return 1;
  1006. dbgln("HTMLInputElement::default_step() not implemented for input type {}", type());
  1007. return 0;
  1008. }
  1009. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-scale
  1010. double HTMLInputElement::step_scale_factor() const
  1011. {
  1012. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-scale
  1013. if (type_state() == TypeAttributeState::Number)
  1014. return 1;
  1015. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-scale
  1016. if (type_state() == TypeAttributeState::Range)
  1017. return 1;
  1018. dbgln("HTMLInputElement::step_scale_factor() not implemented for input type {}", type());
  1019. return 0;
  1020. }
  1021. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step
  1022. Optional<double> HTMLInputElement::allowed_value_step() const
  1023. {
  1024. // 1. If the attribute does not apply, then there is no allowed value step.
  1025. if (!step_applies())
  1026. return {};
  1027. // 2. Otherwise, if the attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.
  1028. auto maybe_step_string = get_attribute(AttributeNames::step);
  1029. if (!maybe_step_string.has_value())
  1030. return default_step() * step_scale_factor();
  1031. auto step_string = *maybe_step_string;
  1032. // 3. Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.
  1033. if (Infra::is_ascii_case_insensitive_match(step_string, "any"_string))
  1034. return {};
  1035. // 4. Otherwise, if the rules for parsing floating-point number values, when they are applied to the attribute's value, return an error,
  1036. // zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.
  1037. auto maybe_step = parse_floating_point_number(step_string);
  1038. if (!maybe_step.has_value() || *maybe_step == 0 || *maybe_step < 0)
  1039. return default_step() * step_scale_factor();
  1040. // 5. Otherwise, the allowed value step is the number returned by the rules for parsing floating-point number values when they are applied
  1041. // to the attribute's value, multiplied by the step scale factor.
  1042. return *maybe_step * step_scale_factor();
  1043. }
  1044. // https://html.spec.whatwg.org/multipage/input.html#concept-input-min-zero
  1045. double HTMLInputElement::step_base() const
  1046. {
  1047. // 1. If the element has a min content attribute, and the result of applying the algorithm to convert a string to a number to the value of
  1048. // the min content attribute is not an error, then return that result.
  1049. if (auto min = this->min(); min.has_value())
  1050. return *min;
  1051. // 2. If the element has a value content attribute, and the result of applying the algorithm to convert a string to a number to the value of
  1052. // the value content attribute is not an error, then return that result.
  1053. if (auto value = convert_string_to_number(this->value()); value.has_value())
  1054. return *value;
  1055. // 3. If a default step base is defined for this element given its type attribute's state, then return it.
  1056. if (type_state() == TypeAttributeState::Week) {
  1057. // The default step base is −259,200,000 (the start of week 1970-W01).
  1058. return -259'200'000;
  1059. }
  1060. // 4. Return zero.
  1061. return 0;
  1062. }
  1063. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1064. WebIDL::ExceptionOr<double> HTMLInputElement::value_as_number() const
  1065. {
  1066. // On getting, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then return a Not-a-Number (NaN) value.
  1067. if (!value_as_number_applies())
  1068. return NAN;
  1069. // Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value;
  1070. // if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
  1071. return convert_string_to_number(value()).value_or(NAN);
  1072. }
  1073. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1074. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  1075. {
  1076. // On setting, if the new value is infinite, then throw a TypeError exception.
  1077. if (!isfinite(value))
  1078. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  1079. // Otherwise, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException.
  1080. if (!value_as_number_applies())
  1081. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
  1082. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  1083. if (value == NAN) {
  1084. TRY(set_value(String {}));
  1085. return {};
  1086. }
  1087. // Otherwise, run the algorithm to convert a number to a string, as defined for that state, on the new value, and set the value of the element to the resulting string.
  1088. TRY(set_value(covert_number_to_string(value)));
  1089. return {};
  1090. }
  1091. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1092. WebIDL::ExceptionOr<void> HTMLInputElement::step_up(long n)
  1093. {
  1094. return step_up_or_down(false, n);
  1095. }
  1096. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepdown
  1097. WebIDL::ExceptionOr<void> HTMLInputElement::step_down(long n)
  1098. {
  1099. return step_up_or_down(true, n);
  1100. }
  1101. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1102. WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, long n)
  1103. {
  1104. // 1. If the stepDown() and stepUp() methods do not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException.
  1105. if (!step_up_or_down_applies())
  1106. return WebIDL::InvalidStateError::create(realm(), MUST(String::formatted("{}: Invalid input type used", is_down ? "stepDown()" : "stepUp()")));
  1107. // 2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.
  1108. auto maybe_allowed_value_step = allowed_value_step();
  1109. if (!maybe_allowed_value_step.has_value())
  1110. return WebIDL::InvalidStateError::create(realm(), "element has no allowed value step"_fly_string);
  1111. double allowed_value_step = *maybe_allowed_value_step;
  1112. // 3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then return.
  1113. auto maybe_minimum = min();
  1114. auto maybe_maximum = max();
  1115. if (maybe_minimum.has_value() && maybe_maximum.has_value() && *maybe_minimum > *maybe_maximum)
  1116. return {};
  1117. // FIXME: 4. If the element has a minimum and a maximum and there is no value greater than or equal to the element's minimum and less than
  1118. // or equal to the element's maximum that, when subtracted from the step base, is an integral multiple of the allowed value step, then return.
  1119. // 5. If applying the algorithm to convert a string to a number to the string given by the element's value does not result in an error,
  1120. // then let value be the result of that algorithm. Otherwise, let value be zero.
  1121. double value = convert_string_to_number(this->value()).value_or(0);
  1122. // 6. Let valueBeforeStepping be value.
  1123. double value_before_stepping = value;
  1124. // 7. If value subtracted from the step base is not an integral multiple of the allowed value step, then set value to the nearest value that,
  1125. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than value if the method invoked was the stepDown() method, and more than value otherwise.
  1126. if (fmod(step_base() - value, allowed_value_step) != 0) {
  1127. double diff = step_base() - value;
  1128. if (is_down) {
  1129. value = diff - fmod(diff, allowed_value_step);
  1130. } else {
  1131. value = diff + fmod(diff, allowed_value_step);
  1132. }
  1133. } else {
  1134. // 1. Let n be the argument.
  1135. // 2. Let delta be the allowed value step multiplied by n.
  1136. double delta = allowed_value_step * n;
  1137. // 3. If the method invoked was the stepDown() method, negate delta.
  1138. if (is_down)
  1139. delta = -delta;
  1140. // 4. Let value be the result of adding delta to value.
  1141. value += delta;
  1142. }
  1143. // 8. If the element has a minimum, and value is less than that minimum, then set value to the smallest value that,
  1144. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is more than or equal to minimum.
  1145. if (maybe_minimum.has_value() && value < *maybe_minimum) {
  1146. value = AK::max(value, *maybe_minimum);
  1147. }
  1148. // 9. If the element has a maximum, and value is greater than that maximum, then set value to the largest value that,
  1149. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than or equal to maximum.
  1150. if (maybe_maximum.has_value() && value > *maybe_maximum) {
  1151. value = AK::min(value, *maybe_maximum);
  1152. }
  1153. // 10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping,
  1154. // or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then return.
  1155. if (is_down) {
  1156. if (value > value_before_stepping)
  1157. return {};
  1158. } else {
  1159. if (value < value_before_stepping)
  1160. return {};
  1161. }
  1162. // 11. Let value as string be the result of running the algorithm to convert a number to a string,
  1163. // as defined for the input element's type attribute's current state, on value.
  1164. auto value_as_string = covert_number_to_string(value);
  1165. // 12. Set the value of the element to value as string.
  1166. TRY(set_value(value_as_string));
  1167. return {};
  1168. }
  1169. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1170. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1171. {
  1172. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1173. return true;
  1174. }
  1175. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1176. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1177. {
  1178. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1179. return true;
  1180. }
  1181. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1182. void HTMLInputElement::set_custom_validity(String const& error)
  1183. {
  1184. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1185. return;
  1186. }
  1187. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  1188. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  1189. {
  1190. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  1191. return {};
  1192. }
  1193. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  1194. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, Optional<String> const& direction)
  1195. {
  1196. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  1197. return {};
  1198. }
  1199. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1200. {
  1201. // https://www.w3.org/TR/html-aria/#el-input-button
  1202. if (type_state() == TypeAttributeState::Button)
  1203. return ARIA::Role::button;
  1204. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1205. if (type_state() == TypeAttributeState::Checkbox)
  1206. return ARIA::Role::checkbox;
  1207. // https://www.w3.org/TR/html-aria/#el-input-email
  1208. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1209. return ARIA::Role::textbox;
  1210. // https://www.w3.org/TR/html-aria/#el-input-image
  1211. if (type_state() == TypeAttributeState::ImageButton)
  1212. return ARIA::Role::button;
  1213. // https://www.w3.org/TR/html-aria/#el-input-number
  1214. if (type_state() == TypeAttributeState::Number)
  1215. return ARIA::Role::spinbutton;
  1216. // https://www.w3.org/TR/html-aria/#el-input-radio
  1217. if (type_state() == TypeAttributeState::RadioButton)
  1218. return ARIA::Role::radio;
  1219. // https://www.w3.org/TR/html-aria/#el-input-range
  1220. if (type_state() == TypeAttributeState::Range)
  1221. return ARIA::Role::slider;
  1222. // https://www.w3.org/TR/html-aria/#el-input-reset
  1223. if (type_state() == TypeAttributeState::ResetButton)
  1224. return ARIA::Role::button;
  1225. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1226. if ((type_state() == TypeAttributeState::Text
  1227. || type_state() == TypeAttributeState::Search
  1228. || type_state() == TypeAttributeState::Telephone
  1229. || type_state() == TypeAttributeState::URL
  1230. || type_state() == TypeAttributeState::Email)
  1231. && has_attribute(AttributeNames::list))
  1232. return ARIA::Role::combobox;
  1233. // https://www.w3.org/TR/html-aria/#el-input-search
  1234. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1235. return ARIA::Role::textbox;
  1236. // https://www.w3.org/TR/html-aria/#el-input-submit
  1237. if (type_state() == TypeAttributeState::SubmitButton)
  1238. return ARIA::Role::button;
  1239. // https://www.w3.org/TR/html-aria/#el-input-tel
  1240. if (type_state() == TypeAttributeState::Telephone)
  1241. return ARIA::Role::textbox;
  1242. // https://www.w3.org/TR/html-aria/#el-input-text
  1243. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1244. return ARIA::Role::textbox;
  1245. // https://www.w3.org/TR/html-aria/#el-input-url
  1246. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1247. return ARIA::Role::textbox;
  1248. // https://www.w3.org/TR/html-aria/#el-input-color
  1249. // https://www.w3.org/TR/html-aria/#el-input-date
  1250. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1251. // https://www.w3.org/TR/html-aria/#el-input-file
  1252. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1253. // https://www.w3.org/TR/html-aria/#el-input-month
  1254. // https://www.w3.org/TR/html-aria/#el-input-password
  1255. // https://www.w3.org/TR/html-aria/#el-input-time
  1256. // https://www.w3.org/TR/html-aria/#el-input-week
  1257. return {};
  1258. }
  1259. bool HTMLInputElement::is_button() const
  1260. {
  1261. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1262. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1263. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1264. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1265. return type_state() == TypeAttributeState::SubmitButton
  1266. || type_state() == TypeAttributeState::ImageButton
  1267. || type_state() == TypeAttributeState::ResetButton
  1268. || type_state() == TypeAttributeState::Button;
  1269. }
  1270. bool HTMLInputElement::is_submit_button() const
  1271. {
  1272. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  1273. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  1274. return type_state() == TypeAttributeState::SubmitButton
  1275. || type_state() == TypeAttributeState::ImageButton;
  1276. }
  1277. bool HTMLInputElement::has_activation_behavior() const
  1278. {
  1279. return true;
  1280. }
  1281. void HTMLInputElement::activation_behavior(DOM::Event const&)
  1282. {
  1283. // The activation behavior for input elements are these steps:
  1284. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  1285. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  1286. run_input_activation_behavior().release_value_but_fixme_should_propagate_errors();
  1287. }
  1288. bool HTMLInputElement::has_input_activation_behavior() const
  1289. {
  1290. switch (type_state()) {
  1291. case TypeAttributeState::Checkbox:
  1292. case TypeAttributeState::Color:
  1293. case TypeAttributeState::FileUpload:
  1294. case TypeAttributeState::ImageButton:
  1295. case TypeAttributeState::RadioButton:
  1296. case TypeAttributeState::ResetButton:
  1297. case TypeAttributeState::SubmitButton:
  1298. return true;
  1299. default:
  1300. return false;
  1301. }
  1302. }
  1303. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:event-change-2
  1304. bool HTMLInputElement::change_event_applies() const
  1305. {
  1306. switch (type_state()) {
  1307. case TypeAttributeState::Checkbox:
  1308. case TypeAttributeState::Color:
  1309. case TypeAttributeState::Date:
  1310. case TypeAttributeState::Email:
  1311. case TypeAttributeState::FileUpload:
  1312. case TypeAttributeState::LocalDateAndTime:
  1313. case TypeAttributeState::Month:
  1314. case TypeAttributeState::Number:
  1315. case TypeAttributeState::Password:
  1316. case TypeAttributeState::RadioButton:
  1317. case TypeAttributeState::Range:
  1318. case TypeAttributeState::Search:
  1319. case TypeAttributeState::Telephone:
  1320. case TypeAttributeState::Text:
  1321. case TypeAttributeState::Time:
  1322. case TypeAttributeState::URL:
  1323. case TypeAttributeState::Week:
  1324. return true;
  1325. default:
  1326. return false;
  1327. }
  1328. }
  1329. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasnumber-3
  1330. bool HTMLInputElement::value_as_number_applies() const
  1331. {
  1332. switch (type_state()) {
  1333. case TypeAttributeState::Date:
  1334. case TypeAttributeState::Month:
  1335. case TypeAttributeState::Week:
  1336. case TypeAttributeState::Time:
  1337. case TypeAttributeState::LocalDateAndTime:
  1338. case TypeAttributeState::Number:
  1339. case TypeAttributeState::Range:
  1340. return true;
  1341. default:
  1342. return false;
  1343. }
  1344. }
  1345. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-step-3
  1346. bool HTMLInputElement::step_applies() const
  1347. {
  1348. return value_as_number_applies();
  1349. }
  1350. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-stepup-3
  1351. bool HTMLInputElement::step_up_or_down_applies() const
  1352. {
  1353. return value_as_number_applies();
  1354. }
  1355. }