HTMLInputElement.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253
  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/Bindings/HTMLInputElementPrototype.h>
  13. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  14. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  15. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  16. #include <LibWeb/DOM/Document.h>
  17. #include <LibWeb/DOM/ElementFactory.h>
  18. #include <LibWeb/DOM/Event.h>
  19. #include <LibWeb/DOM/IDLEventListener.h>
  20. #include <LibWeb/DOM/ShadowRoot.h>
  21. #include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
  22. #include <LibWeb/HTML/BrowsingContext.h>
  23. #include <LibWeb/HTML/Dates.h>
  24. #include <LibWeb/HTML/DecodedImageData.h>
  25. #include <LibWeb/HTML/EventNames.h>
  26. #include <LibWeb/HTML/HTMLDivElement.h>
  27. #include <LibWeb/HTML/HTMLFormElement.h>
  28. #include <LibWeb/HTML/HTMLInputElement.h>
  29. #include <LibWeb/HTML/Numbers.h>
  30. #include <LibWeb/HTML/Parser/HTMLParser.h>
  31. #include <LibWeb/HTML/Scripting/Environments.h>
  32. #include <LibWeb/HTML/SelectedFile.h>
  33. #include <LibWeb/HTML/SharedImageRequest.h>
  34. #include <LibWeb/HTML/ValidityState.h>
  35. #include <LibWeb/HTML/Window.h>
  36. #include <LibWeb/Infra/CharacterTypes.h>
  37. #include <LibWeb/Infra/Strings.h>
  38. #include <LibWeb/Layout/BlockContainer.h>
  39. #include <LibWeb/Layout/CheckBox.h>
  40. #include <LibWeb/Layout/ImageBox.h>
  41. #include <LibWeb/Layout/RadioButton.h>
  42. #include <LibWeb/MimeSniff/MimeType.h>
  43. #include <LibWeb/MimeSniff/Resource.h>
  44. #include <LibWeb/Namespace.h>
  45. #include <LibWeb/Page/Page.h>
  46. #include <LibWeb/UIEvents/EventNames.h>
  47. #include <LibWeb/UIEvents/MouseEvent.h>
  48. #include <LibWeb/WebIDL/DOMException.h>
  49. #include <LibWeb/WebIDL/ExceptionOr.h>
  50. namespace Web::HTML {
  51. JS_DEFINE_ALLOCATOR(HTMLInputElement);
  52. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  53. : HTMLElement(document, move(qualified_name))
  54. {
  55. }
  56. HTMLInputElement::~HTMLInputElement() = default;
  57. void HTMLInputElement::initialize(JS::Realm& realm)
  58. {
  59. Base::initialize(realm);
  60. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLInputElement);
  61. }
  62. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  63. {
  64. Base::visit_edges(visitor);
  65. visitor.visit(m_inner_text_element);
  66. visitor.visit(m_text_node);
  67. visitor.visit(m_placeholder_element);
  68. visitor.visit(m_placeholder_text_node);
  69. visitor.visit(m_color_well_element);
  70. visitor.visit(m_file_button);
  71. visitor.visit(m_file_label);
  72. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group);
  73. visitor.visit(m_selected_files);
  74. visitor.visit(m_slider_thumb);
  75. visitor.visit(m_image_request);
  76. }
  77. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-validity
  78. JS::NonnullGCPtr<ValidityState const> HTMLInputElement::validity() const
  79. {
  80. auto& vm = this->vm();
  81. auto& realm = this->realm();
  82. dbgln("FIXME: Implement validity attribute getter");
  83. return vm.heap().allocate<ValidityState>(realm, realm);
  84. }
  85. JS::GCPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  86. {
  87. if (type_state() == TypeAttributeState::Hidden)
  88. return nullptr;
  89. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton)
  90. return heap().allocate_without_realm<Layout::BlockContainer>(document(), this, move(style));
  91. if (type_state() == TypeAttributeState::ImageButton)
  92. return heap().allocate_without_realm<Layout::ImageBox>(document(), *this, move(style), *this);
  93. if (type_state() == TypeAttributeState::Checkbox)
  94. return heap().allocate_without_realm<Layout::CheckBox>(document(), *this, move(style));
  95. if (type_state() == TypeAttributeState::RadioButton)
  96. return heap().allocate_without_realm<Layout::RadioButton>(document(), *this, move(style));
  97. return Element::create_layout_node_for_display_type(document(), style->display(), style, this);
  98. }
  99. void HTMLInputElement::adjust_computed_style(CSS::StyleProperties& style)
  100. {
  101. if (type_state() == TypeAttributeState::Hidden || type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton || type_state() == TypeAttributeState::ImageButton || type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton)
  102. return;
  103. // AD-HOC: We rewrite `display: inline` to `display: inline-block`.
  104. // This is required for the internal shadow tree to work correctly in layout.
  105. if (style.display().is_inline_outside() && style.display().is_flow_inside())
  106. style.set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::InlineBlock)));
  107. if (type_state() != TypeAttributeState::FileUpload) {
  108. if (style.property(CSS::PropertyID::Width)->has_auto())
  109. style.set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length(size(), CSS::Length::Type::Ch)));
  110. }
  111. }
  112. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  113. {
  114. if (m_checked == checked)
  115. return;
  116. // The dirty checkedness flag must be initially set to false when the element is created,
  117. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  118. if (change_source == ChangeSource::User)
  119. m_dirty_checkedness = true;
  120. m_checked = checked;
  121. // This element's :checked pseudo-class could be used in a sibling's sibling-selector,
  122. // so we need to invalidate the style of all siblings.
  123. if (parent()) {
  124. parent()->for_each_child([&](auto& child) {
  125. child.invalidate_style();
  126. return IterationDecision::Continue;
  127. });
  128. }
  129. }
  130. void HTMLInputElement::set_checked_binding(bool checked)
  131. {
  132. if (type_state() == TypeAttributeState::RadioButton) {
  133. if (checked)
  134. set_checked_within_group();
  135. else
  136. set_checked(false, ChangeSource::Programmatic);
  137. } else {
  138. set_checked(checked, ChangeSource::Programmatic);
  139. }
  140. }
  141. // https://html.spec.whatwg.org/multipage/input.html#dom-input-indeterminate
  142. void HTMLInputElement::set_indeterminate(bool value)
  143. {
  144. // On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.
  145. m_indeterminate = value;
  146. }
  147. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  148. JS::GCPtr<FileAPI::FileList> HTMLInputElement::files()
  149. {
  150. // On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
  151. // The same object must be returned until the list of selected files changes.
  152. // If the IDL attribute does not apply, then it must instead return null.
  153. if (m_type != TypeAttributeState::FileUpload)
  154. return nullptr;
  155. if (!m_selected_files)
  156. m_selected_files = FileAPI::FileList::create(realm(), {});
  157. return m_selected_files;
  158. }
  159. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  160. void HTMLInputElement::set_files(JS::GCPtr<FileAPI::FileList> files)
  161. {
  162. // 1. If the IDL attribute does not apply or the given value is null, then return.
  163. if (m_type != TypeAttributeState::FileUpload || files == nullptr)
  164. return;
  165. // 2. Replace the element's selected files with the given value.
  166. m_selected_files = files;
  167. }
  168. // https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
  169. FileFilter HTMLInputElement::parse_accept_attribute() const
  170. {
  171. FileFilter filter;
  172. // If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII
  173. // case-insensitive match for one of the following:
  174. auto accept = get_attribute_value(HTML::AttributeNames::accept);
  175. accept.bytes_as_string_view().for_each_split_view(',', SplitBehavior::Nothing, [&](StringView value) {
  176. // The string "audio/*"
  177. // Indicates that sound files are accepted.
  178. if (value.equals_ignoring_ascii_case("audio/*"sv))
  179. filter.add_filter(FileFilter::FileType::Audio);
  180. // The string "video/*"
  181. // Indicates that video files are accepted.
  182. if (value.equals_ignoring_ascii_case("video/*"sv))
  183. filter.add_filter(FileFilter::FileType::Video);
  184. // The string "image/*"
  185. // Indicates that image files are accepted.
  186. if (value.equals_ignoring_ascii_case("image/*"sv))
  187. filter.add_filter(FileFilter::FileType::Image);
  188. // A valid MIME type string with no parameters
  189. // Indicates that files of the specified type are accepted.
  190. else if (auto mime_type = MUST(MimeSniff::MimeType::parse(value)); mime_type.has_value() && mime_type->parameters().is_empty())
  191. filter.add_filter(FileFilter::MimeType { mime_type->essence() });
  192. // A string whose first character is a U+002E FULL STOP character (.)
  193. // Indicates that files with the specified file extension are accepted.
  194. else if (value.starts_with('.'))
  195. filter.add_filter(FileFilter::Extension { MUST(String::from_utf8(value.substring_view(1))) });
  196. });
  197. return filter;
  198. }
  199. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  200. void HTMLInputElement::update_the_file_selection(JS::NonnullGCPtr<FileAPI::FileList> files)
  201. {
  202. // 1. Queue an element task on the user interaction task source given element and the following steps:
  203. queue_an_element_task(Task::Source::UserInteraction, [this, files] {
  204. // 1. Update element's selected files so that it represents the user's selection.
  205. this->set_files(files.ptr());
  206. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  207. auto input_event = DOM::Event::create(this->realm(), EventNames::input, { .bubbles = true, .composed = true });
  208. this->dispatch_event(input_event);
  209. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  210. auto change_event = DOM::Event::create(this->realm(), EventNames::change, { .bubbles = true });
  211. this->dispatch_event(change_event);
  212. });
  213. }
  214. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  215. static void show_the_picker_if_applicable(HTMLInputElement& element)
  216. {
  217. // To show the picker, if applicable for an input element element:
  218. // 1. If element's relevant global object does not have transient activation, then return.
  219. auto& global_object = relevant_global_object(element);
  220. if (!is<HTML::Window>(global_object))
  221. return;
  222. auto& relevant_global_object = static_cast<HTML::Window&>(global_object);
  223. if (!relevant_global_object.has_transient_activation())
  224. return;
  225. // 2. If element is not mutable, then return.
  226. if (!element.is_mutable())
  227. return;
  228. // 3. Consume user activation given element's relevant global object.
  229. relevant_global_object.consume_user_activation();
  230. // 4. If element's type attribute is in the File Upload state, then run these steps in parallel:
  231. if (element.type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
  232. // NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
  233. // 1. Optionally, wait until any prior execution of this algorithm has terminated.
  234. // 2. Display a prompt to the user requesting that the user specify some files.
  235. // If the multiple attribute is not set on element, there must be no more than one file selected; otherwise, any number may be selected.
  236. // 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.
  237. // 3. Wait for the user to have made their selection.
  238. // 4. If the user dismissed the prompt without changing their selection,
  239. // then queue an element task on the user interaction task source given element to fire an event named cancel at element,
  240. // with the bubbles attribute initialized to true.
  241. // 5. Otherwise, update the file selection for element.
  242. auto accepted_file_types = element.parse_accept_attribute();
  243. auto allow_multiple_files = element.has_attribute(HTML::AttributeNames::multiple) ? AllowMultipleFiles::Yes : AllowMultipleFiles::No;
  244. auto weak_element = element.make_weak_ptr<HTMLInputElement>();
  245. element.document().browsing_context()->top_level_browsing_context()->page().did_request_file_picker(weak_element, move(accepted_file_types), allow_multiple_files);
  246. return;
  247. }
  248. // 5. Otherwise, the user agent should show any relevant user interface for selecting a value for element,
  249. // 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.)
  250. // If such a user interface is shown, it must respect the requirements stated in the relevant parts of the specification for how element
  251. // behaves given its type attribute state. (For example, various sections describe restrictions on the resulting value string.)
  252. // This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
  253. // (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.)
  254. if (element.type_state() == HTMLInputElement::TypeAttributeState::Color) {
  255. auto weak_element = element.make_weak_ptr<HTMLInputElement>();
  256. 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)));
  257. }
  258. }
  259. // https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
  260. WebIDL::ExceptionOr<void> HTMLInputElement::show_picker()
  261. {
  262. // The showPicker() method steps are:
  263. // 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
  264. if (!m_is_mutable)
  265. return WebIDL::InvalidStateError::create(realm(), "Element is not mutable"_fly_string);
  266. // 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
  267. // and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
  268. // NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
  269. // and has never been guarded by an origin check.
  270. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(*this).top_level_origin)
  271. && m_type != TypeAttributeState::FileUpload && m_type != TypeAttributeState::Color) {
  272. return WebIDL::SecurityError::create(realm(), "Cross origin pickers are not allowed"_fly_string);
  273. }
  274. // 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
  275. // FIXME: The global object we get here should probably not need casted to Window to check for transient activation
  276. auto& global_object = relevant_global_object(*this);
  277. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation()) {
  278. return WebIDL::NotAllowedError::create(realm(), "Too long since user activation to show picker"_fly_string);
  279. }
  280. // 4. Show the picker, if applicable, for this.
  281. show_the_picker_if_applicable(*this);
  282. return {};
  283. }
  284. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  285. WebIDL::ExceptionOr<void> HTMLInputElement::run_input_activation_behavior(DOM::Event const& event)
  286. {
  287. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  288. // 1. If the element is not connected, then return.
  289. if (!is_connected())
  290. return {};
  291. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  292. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  293. input_event->set_bubbles(true);
  294. input_event->set_composed(true);
  295. dispatch_event(input_event);
  296. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  297. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  298. change_event->set_bubbles(true);
  299. dispatch_event(*change_event);
  300. } else if (type_state() == TypeAttributeState::SubmitButton) {
  301. JS::GCPtr<HTMLFormElement> form;
  302. // 1. If the element does not have a form owner, then return.
  303. if (!(form = this->form()))
  304. return {};
  305. // 2. If the element's node document is not fully active, then return.
  306. if (!document().is_fully_active())
  307. return {};
  308. // 3. Submit the element's form owner from the element with userInvolvement set to event's user navigation involvement.
  309. TRY(form->submit_form(*this, { .user_involvement = user_navigation_involvement(event) }));
  310. } else if (type_state() == TypeAttributeState::FileUpload || type_state() == TypeAttributeState::Color) {
  311. show_the_picker_if_applicable(*this);
  312. }
  313. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):input-activation-behavior
  314. else if (type_state() == TypeAttributeState::ImageButton) {
  315. // 1. If the element does not have a form owner, then return.
  316. auto* form = this->form();
  317. if (!form)
  318. return {};
  319. // 2. If the element's node document is not fully active, then return.
  320. if (!document().is_fully_active())
  321. return {};
  322. // 3. If the user activated the control while explicitly selecting a coordinate, then set the element's selected
  323. // coordinate to that coordinate.
  324. if (event.is_trusted() && is<UIEvents::MouseEvent>(event)) {
  325. auto const& mouse_event = static_cast<UIEvents::MouseEvent const&>(event);
  326. CSSPixels x { mouse_event.offset_x() };
  327. CSSPixels y { mouse_event.offset_y() };
  328. m_selected_coordinate = { x.to_int(), y.to_int() };
  329. }
  330. // 4. Submit the element's form owner from the element with userInvolvement set to event's user navigation involvement.
  331. TRY(form->submit_form(*this, { .user_involvement = user_navigation_involvement(event) }));
  332. }
  333. return {};
  334. }
  335. void HTMLInputElement::did_edit_text_node(Badge<Navigable>)
  336. {
  337. // 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.
  338. m_value = value_sanitization_algorithm(m_text_node->data());
  339. m_dirty_value = true;
  340. m_has_uncommitted_changes = true;
  341. update_placeholder_visibility();
  342. user_interaction_did_change_input_value();
  343. }
  344. void HTMLInputElement::did_pick_color(Optional<Color> picked_color, ColorPickerUpdateState state)
  345. {
  346. if (type_state() == TypeAttributeState::Color && picked_color.has_value()) {
  347. // then when the user changes the element's value
  348. m_value = value_sanitization_algorithm(picked_color.value().to_string_without_alpha());
  349. m_dirty_value = true;
  350. update_color_well_element();
  351. // the user agent must queue an element task on the user interaction task source
  352. user_interaction_did_change_input_value();
  353. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  354. // [...] any time the user commits the change, the user agent must queue an element task on the user interaction task source
  355. if (state == ColorPickerUpdateState::Closed) {
  356. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  357. // given the input element
  358. // FIXME: to set its user interacted to true
  359. // and fire an event named change at the input element, with the bubbles attribute initialized to true.
  360. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  361. change_event->set_bubbles(true);
  362. dispatch_event(*change_event);
  363. });
  364. }
  365. }
  366. }
  367. void HTMLInputElement::did_select_files(Span<SelectedFile> selected_files)
  368. {
  369. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  370. // 4. If the user dismissed the prompt without changing their selection, then queue an element task on the user
  371. // interaction task source given element to fire an event named cancel at element, with the bubbles attribute
  372. // initialized to true.
  373. if (selected_files.is_empty()) {
  374. queue_an_element_task(HTML::Task::Source::UserInteraction, [this]() {
  375. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::cancel, { .bubbles = true }));
  376. });
  377. return;
  378. }
  379. Vector<JS::NonnullGCPtr<FileAPI::File>> files;
  380. files.ensure_capacity(selected_files.size());
  381. for (auto& selected_file : selected_files) {
  382. auto contents = selected_file.take_contents();
  383. auto mime_type = MUST(MimeSniff::Resource::sniff(contents));
  384. auto blob = FileAPI::Blob::create(realm(), move(contents), mime_type.essence());
  385. // FIXME: The FileAPI should use ByteString for file names.
  386. auto file_name = MUST(String::from_byte_string(selected_file.name()));
  387. // FIXME: Fill in other fields (e.g. last_modified).
  388. FileAPI::FilePropertyBag options {};
  389. options.type = mime_type.essence();
  390. auto file = MUST(FileAPI::File::create(realm(), { JS::make_handle(blob) }, file_name, move(options)));
  391. files.unchecked_append(file);
  392. }
  393. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  394. // 1. Queue an element task on the user interaction task source given element and the following steps:
  395. queue_an_element_task(HTML::Task::Source::UserInteraction, [this, files = move(files)]() mutable {
  396. // 1. Update element's selected files so that it represents the user's selection.
  397. m_selected_files = FileAPI::FileList::create(realm(), move(files));
  398. update_file_input_shadow_tree();
  399. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  400. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::input, { .bubbles = true, .composed = true }));
  401. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  402. dispatch_event(DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true }));
  403. });
  404. }
  405. String HTMLInputElement::value() const
  406. {
  407. switch (value_attribute_mode()) {
  408. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  409. case ValueAttributeMode::Value:
  410. // Return the current value of the element.
  411. return m_value;
  412. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
  413. case ValueAttributeMode::Default:
  414. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return
  415. // the empty string.
  416. return get_attribute_value(AttributeNames::value);
  417. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
  418. case ValueAttributeMode::DefaultOn:
  419. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return
  420. // the string "on".
  421. return get_attribute(AttributeNames::value).value_or("on"_string);
  422. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  423. case ValueAttributeMode::Filename:
  424. // On getting, return the string "C:\fakepath\" followed by the name of the first file in the list of selected
  425. // files, if any, or the empty string if the list is empty.
  426. if (m_selected_files && m_selected_files->item(0))
  427. return MUST(String::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name()));
  428. return String {};
  429. }
  430. VERIFY_NOT_REACHED();
  431. }
  432. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(String const& value)
  433. {
  434. auto& realm = this->realm();
  435. switch (value_attribute_mode()) {
  436. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  437. case ValueAttributeMode::Value: {
  438. // 1. Let oldValue be the element's value.
  439. auto old_value = move(m_value);
  440. // 2. Set the element's value to the new value.
  441. // NOTE: For the TextNode this is done as part of step 4 below.
  442. // 3. Set the element's dirty value flag to true.
  443. m_dirty_value = true;
  444. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  445. m_value = value_sanitization_algorithm(value);
  446. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  447. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  448. // text control, unselecting any selected text and resetting the selection direction to "none".
  449. if (m_value != old_value) {
  450. if (m_text_node) {
  451. m_text_node->set_data(m_value);
  452. update_placeholder_visibility();
  453. if (auto navigable = document().navigable())
  454. navigable->set_cursor_position(DOM::Position::create(realm, *m_text_node, m_text_node->data().bytes().size()));
  455. }
  456. update_shadow_tree();
  457. }
  458. break;
  459. }
  460. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
  461. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
  462. case ValueAttributeMode::Default:
  463. case ValueAttributeMode::DefaultOn:
  464. // On setting, set the value of the element's value content attribute to the new value.
  465. TRY(set_attribute(HTML::AttributeNames::value, value));
  466. break;
  467. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  468. case ValueAttributeMode::Filename:
  469. // On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.
  470. if (!value.is_empty())
  471. return WebIDL::InvalidStateError::create(realm, "Setting value of input type file to non-empty string"_fly_string);
  472. m_selected_files = nullptr;
  473. break;
  474. }
  475. return {};
  476. }
  477. void HTMLInputElement::commit_pending_changes()
  478. {
  479. // The change event fires when the value is committed, if that makes sense for the control,
  480. // or else when the control loses focus
  481. switch (type_state()) {
  482. case TypeAttributeState::Email:
  483. case TypeAttributeState::Password:
  484. case TypeAttributeState::Search:
  485. case TypeAttributeState::Telephone:
  486. case TypeAttributeState::Text:
  487. case TypeAttributeState::URL:
  488. if (!m_has_uncommitted_changes)
  489. return;
  490. break;
  491. default:
  492. break;
  493. }
  494. m_has_uncommitted_changes = false;
  495. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true });
  496. dispatch_event(change_event);
  497. }
  498. void HTMLInputElement::update_placeholder_visibility()
  499. {
  500. if (!m_placeholder_element)
  501. return;
  502. if (this->placeholder_value().has_value()) {
  503. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  504. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  505. } else {
  506. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  507. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  508. }
  509. }
  510. void HTMLInputElement::update_text_input_shadow_tree()
  511. {
  512. if (m_text_node) {
  513. m_text_node->set_data(m_value);
  514. update_placeholder_visibility();
  515. }
  516. }
  517. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  518. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  519. {
  520. switch (state) {
  521. case HTML::HTMLInputElement::TypeAttributeState::Text:
  522. case HTML::HTMLInputElement::TypeAttributeState::Search:
  523. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  524. case HTML::HTMLInputElement::TypeAttributeState::URL:
  525. case HTML::HTMLInputElement::TypeAttributeState::Email:
  526. case HTML::HTMLInputElement::TypeAttributeState::Password:
  527. case HTML::HTMLInputElement::TypeAttributeState::Date:
  528. case HTML::HTMLInputElement::TypeAttributeState::Month:
  529. case HTML::HTMLInputElement::TypeAttributeState::Week:
  530. case HTML::HTMLInputElement::TypeAttributeState::Time:
  531. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  532. case HTML::HTMLInputElement::TypeAttributeState::Number:
  533. return true;
  534. default:
  535. return false;
  536. }
  537. }
  538. // https://html.spec.whatwg.org/multipage/input.html#attr-input-maxlength
  539. void HTMLInputElement::handle_maxlength_attribute()
  540. {
  541. if (m_text_node) {
  542. auto max_length = this->max_length();
  543. if (max_length >= 0) {
  544. m_text_node->set_max_length(max_length);
  545. } else {
  546. m_text_node->set_max_length({});
  547. }
  548. }
  549. }
  550. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  551. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  552. {
  553. // 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.
  554. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  555. if (m_text_node)
  556. m_text_node->set_always_editable(m_is_mutable);
  557. }
  558. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  559. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  560. {
  561. switch (state) {
  562. case HTML::HTMLInputElement::TypeAttributeState::Text:
  563. case HTML::HTMLInputElement::TypeAttributeState::Search:
  564. case HTML::HTMLInputElement::TypeAttributeState::URL:
  565. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  566. case HTML::HTMLInputElement::TypeAttributeState::Email:
  567. case HTML::HTMLInputElement::TypeAttributeState::Password:
  568. case HTML::HTMLInputElement::TypeAttributeState::Number:
  569. return true;
  570. default:
  571. return false;
  572. }
  573. }
  574. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  575. String HTMLInputElement::placeholder() const
  576. {
  577. auto maybe_placeholder = get_attribute(HTML::AttributeNames::placeholder);
  578. if (!maybe_placeholder.has_value())
  579. return String {};
  580. auto placeholder = *maybe_placeholder;
  581. // The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
  582. StringBuilder builder;
  583. for (auto c : placeholder.bytes_as_string_view()) {
  584. if (c != '\r' && c != '\n')
  585. builder.append(c);
  586. }
  587. return MUST(builder.to_string());
  588. }
  589. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  590. Optional<String> HTMLInputElement::placeholder_value() const
  591. {
  592. if (!m_text_node || !m_text_node->data().is_empty())
  593. return {};
  594. if (!is_allowed_to_have_placeholder(type_state()))
  595. return {};
  596. if (!has_attribute(HTML::AttributeNames::placeholder))
  597. return {};
  598. return placeholder();
  599. }
  600. void HTMLInputElement::create_shadow_tree_if_needed()
  601. {
  602. if (shadow_root())
  603. return;
  604. switch (type_state()) {
  605. case TypeAttributeState::Hidden:
  606. case TypeAttributeState::RadioButton:
  607. case TypeAttributeState::Checkbox:
  608. break;
  609. case TypeAttributeState::Button:
  610. case TypeAttributeState::SubmitButton:
  611. case TypeAttributeState::ResetButton:
  612. create_button_input_shadow_tree();
  613. break;
  614. case TypeAttributeState::ImageButton:
  615. break;
  616. case TypeAttributeState::Color:
  617. create_color_input_shadow_tree();
  618. break;
  619. case TypeAttributeState::FileUpload:
  620. create_file_input_shadow_tree();
  621. break;
  622. case TypeAttributeState::Range:
  623. create_range_input_shadow_tree();
  624. break;
  625. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  626. default:
  627. create_text_input_shadow_tree();
  628. break;
  629. }
  630. }
  631. void HTMLInputElement::update_shadow_tree()
  632. {
  633. switch (type_state()) {
  634. case TypeAttributeState::Color:
  635. update_color_well_element();
  636. break;
  637. case TypeAttributeState::FileUpload:
  638. update_file_input_shadow_tree();
  639. break;
  640. case TypeAttributeState::Range:
  641. update_slider_thumb_element();
  642. break;
  643. default:
  644. update_text_input_shadow_tree();
  645. break;
  646. }
  647. }
  648. void HTMLInputElement::create_button_input_shadow_tree()
  649. {
  650. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  651. set_shadow_root(shadow_root);
  652. m_text_node = heap().allocate<DOM::Text>(realm(), document(), value());
  653. MUST(shadow_root->append_child(*m_text_node));
  654. }
  655. void HTMLInputElement::create_text_input_shadow_tree()
  656. {
  657. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  658. set_shadow_root(shadow_root);
  659. auto initial_value = m_value;
  660. auto element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  661. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  662. display: flex;
  663. height: 100%;
  664. align-items: center;
  665. white-space: pre;
  666. border: none;
  667. padding: 1px 2px;
  668. )~~~"_string));
  669. MUST(shadow_root->append_child(element));
  670. m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  671. m_placeholder_element->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::Placeholder);
  672. // https://www.w3.org/TR/css-ui-4/#input-rules
  673. MUST(m_placeholder_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  674. width: 100%;
  675. height: 1lh;
  676. align-items: center;
  677. text-overflow: clip;
  678. white-space: nowrap;
  679. )~~~"_string));
  680. MUST(element->append_child(*m_placeholder_element));
  681. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), String {});
  682. m_placeholder_text_node->set_data(placeholder());
  683. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  684. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  685. // https://www.w3.org/TR/css-ui-4/#input-rules
  686. m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  687. MUST(m_inner_text_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  688. width: 100%;
  689. height: 1lh;
  690. align-items: center;
  691. text-overflow: clip;
  692. white-space: nowrap;
  693. )~~~"_string));
  694. MUST(element->append_child(*m_inner_text_element));
  695. m_text_node = heap().allocate<DOM::Text>(realm(), document(), move(initial_value));
  696. if (type_state() == TypeAttributeState::FileUpload) {
  697. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  698. m_text_node->set_always_editable(false);
  699. } else {
  700. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  701. }
  702. m_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  703. if (type_state() == TypeAttributeState::Password)
  704. m_text_node->set_is_password_input({}, true);
  705. handle_maxlength_attribute();
  706. MUST(m_inner_text_element->append_child(*m_text_node));
  707. update_placeholder_visibility();
  708. if (type_state() == TypeAttributeState::Number) {
  709. // Up button
  710. auto up_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  711. // FIXME: This cursor property doesn't work
  712. MUST(up_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  713. padding: 0;
  714. cursor: default;
  715. )~~~"_string));
  716. 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));
  717. MUST(element->append_child(up_button));
  718. auto mouseup_callback_function = JS::NativeFunction::create(
  719. realm(), [this](JS::VM&) {
  720. commit_pending_changes();
  721. return JS::js_undefined();
  722. },
  723. 0, "", &realm());
  724. auto mouseup_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*mouseup_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  725. DOM::AddEventListenerOptions mouseup_listener_options;
  726. mouseup_listener_options.once = true;
  727. auto up_callback_function = JS::NativeFunction::create(
  728. realm(), [this](JS::VM&) {
  729. MUST(step_up());
  730. user_interaction_did_change_input_value();
  731. return JS::js_undefined();
  732. },
  733. 0, "", &realm());
  734. auto step_up_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*up_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  735. up_button->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), step_up_callback));
  736. up_button->add_event_listener_without_options(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback));
  737. // Down button
  738. auto down_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  739. MUST(down_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  740. padding: 0;
  741. cursor: default;
  742. )~~~"_string));
  743. 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));
  744. MUST(element->append_child(down_button));
  745. auto down_callback_function = JS::NativeFunction::create(
  746. realm(), [this](JS::VM&) {
  747. MUST(step_down());
  748. user_interaction_did_change_input_value();
  749. return JS::js_undefined();
  750. },
  751. 0, "", &realm());
  752. auto step_down_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*down_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  753. down_button->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), step_down_callback));
  754. down_button->add_event_listener_without_options(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback));
  755. }
  756. }
  757. void HTMLInputElement::create_color_input_shadow_tree()
  758. {
  759. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  760. auto color = value_sanitization_algorithm(m_value);
  761. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  762. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  763. width: fit-content;
  764. height: fit-content;
  765. padding: 4px;
  766. border: 1px solid ButtonBorder;
  767. background-color: ButtonFace;
  768. )~~~"_string));
  769. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  770. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  771. width: 24px;
  772. height: 24px;
  773. border: 1px solid ButtonBorder;
  774. box-sizing: border-box;
  775. )~~~"_string));
  776. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  777. MUST(border->append_child(*m_color_well_element));
  778. MUST(shadow_root->append_child(border));
  779. set_shadow_root(shadow_root);
  780. }
  781. void HTMLInputElement::update_color_well_element()
  782. {
  783. if (!m_color_well_element)
  784. return;
  785. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  786. }
  787. void HTMLInputElement::create_file_input_shadow_tree()
  788. {
  789. auto& realm = this->realm();
  790. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm, document(), *this, Bindings::ShadowRootMode::Closed);
  791. m_file_button = DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  792. m_file_label = DOM::create_element(document(), HTML::TagNames::label, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  793. MUST(m_file_label->set_attribute(HTML::AttributeNames::style, "padding-left: 4px;"_string));
  794. auto on_button_click = [this](JS::VM&) {
  795. show_the_picker_if_applicable(*this);
  796. return JS::js_undefined();
  797. };
  798. auto on_button_click_function = JS::NativeFunction::create(realm, move(on_button_click), 0, "", &realm);
  799. auto on_button_click_callback = realm.heap().allocate_without_realm<WebIDL::CallbackType>(on_button_click_function, Bindings::host_defined_environment_settings_object(realm));
  800. m_file_button->add_event_listener_without_options(UIEvents::EventNames::click, DOM::IDLEventListener::create(realm, on_button_click_callback));
  801. update_file_input_shadow_tree();
  802. MUST(shadow_root->append_child(*m_file_button));
  803. MUST(shadow_root->append_child(*m_file_label));
  804. set_shadow_root(shadow_root);
  805. }
  806. void HTMLInputElement::update_file_input_shadow_tree()
  807. {
  808. if (!m_file_button || !m_file_label)
  809. return;
  810. auto files_label = has_attribute(HTML::AttributeNames::multiple) ? "files"sv : "file"sv;
  811. m_file_button->set_text_content(MUST(String::formatted("Select {}...", files_label)));
  812. if (m_selected_files && m_selected_files->length() > 0) {
  813. if (m_selected_files->length() == 1)
  814. m_file_label->set_text_content(m_selected_files->item(0)->name());
  815. else
  816. m_file_label->set_text_content(MUST(String::formatted("{} files selected.", m_selected_files->length())));
  817. } else {
  818. m_file_label->set_text_content(MUST(String::formatted("No {} selected.", files_label)));
  819. }
  820. document().invalidate_layout();
  821. }
  822. void HTMLInputElement::create_range_input_shadow_tree()
  823. {
  824. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  825. set_shadow_root(shadow_root);
  826. auto slider_runnable_track = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  827. slider_runnable_track->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderRunnableTrack);
  828. MUST(shadow_root->append_child(slider_runnable_track));
  829. m_slider_thumb = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  830. m_slider_thumb->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderThumb);
  831. MUST(slider_runnable_track->append_child(*m_slider_thumb));
  832. update_slider_thumb_element();
  833. auto keydown_callback_function = JS::NativeFunction::create(
  834. realm(), [this](JS::VM& vm) {
  835. auto key = MUST(vm.argument(0).get(vm, "key")).as_string().utf8_string();
  836. if (key == "ArrowLeft" || key == "ArrowDown")
  837. MUST(step_down());
  838. if (key == "PageDown")
  839. MUST(step_down(10));
  840. if (key == "ArrowRight" || key == "ArrowUp")
  841. MUST(step_up());
  842. if (key == "PageUp")
  843. MUST(step_up(10));
  844. user_interaction_did_change_input_value();
  845. return JS::js_undefined();
  846. },
  847. 0, "", &realm());
  848. auto keydown_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*keydown_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  849. add_event_listener_without_options(UIEvents::EventNames::keydown, DOM::IDLEventListener::create(realm(), keydown_callback));
  850. auto wheel_callback_function = JS::NativeFunction::create(
  851. realm(), [this](JS::VM& vm) {
  852. auto deltaY = MUST(vm.argument(0).get(vm, "deltaY")).as_i32();
  853. if (deltaY > 0) {
  854. MUST(step_down());
  855. } else {
  856. MUST(step_up());
  857. }
  858. user_interaction_did_change_input_value();
  859. return JS::js_undefined();
  860. },
  861. 0, "", &realm());
  862. auto wheel_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*wheel_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  863. add_event_listener_without_options(UIEvents::EventNames::wheel, DOM::IDLEventListener::create(realm(), wheel_callback));
  864. auto update_slider_by_mouse = [this](JS::VM& vm) {
  865. auto client_x = MUST(vm.argument(0).get(vm, "clientX")).as_double();
  866. auto rect = get_bounding_client_rect();
  867. double minimum = *min();
  868. double maximum = *max();
  869. // FIXME: Snap new value to input steps
  870. MUST(set_value_as_number(clamp(round(((client_x - rect->left()) / rect->width()) * (maximum - minimum) + minimum), minimum, maximum)));
  871. user_interaction_did_change_input_value();
  872. };
  873. auto mousedown_callback_function = JS::NativeFunction::create(
  874. realm(), [this, update_slider_by_mouse](JS::VM& vm) {
  875. update_slider_by_mouse(vm);
  876. auto mousemove_callback_function = JS::NativeFunction::create(
  877. realm(), [update_slider_by_mouse](JS::VM& vm) {
  878. update_slider_by_mouse(vm);
  879. return JS::js_undefined();
  880. },
  881. 0, "", &realm());
  882. auto mousemove_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*mousemove_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  883. auto mousemove_listener = DOM::IDLEventListener::create(realm(), mousemove_callback);
  884. auto& window = static_cast<HTML::Window&>(relevant_global_object(*this));
  885. window.add_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);
  886. auto mouseup_callback_function = JS::NativeFunction::create(
  887. realm(), [this, mousemove_listener](JS::VM&) {
  888. auto& window = static_cast<HTML::Window&>(relevant_global_object(*this));
  889. window.remove_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);
  890. return JS::js_undefined();
  891. },
  892. 0, "", &realm());
  893. auto mouseup_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*mouseup_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  894. DOM::AddEventListenerOptions mouseup_listener_options;
  895. mouseup_listener_options.once = true;
  896. window.add_event_listener(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback), mouseup_listener_options);
  897. return JS::js_undefined();
  898. },
  899. 0, "", &realm());
  900. auto mousedown_callback = realm().heap().allocate_without_realm<WebIDL::CallbackType>(*mousedown_callback_function, Bindings::host_defined_environment_settings_object(realm()));
  901. add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), mousedown_callback));
  902. }
  903. void HTMLInputElement::user_interaction_did_change_input_value()
  904. {
  905. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  906. // For input elements without a defined input activation behavior, but to which these events apply,
  907. // and for which the user interface involves both interactive manipulation and an explicit commit action,
  908. // then when the user changes the element's value, the user agent must queue an element task on the user interaction task source
  909. // given the input element to fire an event named input at the input element, with the bubbles and composed attributes initialized to true,
  910. // and any time the user commits the change, the user agent must queue an element task on the user interaction task source given the input
  911. // element to set its user validity to true and fire an event named change at the input element, with the bubbles attribute initialized to true.
  912. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  913. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  914. input_event->set_bubbles(true);
  915. input_event->set_composed(true);
  916. dispatch_event(*input_event);
  917. });
  918. }
  919. void HTMLInputElement::update_slider_thumb_element()
  920. {
  921. if (!m_slider_thumb)
  922. return;
  923. double value = value_as_number();
  924. double minimum = *min();
  925. double maximum = *max();
  926. double position = (value - minimum) / (maximum - minimum) * 100;
  927. MUST(m_slider_thumb->style_for_bindings()->set_property(CSS::PropertyID::MarginLeft, MUST(String::formatted("{}%", position))));
  928. }
  929. void HTMLInputElement::did_receive_focus()
  930. {
  931. auto navigable = document().navigable();
  932. if (!navigable)
  933. return;
  934. if (!m_text_node)
  935. return;
  936. navigable->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  937. }
  938. void HTMLInputElement::did_lose_focus()
  939. {
  940. commit_pending_changes();
  941. }
  942. void HTMLInputElement::form_associated_element_attribute_changed(FlyString const& name, Optional<String> const& value)
  943. {
  944. if (name == HTML::AttributeNames::checked) {
  945. if (!value.has_value()) {
  946. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  947. // the user agent must set the checkedness of the element to false.
  948. if (!m_dirty_checkedness)
  949. set_checked(false, ChangeSource::Programmatic);
  950. } else {
  951. // When the checked content attribute is added, if the control does not have dirty checkedness,
  952. // the user agent must set the checkedness of the element to true
  953. if (!m_dirty_checkedness)
  954. set_checked(true, ChangeSource::Programmatic);
  955. }
  956. } else if (name == HTML::AttributeNames::type) {
  957. m_type = parse_type_attribute(value.value_or(String {}));
  958. set_shadow_root(nullptr);
  959. create_shadow_tree_if_needed();
  960. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):the-input-element-4
  961. // the input element's type attribute is changed back to the Image Button state, and the src attribute is present,
  962. // and its value has changed since the last time the type attribute was in the Image Button state
  963. if (type_state() == TypeAttributeState::ImageButton) {
  964. if (auto src = attribute(AttributeNames::src); src.has_value() && src != m_last_src_value)
  965. handle_src_attribute(*src).release_value_but_fixme_should_propagate_errors();
  966. }
  967. } else if (name == HTML::AttributeNames::value) {
  968. if (!m_dirty_value) {
  969. if (!value.has_value()) {
  970. m_value = String {};
  971. } else {
  972. m_value = value_sanitization_algorithm(*value);
  973. }
  974. update_shadow_tree();
  975. }
  976. } else if (name == HTML::AttributeNames::placeholder) {
  977. if (m_placeholder_text_node) {
  978. m_placeholder_text_node->set_data(placeholder());
  979. update_placeholder_visibility();
  980. }
  981. } else if (name == HTML::AttributeNames::readonly) {
  982. handle_readonly_attribute(value);
  983. } else if (name == HTML::AttributeNames::src) {
  984. handle_src_attribute(value.value_or({})).release_value_but_fixme_should_propagate_errors();
  985. } else if (name == HTML::AttributeNames::alt) {
  986. if (layout_node() && type_state() == TypeAttributeState::ImageButton)
  987. did_update_alt_text(verify_cast<Layout::ImageBox>(*layout_node()));
  988. } else if (name == HTML::AttributeNames::maxlength) {
  989. handle_maxlength_attribute();
  990. } else if (name == HTML::AttributeNames::multiple) {
  991. update_shadow_tree();
  992. }
  993. }
  994. // https://html.spec.whatwg.org/multipage/input.html#attr-input-src
  995. WebIDL::ExceptionOr<void> HTMLInputElement::handle_src_attribute(String const& value)
  996. {
  997. auto& realm = this->realm();
  998. auto& vm = realm.vm();
  999. if (type_state() != TypeAttributeState::ImageButton)
  1000. return {};
  1001. m_last_src_value = value;
  1002. // 1. Let url be the result of encoding-parsing a URL given the src attribute's value, relative to the element's
  1003. // node document.
  1004. auto url = document().parse_url(value);
  1005. // 2. If url is failure, then return.
  1006. if (!url.is_valid())
  1007. return {};
  1008. // 3. Let request be a new request whose URL is url, client is the element's node document's relevant settings
  1009. // object, destination is "image", initiator type is "input", credentials mode is "include", and whose
  1010. // use-URL-credentials flag is set.
  1011. auto request = Fetch::Infrastructure::Request::create(vm);
  1012. request->set_url(move(url));
  1013. request->set_client(&document().relevant_settings_object());
  1014. request->set_destination(Fetch::Infrastructure::Request::Destination::Image);
  1015. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Input);
  1016. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  1017. request->set_use_url_credentials(true);
  1018. // 4. Fetch request, with processResponseEndOfBody set to the following step given response response:
  1019. m_image_request = SharedImageRequest::get_or_create(realm, document().page(), request->url());
  1020. m_image_request->add_callbacks(
  1021. [this, &realm]() {
  1022. // 1. If the download was successful and the image is available, queue an element task on the user interaction
  1023. // task source given the input element to fire an event named load at the input element.
  1024. queue_an_element_task(HTML::Task::Source::UserInteraction, [this, &realm]() {
  1025. dispatch_event(DOM::Event::create(realm, HTML::EventNames::load));
  1026. });
  1027. m_load_event_delayer.clear();
  1028. document().invalidate_layout();
  1029. },
  1030. [this, &realm]() {
  1031. // 2. Otherwise, if the fetching process fails without a response from the remote server, or completes but the
  1032. // image is not a valid or supported image, then queue an element task on the user interaction task source
  1033. // given the input element to fire an event named error on the input element.
  1034. queue_an_element_task(HTML::Task::Source::UserInteraction, [this, &realm]() {
  1035. dispatch_event(DOM::Event::create(realm, HTML::EventNames::error));
  1036. });
  1037. m_load_event_delayer.clear();
  1038. });
  1039. if (m_image_request->needs_fetching()) {
  1040. m_image_request->fetch_image(realm, request);
  1041. }
  1042. // Fetching the image must delay the load event of the element's node document until the task that is queued by the
  1043. // networking task source once the resource has been fetched (defined below) has been run.
  1044. m_load_event_delayer.emplace(document());
  1045. return {};
  1046. }
  1047. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  1048. {
  1049. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  1050. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  1051. return HTMLInputElement::TypeAttributeState::state;
  1052. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  1053. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  1054. // The missing value default and the invalid value default are the Text state.
  1055. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  1056. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  1057. return HTMLInputElement::TypeAttributeState::Text;
  1058. }
  1059. StringView HTMLInputElement::type() const
  1060. {
  1061. // FIXME: This should probably be `Reflect` in the IDL.
  1062. switch (m_type) {
  1063. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  1064. case TypeAttributeState::state: \
  1065. return #keyword##sv;
  1066. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  1067. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  1068. }
  1069. VERIFY_NOT_REACHED();
  1070. }
  1071. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  1072. {
  1073. return set_attribute(HTML::AttributeNames::type, type);
  1074. }
  1075. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  1076. static bool is_valid_simple_color(StringView value)
  1077. {
  1078. // if it is exactly seven characters long,
  1079. if (value.length() != 7)
  1080. return false;
  1081. // and the first character is a U+0023 NUMBER SIGN character (#),
  1082. if (!value.starts_with('#'))
  1083. return false;
  1084. // and the remaining six characters are all ASCII hex digits
  1085. for (size_t i = 1; i < value.length(); i++)
  1086. if (!is_ascii_hex_digit(value[i]))
  1087. return false;
  1088. return true;
  1089. }
  1090. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  1091. String HTMLInputElement::value_sanitization_algorithm(String const& value) const
  1092. {
  1093. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  1094. // Strip newlines from the value.
  1095. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1096. StringBuilder builder;
  1097. for (auto c : value.bytes_as_string_view()) {
  1098. if (c != '\r' && c != '\n')
  1099. builder.append(c);
  1100. }
  1101. return MUST(builder.to_string());
  1102. }
  1103. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  1104. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  1105. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1106. StringBuilder builder;
  1107. for (auto c : value.bytes_as_string_view()) {
  1108. if (c != '\r' && c != '\n')
  1109. builder.append(c);
  1110. }
  1111. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  1112. }
  1113. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  1114. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  1115. // FIXME: handle the `multiple` attribute
  1116. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  1117. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1118. StringBuilder builder;
  1119. for (auto c : value.bytes_as_string_view()) {
  1120. if (c != '\r' && c != '\n')
  1121. builder.append(c);
  1122. }
  1123. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  1124. }
  1125. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  1126. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  1127. auto maybe_value = parse_floating_point_number(value);
  1128. if (!maybe_value.has_value() || !isfinite(maybe_value.value()))
  1129. return String {};
  1130. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  1131. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  1132. if (!is_valid_date_string(value))
  1133. return String {};
  1134. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  1135. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  1136. if (!is_valid_month_string(value))
  1137. return String {};
  1138. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  1139. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  1140. if (!is_valid_week_string(value))
  1141. return String {};
  1142. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  1143. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  1144. if (!is_valid_time_string(value))
  1145. return String {};
  1146. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  1147. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  1148. if (is_valid_local_date_and_time_string(value))
  1149. return normalize_local_date_and_time_string(value);
  1150. return String {};
  1151. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  1152. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  1153. // 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.
  1154. auto maybe_value = parse_floating_point_number(value);
  1155. if (!maybe_value.has_value() || !isfinite(maybe_value.value())) {
  1156. // 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.
  1157. auto minimum = *min();
  1158. auto maximum = *max();
  1159. if (maximum > minimum)
  1160. return JS::number_to_string(minimum);
  1161. return JS::number_to_string(minimum + (maximum - minimum) / 2);
  1162. }
  1163. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  1164. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  1165. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  1166. if (is_valid_simple_color(value))
  1167. return MUST(Infra::to_ascii_lowercase(value));
  1168. // otherwise, set it to the string "#000000".
  1169. return "#000000"_string;
  1170. }
  1171. return value;
  1172. }
  1173. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  1174. void HTMLInputElement::reset_algorithm()
  1175. {
  1176. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  1177. m_dirty_value = false;
  1178. m_dirty_checkedness = false;
  1179. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  1180. m_value = get_attribute_value(AttributeNames::value);
  1181. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  1182. m_checked = has_attribute(AttributeNames::checked);
  1183. // empty the list of selected files,
  1184. m_selected_files = FileAPI::FileList::create(realm(), {});
  1185. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  1186. m_value = value_sanitization_algorithm(m_value);
  1187. if (m_text_node) {
  1188. m_text_node->set_data(m_value);
  1189. update_placeholder_visibility();
  1190. }
  1191. update_shadow_tree();
  1192. }
  1193. void HTMLInputElement::form_associated_element_was_inserted()
  1194. {
  1195. create_shadow_tree_if_needed();
  1196. }
  1197. void HTMLInputElement::form_associated_element_was_removed(DOM::Node*)
  1198. {
  1199. set_shadow_root(nullptr);
  1200. }
  1201. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  1202. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  1203. {
  1204. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  1205. return !value_a.is_empty() && value_a == value_b;
  1206. };
  1207. // The radio button group that contains an input element a also contains all the
  1208. // other input elements b that fulfill all of the following conditions:
  1209. return (
  1210. // - Both a and b are in the same tree.
  1211. // - The input element b's type attribute is in the Radio Button state.
  1212. a.type_state() == b.type_state()
  1213. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  1214. // - Either a and b have the same form owner, or they both have no form owner.
  1215. && a.form() == b.form()
  1216. // - They both have a name attribute, their name attributes are not empty, and the
  1217. // value of a's name attribute equals the value of b's name attribute.
  1218. && a.name().has_value()
  1219. && b.name().has_value()
  1220. && non_empty_equals(a.name().value(), b.name().value()));
  1221. }
  1222. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  1223. void HTMLInputElement::set_checked_within_group()
  1224. {
  1225. if (checked())
  1226. return;
  1227. set_checked(true, ChangeSource::User);
  1228. // No point iterating the tree if we have an empty name.
  1229. if (!name().has_value() || name()->is_empty())
  1230. return;
  1231. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  1232. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  1233. element.set_checked(false, ChangeSource::User);
  1234. return TraversalDecision::Continue;
  1235. });
  1236. }
  1237. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  1238. void HTMLInputElement::legacy_pre_activation_behavior()
  1239. {
  1240. m_before_legacy_pre_activation_behavior_checked = checked();
  1241. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  1242. // 1. If this element's type attribute is in the Checkbox state, then set
  1243. // this element's checkedness to its opposite value (i.e. true if it is
  1244. // false, false if it is true) and set this element's indeterminate IDL
  1245. // attribute to false.
  1246. if (type_state() == TypeAttributeState::Checkbox) {
  1247. set_checked(!checked(), ChangeSource::User);
  1248. set_indeterminate(false);
  1249. }
  1250. // 2. If this element's type attribute is in the Radio Button state, then
  1251. // get a reference to the element in this element's radio button group that
  1252. // has its checkedness set to true, if any, and then set this element's
  1253. // checkedness to true.
  1254. if (type_state() == TypeAttributeState::RadioButton) {
  1255. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  1256. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  1257. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  1258. return TraversalDecision::Break;
  1259. }
  1260. return TraversalDecision::Continue;
  1261. });
  1262. set_checked_within_group();
  1263. }
  1264. }
  1265. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  1266. void HTMLInputElement::legacy_cancelled_activation_behavior()
  1267. {
  1268. // 1. If the element's type attribute is in the Checkbox state, then set the
  1269. // element's checkedness and the element's indeterminate IDL attribute back
  1270. // to the values they had before the legacy-pre-activation behavior was run.
  1271. if (type_state() == TypeAttributeState::Checkbox) {
  1272. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  1273. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  1274. }
  1275. // 2. If this element 's type attribute is in the Radio Button state, then
  1276. // if the element to which a reference was obtained in the
  1277. // legacy-pre-activation behavior, if any, is still in what is now this
  1278. // element' s radio button group, if it still has one, and if so, setting
  1279. // that element 's checkedness to true; or else, if there was no such
  1280. // element, or that element is no longer in this element' s radio button
  1281. // group, or if this element no longer has a radio button group, setting
  1282. // this element's checkedness to false.
  1283. if (type_state() == TypeAttributeState::RadioButton) {
  1284. bool did_reselect_previous_element = false;
  1285. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  1286. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  1287. if (is_in_same_radio_button_group(*this, element_in_group)) {
  1288. element_in_group.set_checked_within_group();
  1289. did_reselect_previous_element = true;
  1290. }
  1291. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  1292. }
  1293. if (!did_reselect_previous_element)
  1294. set_checked(false, ChangeSource::User);
  1295. }
  1296. }
  1297. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  1298. {
  1299. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  1300. }
  1301. JS::GCPtr<DecodedImageData> HTMLInputElement::image_data() const
  1302. {
  1303. if (m_image_request)
  1304. return m_image_request->image_data();
  1305. return nullptr;
  1306. }
  1307. bool HTMLInputElement::is_image_available() const
  1308. {
  1309. return image_data() != nullptr;
  1310. }
  1311. Optional<CSSPixels> HTMLInputElement::intrinsic_width() const
  1312. {
  1313. if (auto image_data = this->image_data())
  1314. return image_data->intrinsic_width();
  1315. return {};
  1316. }
  1317. Optional<CSSPixels> HTMLInputElement::intrinsic_height() const
  1318. {
  1319. if (auto image_data = this->image_data())
  1320. return image_data->intrinsic_height();
  1321. return {};
  1322. }
  1323. Optional<CSSPixelFraction> HTMLInputElement::intrinsic_aspect_ratio() const
  1324. {
  1325. if (auto image_data = this->image_data())
  1326. return image_data->intrinsic_aspect_ratio();
  1327. return {};
  1328. }
  1329. RefPtr<Gfx::ImmutableBitmap> HTMLInputElement::current_image_bitmap(Gfx::IntSize size) const
  1330. {
  1331. if (auto image_data = this->image_data())
  1332. return image_data->bitmap(0, size);
  1333. return nullptr;
  1334. }
  1335. void HTMLInputElement::set_visible_in_viewport(bool)
  1336. {
  1337. // FIXME: Loosen grip on image data when it's not visible, e.g via volatile memory.
  1338. }
  1339. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  1340. i32 HTMLInputElement::default_tab_index_value() const
  1341. {
  1342. // See the base function for the spec comments.
  1343. return 0;
  1344. }
  1345. // https://html.spec.whatwg.org/multipage/input.html#dom-input-maxlength
  1346. WebIDL::Long HTMLInputElement::max_length() const
  1347. {
  1348. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  1349. if (auto maxlength_string = get_attribute(HTML::AttributeNames::maxlength); maxlength_string.has_value()) {
  1350. if (auto maxlength = parse_non_negative_integer(*maxlength_string); maxlength.has_value())
  1351. return *maxlength;
  1352. }
  1353. return -1;
  1354. }
  1355. WebIDL::ExceptionOr<void> HTMLInputElement::set_max_length(WebIDL::Long value)
  1356. {
  1357. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  1358. return set_attribute(HTML::AttributeNames::maxlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  1359. }
  1360. // https://html.spec.whatwg.org/multipage/input.html#dom-input-minlength
  1361. WebIDL::Long HTMLInputElement::min_length() const
  1362. {
  1363. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  1364. if (auto minlength_string = get_attribute(HTML::AttributeNames::minlength); minlength_string.has_value()) {
  1365. if (auto minlength = parse_non_negative_integer(*minlength_string); minlength.has_value())
  1366. return *minlength;
  1367. }
  1368. return -1;
  1369. }
  1370. WebIDL::ExceptionOr<void> HTMLInputElement::set_min_length(WebIDL::Long value)
  1371. {
  1372. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  1373. return set_attribute(HTML::AttributeNames::minlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  1374. }
  1375. // https://html.spec.whatwg.org/multipage/input.html#the-size-attribute
  1376. unsigned HTMLInputElement::size() const
  1377. {
  1378. // The size IDL attribute is limited to only positive numbers and has a default value of 20.
  1379. if (auto size_string = get_attribute(HTML::AttributeNames::size); size_string.has_value()) {
  1380. if (auto size = parse_non_negative_integer(*size_string); size.has_value())
  1381. return *size;
  1382. }
  1383. return 20;
  1384. }
  1385. WebIDL::ExceptionOr<void> HTMLInputElement::set_size(unsigned value)
  1386. {
  1387. return set_attribute(HTML::AttributeNames::size, MUST(String::number(value)));
  1388. }
  1389. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  1390. Optional<double> HTMLInputElement::convert_string_to_number(StringView input) const
  1391. {
  1392. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-string-number
  1393. if (type_state() == TypeAttributeState::Number)
  1394. return parse_floating_point_number(input);
  1395. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-string-number
  1396. if (type_state() == TypeAttributeState::Range)
  1397. return parse_floating_point_number(input);
  1398. dbgln("HTMLInputElement::convert_string_to_number() not implemented for input type {}", type());
  1399. return {};
  1400. }
  1401. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  1402. String HTMLInputElement::convert_number_to_string(double input) const
  1403. {
  1404. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-number-string
  1405. if (type_state() == TypeAttributeState::Number)
  1406. return MUST(String::number(input));
  1407. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-number-string
  1408. if (type_state() == TypeAttributeState::Range)
  1409. return MUST(String::number(input));
  1410. dbgln("HTMLInputElement::convert_number_to_string() not implemented for input type {}", type());
  1411. return {};
  1412. }
  1413. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-date
  1414. WebIDL::ExceptionOr<JS::GCPtr<JS::Date>> HTMLInputElement::convert_string_to_date(StringView input) const
  1415. {
  1416. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-string-date
  1417. if (type_state() == TypeAttributeState::Date) {
  1418. // If parsing a date from input results in an error, then return an error;
  1419. auto maybe_date = parse_date_string(realm(), input);
  1420. if (maybe_date.is_exception())
  1421. return maybe_date.exception();
  1422. // otherwise, return a new Date object representing midnight UTC on the morning of the parsed date.
  1423. return maybe_date.value();
  1424. }
  1425. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  1426. if (type_state() == TypeAttributeState::Time) {
  1427. // If parsing a time from input results in an error, then return an error;
  1428. auto maybe_time = parse_time_string(realm(), input);
  1429. if (maybe_time.is_exception())
  1430. return maybe_time.exception();
  1431. // otherwise, return a new Date object representing the parsed time in UTC on 1970-01-01.
  1432. return maybe_time.value();
  1433. }
  1434. dbgln("HTMLInputElement::convert_string_to_date() not implemented for input type {}", type());
  1435. return nullptr;
  1436. }
  1437. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-date-string
  1438. String HTMLInputElement::covert_date_to_string(JS::NonnullGCPtr<JS::Date> input) const
  1439. {
  1440. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-date-string
  1441. if (type_state() == TypeAttributeState::Date) {
  1442. // Return a valid date string that represents the date current at the time represented by input in the UTC time zone.
  1443. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  1444. 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())));
  1445. }
  1446. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  1447. if (type_state() == TypeAttributeState::Time) {
  1448. // Return a valid time string that represents the UTC time component that is represented by input.
  1449. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  1450. auto seconds = JS::sec_from_time(input->date_value());
  1451. auto milliseconds = JS::ms_from_time(input->date_value());
  1452. if (seconds > 0) {
  1453. if (milliseconds > 0)
  1454. return MUST(String::formatted("{:02d}:{:02d}:{:02d}.{:3d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds, milliseconds));
  1455. return MUST(String::formatted("{:02d}:{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds));
  1456. }
  1457. return MUST(String::formatted("{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value())));
  1458. }
  1459. dbgln("HTMLInputElement::covert_date_to_string() not implemented for input type {}", type());
  1460. return {};
  1461. }
  1462. // https://html.spec.whatwg.org/multipage/input.html#attr-input-min
  1463. Optional<double> HTMLInputElement::min() const
  1464. {
  1465. // If the element has a min attribute, and the result of applying the algorithm to convert a string to a number to
  1466. // the value of the min attribute is a number, then that number is the element's minimum; otherwise, if the type
  1467. // attribute's current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.
  1468. if (auto min_string = get_attribute(HTML::AttributeNames::min); min_string.has_value()) {
  1469. if (auto min = convert_string_to_number(*min_string); min.has_value())
  1470. return *min;
  1471. }
  1472. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-min-default
  1473. if (type_state() == TypeAttributeState::Range)
  1474. return 0;
  1475. return {};
  1476. }
  1477. // https://html.spec.whatwg.org/multipage/input.html#attr-input-max
  1478. Optional<double> HTMLInputElement::max() const
  1479. {
  1480. // If the element has a max attribute, and the result of applying the algorithm to convert a string to a number to the
  1481. // value of the max attribute is a number, then that number is the element's maximum; otherwise, if the type attribute's
  1482. // current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.
  1483. if (auto max_string = get_attribute(HTML::AttributeNames::max); max_string.has_value()) {
  1484. if (auto max = convert_string_to_number(*max_string); max.has_value())
  1485. return *max;
  1486. }
  1487. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-max-default
  1488. if (type_state() == TypeAttributeState::Range)
  1489. return 100;
  1490. return {};
  1491. }
  1492. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default
  1493. double HTMLInputElement::default_step() const
  1494. {
  1495. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-default
  1496. if (type_state() == TypeAttributeState::Number)
  1497. return 1;
  1498. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-default
  1499. if (type_state() == TypeAttributeState::Range)
  1500. return 1;
  1501. dbgln("HTMLInputElement::default_step() not implemented for input type {}", type());
  1502. return 0;
  1503. }
  1504. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-scale
  1505. double HTMLInputElement::step_scale_factor() const
  1506. {
  1507. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-scale
  1508. if (type_state() == TypeAttributeState::Number)
  1509. return 1;
  1510. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-scale
  1511. if (type_state() == TypeAttributeState::Range)
  1512. return 1;
  1513. dbgln("HTMLInputElement::step_scale_factor() not implemented for input type {}", type());
  1514. return 0;
  1515. }
  1516. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step
  1517. Optional<double> HTMLInputElement::allowed_value_step() const
  1518. {
  1519. // 1. If the attribute does not apply, then there is no allowed value step.
  1520. if (!step_applies())
  1521. return {};
  1522. // 2. Otherwise, if the attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.
  1523. auto maybe_step_string = get_attribute(AttributeNames::step);
  1524. if (!maybe_step_string.has_value())
  1525. return default_step() * step_scale_factor();
  1526. auto step_string = *maybe_step_string;
  1527. // 3. Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.
  1528. if (Infra::is_ascii_case_insensitive_match(step_string, "any"_string))
  1529. return {};
  1530. // 4. Otherwise, if the rules for parsing floating-point number values, when they are applied to the attribute's value, return an error,
  1531. // zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.
  1532. auto maybe_step = parse_floating_point_number(step_string);
  1533. if (!maybe_step.has_value() || *maybe_step == 0 || *maybe_step < 0)
  1534. return default_step() * step_scale_factor();
  1535. // 5. Otherwise, the allowed value step is the number returned by the rules for parsing floating-point number values when they are applied
  1536. // to the attribute's value, multiplied by the step scale factor.
  1537. return *maybe_step * step_scale_factor();
  1538. }
  1539. // https://html.spec.whatwg.org/multipage/input.html#concept-input-min-zero
  1540. double HTMLInputElement::step_base() const
  1541. {
  1542. // 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
  1543. // the min content attribute is not an error, then return that result.
  1544. if (auto min = this->min(); min.has_value())
  1545. return *min;
  1546. // 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
  1547. // the value content attribute is not an error, then return that result.
  1548. if (auto value = convert_string_to_number(this->value()); value.has_value())
  1549. return *value;
  1550. // 3. If a default step base is defined for this element given its type attribute's state, then return it.
  1551. if (type_state() == TypeAttributeState::Week) {
  1552. // The default step base is −259,200,000 (the start of week 1970-W01).
  1553. return -259'200'000;
  1554. }
  1555. // 4. Return zero.
  1556. return 0;
  1557. }
  1558. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1559. JS::Object* HTMLInputElement::value_as_date() const
  1560. {
  1561. // On getting, if the valueAsDate attribute does not apply, as defined for the input element's type attribute's current state, then return null.
  1562. if (!value_as_date_applies())
  1563. return nullptr;
  1564. // Otherwise, run the algorithm to convert a string to a Date object defined for that state to the element's value;
  1565. // if the algorithm returned a Date object, then return it, otherwise, return null.
  1566. auto maybe_date = convert_string_to_date(value());
  1567. if (!maybe_date.is_exception())
  1568. return maybe_date.value().ptr();
  1569. return nullptr;
  1570. }
  1571. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1572. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_date(Optional<JS::Handle<JS::Object>> const& value)
  1573. {
  1574. // 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;
  1575. if (!value_as_date_applies())
  1576. return WebIDL::InvalidStateError::create(realm(), "valueAsDate: Invalid input type used"_fly_string);
  1577. // otherwise, if the new value is not null and not a Date object throw a TypeError exception;
  1578. if (value.has_value() && !is<JS::Date>(**value))
  1579. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsDate: input is not a Date"sv };
  1580. // 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;
  1581. if (!value.has_value()) {
  1582. TRY(set_value(String {}));
  1583. return {};
  1584. }
  1585. auto& date = static_cast<JS::Date&>(**value);
  1586. if (!isfinite(date.date_value())) {
  1587. TRY(set_value(String {}));
  1588. return {};
  1589. }
  1590. // 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.
  1591. TRY(set_value(covert_date_to_string(date)));
  1592. return {};
  1593. }
  1594. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1595. double HTMLInputElement::value_as_number() const
  1596. {
  1597. // 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.
  1598. if (!value_as_number_applies())
  1599. return NAN;
  1600. // Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value;
  1601. // if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
  1602. return convert_string_to_number(value()).value_or(NAN);
  1603. }
  1604. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1605. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  1606. {
  1607. // On setting, if the new value is infinite, then throw a TypeError exception.
  1608. if (!isfinite(value))
  1609. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  1610. // 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.
  1611. if (!value_as_number_applies())
  1612. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
  1613. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  1614. if (value == NAN) {
  1615. TRY(set_value(String {}));
  1616. return {};
  1617. }
  1618. // 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.
  1619. TRY(set_value(convert_number_to_string(value)));
  1620. return {};
  1621. }
  1622. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1623. WebIDL::ExceptionOr<void> HTMLInputElement::step_up(WebIDL::Long n)
  1624. {
  1625. return step_up_or_down(false, n);
  1626. }
  1627. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepdown
  1628. WebIDL::ExceptionOr<void> HTMLInputElement::step_down(WebIDL::Long n)
  1629. {
  1630. return step_up_or_down(true, n);
  1631. }
  1632. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1633. WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, WebIDL::Long n)
  1634. {
  1635. // 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.
  1636. if (!step_up_or_down_applies())
  1637. return WebIDL::InvalidStateError::create(realm(), MUST(String::formatted("{}: Invalid input type used", is_down ? "stepDown()" : "stepUp()")));
  1638. // 2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.
  1639. auto maybe_allowed_value_step = allowed_value_step();
  1640. if (!maybe_allowed_value_step.has_value())
  1641. return WebIDL::InvalidStateError::create(realm(), "element has no allowed value step"_fly_string);
  1642. double allowed_value_step = *maybe_allowed_value_step;
  1643. // 3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then return.
  1644. auto maybe_minimum = min();
  1645. auto maybe_maximum = max();
  1646. if (maybe_minimum.has_value() && maybe_maximum.has_value() && *maybe_minimum > *maybe_maximum)
  1647. return {};
  1648. // 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
  1649. // 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.
  1650. // 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,
  1651. // then let value be the result of that algorithm. Otherwise, let value be zero.
  1652. double value = convert_string_to_number(this->value()).value_or(0);
  1653. // 6. Let valueBeforeStepping be value.
  1654. double value_before_stepping = value;
  1655. // 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,
  1656. // 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.
  1657. if (fmod(step_base() - value, allowed_value_step) != 0) {
  1658. double diff = step_base() - value;
  1659. if (is_down) {
  1660. value = diff - fmod(diff, allowed_value_step);
  1661. } else {
  1662. value = diff + fmod(diff, allowed_value_step);
  1663. }
  1664. } else {
  1665. // 1. Let n be the argument.
  1666. // 2. Let delta be the allowed value step multiplied by n.
  1667. double delta = allowed_value_step * n;
  1668. // 3. If the method invoked was the stepDown() method, negate delta.
  1669. if (is_down)
  1670. delta = -delta;
  1671. // 4. Let value be the result of adding delta to value.
  1672. value += delta;
  1673. }
  1674. // 8. If the element has a minimum, and value is less than that minimum, then set value to the smallest value that,
  1675. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is more than or equal to minimum.
  1676. if (maybe_minimum.has_value() && value < *maybe_minimum) {
  1677. value = AK::max(value, *maybe_minimum);
  1678. }
  1679. // 9. If the element has a maximum, and value is greater than that maximum, then set value to the largest value that,
  1680. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than or equal to maximum.
  1681. if (maybe_maximum.has_value() && value > *maybe_maximum) {
  1682. value = AK::min(value, *maybe_maximum);
  1683. }
  1684. // 10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping,
  1685. // or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then return.
  1686. if (is_down) {
  1687. if (value > value_before_stepping)
  1688. return {};
  1689. } else {
  1690. if (value < value_before_stepping)
  1691. return {};
  1692. }
  1693. // 11. Let value as string be the result of running the algorithm to convert a number to a string,
  1694. // as defined for the input element's type attribute's current state, on value.
  1695. auto value_as_string = convert_number_to_string(value);
  1696. // 12. Set the value of the element to value as string.
  1697. TRY(set_value(value_as_string));
  1698. return {};
  1699. }
  1700. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1701. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1702. {
  1703. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1704. return true;
  1705. }
  1706. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1707. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1708. {
  1709. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1710. return true;
  1711. }
  1712. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1713. void HTMLInputElement::set_custom_validity(String const& error)
  1714. {
  1715. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1716. return;
  1717. }
  1718. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  1719. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  1720. {
  1721. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  1722. return {};
  1723. }
  1724. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  1725. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, Optional<String> const& direction)
  1726. {
  1727. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  1728. return {};
  1729. }
  1730. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1731. {
  1732. // https://www.w3.org/TR/html-aria/#el-input-button
  1733. if (type_state() == TypeAttributeState::Button)
  1734. return ARIA::Role::button;
  1735. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1736. if (type_state() == TypeAttributeState::Checkbox)
  1737. return ARIA::Role::checkbox;
  1738. // https://www.w3.org/TR/html-aria/#el-input-email
  1739. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1740. return ARIA::Role::textbox;
  1741. // https://www.w3.org/TR/html-aria/#el-input-image
  1742. if (type_state() == TypeAttributeState::ImageButton)
  1743. return ARIA::Role::button;
  1744. // https://www.w3.org/TR/html-aria/#el-input-number
  1745. if (type_state() == TypeAttributeState::Number)
  1746. return ARIA::Role::spinbutton;
  1747. // https://www.w3.org/TR/html-aria/#el-input-radio
  1748. if (type_state() == TypeAttributeState::RadioButton)
  1749. return ARIA::Role::radio;
  1750. // https://www.w3.org/TR/html-aria/#el-input-range
  1751. if (type_state() == TypeAttributeState::Range)
  1752. return ARIA::Role::slider;
  1753. // https://www.w3.org/TR/html-aria/#el-input-reset
  1754. if (type_state() == TypeAttributeState::ResetButton)
  1755. return ARIA::Role::button;
  1756. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1757. if ((type_state() == TypeAttributeState::Text
  1758. || type_state() == TypeAttributeState::Search
  1759. || type_state() == TypeAttributeState::Telephone
  1760. || type_state() == TypeAttributeState::URL
  1761. || type_state() == TypeAttributeState::Email)
  1762. && has_attribute(AttributeNames::list))
  1763. return ARIA::Role::combobox;
  1764. // https://www.w3.org/TR/html-aria/#el-input-search
  1765. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1766. return ARIA::Role::textbox;
  1767. // https://www.w3.org/TR/html-aria/#el-input-submit
  1768. if (type_state() == TypeAttributeState::SubmitButton)
  1769. return ARIA::Role::button;
  1770. // https://www.w3.org/TR/html-aria/#el-input-tel
  1771. if (type_state() == TypeAttributeState::Telephone)
  1772. return ARIA::Role::textbox;
  1773. // https://www.w3.org/TR/html-aria/#el-input-text
  1774. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1775. return ARIA::Role::textbox;
  1776. // https://www.w3.org/TR/html-aria/#el-input-url
  1777. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1778. return ARIA::Role::textbox;
  1779. // https://www.w3.org/TR/html-aria/#el-input-color
  1780. // https://www.w3.org/TR/html-aria/#el-input-date
  1781. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1782. // https://www.w3.org/TR/html-aria/#el-input-file
  1783. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1784. // https://www.w3.org/TR/html-aria/#el-input-month
  1785. // https://www.w3.org/TR/html-aria/#el-input-password
  1786. // https://www.w3.org/TR/html-aria/#el-input-time
  1787. // https://www.w3.org/TR/html-aria/#el-input-week
  1788. return {};
  1789. }
  1790. bool HTMLInputElement::is_button() const
  1791. {
  1792. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1793. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1794. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1795. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1796. return type_state() == TypeAttributeState::SubmitButton
  1797. || type_state() == TypeAttributeState::ImageButton
  1798. || type_state() == TypeAttributeState::ResetButton
  1799. || type_state() == TypeAttributeState::Button;
  1800. }
  1801. bool HTMLInputElement::is_submit_button() const
  1802. {
  1803. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  1804. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  1805. return type_state() == TypeAttributeState::SubmitButton
  1806. || type_state() == TypeAttributeState::ImageButton;
  1807. }
  1808. bool HTMLInputElement::has_activation_behavior() const
  1809. {
  1810. return true;
  1811. }
  1812. void HTMLInputElement::activation_behavior(DOM::Event const& event)
  1813. {
  1814. // The activation behavior for input elements are these steps:
  1815. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  1816. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  1817. run_input_activation_behavior(event).release_value_but_fixme_should_propagate_errors();
  1818. }
  1819. bool HTMLInputElement::has_input_activation_behavior() const
  1820. {
  1821. switch (type_state()) {
  1822. case TypeAttributeState::Checkbox:
  1823. case TypeAttributeState::Color:
  1824. case TypeAttributeState::FileUpload:
  1825. case TypeAttributeState::ImageButton:
  1826. case TypeAttributeState::RadioButton:
  1827. case TypeAttributeState::ResetButton:
  1828. case TypeAttributeState::SubmitButton:
  1829. return true;
  1830. default:
  1831. return false;
  1832. }
  1833. }
  1834. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:event-change-2
  1835. bool HTMLInputElement::change_event_applies() const
  1836. {
  1837. switch (type_state()) {
  1838. case TypeAttributeState::Checkbox:
  1839. case TypeAttributeState::Color:
  1840. case TypeAttributeState::Date:
  1841. case TypeAttributeState::Email:
  1842. case TypeAttributeState::FileUpload:
  1843. case TypeAttributeState::LocalDateAndTime:
  1844. case TypeAttributeState::Month:
  1845. case TypeAttributeState::Number:
  1846. case TypeAttributeState::Password:
  1847. case TypeAttributeState::RadioButton:
  1848. case TypeAttributeState::Range:
  1849. case TypeAttributeState::Search:
  1850. case TypeAttributeState::Telephone:
  1851. case TypeAttributeState::Text:
  1852. case TypeAttributeState::Time:
  1853. case TypeAttributeState::URL:
  1854. case TypeAttributeState::Week:
  1855. return true;
  1856. default:
  1857. return false;
  1858. }
  1859. }
  1860. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasdate-3
  1861. bool HTMLInputElement::value_as_date_applies() const
  1862. {
  1863. switch (type_state()) {
  1864. case TypeAttributeState::Date:
  1865. case TypeAttributeState::Month:
  1866. case TypeAttributeState::Week:
  1867. case TypeAttributeState::Time:
  1868. return true;
  1869. default:
  1870. return false;
  1871. }
  1872. }
  1873. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasnumber-3
  1874. bool HTMLInputElement::value_as_number_applies() const
  1875. {
  1876. switch (type_state()) {
  1877. case TypeAttributeState::Date:
  1878. case TypeAttributeState::Month:
  1879. case TypeAttributeState::Week:
  1880. case TypeAttributeState::Time:
  1881. case TypeAttributeState::LocalDateAndTime:
  1882. case TypeAttributeState::Number:
  1883. case TypeAttributeState::Range:
  1884. return true;
  1885. default:
  1886. return false;
  1887. }
  1888. }
  1889. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-step-3
  1890. bool HTMLInputElement::step_applies() const
  1891. {
  1892. return value_as_number_applies();
  1893. }
  1894. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-stepup-3
  1895. bool HTMLInputElement::step_up_or_down_applies() const
  1896. {
  1897. return value_as_number_applies();
  1898. }
  1899. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-value-2
  1900. HTMLInputElement::ValueAttributeMode HTMLInputElement::value_attribute_mode() const
  1901. {
  1902. switch (type_state()) {
  1903. case TypeAttributeState::Text:
  1904. case TypeAttributeState::Search:
  1905. case TypeAttributeState::Telephone:
  1906. case TypeAttributeState::URL:
  1907. case TypeAttributeState::Email:
  1908. case TypeAttributeState::Password:
  1909. case TypeAttributeState::Date:
  1910. case TypeAttributeState::Month:
  1911. case TypeAttributeState::Week:
  1912. case TypeAttributeState::Time:
  1913. case TypeAttributeState::LocalDateAndTime:
  1914. case TypeAttributeState::Number:
  1915. case TypeAttributeState::Range:
  1916. case TypeAttributeState::Color:
  1917. return ValueAttributeMode::Value;
  1918. case TypeAttributeState::Hidden:
  1919. case TypeAttributeState::SubmitButton:
  1920. case TypeAttributeState::ImageButton:
  1921. case TypeAttributeState::ResetButton:
  1922. case TypeAttributeState::Button:
  1923. return ValueAttributeMode::Default;
  1924. case TypeAttributeState::Checkbox:
  1925. case TypeAttributeState::RadioButton:
  1926. return ValueAttributeMode::DefaultOn;
  1927. case TypeAttributeState::FileUpload:
  1928. return ValueAttributeMode::Filename;
  1929. }
  1930. VERIFY_NOT_REACHED();
  1931. }
  1932. }