HTMLInputElement.cpp 104 KB

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