HTMLInputElement.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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(DOM::Event const& event)
  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 element's form owner from the element with userInvolvement set to event's user navigation involvement.
  239. TRY(form->submit_form(*this, { .user_involvement = user_navigation_involvement(event) }));
  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. update_color_well_element();
  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_value != old_value) {
  346. if (m_text_node) {
  347. m_text_node->set_data(m_value);
  348. update_placeholder_visibility();
  349. if (auto* browsing_context = document().browsing_context())
  350. browsing_context->set_cursor_position(DOM::Position::create(realm, *m_text_node, m_text_node->data().bytes().size()));
  351. }
  352. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  353. update_color_well_element();
  354. if (type_state() == TypeAttributeState::Range && m_slider_thumb)
  355. update_slider_thumb_element();
  356. }
  357. return {};
  358. }
  359. void HTMLInputElement::commit_pending_changes()
  360. {
  361. // The change event fires when the value is committed, if that makes sense for the control,
  362. // or else when the control loses focus
  363. switch (type_state()) {
  364. case TypeAttributeState::Email:
  365. case TypeAttributeState::Password:
  366. case TypeAttributeState::Search:
  367. case TypeAttributeState::Telephone:
  368. case TypeAttributeState::Text:
  369. case TypeAttributeState::URL:
  370. if (!m_has_uncommitted_changes)
  371. return;
  372. break;
  373. default:
  374. break;
  375. }
  376. m_has_uncommitted_changes = false;
  377. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true });
  378. dispatch_event(change_event);
  379. }
  380. void HTMLInputElement::update_placeholder_visibility()
  381. {
  382. if (!m_placeholder_element)
  383. return;
  384. auto placeholder_text = this->placeholder_value();
  385. if (placeholder_text.has_value()) {
  386. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  387. } else {
  388. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  389. }
  390. }
  391. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  392. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  393. {
  394. switch (state) {
  395. case HTML::HTMLInputElement::TypeAttributeState::Text:
  396. case HTML::HTMLInputElement::TypeAttributeState::Search:
  397. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  398. case HTML::HTMLInputElement::TypeAttributeState::URL:
  399. case HTML::HTMLInputElement::TypeAttributeState::Email:
  400. case HTML::HTMLInputElement::TypeAttributeState::Password:
  401. case HTML::HTMLInputElement::TypeAttributeState::Date:
  402. case HTML::HTMLInputElement::TypeAttributeState::Month:
  403. case HTML::HTMLInputElement::TypeAttributeState::Week:
  404. case HTML::HTMLInputElement::TypeAttributeState::Time:
  405. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  406. case HTML::HTMLInputElement::TypeAttributeState::Number:
  407. return true;
  408. default:
  409. return false;
  410. }
  411. }
  412. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  413. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  414. {
  415. // 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.
  416. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  417. if (m_text_node)
  418. m_text_node->set_always_editable(m_is_mutable);
  419. }
  420. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  421. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  422. {
  423. switch (state) {
  424. case HTML::HTMLInputElement::TypeAttributeState::Text:
  425. case HTML::HTMLInputElement::TypeAttributeState::Search:
  426. case HTML::HTMLInputElement::TypeAttributeState::URL:
  427. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  428. case HTML::HTMLInputElement::TypeAttributeState::Email:
  429. case HTML::HTMLInputElement::TypeAttributeState::Password:
  430. case HTML::HTMLInputElement::TypeAttributeState::Number:
  431. return true;
  432. default:
  433. return false;
  434. }
  435. }
  436. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  437. String HTMLInputElement::placeholder() const
  438. {
  439. auto maybe_placeholder = get_attribute(HTML::AttributeNames::placeholder);
  440. if (!maybe_placeholder.has_value())
  441. return String {};
  442. auto placeholder = *maybe_placeholder;
  443. // The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
  444. StringBuilder builder;
  445. for (auto c : placeholder.bytes_as_string_view()) {
  446. if (c != '\r' && c != '\n')
  447. builder.append(c);
  448. }
  449. return MUST(builder.to_string());
  450. }
  451. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  452. Optional<ByteString> HTMLInputElement::placeholder_value() const
  453. {
  454. if (!m_text_node || !m_text_node->data().is_empty())
  455. return {};
  456. if (!is_allowed_to_have_placeholder(type_state()))
  457. return {};
  458. if (!has_attribute(HTML::AttributeNames::placeholder))
  459. return {};
  460. return placeholder().to_byte_string();
  461. }
  462. void HTMLInputElement::create_shadow_tree_if_needed()
  463. {
  464. if (shadow_root_internal())
  465. return;
  466. switch (type_state()) {
  467. case TypeAttributeState::Hidden:
  468. case TypeAttributeState::RadioButton:
  469. case TypeAttributeState::Checkbox:
  470. case TypeAttributeState::Button:
  471. case TypeAttributeState::SubmitButton:
  472. case TypeAttributeState::ResetButton:
  473. case TypeAttributeState::ImageButton:
  474. break;
  475. case TypeAttributeState::Color:
  476. create_color_input_shadow_tree();
  477. break;
  478. case TypeAttributeState::Range:
  479. create_range_input_shadow_tree();
  480. break;
  481. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  482. default:
  483. create_text_input_shadow_tree();
  484. break;
  485. }
  486. }
  487. void HTMLInputElement::create_text_input_shadow_tree()
  488. {
  489. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  490. set_shadow_root(shadow_root);
  491. auto initial_value = m_value;
  492. auto element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  493. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  494. display: flex;
  495. height: 100%;
  496. align-items: center;
  497. white-space: pre;
  498. border: none;
  499. padding: 1px 2px;
  500. )~~~"_string));
  501. MUST(shadow_root->append_child(element));
  502. m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  503. m_placeholder_element->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::Placeholder);
  504. MUST(m_placeholder_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  505. flex: 1;
  506. height: 1lh;
  507. )~~~"_string));
  508. MUST(element->append_child(*m_placeholder_element));
  509. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), String {});
  510. m_placeholder_text_node->set_data(placeholder());
  511. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  512. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  513. m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  514. MUST(m_inner_text_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  515. flex: 1;
  516. height: 1lh;
  517. )~~~"_string));
  518. MUST(element->append_child(*m_inner_text_element));
  519. m_text_node = heap().allocate<DOM::Text>(realm(), document(), move(initial_value));
  520. if (type_state() == TypeAttributeState::FileUpload) {
  521. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  522. m_text_node->set_always_editable(false);
  523. } else {
  524. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  525. }
  526. m_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  527. if (type_state() == TypeAttributeState::Password)
  528. m_text_node->set_is_password_input({}, true);
  529. MUST(m_inner_text_element->append_child(*m_text_node));
  530. update_placeholder_visibility();
  531. if (type_state() == TypeAttributeState::Number) {
  532. // Up button
  533. auto up_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  534. // FIXME: This cursor property doesn't work
  535. MUST(up_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  536. padding: 0;
  537. cursor: default;
  538. )~~~"_string));
  539. 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));
  540. MUST(element->append_child(up_button));
  541. auto up_callback_function = JS::NativeFunction::create(
  542. realm(), [this](JS::VM&) {
  543. (void)step_up();
  544. return JS::js_undefined();
  545. },
  546. 0, "", &realm());
  547. auto up_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*up_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  548. up_button->add_event_listener_without_options("click"_fly_string, DOM::IDLEventListener::create(realm(), up_callback));
  549. // Down button
  550. auto down_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  551. MUST(down_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  552. padding: 0;
  553. cursor: default;
  554. )~~~"_string));
  555. 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));
  556. MUST(element->append_child(down_button));
  557. auto down_callback_function = JS::NativeFunction::create(
  558. realm(), [this](JS::VM&) {
  559. (void)step_down();
  560. return JS::js_undefined();
  561. },
  562. 0, "", &realm());
  563. auto down_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*down_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  564. down_button->add_event_listener_without_options("click"_fly_string, DOM::IDLEventListener::create(realm(), down_callback));
  565. }
  566. }
  567. void HTMLInputElement::create_color_input_shadow_tree()
  568. {
  569. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  570. auto color = value_sanitization_algorithm(m_value);
  571. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  572. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  573. width: fit-content;
  574. height: fit-content;
  575. padding: 4px;
  576. border: 1px solid ButtonBorder;
  577. background-color: ButtonFace;
  578. )~~~"_string));
  579. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  580. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  581. width: 24px;
  582. height: 24px;
  583. border: 1px solid ButtonBorder;
  584. box-sizing: border-box;
  585. )~~~"_string));
  586. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  587. MUST(border->append_child(*m_color_well_element));
  588. MUST(shadow_root->append_child(border));
  589. set_shadow_root(shadow_root);
  590. }
  591. void HTMLInputElement::update_color_well_element()
  592. {
  593. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  594. }
  595. void HTMLInputElement::create_range_input_shadow_tree()
  596. {
  597. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  598. set_shadow_root(shadow_root);
  599. auto slider_runnable_track = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  600. slider_runnable_track->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderRunnableTrack);
  601. MUST(shadow_root->append_child(slider_runnable_track));
  602. m_slider_thumb = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  603. m_slider_thumb->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderThumb);
  604. MUST(slider_runnable_track->append_child(*m_slider_thumb));
  605. update_slider_thumb_element();
  606. }
  607. void HTMLInputElement::update_slider_thumb_element()
  608. {
  609. double minimum = *min();
  610. double maximum = *max();
  611. double default_value = minimum + (maximum - minimum) / 2;
  612. if (maximum < minimum)
  613. default_value = minimum;
  614. double value = value_as_number();
  615. if (!isfinite(value))
  616. value = default_value;
  617. double position = (value - minimum) / (maximum - minimum) * 100;
  618. MUST(m_slider_thumb->style_for_bindings()->set_property(CSS::PropertyID::MarginLeft, MUST(String::formatted("{}%", position))));
  619. }
  620. void HTMLInputElement::did_receive_focus()
  621. {
  622. auto* browsing_context = document().browsing_context();
  623. if (!browsing_context)
  624. return;
  625. if (!m_text_node)
  626. return;
  627. browsing_context->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  628. }
  629. void HTMLInputElement::did_lose_focus()
  630. {
  631. commit_pending_changes();
  632. }
  633. void HTMLInputElement::attribute_changed(FlyString const& name, Optional<String> const& value)
  634. {
  635. HTMLElement::attribute_changed(name, value);
  636. if (name == HTML::AttributeNames::checked) {
  637. if (!value.has_value()) {
  638. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  639. // the user agent must set the checkedness of the element to false.
  640. if (!m_dirty_checkedness)
  641. set_checked(false, ChangeSource::Programmatic);
  642. } else {
  643. // When the checked content attribute is added, if the control does not have dirty checkedness,
  644. // the user agent must set the checkedness of the element to true
  645. if (!m_dirty_checkedness)
  646. set_checked(true, ChangeSource::Programmatic);
  647. }
  648. } else if (name == HTML::AttributeNames::type) {
  649. m_type = parse_type_attribute(value.value_or(String {}));
  650. } else if (name == HTML::AttributeNames::value) {
  651. if (!m_dirty_value) {
  652. if (!value.has_value()) {
  653. m_value = String {};
  654. } else {
  655. m_value = value_sanitization_algorithm(*value);
  656. }
  657. update_placeholder_visibility();
  658. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  659. update_color_well_element();
  660. if (type_state() == TypeAttributeState::Range && m_slider_thumb)
  661. update_slider_thumb_element();
  662. }
  663. } else if (name == HTML::AttributeNames::placeholder) {
  664. if (m_placeholder_text_node)
  665. m_placeholder_text_node->set_data(placeholder());
  666. } else if (name == HTML::AttributeNames::readonly) {
  667. handle_readonly_attribute(value);
  668. }
  669. }
  670. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  671. {
  672. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  673. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  674. return HTMLInputElement::TypeAttributeState::state;
  675. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  676. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  677. // The missing value default and the invalid value default are the Text state.
  678. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  679. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  680. return HTMLInputElement::TypeAttributeState::Text;
  681. }
  682. StringView HTMLInputElement::type() const
  683. {
  684. // FIXME: This should probably be `Reflect` in the IDL.
  685. switch (m_type) {
  686. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  687. case TypeAttributeState::state: \
  688. return #keyword##sv;
  689. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  690. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  691. }
  692. VERIFY_NOT_REACHED();
  693. }
  694. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  695. {
  696. return set_attribute(HTML::AttributeNames::type, type);
  697. }
  698. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  699. static bool is_valid_simple_color(StringView value)
  700. {
  701. // if it is exactly seven characters long,
  702. if (value.length() != 7)
  703. return false;
  704. // and the first character is a U+0023 NUMBER SIGN character (#),
  705. if (!value.starts_with('#'))
  706. return false;
  707. // and the remaining six characters are all ASCII hex digits
  708. for (size_t i = 1; i < value.length(); i++)
  709. if (!is_ascii_hex_digit(value[i]))
  710. return false;
  711. return true;
  712. }
  713. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  714. String HTMLInputElement::value_sanitization_algorithm(String const& value) const
  715. {
  716. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  717. // Strip newlines from the value.
  718. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  719. StringBuilder builder;
  720. for (auto c : value.bytes_as_string_view()) {
  721. if (c != '\r' && c != '\n')
  722. builder.append(c);
  723. }
  724. return MUST(builder.to_string());
  725. }
  726. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  727. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  728. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  729. StringBuilder builder;
  730. for (auto c : value.bytes_as_string_view()) {
  731. if (c != '\r' && c != '\n')
  732. builder.append(c);
  733. }
  734. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  735. }
  736. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  737. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  738. // FIXME: handle the `multiple` attribute
  739. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  740. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  741. StringBuilder builder;
  742. for (auto c : value.bytes_as_string_view()) {
  743. if (c != '\r' && c != '\n')
  744. builder.append(c);
  745. }
  746. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  747. }
  748. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  749. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  750. auto maybe_value = parse_floating_point_number(value);
  751. if (!maybe_value.has_value() || !isfinite(maybe_value.value()))
  752. return String {};
  753. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  754. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  755. if (!is_valid_date_string(value))
  756. return String {};
  757. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  758. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  759. if (!is_valid_month_string(value))
  760. return String {};
  761. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  762. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  763. if (!is_valid_week_string(value))
  764. return String {};
  765. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  766. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  767. if (!is_valid_time_string(value))
  768. return String {};
  769. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  770. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  771. if (is_valid_local_date_and_time_string(value))
  772. return normalize_local_date_and_time_string(value);
  773. return String {};
  774. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  775. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  776. // 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.
  777. auto maybe_value = parse_floating_point_number(value);
  778. if (!maybe_value.has_value() || !isfinite(maybe_value.value())) {
  779. // 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.
  780. auto min = parse_floating_point_number(get_attribute(HTML::AttributeNames::min).value_or("0"_string)).value_or(0);
  781. auto max = parse_floating_point_number(get_attribute(HTML::AttributeNames::max).value_or("1"_string)).value_or(1);
  782. if (max > min)
  783. return JS::number_to_string(min);
  784. return JS::number_to_string(min + (max - min) / 2);
  785. }
  786. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  787. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  788. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  789. if (is_valid_simple_color(value))
  790. return MUST(Infra::to_ascii_lowercase(value));
  791. // otherwise, set it to the string "#000000".
  792. return "#000000"_string;
  793. }
  794. return value;
  795. }
  796. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  797. void HTMLInputElement::reset_algorithm()
  798. {
  799. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  800. m_dirty_value = false;
  801. m_dirty_checkedness = false;
  802. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  803. m_value = get_attribute(AttributeNames::value).value_or(String {});
  804. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  805. m_checked = has_attribute(AttributeNames::checked);
  806. // empty the list of selected files,
  807. m_selected_files = FileAPI::FileList::create(realm(), {});
  808. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  809. m_value = value_sanitization_algorithm(m_value);
  810. if (m_text_node) {
  811. m_text_node->set_data(m_value);
  812. update_placeholder_visibility();
  813. }
  814. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  815. update_color_well_element();
  816. if (type_state() == TypeAttributeState::Range && m_slider_thumb)
  817. update_slider_thumb_element();
  818. }
  819. void HTMLInputElement::form_associated_element_was_inserted()
  820. {
  821. create_shadow_tree_if_needed();
  822. }
  823. void HTMLInputElement::form_associated_element_was_removed(DOM::Node*)
  824. {
  825. set_shadow_root(nullptr);
  826. }
  827. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  828. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  829. {
  830. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  831. return !value_a.is_empty() && value_a == value_b;
  832. };
  833. // The radio button group that contains an input element a also contains all the
  834. // other input elements b that fulfill all of the following conditions:
  835. return (
  836. // - Both a and b are in the same tree.
  837. // - The input element b's type attribute is in the Radio Button state.
  838. a.type_state() == b.type_state()
  839. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  840. // - Either a and b have the same form owner, or they both have no form owner.
  841. && a.form() == b.form()
  842. // - They both have a name attribute, their name attributes are not empty, and the
  843. // value of a's name attribute equals the value of b's name attribute.
  844. && a.name().has_value()
  845. && b.name().has_value()
  846. && non_empty_equals(a.name().value(), b.name().value()));
  847. }
  848. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  849. void HTMLInputElement::set_checked_within_group()
  850. {
  851. if (checked())
  852. return;
  853. set_checked(true, ChangeSource::User);
  854. // No point iterating the tree if we have an empty name.
  855. if (!name().has_value() || name()->is_empty())
  856. return;
  857. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  858. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  859. element.set_checked(false, ChangeSource::User);
  860. return IterationDecision::Continue;
  861. });
  862. }
  863. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  864. void HTMLInputElement::legacy_pre_activation_behavior()
  865. {
  866. m_before_legacy_pre_activation_behavior_checked = checked();
  867. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  868. // 1. If this element's type attribute is in the Checkbox state, then set
  869. // this element's checkedness to its opposite value (i.e. true if it is
  870. // false, false if it is true) and set this element's indeterminate IDL
  871. // attribute to false.
  872. if (type_state() == TypeAttributeState::Checkbox) {
  873. set_checked(!checked(), ChangeSource::User);
  874. set_indeterminate(false);
  875. }
  876. // 2. If this element's type attribute is in the Radio Button state, then
  877. // get a reference to the element in this element's radio button group that
  878. // has its checkedness set to true, if any, and then set this element's
  879. // checkedness to true.
  880. if (type_state() == TypeAttributeState::RadioButton) {
  881. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  882. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  883. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  884. return IterationDecision::Break;
  885. }
  886. return IterationDecision::Continue;
  887. });
  888. set_checked_within_group();
  889. }
  890. }
  891. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  892. void HTMLInputElement::legacy_cancelled_activation_behavior()
  893. {
  894. // 1. If the element's type attribute is in the Checkbox state, then set the
  895. // element's checkedness and the element's indeterminate IDL attribute back
  896. // to the values they had before the legacy-pre-activation behavior was run.
  897. if (type_state() == TypeAttributeState::Checkbox) {
  898. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  899. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  900. }
  901. // 2. If this element 's type attribute is in the Radio Button state, then
  902. // if the element to which a reference was obtained in the
  903. // legacy-pre-activation behavior, if any, is still in what is now this
  904. // element' s radio button group, if it still has one, and if so, setting
  905. // that element 's checkedness to true; or else, if there was no such
  906. // element, or that element is no longer in this element' s radio button
  907. // group, or if this element no longer has a radio button group, setting
  908. // this element's checkedness to false.
  909. if (type_state() == TypeAttributeState::RadioButton) {
  910. bool did_reselect_previous_element = false;
  911. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  912. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  913. if (is_in_same_radio_button_group(*this, element_in_group)) {
  914. element_in_group.set_checked_within_group();
  915. did_reselect_previous_element = true;
  916. }
  917. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  918. }
  919. if (!did_reselect_previous_element)
  920. set_checked(false, ChangeSource::User);
  921. }
  922. }
  923. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  924. {
  925. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  926. }
  927. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  928. i32 HTMLInputElement::default_tab_index_value() const
  929. {
  930. // See the base function for the spec comments.
  931. return 0;
  932. }
  933. // https://html.spec.whatwg.org/multipage/input.html#the-size-attribute
  934. unsigned HTMLInputElement::size() const
  935. {
  936. // The size IDL attribute is limited to only positive numbers and has a default value of 20.
  937. if (auto size_string = get_attribute(HTML::AttributeNames::size); size_string.has_value()) {
  938. if (auto size = parse_non_negative_integer(*size_string); size.has_value())
  939. return *size;
  940. }
  941. return 20;
  942. }
  943. WebIDL::ExceptionOr<void> HTMLInputElement::set_size(unsigned value)
  944. {
  945. return set_attribute(HTML::AttributeNames::size, MUST(String::number(value)));
  946. }
  947. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  948. Optional<double> HTMLInputElement::convert_string_to_number(StringView input) const
  949. {
  950. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-string-number
  951. if (type_state() == TypeAttributeState::Number)
  952. return parse_floating_point_number(input);
  953. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-string-number
  954. if (type_state() == TypeAttributeState::Range)
  955. return parse_floating_point_number(input);
  956. dbgln("HTMLInputElement::convert_string_to_number() not implemented for input type {}", type());
  957. return {};
  958. }
  959. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  960. String HTMLInputElement::covert_number_to_string(double input) const
  961. {
  962. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-number-string
  963. if (type_state() == TypeAttributeState::Number)
  964. return MUST(String::number(input));
  965. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-number-string
  966. if (type_state() == TypeAttributeState::Range)
  967. return MUST(String::number(input));
  968. dbgln("HTMLInputElement::covert_number_to_string() not implemented for input type {}", type());
  969. return {};
  970. }
  971. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-date
  972. WebIDL::ExceptionOr<JS::GCPtr<JS::Date>> HTMLInputElement::convert_string_to_date(StringView input) const
  973. {
  974. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-string-date
  975. if (type_state() == TypeAttributeState::Date) {
  976. // If parsing a date from input results in an error, then return an error;
  977. auto maybe_date = parse_date_string(realm(), input);
  978. if (maybe_date.is_exception())
  979. return maybe_date.exception();
  980. // otherwise, return a new Date object representing midnight UTC on the morning of the parsed date.
  981. return maybe_date.value();
  982. }
  983. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  984. if (type_state() == TypeAttributeState::Time) {
  985. // If parsing a time from input results in an error, then return an error;
  986. auto maybe_time = parse_time_string(realm(), input);
  987. if (maybe_time.is_exception())
  988. return maybe_time.exception();
  989. // otherwise, return a new Date object representing the parsed time in UTC on 1970-01-01.
  990. return maybe_time.value();
  991. }
  992. dbgln("HTMLInputElement::convert_string_to_date() not implemented for input type {}", type());
  993. return nullptr;
  994. }
  995. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-date-string
  996. String HTMLInputElement::covert_date_to_string(JS::NonnullGCPtr<JS::Date> input) const
  997. {
  998. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-date-string
  999. if (type_state() == TypeAttributeState::Date) {
  1000. // Return a valid date string that represents the date current at the time represented by input in the UTC time zone.
  1001. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  1002. 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())));
  1003. }
  1004. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  1005. if (type_state() == TypeAttributeState::Time) {
  1006. // Return a valid time string that represents the UTC time component that is represented by input.
  1007. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  1008. auto seconds = JS::sec_from_time(input->date_value());
  1009. auto milliseconds = JS::ms_from_time(input->date_value());
  1010. if (seconds > 0) {
  1011. if (milliseconds > 0)
  1012. return MUST(String::formatted("{:02d}:{:02d}:{:02d}.{:3d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds, milliseconds));
  1013. return MUST(String::formatted("{:02d}:{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds));
  1014. }
  1015. return MUST(String::formatted("{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value())));
  1016. }
  1017. dbgln("HTMLInputElement::covert_date_to_string() not implemented for input type {}", type());
  1018. return {};
  1019. }
  1020. // https://html.spec.whatwg.org/multipage/input.html#attr-input-min
  1021. Optional<double> HTMLInputElement::min() const
  1022. {
  1023. // If the element has a min attribute, and the result of applying the algorithm to convert a string to a number to
  1024. // the value of the min attribute is a number, then that number is the element's minimum; otherwise, if the type
  1025. // attribute's current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.
  1026. if (auto min_string = get_attribute(HTML::AttributeNames::min); min_string.has_value()) {
  1027. if (auto min = convert_string_to_number(*min_string); min.has_value())
  1028. return *min;
  1029. }
  1030. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-min-default
  1031. if (type_state() == TypeAttributeState::Range)
  1032. return 0;
  1033. return {};
  1034. }
  1035. // https://html.spec.whatwg.org/multipage/input.html#attr-input-max
  1036. Optional<double> HTMLInputElement::max() const
  1037. {
  1038. // If the element has a max attribute, and the result of applying the algorithm to convert a string to a number to the
  1039. // value of the max attribute is a number, then that number is the element's maximum; otherwise, if the type attribute's
  1040. // current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.
  1041. if (auto max_string = get_attribute(HTML::AttributeNames::max); max_string.has_value()) {
  1042. if (auto max = convert_string_to_number(*max_string); max.has_value())
  1043. return *max;
  1044. }
  1045. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-max-default
  1046. if (type_state() == TypeAttributeState::Range)
  1047. return 100;
  1048. return {};
  1049. }
  1050. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default
  1051. double HTMLInputElement::default_step() const
  1052. {
  1053. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-default
  1054. if (type_state() == TypeAttributeState::Number)
  1055. return 1;
  1056. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-default
  1057. if (type_state() == TypeAttributeState::Range)
  1058. return 1;
  1059. dbgln("HTMLInputElement::default_step() not implemented for input type {}", type());
  1060. return 0;
  1061. }
  1062. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-scale
  1063. double HTMLInputElement::step_scale_factor() const
  1064. {
  1065. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-scale
  1066. if (type_state() == TypeAttributeState::Number)
  1067. return 1;
  1068. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-scale
  1069. if (type_state() == TypeAttributeState::Range)
  1070. return 1;
  1071. dbgln("HTMLInputElement::step_scale_factor() not implemented for input type {}", type());
  1072. return 0;
  1073. }
  1074. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step
  1075. Optional<double> HTMLInputElement::allowed_value_step() const
  1076. {
  1077. // 1. If the attribute does not apply, then there is no allowed value step.
  1078. if (!step_applies())
  1079. return {};
  1080. // 2. Otherwise, if the attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.
  1081. auto maybe_step_string = get_attribute(AttributeNames::step);
  1082. if (!maybe_step_string.has_value())
  1083. return default_step() * step_scale_factor();
  1084. auto step_string = *maybe_step_string;
  1085. // 3. Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.
  1086. if (Infra::is_ascii_case_insensitive_match(step_string, "any"_string))
  1087. return {};
  1088. // 4. Otherwise, if the rules for parsing floating-point number values, when they are applied to the attribute's value, return an error,
  1089. // zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.
  1090. auto maybe_step = parse_floating_point_number(step_string);
  1091. if (!maybe_step.has_value() || *maybe_step == 0 || *maybe_step < 0)
  1092. return default_step() * step_scale_factor();
  1093. // 5. Otherwise, the allowed value step is the number returned by the rules for parsing floating-point number values when they are applied
  1094. // to the attribute's value, multiplied by the step scale factor.
  1095. return *maybe_step * step_scale_factor();
  1096. }
  1097. // https://html.spec.whatwg.org/multipage/input.html#concept-input-min-zero
  1098. double HTMLInputElement::step_base() const
  1099. {
  1100. // 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
  1101. // the min content attribute is not an error, then return that result.
  1102. if (auto min = this->min(); min.has_value())
  1103. return *min;
  1104. // 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
  1105. // the value content attribute is not an error, then return that result.
  1106. if (auto value = convert_string_to_number(this->value()); value.has_value())
  1107. return *value;
  1108. // 3. If a default step base is defined for this element given its type attribute's state, then return it.
  1109. if (type_state() == TypeAttributeState::Week) {
  1110. // The default step base is −259,200,000 (the start of week 1970-W01).
  1111. return -259'200'000;
  1112. }
  1113. // 4. Return zero.
  1114. return 0;
  1115. }
  1116. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1117. JS::Object* HTMLInputElement::value_as_date() const
  1118. {
  1119. // On getting, if the valueAsDate attribute does not apply, as defined for the input element's type attribute's current state, then return null.
  1120. if (!value_as_date_applies())
  1121. return nullptr;
  1122. // Otherwise, run the algorithm to convert a string to a Date object defined for that state to the element's value;
  1123. // if the algorithm returned a Date object, then return it, otherwise, return null.
  1124. auto maybe_date = convert_string_to_date(value());
  1125. if (!maybe_date.is_exception())
  1126. return maybe_date.value().ptr();
  1127. return nullptr;
  1128. }
  1129. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1130. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_date(Optional<JS::Handle<JS::Object>> const& value)
  1131. {
  1132. // 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;
  1133. if (!value_as_date_applies())
  1134. return WebIDL::InvalidStateError::create(realm(), "valueAsDate: Invalid input type used"_fly_string);
  1135. // otherwise, if the new value is not null and not a Date object throw a TypeError exception;
  1136. if (value.has_value() && !is<JS::Date>(**value))
  1137. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsDate: input is not a Date"sv };
  1138. // 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;
  1139. if (!value.has_value()) {
  1140. TRY(set_value(String {}));
  1141. return {};
  1142. }
  1143. auto& date = static_cast<JS::Date&>(**value);
  1144. if (!isfinite(date.date_value())) {
  1145. TRY(set_value(String {}));
  1146. return {};
  1147. }
  1148. // 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.
  1149. TRY(set_value(covert_date_to_string(date)));
  1150. return {};
  1151. }
  1152. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1153. double HTMLInputElement::value_as_number() const
  1154. {
  1155. // 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.
  1156. if (!value_as_number_applies())
  1157. return NAN;
  1158. // Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value;
  1159. // if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
  1160. return convert_string_to_number(value()).value_or(NAN);
  1161. }
  1162. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1163. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  1164. {
  1165. // On setting, if the new value is infinite, then throw a TypeError exception.
  1166. if (!isfinite(value))
  1167. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  1168. // 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.
  1169. if (!value_as_number_applies())
  1170. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
  1171. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  1172. if (value == NAN) {
  1173. TRY(set_value(String {}));
  1174. return {};
  1175. }
  1176. // 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.
  1177. TRY(set_value(covert_number_to_string(value)));
  1178. return {};
  1179. }
  1180. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1181. WebIDL::ExceptionOr<void> HTMLInputElement::step_up(long n)
  1182. {
  1183. return step_up_or_down(false, n);
  1184. }
  1185. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepdown
  1186. WebIDL::ExceptionOr<void> HTMLInputElement::step_down(long n)
  1187. {
  1188. return step_up_or_down(true, n);
  1189. }
  1190. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1191. WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, long n)
  1192. {
  1193. // 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.
  1194. if (!step_up_or_down_applies())
  1195. return WebIDL::InvalidStateError::create(realm(), MUST(String::formatted("{}: Invalid input type used", is_down ? "stepDown()" : "stepUp()")));
  1196. // 2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.
  1197. auto maybe_allowed_value_step = allowed_value_step();
  1198. if (!maybe_allowed_value_step.has_value())
  1199. return WebIDL::InvalidStateError::create(realm(), "element has no allowed value step"_fly_string);
  1200. double allowed_value_step = *maybe_allowed_value_step;
  1201. // 3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then return.
  1202. auto maybe_minimum = min();
  1203. auto maybe_maximum = max();
  1204. if (maybe_minimum.has_value() && maybe_maximum.has_value() && *maybe_minimum > *maybe_maximum)
  1205. return {};
  1206. // 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
  1207. // 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.
  1208. // 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,
  1209. // then let value be the result of that algorithm. Otherwise, let value be zero.
  1210. double value = convert_string_to_number(this->value()).value_or(0);
  1211. // 6. Let valueBeforeStepping be value.
  1212. double value_before_stepping = value;
  1213. // 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,
  1214. // 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.
  1215. if (fmod(step_base() - value, allowed_value_step) != 0) {
  1216. double diff = step_base() - value;
  1217. if (is_down) {
  1218. value = diff - fmod(diff, allowed_value_step);
  1219. } else {
  1220. value = diff + fmod(diff, allowed_value_step);
  1221. }
  1222. } else {
  1223. // 1. Let n be the argument.
  1224. // 2. Let delta be the allowed value step multiplied by n.
  1225. double delta = allowed_value_step * n;
  1226. // 3. If the method invoked was the stepDown() method, negate delta.
  1227. if (is_down)
  1228. delta = -delta;
  1229. // 4. Let value be the result of adding delta to value.
  1230. value += delta;
  1231. }
  1232. // 8. If the element has a minimum, and value is less than that minimum, then set value to the smallest value that,
  1233. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is more than or equal to minimum.
  1234. if (maybe_minimum.has_value() && value < *maybe_minimum) {
  1235. value = AK::max(value, *maybe_minimum);
  1236. }
  1237. // 9. If the element has a maximum, and value is greater than that maximum, then set value to the largest value that,
  1238. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than or equal to maximum.
  1239. if (maybe_maximum.has_value() && value > *maybe_maximum) {
  1240. value = AK::min(value, *maybe_maximum);
  1241. }
  1242. // 10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping,
  1243. // or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then return.
  1244. if (is_down) {
  1245. if (value > value_before_stepping)
  1246. return {};
  1247. } else {
  1248. if (value < value_before_stepping)
  1249. return {};
  1250. }
  1251. // 11. Let value as string be the result of running the algorithm to convert a number to a string,
  1252. // as defined for the input element's type attribute's current state, on value.
  1253. auto value_as_string = covert_number_to_string(value);
  1254. // 12. Set the value of the element to value as string.
  1255. TRY(set_value(value_as_string));
  1256. return {};
  1257. }
  1258. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1259. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1260. {
  1261. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1262. return true;
  1263. }
  1264. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1265. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1266. {
  1267. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1268. return true;
  1269. }
  1270. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1271. void HTMLInputElement::set_custom_validity(String const& error)
  1272. {
  1273. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1274. return;
  1275. }
  1276. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  1277. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  1278. {
  1279. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  1280. return {};
  1281. }
  1282. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  1283. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, Optional<String> const& direction)
  1284. {
  1285. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  1286. return {};
  1287. }
  1288. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1289. {
  1290. // https://www.w3.org/TR/html-aria/#el-input-button
  1291. if (type_state() == TypeAttributeState::Button)
  1292. return ARIA::Role::button;
  1293. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1294. if (type_state() == TypeAttributeState::Checkbox)
  1295. return ARIA::Role::checkbox;
  1296. // https://www.w3.org/TR/html-aria/#el-input-email
  1297. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1298. return ARIA::Role::textbox;
  1299. // https://www.w3.org/TR/html-aria/#el-input-image
  1300. if (type_state() == TypeAttributeState::ImageButton)
  1301. return ARIA::Role::button;
  1302. // https://www.w3.org/TR/html-aria/#el-input-number
  1303. if (type_state() == TypeAttributeState::Number)
  1304. return ARIA::Role::spinbutton;
  1305. // https://www.w3.org/TR/html-aria/#el-input-radio
  1306. if (type_state() == TypeAttributeState::RadioButton)
  1307. return ARIA::Role::radio;
  1308. // https://www.w3.org/TR/html-aria/#el-input-range
  1309. if (type_state() == TypeAttributeState::Range)
  1310. return ARIA::Role::slider;
  1311. // https://www.w3.org/TR/html-aria/#el-input-reset
  1312. if (type_state() == TypeAttributeState::ResetButton)
  1313. return ARIA::Role::button;
  1314. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1315. if ((type_state() == TypeAttributeState::Text
  1316. || type_state() == TypeAttributeState::Search
  1317. || type_state() == TypeAttributeState::Telephone
  1318. || type_state() == TypeAttributeState::URL
  1319. || type_state() == TypeAttributeState::Email)
  1320. && has_attribute(AttributeNames::list))
  1321. return ARIA::Role::combobox;
  1322. // https://www.w3.org/TR/html-aria/#el-input-search
  1323. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1324. return ARIA::Role::textbox;
  1325. // https://www.w3.org/TR/html-aria/#el-input-submit
  1326. if (type_state() == TypeAttributeState::SubmitButton)
  1327. return ARIA::Role::button;
  1328. // https://www.w3.org/TR/html-aria/#el-input-tel
  1329. if (type_state() == TypeAttributeState::Telephone)
  1330. return ARIA::Role::textbox;
  1331. // https://www.w3.org/TR/html-aria/#el-input-text
  1332. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1333. return ARIA::Role::textbox;
  1334. // https://www.w3.org/TR/html-aria/#el-input-url
  1335. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1336. return ARIA::Role::textbox;
  1337. // https://www.w3.org/TR/html-aria/#el-input-color
  1338. // https://www.w3.org/TR/html-aria/#el-input-date
  1339. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1340. // https://www.w3.org/TR/html-aria/#el-input-file
  1341. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1342. // https://www.w3.org/TR/html-aria/#el-input-month
  1343. // https://www.w3.org/TR/html-aria/#el-input-password
  1344. // https://www.w3.org/TR/html-aria/#el-input-time
  1345. // https://www.w3.org/TR/html-aria/#el-input-week
  1346. return {};
  1347. }
  1348. bool HTMLInputElement::is_button() const
  1349. {
  1350. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1351. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1352. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1353. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1354. return type_state() == TypeAttributeState::SubmitButton
  1355. || type_state() == TypeAttributeState::ImageButton
  1356. || type_state() == TypeAttributeState::ResetButton
  1357. || type_state() == TypeAttributeState::Button;
  1358. }
  1359. bool HTMLInputElement::is_submit_button() const
  1360. {
  1361. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  1362. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  1363. return type_state() == TypeAttributeState::SubmitButton
  1364. || type_state() == TypeAttributeState::ImageButton;
  1365. }
  1366. bool HTMLInputElement::has_activation_behavior() const
  1367. {
  1368. return true;
  1369. }
  1370. void HTMLInputElement::activation_behavior(DOM::Event const& event)
  1371. {
  1372. // The activation behavior for input elements are these steps:
  1373. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  1374. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  1375. run_input_activation_behavior(event).release_value_but_fixme_should_propagate_errors();
  1376. }
  1377. bool HTMLInputElement::has_input_activation_behavior() const
  1378. {
  1379. switch (type_state()) {
  1380. case TypeAttributeState::Checkbox:
  1381. case TypeAttributeState::Color:
  1382. case TypeAttributeState::FileUpload:
  1383. case TypeAttributeState::ImageButton:
  1384. case TypeAttributeState::RadioButton:
  1385. case TypeAttributeState::ResetButton:
  1386. case TypeAttributeState::SubmitButton:
  1387. return true;
  1388. default:
  1389. return false;
  1390. }
  1391. }
  1392. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:event-change-2
  1393. bool HTMLInputElement::change_event_applies() const
  1394. {
  1395. switch (type_state()) {
  1396. case TypeAttributeState::Checkbox:
  1397. case TypeAttributeState::Color:
  1398. case TypeAttributeState::Date:
  1399. case TypeAttributeState::Email:
  1400. case TypeAttributeState::FileUpload:
  1401. case TypeAttributeState::LocalDateAndTime:
  1402. case TypeAttributeState::Month:
  1403. case TypeAttributeState::Number:
  1404. case TypeAttributeState::Password:
  1405. case TypeAttributeState::RadioButton:
  1406. case TypeAttributeState::Range:
  1407. case TypeAttributeState::Search:
  1408. case TypeAttributeState::Telephone:
  1409. case TypeAttributeState::Text:
  1410. case TypeAttributeState::Time:
  1411. case TypeAttributeState::URL:
  1412. case TypeAttributeState::Week:
  1413. return true;
  1414. default:
  1415. return false;
  1416. }
  1417. }
  1418. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasdate-3
  1419. bool HTMLInputElement::value_as_date_applies() const
  1420. {
  1421. switch (type_state()) {
  1422. case TypeAttributeState::Date:
  1423. case TypeAttributeState::Month:
  1424. case TypeAttributeState::Week:
  1425. case TypeAttributeState::Time:
  1426. return true;
  1427. default:
  1428. return false;
  1429. }
  1430. }
  1431. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasnumber-3
  1432. bool HTMLInputElement::value_as_number_applies() const
  1433. {
  1434. switch (type_state()) {
  1435. case TypeAttributeState::Date:
  1436. case TypeAttributeState::Month:
  1437. case TypeAttributeState::Week:
  1438. case TypeAttributeState::Time:
  1439. case TypeAttributeState::LocalDateAndTime:
  1440. case TypeAttributeState::Number:
  1441. case TypeAttributeState::Range:
  1442. return true;
  1443. default:
  1444. return false;
  1445. }
  1446. }
  1447. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-step-3
  1448. bool HTMLInputElement::step_applies() const
  1449. {
  1450. return value_as_number_applies();
  1451. }
  1452. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-stepup-3
  1453. bool HTMLInputElement::step_up_or_down_applies() const
  1454. {
  1455. return value_as_number_applies();
  1456. }
  1457. }