HTMLInputElement.cpp 110 KB

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