HTMLInputElement.cpp 116 KB

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