HTMLInputElement.cpp 99 KB

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