HTMLInputElement.cpp 77 KB

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