HTMLInputElement.cpp 106 KB

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