HTMLInputElement.cpp 101 KB

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