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