HTMLInputElement.cpp 116 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600
  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. JS_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. JS::NonnullGCPtr<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. JS::GCPtr<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. JS::GCPtr<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(JS::GCPtr<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(JS::NonnullGCPtr<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. JS::GCPtr<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(), { JS::make_handle(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. if (!m_has_uncommitted_changes)
  528. return;
  529. break;
  530. default:
  531. break;
  532. }
  533. m_has_uncommitted_changes = false;
  534. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true });
  535. dispatch_event(change_event);
  536. }
  537. void HTMLInputElement::update_placeholder_visibility()
  538. {
  539. if (!m_placeholder_element)
  540. return;
  541. if (this->placeholder_value().has_value()) {
  542. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  543. } else {
  544. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  545. }
  546. }
  547. void HTMLInputElement::update_text_input_shadow_tree()
  548. {
  549. if (m_text_node) {
  550. m_text_node->set_data(m_value);
  551. update_placeholder_visibility();
  552. }
  553. }
  554. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  555. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  556. {
  557. switch (state) {
  558. case HTML::HTMLInputElement::TypeAttributeState::Text:
  559. case HTML::HTMLInputElement::TypeAttributeState::Search:
  560. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  561. case HTML::HTMLInputElement::TypeAttributeState::URL:
  562. case HTML::HTMLInputElement::TypeAttributeState::Email:
  563. case HTML::HTMLInputElement::TypeAttributeState::Password:
  564. case HTML::HTMLInputElement::TypeAttributeState::Date:
  565. case HTML::HTMLInputElement::TypeAttributeState::Month:
  566. case HTML::HTMLInputElement::TypeAttributeState::Week:
  567. case HTML::HTMLInputElement::TypeAttributeState::Time:
  568. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  569. case HTML::HTMLInputElement::TypeAttributeState::Number:
  570. return true;
  571. default:
  572. return false;
  573. }
  574. }
  575. // https://html.spec.whatwg.org/multipage/input.html#attr-input-maxlength
  576. void HTMLInputElement::handle_maxlength_attribute()
  577. {
  578. if (m_text_node) {
  579. auto max_length = this->max_length();
  580. if (max_length >= 0) {
  581. m_text_node->set_max_length(max_length);
  582. } else {
  583. m_text_node->set_max_length({});
  584. }
  585. }
  586. }
  587. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  588. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  589. {
  590. // 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.
  591. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  592. if (m_text_node)
  593. m_text_node->set_always_editable(m_is_mutable);
  594. }
  595. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  596. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  597. {
  598. switch (state) {
  599. case HTML::HTMLInputElement::TypeAttributeState::Text:
  600. case HTML::HTMLInputElement::TypeAttributeState::Search:
  601. case HTML::HTMLInputElement::TypeAttributeState::URL:
  602. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  603. case HTML::HTMLInputElement::TypeAttributeState::Email:
  604. case HTML::HTMLInputElement::TypeAttributeState::Password:
  605. case HTML::HTMLInputElement::TypeAttributeState::Number:
  606. return true;
  607. default:
  608. return false;
  609. }
  610. }
  611. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  612. String HTMLInputElement::placeholder() const
  613. {
  614. auto maybe_placeholder = get_attribute(HTML::AttributeNames::placeholder);
  615. if (!maybe_placeholder.has_value())
  616. return String {};
  617. auto placeholder = *maybe_placeholder;
  618. // The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.
  619. StringBuilder builder;
  620. for (auto c : placeholder.bytes_as_string_view()) {
  621. if (c != '\r' && c != '\n')
  622. builder.append(c);
  623. }
  624. return MUST(builder.to_string());
  625. }
  626. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  627. Optional<String> HTMLInputElement::placeholder_value() const
  628. {
  629. if (!m_text_node || !m_text_node->data().is_empty())
  630. return {};
  631. if (!is_allowed_to_have_placeholder(type_state()))
  632. return {};
  633. if (!has_attribute(HTML::AttributeNames::placeholder))
  634. return {};
  635. return placeholder();
  636. }
  637. void HTMLInputElement::create_shadow_tree_if_needed()
  638. {
  639. if (shadow_root())
  640. return;
  641. switch (type_state()) {
  642. case TypeAttributeState::Hidden:
  643. case TypeAttributeState::RadioButton:
  644. case TypeAttributeState::Checkbox:
  645. break;
  646. case TypeAttributeState::Button:
  647. case TypeAttributeState::SubmitButton:
  648. case TypeAttributeState::ResetButton:
  649. create_button_input_shadow_tree();
  650. break;
  651. case TypeAttributeState::ImageButton:
  652. break;
  653. case TypeAttributeState::Color:
  654. create_color_input_shadow_tree();
  655. break;
  656. case TypeAttributeState::FileUpload:
  657. create_file_input_shadow_tree();
  658. break;
  659. case TypeAttributeState::Range:
  660. create_range_input_shadow_tree();
  661. break;
  662. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  663. default:
  664. create_text_input_shadow_tree();
  665. break;
  666. }
  667. }
  668. void HTMLInputElement::update_shadow_tree()
  669. {
  670. switch (type_state()) {
  671. case TypeAttributeState::Color:
  672. update_color_well_element();
  673. break;
  674. case TypeAttributeState::FileUpload:
  675. update_file_input_shadow_tree();
  676. break;
  677. case TypeAttributeState::Range:
  678. update_slider_shadow_tree_elements();
  679. break;
  680. default:
  681. update_text_input_shadow_tree();
  682. break;
  683. }
  684. }
  685. void HTMLInputElement::create_button_input_shadow_tree()
  686. {
  687. auto shadow_root = realm().create<DOM::ShadowRoot>(document(), *this, Bindings::ShadowRootMode::Closed);
  688. set_shadow_root(shadow_root);
  689. auto text_container = MUST(DOM::create_element(document(), HTML::TagNames::span, Namespace::HTML));
  690. MUST(text_container->set_attribute(HTML::AttributeNames::style, "display: inline-block; pointer-events: none;"_string));
  691. m_text_node = realm().create<DOM::Text>(document(), value());
  692. MUST(text_container->append_child(*m_text_node));
  693. MUST(shadow_root->append_child(*text_container));
  694. }
  695. void HTMLInputElement::create_text_input_shadow_tree()
  696. {
  697. auto shadow_root = realm().create<DOM::ShadowRoot>(document(), *this, Bindings::ShadowRootMode::Closed);
  698. set_shadow_root(shadow_root);
  699. auto initial_value = m_value;
  700. auto element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  701. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  702. display: flex;
  703. height: 100%;
  704. align-items: center;
  705. white-space: pre;
  706. border: none;
  707. padding: 1px 2px;
  708. )~~~"_string));
  709. MUST(shadow_root->append_child(element));
  710. m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  711. m_placeholder_element->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::Placeholder);
  712. // https://www.w3.org/TR/css-ui-4/#input-rules
  713. MUST(m_placeholder_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  714. width: 100%;
  715. align-items: center;
  716. text-overflow: clip;
  717. white-space: nowrap;
  718. )~~~"_string));
  719. MUST(element->append_child(*m_placeholder_element));
  720. m_placeholder_text_node = realm().create<DOM::Text>(document(), String {});
  721. m_placeholder_text_node->set_data(placeholder());
  722. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  723. // https://www.w3.org/TR/css-ui-4/#input-rules
  724. m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  725. MUST(m_inner_text_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  726. width: 100%;
  727. height: 1lh;
  728. align-items: center;
  729. text-overflow: clip;
  730. white-space: nowrap;
  731. )~~~"_string));
  732. MUST(element->append_child(*m_inner_text_element));
  733. m_text_node = realm().create<DOM::Text>(document(), move(initial_value));
  734. if (type_state() == TypeAttributeState::FileUpload) {
  735. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  736. m_text_node->set_always_editable(false);
  737. } else {
  738. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  739. }
  740. if (type_state() == TypeAttributeState::Password)
  741. m_text_node->set_is_password_input({}, true);
  742. handle_maxlength_attribute();
  743. MUST(m_inner_text_element->append_child(*m_text_node));
  744. update_placeholder_visibility();
  745. if (type_state() == TypeAttributeState::Number) {
  746. // Up button
  747. auto up_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  748. // FIXME: This cursor property doesn't work
  749. MUST(up_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  750. padding: 0;
  751. cursor: default;
  752. )~~~"_string));
  753. 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));
  754. MUST(element->append_child(up_button));
  755. auto mouseup_callback_function = JS::NativeFunction::create(
  756. realm(), [this](JS::VM&) {
  757. commit_pending_changes();
  758. return JS::js_undefined();
  759. },
  760. 0, "", &realm());
  761. auto mouseup_callback = realm().heap().allocate<WebIDL::CallbackType>(*mouseup_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  762. DOM::AddEventListenerOptions mouseup_listener_options;
  763. mouseup_listener_options.once = true;
  764. auto up_callback_function = JS::NativeFunction::create(
  765. realm(), [this](JS::VM&) {
  766. if (m_is_mutable) {
  767. MUST(step_up());
  768. user_interaction_did_change_input_value();
  769. }
  770. return JS::js_undefined();
  771. },
  772. 0, "", &realm());
  773. auto step_up_callback = realm().heap().allocate<WebIDL::CallbackType>(*up_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  774. up_button->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), step_up_callback));
  775. up_button->add_event_listener_without_options(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback));
  776. // Down button
  777. auto down_button = MUST(DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML));
  778. MUST(down_button->set_attribute(HTML::AttributeNames::style, R"~~~(
  779. padding: 0;
  780. cursor: default;
  781. )~~~"_string));
  782. 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));
  783. MUST(element->append_child(down_button));
  784. auto down_callback_function = JS::NativeFunction::create(
  785. realm(), [this](JS::VM&) {
  786. if (m_is_mutable) {
  787. MUST(step_down());
  788. user_interaction_did_change_input_value();
  789. }
  790. return JS::js_undefined();
  791. },
  792. 0, "", &realm());
  793. auto step_down_callback = realm().heap().allocate<WebIDL::CallbackType>(*down_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  794. down_button->add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), step_down_callback));
  795. down_button->add_event_listener_without_options(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback));
  796. }
  797. }
  798. void HTMLInputElement::create_color_input_shadow_tree()
  799. {
  800. auto shadow_root = realm().create<DOM::ShadowRoot>(document(), *this, Bindings::ShadowRootMode::Closed);
  801. auto color = value_sanitization_algorithm(m_value);
  802. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  803. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  804. width: fit-content;
  805. height: fit-content;
  806. padding: 4px;
  807. border: 1px solid ButtonBorder;
  808. background-color: ButtonFace;
  809. )~~~"_string));
  810. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  811. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  812. width: 32px;
  813. height: 16px;
  814. border: 1px solid ButtonBorder;
  815. box-sizing: border-box;
  816. )~~~"_string));
  817. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  818. MUST(border->append_child(*m_color_well_element));
  819. MUST(shadow_root->append_child(border));
  820. set_shadow_root(shadow_root);
  821. }
  822. void HTMLInputElement::update_color_well_element()
  823. {
  824. if (!m_color_well_element)
  825. return;
  826. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  827. }
  828. void HTMLInputElement::create_file_input_shadow_tree()
  829. {
  830. auto& realm = this->realm();
  831. auto shadow_root = realm.create<DOM::ShadowRoot>(document(), *this, Bindings::ShadowRootMode::Closed);
  832. m_file_button = DOM::create_element(document(), HTML::TagNames::button, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  833. m_file_label = DOM::create_element(document(), HTML::TagNames::label, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  834. MUST(m_file_label->set_attribute(HTML::AttributeNames::style, "padding-left: 4px;"_string));
  835. auto on_button_click = [this](JS::VM&) {
  836. show_the_picker_if_applicable(*this);
  837. return JS::js_undefined();
  838. };
  839. auto on_button_click_function = JS::NativeFunction::create(realm, move(on_button_click), 0, "", &realm);
  840. auto on_button_click_callback = realm.heap().allocate<WebIDL::CallbackType>(on_button_click_function, Bindings::principal_host_defined_environment_settings_object(realm));
  841. m_file_button->add_event_listener_without_options(UIEvents::EventNames::click, DOM::IDLEventListener::create(realm, on_button_click_callback));
  842. update_file_input_shadow_tree();
  843. MUST(shadow_root->append_child(*m_file_button));
  844. MUST(shadow_root->append_child(*m_file_label));
  845. set_shadow_root(shadow_root);
  846. }
  847. void HTMLInputElement::update_file_input_shadow_tree()
  848. {
  849. if (!m_file_button || !m_file_label)
  850. return;
  851. auto files_label = has_attribute(HTML::AttributeNames::multiple) ? "files"sv : "file"sv;
  852. m_file_button->set_text_content(MUST(String::formatted("Select {}...", files_label)));
  853. if (m_selected_files && m_selected_files->length() > 0) {
  854. if (m_selected_files->length() == 1)
  855. m_file_label->set_text_content(m_selected_files->item(0)->name());
  856. else
  857. m_file_label->set_text_content(MUST(String::formatted("{} files selected.", m_selected_files->length())));
  858. } else {
  859. m_file_label->set_text_content(MUST(String::formatted("No {} selected.", files_label)));
  860. }
  861. document().invalidate_layout_tree();
  862. }
  863. void HTMLInputElement::create_range_input_shadow_tree()
  864. {
  865. auto shadow_root = realm().create<DOM::ShadowRoot>(document(), *this, Bindings::ShadowRootMode::Closed);
  866. set_shadow_root(shadow_root);
  867. m_slider_runnable_track = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  868. m_slider_runnable_track->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderRunnableTrack);
  869. MUST(shadow_root->append_child(*m_slider_runnable_track));
  870. m_slider_progress_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  871. MUST(m_slider_progress_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  872. display: block;
  873. position: absolute;
  874. height: 100%;
  875. )~~~"_string));
  876. MUST(m_slider_runnable_track->append_child(*m_slider_progress_element));
  877. m_slider_thumb = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  878. m_slider_thumb->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::SliderThumb);
  879. MUST(m_slider_runnable_track->append_child(*m_slider_thumb));
  880. update_slider_shadow_tree_elements();
  881. auto keydown_callback_function = JS::NativeFunction::create(
  882. realm(), [this](JS::VM& vm) {
  883. auto key = MUST(vm.argument(0).get(vm, "key")).as_string().utf8_string();
  884. if (key == "ArrowLeft" || key == "ArrowDown")
  885. MUST(step_down());
  886. if (key == "PageDown")
  887. MUST(step_down(10));
  888. if (key == "ArrowRight" || key == "ArrowUp")
  889. MUST(step_up());
  890. if (key == "PageUp")
  891. MUST(step_up(10));
  892. user_interaction_did_change_input_value();
  893. return JS::js_undefined();
  894. },
  895. 0, "", &realm());
  896. auto keydown_callback = realm().heap().allocate<WebIDL::CallbackType>(*keydown_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  897. add_event_listener_without_options(UIEvents::EventNames::keydown, DOM::IDLEventListener::create(realm(), keydown_callback));
  898. auto wheel_callback_function = JS::NativeFunction::create(
  899. realm(), [this](JS::VM& vm) {
  900. auto delta_y = MUST(vm.argument(0).get(vm, "deltaY")).as_i32();
  901. if (delta_y > 0) {
  902. MUST(step_down());
  903. } else {
  904. MUST(step_up());
  905. }
  906. user_interaction_did_change_input_value();
  907. return JS::js_undefined();
  908. },
  909. 0, "", &realm());
  910. auto wheel_callback = realm().heap().allocate<WebIDL::CallbackType>(*wheel_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  911. add_event_listener_without_options(UIEvents::EventNames::wheel, DOM::IDLEventListener::create(realm(), wheel_callback));
  912. auto update_slider_by_mouse = [this](JS::VM& vm) {
  913. auto client_x = MUST(vm.argument(0).get(vm, "clientX")).as_double();
  914. auto rect = get_bounding_client_rect();
  915. double minimum = *min();
  916. double maximum = *max();
  917. // FIXME: Snap new value to input steps
  918. MUST(set_value_as_number(clamp(round(((client_x - rect->left()) / rect->width()) * (maximum - minimum) + minimum), minimum, maximum)));
  919. user_interaction_did_change_input_value();
  920. };
  921. auto mousedown_callback_function = JS::NativeFunction::create(
  922. realm(), [this, update_slider_by_mouse](JS::VM& vm) {
  923. update_slider_by_mouse(vm);
  924. auto mousemove_callback_function = JS::NativeFunction::create(
  925. realm(), [update_slider_by_mouse](JS::VM& vm) {
  926. update_slider_by_mouse(vm);
  927. return JS::js_undefined();
  928. },
  929. 0, "", &realm());
  930. auto mousemove_callback = realm().heap().allocate<WebIDL::CallbackType>(*mousemove_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  931. auto mousemove_listener = DOM::IDLEventListener::create(realm(), mousemove_callback);
  932. auto& window = static_cast<HTML::Window&>(relevant_global_object(*this));
  933. window.add_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);
  934. auto mouseup_callback_function = JS::NativeFunction::create(
  935. realm(), [this, mousemove_listener](JS::VM&) {
  936. auto& window = static_cast<HTML::Window&>(relevant_global_object(*this));
  937. window.remove_event_listener_without_options(UIEvents::EventNames::mousemove, mousemove_listener);
  938. return JS::js_undefined();
  939. },
  940. 0, "", &realm());
  941. auto mouseup_callback = realm().heap().allocate<WebIDL::CallbackType>(*mouseup_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  942. DOM::AddEventListenerOptions mouseup_listener_options;
  943. mouseup_listener_options.once = true;
  944. window.add_event_listener(UIEvents::EventNames::mouseup, DOM::IDLEventListener::create(realm(), mouseup_callback), mouseup_listener_options);
  945. return JS::js_undefined();
  946. },
  947. 0, "", &realm());
  948. auto mousedown_callback = realm().heap().allocate<WebIDL::CallbackType>(*mousedown_callback_function, Bindings::principal_host_defined_environment_settings_object(realm()));
  949. add_event_listener_without_options(UIEvents::EventNames::mousedown, DOM::IDLEventListener::create(realm(), mousedown_callback));
  950. }
  951. void HTMLInputElement::computed_css_values_changed()
  952. {
  953. auto appearance = computed_css_values()->appearance();
  954. if (!appearance.has_value() || *appearance == CSS::Appearance::None)
  955. return;
  956. auto palette = document().page().palette();
  957. auto accent_color = palette.color(ColorRole::Accent).to_string();
  958. auto const& accent_color_property = computed_css_values()->property(CSS::PropertyID::AccentColor);
  959. if (accent_color_property.has_color())
  960. accent_color = accent_color_property.to_string();
  961. if (m_slider_progress_element)
  962. MUST(m_slider_progress_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, accent_color));
  963. if (m_slider_thumb)
  964. MUST(m_slider_thumb->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, accent_color));
  965. }
  966. void HTMLInputElement::user_interaction_did_change_input_value()
  967. {
  968. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  969. // For input elements without a defined input activation behavior, but to which these events apply,
  970. // and for which the user interface involves both interactive manipulation and an explicit commit action,
  971. // then when the user changes the element's value, the user agent must queue an element task on the user interaction task source
  972. // given the input element to fire an event named input at the input element, with the bubbles and composed attributes initialized to true,
  973. // 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
  974. // 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.
  975. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  976. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  977. input_event->set_bubbles(true);
  978. input_event->set_composed(true);
  979. dispatch_event(*input_event);
  980. });
  981. }
  982. void HTMLInputElement::update_slider_shadow_tree_elements()
  983. {
  984. double value = convert_string_to_number(value_sanitization_algorithm(m_value)).value_or(0);
  985. double minimum = *min();
  986. double maximum = *max();
  987. double position = (value - minimum) / (maximum - minimum) * 100;
  988. if (m_slider_progress_element)
  989. MUST(m_slider_progress_element->style_for_bindings()->set_property(CSS::PropertyID::Width, MUST(String::formatted("{}%", position))));
  990. if (m_slider_thumb)
  991. MUST(m_slider_thumb->style_for_bindings()->set_property(CSS::PropertyID::MarginLeft, MUST(String::formatted("{}%", position))));
  992. }
  993. void HTMLInputElement::did_receive_focus()
  994. {
  995. if (!m_text_node)
  996. return;
  997. m_text_node->invalidate_style(DOM::StyleInvalidationReason::DidReceiveFocus);
  998. if (auto* paintable = m_text_node->paintable())
  999. paintable->set_selected(true);
  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. if (auto* paintable = m_text_node->paintable())
  1008. paintable->set_selected(false);
  1009. }
  1010. if (m_placeholder_text_node)
  1011. m_placeholder_text_node->invalidate_style(DOM::StyleInvalidationReason::DidLoseFocus);
  1012. commit_pending_changes();
  1013. }
  1014. void HTMLInputElement::form_associated_element_attribute_changed(FlyString const& name, Optional<String> const& value)
  1015. {
  1016. if (name == HTML::AttributeNames::checked) {
  1017. if (!value.has_value()) {
  1018. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  1019. // the user agent must set the checkedness of the element to false.
  1020. if (!m_dirty_checkedness)
  1021. set_checked(false, ChangeSource::Programmatic);
  1022. } else {
  1023. // When the checked content attribute is added, if the control does not have dirty checkedness,
  1024. // the user agent must set the checkedness of the element to true
  1025. if (!m_dirty_checkedness)
  1026. set_checked(true, ChangeSource::Programmatic);
  1027. }
  1028. } else if (name == HTML::AttributeNames::type) {
  1029. auto new_type_attribute_state = parse_type_attribute(value.value_or(String {}));
  1030. type_attribute_changed(m_type, new_type_attribute_state);
  1031. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):the-input-element-4
  1032. // the input element's type attribute is changed back to the Image Button state, and the src attribute is present,
  1033. // and its value has changed since the last time the type attribute was in the Image Button state
  1034. if (type_state() == TypeAttributeState::ImageButton) {
  1035. if (auto src = attribute(AttributeNames::src); src.has_value() && src != m_last_src_value)
  1036. handle_src_attribute(*src).release_value_but_fixme_should_propagate_errors();
  1037. }
  1038. } else if (name == HTML::AttributeNames::value) {
  1039. if (!m_dirty_value) {
  1040. auto old_value = move(m_value);
  1041. if (!value.has_value()) {
  1042. m_value = String {};
  1043. } else {
  1044. m_value = value_sanitization_algorithm(*value);
  1045. }
  1046. if (m_value != old_value)
  1047. relevant_value_was_changed();
  1048. update_shadow_tree();
  1049. }
  1050. } else if (name == HTML::AttributeNames::placeholder) {
  1051. if (m_placeholder_text_node) {
  1052. m_placeholder_text_node->set_data(placeholder());
  1053. update_placeholder_visibility();
  1054. }
  1055. } else if (name == HTML::AttributeNames::readonly) {
  1056. handle_readonly_attribute(value);
  1057. } else if (name == HTML::AttributeNames::src) {
  1058. handle_src_attribute(value.value_or({})).release_value_but_fixme_should_propagate_errors();
  1059. } else if (name == HTML::AttributeNames::alt) {
  1060. if (layout_node() && type_state() == TypeAttributeState::ImageButton)
  1061. did_update_alt_text(verify_cast<Layout::ImageBox>(*layout_node()));
  1062. } else if (name == HTML::AttributeNames::maxlength) {
  1063. handle_maxlength_attribute();
  1064. } else if (name == HTML::AttributeNames::multiple) {
  1065. update_shadow_tree();
  1066. }
  1067. }
  1068. // https://html.spec.whatwg.org/multipage/input.html#input-type-change
  1069. void HTMLInputElement::type_attribute_changed(TypeAttributeState old_state, TypeAttributeState new_state)
  1070. {
  1071. auto new_value_attribute_mode = value_attribute_mode_for_type_state(new_state);
  1072. auto old_value_attribute_mode = value_attribute_mode_for_type_state(old_state);
  1073. // 1. If the previous state of the element's type attribute put the value IDL attribute in the value mode, and the element's
  1074. // value is not the empty string, and the new state of the element's type attribute puts the value IDL attribute in either
  1075. // the default mode or the default/on mode, then set the element's value content attribute to the element's value.
  1076. if (old_value_attribute_mode == ValueAttributeMode::Value && !m_value.is_empty() && (first_is_one_of(new_value_attribute_mode, ValueAttributeMode::Default, ValueAttributeMode::DefaultOn))) {
  1077. MUST(set_attribute(HTML::AttributeNames::value, m_value));
  1078. }
  1079. // 2. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other
  1080. // than the value mode, and the new state of the element's type attribute puts the value IDL attribute in the value mode,
  1081. // then set the value of the element to the value of the value content attribute, if there is one, or the empty string
  1082. // otherwise, and then set the control's dirty value flag to false.
  1083. else if (old_value_attribute_mode != ValueAttributeMode::Value && new_value_attribute_mode == ValueAttributeMode::Value) {
  1084. m_value = attribute(HTML::AttributeNames::value).value_or({});
  1085. m_dirty_value = false;
  1086. }
  1087. // 3. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other
  1088. // than the filename mode, and the new state of the element's type attribute puts the value IDL attribute in the filename mode,
  1089. // then set the value of the element to the empty string.
  1090. else if (old_value_attribute_mode != ValueAttributeMode::Filename && new_value_attribute_mode == ValueAttributeMode::Filename) {
  1091. m_value = String {};
  1092. }
  1093. // 4. Update the element's rendering and behavior to the new state's.
  1094. m_type = new_state;
  1095. set_shadow_root(nullptr);
  1096. create_shadow_tree_if_needed();
  1097. // FIXME: 5. Signal a type change for the element. (The Radio Button state uses this, in particular.)
  1098. // 6. Invoke the value sanitization algorithm, if one is defined for the type attribute's new state.
  1099. m_value = value_sanitization_algorithm(m_value);
  1100. // 7. Let previouslySelectable be true if setRangeText() previously applied to the element, and false otherwise.
  1101. auto previously_selectable = selection_or_range_applies_for_type_state(old_state);
  1102. // 8. Let nowSelectable be true if setRangeText() now applies to the element, and false otherwise.
  1103. auto now_selectable = selection_or_range_applies_for_type_state(new_state);
  1104. // 9. If previouslySelectable is false and nowSelectable is true, set the element's text entry cursor position to the
  1105. // beginning of the text control, and set its selection direction to "none".
  1106. if (!previously_selectable && now_selectable) {
  1107. set_selection_direction(OptionalNone {});
  1108. }
  1109. }
  1110. // https://html.spec.whatwg.org/multipage/input.html#attr-input-src
  1111. WebIDL::ExceptionOr<void> HTMLInputElement::handle_src_attribute(String const& value)
  1112. {
  1113. auto& realm = this->realm();
  1114. auto& vm = realm.vm();
  1115. if (type_state() != TypeAttributeState::ImageButton)
  1116. return {};
  1117. m_last_src_value = value;
  1118. // 1. Let url be the result of encoding-parsing a URL given the src attribute's value, relative to the element's
  1119. // node document.
  1120. auto url = document().parse_url(value);
  1121. // 2. If url is failure, then return.
  1122. if (!url.is_valid())
  1123. return {};
  1124. // 3. Let request be a new request whose URL is url, client is the element's node document's relevant settings
  1125. // object, destination is "image", initiator type is "input", credentials mode is "include", and whose
  1126. // use-URL-credentials flag is set.
  1127. auto request = Fetch::Infrastructure::Request::create(vm);
  1128. request->set_url(move(url));
  1129. request->set_client(&document().relevant_settings_object());
  1130. request->set_destination(Fetch::Infrastructure::Request::Destination::Image);
  1131. request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Input);
  1132. request->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include);
  1133. request->set_use_url_credentials(true);
  1134. // 4. Fetch request, with processResponseEndOfBody set to the following step given response response:
  1135. m_resource_request = SharedResourceRequest::get_or_create(realm, document().page(), request->url());
  1136. m_resource_request->add_callbacks(
  1137. [this, &realm]() {
  1138. // 1. If the download was successful and the image is available, queue an element task on the user interaction
  1139. // task source given the input element to fire an event named load at the input element.
  1140. queue_an_element_task(HTML::Task::Source::UserInteraction, [this, &realm]() {
  1141. dispatch_event(DOM::Event::create(realm, HTML::EventNames::load));
  1142. });
  1143. m_load_event_delayer.clear();
  1144. document().invalidate_layout_tree();
  1145. },
  1146. [this, &realm]() {
  1147. // 2. Otherwise, if the fetching process fails without a response from the remote server, or completes but the
  1148. // image is not a valid or supported image, then queue an element task on the user interaction task source
  1149. // given the input element to fire an event named error on the input element.
  1150. queue_an_element_task(HTML::Task::Source::UserInteraction, [this, &realm]() {
  1151. dispatch_event(DOM::Event::create(realm, HTML::EventNames::error));
  1152. });
  1153. m_load_event_delayer.clear();
  1154. });
  1155. if (m_resource_request->needs_fetching()) {
  1156. m_resource_request->fetch_resource(realm, request);
  1157. }
  1158. // Fetching the image must delay the load event of the element's node document until the task that is queued by the
  1159. // networking task source once the resource has been fetched (defined below) has been run.
  1160. m_load_event_delayer.emplace(document());
  1161. return {};
  1162. }
  1163. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  1164. {
  1165. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  1166. if (type.equals_ignoring_ascii_case(keyword##sv)) \
  1167. return HTMLInputElement::TypeAttributeState::state;
  1168. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  1169. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  1170. // The missing value default and the invalid value default are the Text state.
  1171. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  1172. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  1173. return HTMLInputElement::TypeAttributeState::Text;
  1174. }
  1175. StringView HTMLInputElement::type() const
  1176. {
  1177. // FIXME: This should probably be `Reflect` in the IDL.
  1178. switch (m_type) {
  1179. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  1180. case TypeAttributeState::state: \
  1181. return keyword##sv;
  1182. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  1183. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  1184. }
  1185. VERIFY_NOT_REACHED();
  1186. }
  1187. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  1188. {
  1189. return set_attribute(HTML::AttributeNames::type, type);
  1190. }
  1191. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  1192. static bool is_valid_simple_color(StringView value)
  1193. {
  1194. // if it is exactly seven characters long,
  1195. if (value.length() != 7)
  1196. return false;
  1197. // and the first character is a U+0023 NUMBER SIGN character (#),
  1198. if (!value.starts_with('#'))
  1199. return false;
  1200. // and the remaining six characters are all ASCII hex digits
  1201. for (size_t i = 1; i < value.length(); i++)
  1202. if (!is_ascii_hex_digit(value[i]))
  1203. return false;
  1204. return true;
  1205. }
  1206. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  1207. String HTMLInputElement::value_sanitization_algorithm(String const& value) const
  1208. {
  1209. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  1210. // Strip newlines from the value.
  1211. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1212. StringBuilder builder;
  1213. for (auto c : value.bytes_as_string_view()) {
  1214. if (c != '\r' && c != '\n')
  1215. builder.append(c);
  1216. }
  1217. return MUST(builder.to_string());
  1218. }
  1219. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  1220. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  1221. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1222. StringBuilder builder;
  1223. for (auto c : value.bytes_as_string_view()) {
  1224. if (c != '\r' && c != '\n')
  1225. builder.append(c);
  1226. }
  1227. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  1228. }
  1229. return MUST(value.trim(Infra::ASCII_WHITESPACE));
  1230. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  1231. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  1232. // FIXME: handle the `multiple` attribute
  1233. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  1234. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  1235. StringBuilder builder;
  1236. for (auto c : value.bytes_as_string_view()) {
  1237. if (c != '\r' && c != '\n')
  1238. builder.append(c);
  1239. }
  1240. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  1241. }
  1242. return MUST(value.trim(Infra::ASCII_WHITESPACE));
  1243. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  1244. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):value-sanitization-algorithm
  1245. // If the value of the element is not a valid floating-point number, then set it
  1246. // to the empty string instead.
  1247. if (!is_valid_floating_point_number(value))
  1248. return String {};
  1249. auto maybe_value = parse_floating_point_number(value);
  1250. // AD-HOC: The spec doesn’t require these checks — but other engines do them, and
  1251. // there’s a WPT case which tests that the value is less than Number.MAX_VALUE.
  1252. if (!maybe_value.has_value() || !isfinite(maybe_value.value()))
  1253. return String {};
  1254. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  1255. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  1256. if (!is_valid_date_string(value))
  1257. return String {};
  1258. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  1259. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  1260. if (!is_valid_month_string(value))
  1261. return String {};
  1262. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  1263. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  1264. if (!is_valid_week_string(value))
  1265. return String {};
  1266. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  1267. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  1268. if (!is_valid_time_string(value))
  1269. return String {};
  1270. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  1271. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  1272. if (is_valid_local_date_and_time_string(value))
  1273. return normalize_local_date_and_time_string(value);
  1274. return String {};
  1275. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  1276. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  1277. // 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.
  1278. auto maybe_value = parse_floating_point_number(value);
  1279. if (!is_valid_floating_point_number(value) ||
  1280. // AD-HOC: The spec doesn’t require these checks — but other engines do them.
  1281. !maybe_value.has_value() || !isfinite(maybe_value.value())) {
  1282. // 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.
  1283. auto minimum = *min();
  1284. auto maximum = *max();
  1285. if (maximum < minimum)
  1286. return JS::number_to_string(minimum);
  1287. return JS::number_to_string(minimum + (maximum - minimum) / 2);
  1288. }
  1289. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  1290. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  1291. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  1292. if (is_valid_simple_color(value))
  1293. return value.to_ascii_lowercase();
  1294. // otherwise, set it to the string "#000000".
  1295. return "#000000"_string;
  1296. }
  1297. return value;
  1298. }
  1299. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  1300. void HTMLInputElement::reset_algorithm()
  1301. {
  1302. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  1303. m_dirty_value = false;
  1304. m_dirty_checkedness = false;
  1305. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  1306. auto old_value = move(m_value);
  1307. m_value = get_attribute_value(AttributeNames::value);
  1308. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  1309. m_checked = has_attribute(AttributeNames::checked);
  1310. // empty the list of selected files,
  1311. if (m_selected_files)
  1312. m_selected_files = FileAPI::FileList::create(realm());
  1313. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  1314. m_value = value_sanitization_algorithm(m_value);
  1315. if (m_value != old_value)
  1316. relevant_value_was_changed();
  1317. if (m_text_node) {
  1318. m_text_node->set_data(m_value);
  1319. update_placeholder_visibility();
  1320. }
  1321. update_shadow_tree();
  1322. }
  1323. // https://w3c.github.io/webdriver/#dfn-clear-algorithm
  1324. void HTMLInputElement::clear_algorithm()
  1325. {
  1326. // The clear algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  1327. m_dirty_value = false;
  1328. m_dirty_checkedness = false;
  1329. // set the value of the element to an empty string,
  1330. auto old_value = move(m_value);
  1331. m_value = String {};
  1332. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  1333. m_checked = has_attribute(AttributeNames::checked);
  1334. // empty the list of selected files,
  1335. if (m_selected_files)
  1336. m_selected_files = FileAPI::FileList::create(realm());
  1337. // and then invoke the value sanitization algorithm iff the type attribute's current state defines one.
  1338. m_value = value_sanitization_algorithm(m_value);
  1339. // Unlike their associated reset algorithms, changes made to form controls as part of these algorithms do count as
  1340. // changes caused by the user (and thus, e.g. do cause input events to fire).
  1341. user_interaction_did_change_input_value();
  1342. if (m_value != old_value)
  1343. relevant_value_was_changed();
  1344. if (m_text_node) {
  1345. m_text_node->set_data(m_value);
  1346. update_placeholder_visibility();
  1347. }
  1348. update_shadow_tree();
  1349. }
  1350. void HTMLInputElement::form_associated_element_was_inserted()
  1351. {
  1352. create_shadow_tree_if_needed();
  1353. }
  1354. void HTMLInputElement::form_associated_element_was_removed(DOM::Node*)
  1355. {
  1356. set_shadow_root(nullptr);
  1357. }
  1358. void HTMLInputElement::apply_presentational_hints(CSS::StyleProperties& style) const
  1359. {
  1360. if (type_state() != TypeAttributeState::ImageButton)
  1361. return;
  1362. for_each_attribute([&](auto& name, auto& value) {
  1363. if (name == HTML::AttributeNames::align) {
  1364. if (value.equals_ignoring_ascii_case("center"sv))
  1365. style.set_property(CSS::PropertyID::TextAlign, CSS::CSSKeywordValue::create(CSS::Keyword::Center));
  1366. else if (value.equals_ignoring_ascii_case("middle"sv))
  1367. style.set_property(CSS::PropertyID::TextAlign, CSS::CSSKeywordValue::create(CSS::Keyword::Middle));
  1368. } else if (name == HTML::AttributeNames::border) {
  1369. if (auto parsed_value = parse_non_negative_integer(value); parsed_value.has_value() && *parsed_value > 0) {
  1370. auto width_style_value = CSS::LengthStyleValue::create(CSS::Length::make_px(*parsed_value));
  1371. style.set_property(CSS::PropertyID::BorderTopWidth, width_style_value);
  1372. style.set_property(CSS::PropertyID::BorderRightWidth, width_style_value);
  1373. style.set_property(CSS::PropertyID::BorderBottomWidth, width_style_value);
  1374. style.set_property(CSS::PropertyID::BorderLeftWidth, width_style_value);
  1375. auto border_style_value = CSS::CSSKeywordValue::create(CSS::Keyword::Solid);
  1376. style.set_property(CSS::PropertyID::BorderTopStyle, border_style_value);
  1377. style.set_property(CSS::PropertyID::BorderRightStyle, border_style_value);
  1378. style.set_property(CSS::PropertyID::BorderBottomStyle, border_style_value);
  1379. style.set_property(CSS::PropertyID::BorderLeftStyle, border_style_value);
  1380. }
  1381. } else if (name == HTML::AttributeNames::height) {
  1382. if (auto parsed_value = parse_dimension_value(value)) {
  1383. style.set_property(CSS::PropertyID::Height, *parsed_value);
  1384. }
  1385. }
  1386. // https://html.spec.whatwg.org/multipage/rendering.html#attributes-for-embedded-content-and-images:maps-to-the-dimension-property
  1387. else if (name == HTML::AttributeNames::hspace) {
  1388. if (auto parsed_value = parse_dimension_value(value)) {
  1389. style.set_property(CSS::PropertyID::MarginLeft, *parsed_value);
  1390. style.set_property(CSS::PropertyID::MarginRight, *parsed_value);
  1391. }
  1392. } else if (name == HTML::AttributeNames::vspace) {
  1393. if (auto parsed_value = parse_dimension_value(value)) {
  1394. style.set_property(CSS::PropertyID::MarginTop, *parsed_value);
  1395. style.set_property(CSS::PropertyID::MarginBottom, *parsed_value);
  1396. }
  1397. } else if (name == HTML::AttributeNames::width) {
  1398. if (auto parsed_value = parse_dimension_value(value)) {
  1399. style.set_property(CSS::PropertyID::Width, *parsed_value);
  1400. }
  1401. }
  1402. });
  1403. }
  1404. // https://html.spec.whatwg.org/multipage/input.html#the-input-element%3Aconcept-node-clone-ext
  1405. WebIDL::ExceptionOr<void> HTMLInputElement::cloned(DOM::Node& copy, bool)
  1406. {
  1407. // 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.
  1408. auto& input_clone = verify_cast<HTMLInputElement>(copy);
  1409. input_clone.m_value = m_value;
  1410. input_clone.m_dirty_value = m_dirty_value;
  1411. input_clone.m_checked = m_checked;
  1412. input_clone.m_dirty_checkedness = m_dirty_checkedness;
  1413. return {};
  1414. }
  1415. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  1416. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  1417. {
  1418. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  1419. return !value_a.is_empty() && value_a == value_b;
  1420. };
  1421. // The radio button group that contains an input element a also contains all the
  1422. // other input elements b that fulfill all of the following conditions:
  1423. return (
  1424. // - Both a and b are in the same tree.
  1425. &a.root() == &b.root()
  1426. // - The input element b's type attribute is in the Radio Button state.
  1427. && a.type_state() == b.type_state()
  1428. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  1429. // - Either a and b have the same form owner, or they both have no form owner.
  1430. && a.form() == b.form()
  1431. // - They both have a name attribute, their name attributes are not empty, and the
  1432. // value of a's name attribute equals the value of b's name attribute.
  1433. && a.name().has_value()
  1434. && b.name().has_value()
  1435. && non_empty_equals(a.name().value(), b.name().value()));
  1436. }
  1437. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  1438. void HTMLInputElement::set_checked_within_group()
  1439. {
  1440. if (checked())
  1441. return;
  1442. set_checked(true, ChangeSource::User);
  1443. // No point iterating the tree if we have an empty name.
  1444. if (!name().has_value() || name()->is_empty())
  1445. return;
  1446. root().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  1447. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  1448. element.set_checked(false, ChangeSource::User);
  1449. return TraversalDecision::Continue;
  1450. });
  1451. }
  1452. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  1453. void HTMLInputElement::legacy_pre_activation_behavior()
  1454. {
  1455. m_before_legacy_pre_activation_behavior_checked = checked();
  1456. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  1457. // 1. If this element's type attribute is in the Checkbox state, then set
  1458. // this element's checkedness to its opposite value (i.e. true if it is
  1459. // false, false if it is true) and set this element's indeterminate IDL
  1460. // attribute to false.
  1461. if (type_state() == TypeAttributeState::Checkbox) {
  1462. set_checked(!checked(), ChangeSource::User);
  1463. set_indeterminate(false);
  1464. }
  1465. // 2. If this element's type attribute is in the Radio Button state, then
  1466. // get a reference to the element in this element's radio button group that
  1467. // has its checkedness set to true, if any, and then set this element's
  1468. // checkedness to true.
  1469. if (type_state() == TypeAttributeState::RadioButton) {
  1470. root().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  1471. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  1472. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  1473. return TraversalDecision::Break;
  1474. }
  1475. return TraversalDecision::Continue;
  1476. });
  1477. set_checked_within_group();
  1478. }
  1479. }
  1480. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  1481. void HTMLInputElement::legacy_cancelled_activation_behavior()
  1482. {
  1483. // 1. If the element's type attribute is in the Checkbox state, then set the
  1484. // element's checkedness and the element's indeterminate IDL attribute back
  1485. // to the values they had before the legacy-pre-activation behavior was run.
  1486. if (type_state() == TypeAttributeState::Checkbox) {
  1487. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  1488. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  1489. }
  1490. // 2. If this element 's type attribute is in the Radio Button state, then
  1491. // if the element to which a reference was obtained in the
  1492. // legacy-pre-activation behavior, if any, is still in what is now this
  1493. // element' s radio button group, if it still has one, and if so, setting
  1494. // that element 's checkedness to true; or else, if there was no such
  1495. // element, or that element is no longer in this element' s radio button
  1496. // group, or if this element no longer has a radio button group, setting
  1497. // this element's checkedness to false.
  1498. if (type_state() == TypeAttributeState::RadioButton) {
  1499. bool did_reselect_previous_element = false;
  1500. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  1501. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  1502. if (is_in_same_radio_button_group(*this, element_in_group)) {
  1503. element_in_group.set_checked_within_group();
  1504. did_reselect_previous_element = true;
  1505. }
  1506. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  1507. }
  1508. if (!did_reselect_previous_element)
  1509. set_checked(false, ChangeSource::User);
  1510. }
  1511. }
  1512. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  1513. {
  1514. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  1515. }
  1516. JS::GCPtr<DecodedImageData> HTMLInputElement::image_data() const
  1517. {
  1518. if (m_resource_request)
  1519. return m_resource_request->image_data();
  1520. return nullptr;
  1521. }
  1522. bool HTMLInputElement::is_image_available() const
  1523. {
  1524. return image_data() != nullptr;
  1525. }
  1526. Optional<CSSPixels> HTMLInputElement::intrinsic_width() const
  1527. {
  1528. if (auto image_data = this->image_data())
  1529. return image_data->intrinsic_width();
  1530. return {};
  1531. }
  1532. Optional<CSSPixels> HTMLInputElement::intrinsic_height() const
  1533. {
  1534. if (auto image_data = this->image_data())
  1535. return image_data->intrinsic_height();
  1536. return {};
  1537. }
  1538. Optional<CSSPixelFraction> HTMLInputElement::intrinsic_aspect_ratio() const
  1539. {
  1540. if (auto image_data = this->image_data())
  1541. return image_data->intrinsic_aspect_ratio();
  1542. return {};
  1543. }
  1544. RefPtr<Gfx::ImmutableBitmap> HTMLInputElement::current_image_bitmap(Gfx::IntSize size) const
  1545. {
  1546. if (auto image_data = this->image_data())
  1547. return image_data->bitmap(0, size);
  1548. return nullptr;
  1549. }
  1550. void HTMLInputElement::set_visible_in_viewport(bool)
  1551. {
  1552. // FIXME: Loosen grip on image data when it's not visible, e.g via volatile memory.
  1553. }
  1554. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  1555. i32 HTMLInputElement::default_tab_index_value() const
  1556. {
  1557. // See the base function for the spec comments.
  1558. return 0;
  1559. }
  1560. // https://html.spec.whatwg.org/multipage/input.html#dom-input-maxlength
  1561. WebIDL::Long HTMLInputElement::max_length() const
  1562. {
  1563. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  1564. if (auto maxlength_string = get_attribute(HTML::AttributeNames::maxlength); maxlength_string.has_value()) {
  1565. if (auto maxlength = parse_non_negative_integer(*maxlength_string); maxlength.has_value())
  1566. return *maxlength;
  1567. }
  1568. return -1;
  1569. }
  1570. WebIDL::ExceptionOr<void> HTMLInputElement::set_max_length(WebIDL::Long value)
  1571. {
  1572. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  1573. return set_attribute(HTML::AttributeNames::maxlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  1574. }
  1575. // https://html.spec.whatwg.org/multipage/input.html#dom-input-minlength
  1576. WebIDL::Long HTMLInputElement::min_length() const
  1577. {
  1578. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  1579. if (auto minlength_string = get_attribute(HTML::AttributeNames::minlength); minlength_string.has_value()) {
  1580. if (auto minlength = parse_non_negative_integer(*minlength_string); minlength.has_value())
  1581. return *minlength;
  1582. }
  1583. return -1;
  1584. }
  1585. WebIDL::ExceptionOr<void> HTMLInputElement::set_min_length(WebIDL::Long value)
  1586. {
  1587. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  1588. return set_attribute(HTML::AttributeNames::minlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  1589. }
  1590. // https://html.spec.whatwg.org/multipage/input.html#the-size-attribute
  1591. unsigned HTMLInputElement::size() const
  1592. {
  1593. // The size IDL attribute is limited to only positive numbers and has a default value of 20.
  1594. if (auto size_string = get_attribute(HTML::AttributeNames::size); size_string.has_value()) {
  1595. if (auto size = parse_non_negative_integer(*size_string); size.has_value())
  1596. return *size;
  1597. }
  1598. return 20;
  1599. }
  1600. WebIDL::ExceptionOr<void> HTMLInputElement::set_size(unsigned value)
  1601. {
  1602. return set_attribute(HTML::AttributeNames::size, String::number(value));
  1603. }
  1604. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  1605. Optional<double> HTMLInputElement::convert_string_to_number(StringView input) const
  1606. {
  1607. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-string-number
  1608. if (type_state() == TypeAttributeState::Number)
  1609. return parse_floating_point_number(input);
  1610. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-string-number
  1611. if (type_state() == TypeAttributeState::Range)
  1612. return parse_floating_point_number(input);
  1613. dbgln("HTMLInputElement::convert_string_to_number() not implemented for input type {}", type());
  1614. return {};
  1615. }
  1616. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-number
  1617. String HTMLInputElement::convert_number_to_string(double input) const
  1618. {
  1619. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-value-number-string
  1620. if (type_state() == TypeAttributeState::Number)
  1621. return String::number(input);
  1622. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-value-number-string
  1623. if (type_state() == TypeAttributeState::Range)
  1624. return String::number(input);
  1625. dbgln("HTMLInputElement::convert_number_to_string() not implemented for input type {}", type());
  1626. return {};
  1627. }
  1628. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-string-date
  1629. WebIDL::ExceptionOr<JS::GCPtr<JS::Date>> HTMLInputElement::convert_string_to_date(StringView input) const
  1630. {
  1631. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-string-date
  1632. if (type_state() == TypeAttributeState::Date) {
  1633. // If parsing a date from input results in an error, then return an error;
  1634. auto maybe_date = parse_date_string(realm(), input);
  1635. if (maybe_date.is_exception())
  1636. return maybe_date.exception();
  1637. // otherwise, return a new Date object representing midnight UTC on the morning of the parsed date.
  1638. return maybe_date.value();
  1639. }
  1640. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  1641. if (type_state() == TypeAttributeState::Time) {
  1642. // If parsing a time from input results in an error, then return an error;
  1643. auto maybe_time = parse_time_string(realm(), input);
  1644. if (maybe_time.is_exception())
  1645. return maybe_time.exception();
  1646. // otherwise, return a new Date object representing the parsed time in UTC on 1970-01-01.
  1647. return maybe_time.value();
  1648. }
  1649. dbgln("HTMLInputElement::convert_string_to_date() not implemented for input type {}", type());
  1650. return nullptr;
  1651. }
  1652. // https://html.spec.whatwg.org/multipage/input.html#concept-input-value-date-string
  1653. String HTMLInputElement::covert_date_to_string(JS::NonnullGCPtr<JS::Date> input) const
  1654. {
  1655. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):concept-input-value-date-string
  1656. if (type_state() == TypeAttributeState::Date) {
  1657. // Return a valid date string that represents the date current at the time represented by input in the UTC time zone.
  1658. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  1659. 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())));
  1660. }
  1661. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):concept-input-value-string-date
  1662. if (type_state() == TypeAttributeState::Time) {
  1663. // Return a valid time string that represents the UTC time component that is represented by input.
  1664. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  1665. auto seconds = JS::sec_from_time(input->date_value());
  1666. auto milliseconds = JS::ms_from_time(input->date_value());
  1667. if (seconds > 0) {
  1668. if (milliseconds > 0)
  1669. return MUST(String::formatted("{:02d}:{:02d}:{:02d}.{:3d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds, milliseconds));
  1670. return MUST(String::formatted("{:02d}:{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value()), seconds));
  1671. }
  1672. return MUST(String::formatted("{:02d}:{:02d}", JS::hour_from_time(input->date_value()), JS::min_from_time(input->date_value())));
  1673. }
  1674. dbgln("HTMLInputElement::covert_date_to_string() not implemented for input type {}", type());
  1675. return {};
  1676. }
  1677. // https://html.spec.whatwg.org/multipage/input.html#attr-input-min
  1678. Optional<double> HTMLInputElement::min() const
  1679. {
  1680. // If the element has a min attribute, and the result of applying the algorithm to convert a string to a number to
  1681. // the value of the min attribute is a number, then that number is the element's minimum; otherwise, if the type
  1682. // attribute's current state defines a default minimum, then that is the minimum; otherwise, the element has no minimum.
  1683. if (auto min_string = get_attribute(HTML::AttributeNames::min); min_string.has_value()) {
  1684. if (auto min = convert_string_to_number(*min_string); min.has_value())
  1685. return *min;
  1686. }
  1687. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-min-default
  1688. if (type_state() == TypeAttributeState::Range)
  1689. return 0;
  1690. return {};
  1691. }
  1692. // https://html.spec.whatwg.org/multipage/input.html#attr-input-max
  1693. Optional<double> HTMLInputElement::max() const
  1694. {
  1695. // If the element has a max attribute, and the result of applying the algorithm to convert a string to a number to the
  1696. // value of the max attribute is a number, then that number is the element's maximum; otherwise, if the type attribute's
  1697. // current state defines a default maximum, then that is the maximum; otherwise, the element has no maximum.
  1698. if (auto max_string = get_attribute(HTML::AttributeNames::max); max_string.has_value()) {
  1699. if (auto max = convert_string_to_number(*max_string); max.has_value())
  1700. return *max;
  1701. }
  1702. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-max-default
  1703. if (type_state() == TypeAttributeState::Range)
  1704. return 100;
  1705. return {};
  1706. }
  1707. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-default
  1708. double HTMLInputElement::default_step() const
  1709. {
  1710. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-default
  1711. if (type_state() == TypeAttributeState::Number)
  1712. return 1;
  1713. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-default
  1714. if (type_state() == TypeAttributeState::Range)
  1715. return 1;
  1716. dbgln("HTMLInputElement::default_step() not implemented for input type {}", type());
  1717. return 0;
  1718. }
  1719. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step-scale
  1720. double HTMLInputElement::step_scale_factor() const
  1721. {
  1722. // https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number):concept-input-step-scale
  1723. if (type_state() == TypeAttributeState::Number)
  1724. return 1;
  1725. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):concept-input-step-scale
  1726. if (type_state() == TypeAttributeState::Range)
  1727. return 1;
  1728. dbgln("HTMLInputElement::step_scale_factor() not implemented for input type {}", type());
  1729. return 0;
  1730. }
  1731. // https://html.spec.whatwg.org/multipage/input.html#concept-input-step
  1732. Optional<double> HTMLInputElement::allowed_value_step() const
  1733. {
  1734. // 1. If the attribute does not apply, then there is no allowed value step.
  1735. if (!step_applies())
  1736. return {};
  1737. // 2. Otherwise, if the attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.
  1738. auto maybe_step_string = get_attribute(AttributeNames::step);
  1739. if (!maybe_step_string.has_value())
  1740. return default_step() * step_scale_factor();
  1741. auto step_string = *maybe_step_string;
  1742. // 3. Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.
  1743. if (Infra::is_ascii_case_insensitive_match(step_string, "any"_string))
  1744. return {};
  1745. // 4. Otherwise, if the rules for parsing floating-point number values, when they are applied to the attribute's value, return an error,
  1746. // zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.
  1747. auto maybe_step = parse_floating_point_number(step_string);
  1748. if (!maybe_step.has_value() || *maybe_step == 0 || *maybe_step < 0)
  1749. return default_step() * step_scale_factor();
  1750. // 5. Otherwise, the allowed value step is the number returned by the rules for parsing floating-point number values when they are applied
  1751. // to the attribute's value, multiplied by the step scale factor.
  1752. return *maybe_step * step_scale_factor();
  1753. }
  1754. // https://html.spec.whatwg.org/multipage/input.html#concept-input-min-zero
  1755. double HTMLInputElement::step_base() const
  1756. {
  1757. // 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
  1758. // the min content attribute is not an error, then return that result.
  1759. if (auto min = this->min(); min.has_value())
  1760. return *min;
  1761. // 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
  1762. // the value content attribute is not an error, then return that result.
  1763. if (auto value = convert_string_to_number(this->value()); value.has_value())
  1764. return *value;
  1765. // 3. If a default step base is defined for this element given its type attribute's state, then return it.
  1766. if (type_state() == TypeAttributeState::Week) {
  1767. // The default step base is −259,200,000 (the start of week 1970-W01).
  1768. return -259'200'000;
  1769. }
  1770. // 4. Return zero.
  1771. return 0;
  1772. }
  1773. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1774. JS::Object* HTMLInputElement::value_as_date() const
  1775. {
  1776. // On getting, if the valueAsDate attribute does not apply, as defined for the input element's type attribute's current state, then return null.
  1777. if (!value_as_date_applies())
  1778. return nullptr;
  1779. // Otherwise, run the algorithm to convert a string to a Date object defined for that state to the element's value;
  1780. // if the algorithm returned a Date object, then return it, otherwise, return null.
  1781. auto maybe_date = convert_string_to_date(value());
  1782. if (!maybe_date.is_exception())
  1783. return maybe_date.value().ptr();
  1784. return nullptr;
  1785. }
  1786. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasdate
  1787. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_date(Optional<JS::Handle<JS::Object>> const& value)
  1788. {
  1789. // 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;
  1790. if (!value_as_date_applies())
  1791. return WebIDL::InvalidStateError::create(realm(), "valueAsDate: Invalid input type used"_string);
  1792. // otherwise, if the new value is not null and not a Date object throw a TypeError exception;
  1793. if (value.has_value() && !is<JS::Date>(**value))
  1794. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsDate: input is not a Date"sv };
  1795. // 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;
  1796. if (!value.has_value()) {
  1797. TRY(set_value(String {}));
  1798. return {};
  1799. }
  1800. auto& date = static_cast<JS::Date&>(**value);
  1801. if (!isfinite(date.date_value())) {
  1802. TRY(set_value(String {}));
  1803. return {};
  1804. }
  1805. // 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.
  1806. TRY(set_value(covert_date_to_string(date)));
  1807. return {};
  1808. }
  1809. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1810. double HTMLInputElement::value_as_number() const
  1811. {
  1812. // 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.
  1813. if (!value_as_number_applies())
  1814. return NAN;
  1815. // Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value;
  1816. // if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
  1817. return convert_string_to_number(value()).value_or(NAN);
  1818. }
  1819. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1820. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  1821. {
  1822. // On setting, if the new value is infinite, then throw a TypeError exception.
  1823. if (!isfinite(value))
  1824. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  1825. // 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.
  1826. if (!value_as_number_applies())
  1827. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_string);
  1828. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  1829. if (value == NAN) {
  1830. TRY(set_value(String {}));
  1831. return {};
  1832. }
  1833. // 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.
  1834. TRY(set_value(convert_number_to_string(value)));
  1835. return {};
  1836. }
  1837. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1838. WebIDL::ExceptionOr<void> HTMLInputElement::step_up(WebIDL::Long n)
  1839. {
  1840. return step_up_or_down(false, n);
  1841. }
  1842. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepdown
  1843. WebIDL::ExceptionOr<void> HTMLInputElement::step_down(WebIDL::Long n)
  1844. {
  1845. return step_up_or_down(true, n);
  1846. }
  1847. // https://html.spec.whatwg.org/multipage/input.html#dom-input-stepup
  1848. WebIDL::ExceptionOr<void> HTMLInputElement::step_up_or_down(bool is_down, WebIDL::Long n)
  1849. {
  1850. // 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.
  1851. if (!step_up_or_down_applies())
  1852. return WebIDL::InvalidStateError::create(realm(), MUST(String::formatted("{}: Invalid input type used", is_down ? "stepDown()" : "stepUp()")));
  1853. // 2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.
  1854. auto maybe_allowed_value_step = allowed_value_step();
  1855. if (!maybe_allowed_value_step.has_value())
  1856. return WebIDL::InvalidStateError::create(realm(), "element has no allowed value step"_string);
  1857. double allowed_value_step = *maybe_allowed_value_step;
  1858. // 3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then return.
  1859. auto maybe_minimum = min();
  1860. auto maybe_maximum = max();
  1861. if (maybe_minimum.has_value() && maybe_maximum.has_value() && *maybe_minimum > *maybe_maximum)
  1862. return {};
  1863. // 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
  1864. // 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.
  1865. // 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,
  1866. // then let value be the result of that algorithm. Otherwise, let value be zero.
  1867. double value = convert_string_to_number(this->value()).value_or(0);
  1868. // 6. Let valueBeforeStepping be value.
  1869. double value_before_stepping = value;
  1870. // 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,
  1871. // 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.
  1872. if (fmod(step_base() - value, allowed_value_step) != 0) {
  1873. double diff = step_base() - value;
  1874. if (is_down) {
  1875. value = diff - fmod(diff, allowed_value_step);
  1876. } else {
  1877. value = diff + fmod(diff, allowed_value_step);
  1878. }
  1879. } else {
  1880. // 1. Let n be the argument.
  1881. // 2. Let delta be the allowed value step multiplied by n.
  1882. double delta = allowed_value_step * n;
  1883. // 3. If the method invoked was the stepDown() method, negate delta.
  1884. if (is_down)
  1885. delta = -delta;
  1886. // 4. Let value be the result of adding delta to value.
  1887. value += delta;
  1888. }
  1889. // 8. If the element has a minimum, and value is less than that minimum, then set value to the smallest value that,
  1890. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is more than or equal to minimum.
  1891. if (maybe_minimum.has_value() && value < *maybe_minimum) {
  1892. value = AK::max(value, *maybe_minimum);
  1893. }
  1894. // 9. If the element has a maximum, and value is greater than that maximum, then set value to the largest value that,
  1895. // when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than or equal to maximum.
  1896. if (maybe_maximum.has_value() && value > *maybe_maximum) {
  1897. value = AK::min(value, *maybe_maximum);
  1898. }
  1899. // 10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping,
  1900. // or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then return.
  1901. if (is_down) {
  1902. if (value > value_before_stepping)
  1903. return {};
  1904. } else {
  1905. if (value < value_before_stepping)
  1906. return {};
  1907. }
  1908. // 11. Let value as string be the result of running the algorithm to convert a number to a string,
  1909. // as defined for the input element's type attribute's current state, on value.
  1910. auto value_as_string = convert_number_to_string(value);
  1911. // 12. Set the value of the element to value as string.
  1912. TRY(set_value(value_as_string));
  1913. return {};
  1914. }
  1915. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1916. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1917. {
  1918. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1919. return true;
  1920. }
  1921. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1922. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1923. {
  1924. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1925. return true;
  1926. }
  1927. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1928. void HTMLInputElement::set_custom_validity(String const& error)
  1929. {
  1930. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1931. return;
  1932. }
  1933. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1934. {
  1935. // https://www.w3.org/TR/html-aria/#el-input-button
  1936. if (type_state() == TypeAttributeState::Button)
  1937. return ARIA::Role::button;
  1938. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1939. if (type_state() == TypeAttributeState::Checkbox)
  1940. return ARIA::Role::checkbox;
  1941. // https://www.w3.org/TR/html-aria/#el-input-email
  1942. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1943. return ARIA::Role::textbox;
  1944. // https://www.w3.org/TR/html-aria/#el-input-image
  1945. if (type_state() == TypeAttributeState::ImageButton)
  1946. return ARIA::Role::button;
  1947. // https://www.w3.org/TR/html-aria/#el-input-number
  1948. if (type_state() == TypeAttributeState::Number)
  1949. return ARIA::Role::spinbutton;
  1950. // https://www.w3.org/TR/html-aria/#el-input-radio
  1951. if (type_state() == TypeAttributeState::RadioButton)
  1952. return ARIA::Role::radio;
  1953. // https://www.w3.org/TR/html-aria/#el-input-range
  1954. if (type_state() == TypeAttributeState::Range)
  1955. return ARIA::Role::slider;
  1956. // https://www.w3.org/TR/html-aria/#el-input-reset
  1957. if (type_state() == TypeAttributeState::ResetButton)
  1958. return ARIA::Role::button;
  1959. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1960. if ((type_state() == TypeAttributeState::Text
  1961. || type_state() == TypeAttributeState::Search
  1962. || type_state() == TypeAttributeState::Telephone
  1963. || type_state() == TypeAttributeState::URL
  1964. || type_state() == TypeAttributeState::Email)
  1965. && has_attribute(AttributeNames::list))
  1966. return ARIA::Role::combobox;
  1967. // https://www.w3.org/TR/html-aria/#el-input-search
  1968. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1969. return ARIA::Role::searchbox;
  1970. // https://www.w3.org/TR/html-aria/#el-input-submit
  1971. if (type_state() == TypeAttributeState::SubmitButton)
  1972. return ARIA::Role::button;
  1973. // https://www.w3.org/TR/html-aria/#el-input-tel
  1974. if (type_state() == TypeAttributeState::Telephone)
  1975. return ARIA::Role::textbox;
  1976. // https://www.w3.org/TR/html-aria/#el-input-text
  1977. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1978. return ARIA::Role::textbox;
  1979. // https://www.w3.org/TR/html-aria/#el-input-url
  1980. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1981. return ARIA::Role::textbox;
  1982. // https://www.w3.org/TR/html-aria/#el-input-color
  1983. // https://www.w3.org/TR/html-aria/#el-input-date
  1984. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1985. // https://www.w3.org/TR/html-aria/#el-input-file
  1986. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1987. // https://www.w3.org/TR/html-aria/#el-input-month
  1988. // https://www.w3.org/TR/html-aria/#el-input-password
  1989. // https://www.w3.org/TR/html-aria/#el-input-time
  1990. // https://www.w3.org/TR/html-aria/#el-input-week
  1991. return {};
  1992. }
  1993. bool HTMLInputElement::is_button() const
  1994. {
  1995. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1996. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1997. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1998. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1999. return type_state() == TypeAttributeState::SubmitButton
  2000. || type_state() == TypeAttributeState::ImageButton
  2001. || type_state() == TypeAttributeState::ResetButton
  2002. || type_state() == TypeAttributeState::Button;
  2003. }
  2004. bool HTMLInputElement::is_submit_button() const
  2005. {
  2006. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  2007. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  2008. return type_state() == TypeAttributeState::SubmitButton
  2009. || type_state() == TypeAttributeState::ImageButton;
  2010. }
  2011. // https://html.spec.whatwg.org/multipage/input.html#text-(type=text)-state-and-search-state-(type=search)
  2012. // https://html.spec.whatwg.org/multipage/input.html#password-state-(type=password)
  2013. // "one line plain text edit control"
  2014. bool HTMLInputElement::is_single_line() const
  2015. {
  2016. // NOTE: For web compatibility reasons, we consider other types
  2017. // in addition to Text, Search, and Password as single line inputs.
  2018. return type_state() == TypeAttributeState::Text
  2019. || type_state() == TypeAttributeState::Search
  2020. || type_state() == TypeAttributeState::Password
  2021. || type_state() == TypeAttributeState::Email
  2022. || type_state() == TypeAttributeState::Telephone
  2023. || type_state() == TypeAttributeState::Number;
  2024. }
  2025. bool HTMLInputElement::has_activation_behavior() const
  2026. {
  2027. return true;
  2028. }
  2029. void HTMLInputElement::activation_behavior(DOM::Event const& event)
  2030. {
  2031. // The activation behavior for input elements are these steps:
  2032. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  2033. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  2034. run_input_activation_behavior(event).release_value_but_fixme_should_propagate_errors();
  2035. }
  2036. bool HTMLInputElement::has_input_activation_behavior() const
  2037. {
  2038. switch (type_state()) {
  2039. case TypeAttributeState::Checkbox:
  2040. case TypeAttributeState::Color:
  2041. case TypeAttributeState::FileUpload:
  2042. case TypeAttributeState::ImageButton:
  2043. case TypeAttributeState::RadioButton:
  2044. case TypeAttributeState::ResetButton:
  2045. case TypeAttributeState::SubmitButton:
  2046. return true;
  2047. default:
  2048. return false;
  2049. }
  2050. }
  2051. // https://html.spec.whatwg.org/multipage/input.html#do-not-apply
  2052. bool HTMLInputElement::select_applies() const
  2053. {
  2054. switch (type_state()) {
  2055. case TypeAttributeState::Button:
  2056. case TypeAttributeState::Checkbox:
  2057. case TypeAttributeState::Hidden:
  2058. case TypeAttributeState::ImageButton:
  2059. case TypeAttributeState::RadioButton:
  2060. case TypeAttributeState::Range:
  2061. case TypeAttributeState::ResetButton:
  2062. case TypeAttributeState::SubmitButton:
  2063. return false;
  2064. default:
  2065. return true;
  2066. }
  2067. }
  2068. // https://html.spec.whatwg.org/multipage/input.html#do-not-apply
  2069. bool HTMLInputElement::selection_or_range_applies() const
  2070. {
  2071. return selection_or_range_applies_for_type_state(type_state());
  2072. }
  2073. // https://html.spec.whatwg.org/multipage/input.html#do-not-apply
  2074. bool HTMLInputElement::selection_direction_applies() const
  2075. {
  2076. switch (type_state()) {
  2077. case TypeAttributeState::Text:
  2078. case TypeAttributeState::Search:
  2079. case TypeAttributeState::Telephone:
  2080. case TypeAttributeState::URL:
  2081. case TypeAttributeState::Password:
  2082. return true;
  2083. default:
  2084. return false;
  2085. }
  2086. }
  2087. bool HTMLInputElement::has_selectable_text() const
  2088. {
  2089. // Potential FIXME: Date, Month, Week, Time and LocalDateAndTime are rendered as a basic text input for now,
  2090. // thus they have selectable text, this need to change when we will have a visual date/time selector.
  2091. switch (type_state()) {
  2092. case TypeAttributeState::Text:
  2093. case TypeAttributeState::Search:
  2094. case TypeAttributeState::Telephone:
  2095. case TypeAttributeState::URL:
  2096. case TypeAttributeState::Password:
  2097. case TypeAttributeState::Date:
  2098. case TypeAttributeState::Month:
  2099. case TypeAttributeState::Week:
  2100. case TypeAttributeState::Time:
  2101. case TypeAttributeState::LocalDateAndTime:
  2102. case TypeAttributeState::Number:
  2103. return true;
  2104. default:
  2105. return false;
  2106. }
  2107. }
  2108. bool HTMLInputElement::selection_or_range_applies_for_type_state(TypeAttributeState type_state)
  2109. {
  2110. switch (type_state) {
  2111. case TypeAttributeState::Text:
  2112. case TypeAttributeState::Search:
  2113. case TypeAttributeState::Telephone:
  2114. case TypeAttributeState::URL:
  2115. case TypeAttributeState::Password:
  2116. return true;
  2117. default:
  2118. return false;
  2119. }
  2120. }
  2121. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:event-change-2
  2122. bool HTMLInputElement::change_event_applies() const
  2123. {
  2124. switch (type_state()) {
  2125. case TypeAttributeState::Checkbox:
  2126. case TypeAttributeState::Color:
  2127. case TypeAttributeState::Date:
  2128. case TypeAttributeState::Email:
  2129. case TypeAttributeState::FileUpload:
  2130. case TypeAttributeState::LocalDateAndTime:
  2131. case TypeAttributeState::Month:
  2132. case TypeAttributeState::Number:
  2133. case TypeAttributeState::Password:
  2134. case TypeAttributeState::RadioButton:
  2135. case TypeAttributeState::Range:
  2136. case TypeAttributeState::Search:
  2137. case TypeAttributeState::Telephone:
  2138. case TypeAttributeState::Text:
  2139. case TypeAttributeState::Time:
  2140. case TypeAttributeState::URL:
  2141. case TypeAttributeState::Week:
  2142. return true;
  2143. default:
  2144. return false;
  2145. }
  2146. }
  2147. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasdate-3
  2148. bool HTMLInputElement::value_as_date_applies() const
  2149. {
  2150. switch (type_state()) {
  2151. case TypeAttributeState::Date:
  2152. case TypeAttributeState::Month:
  2153. case TypeAttributeState::Week:
  2154. case TypeAttributeState::Time:
  2155. return true;
  2156. default:
  2157. return false;
  2158. }
  2159. }
  2160. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-valueasnumber-3
  2161. bool HTMLInputElement::value_as_number_applies() const
  2162. {
  2163. switch (type_state()) {
  2164. case TypeAttributeState::Date:
  2165. case TypeAttributeState::Month:
  2166. case TypeAttributeState::Week:
  2167. case TypeAttributeState::Time:
  2168. case TypeAttributeState::LocalDateAndTime:
  2169. case TypeAttributeState::Number:
  2170. case TypeAttributeState::Range:
  2171. return true;
  2172. default:
  2173. return false;
  2174. }
  2175. }
  2176. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-step-3
  2177. bool HTMLInputElement::step_applies() const
  2178. {
  2179. return value_as_number_applies();
  2180. }
  2181. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-stepup-3
  2182. bool HTMLInputElement::step_up_or_down_applies() const
  2183. {
  2184. return value_as_number_applies();
  2185. }
  2186. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:dom-input-value-2
  2187. HTMLInputElement::ValueAttributeMode HTMLInputElement::value_attribute_mode_for_type_state(TypeAttributeState type_state)
  2188. {
  2189. switch (type_state) {
  2190. case TypeAttributeState::Text:
  2191. case TypeAttributeState::Search:
  2192. case TypeAttributeState::Telephone:
  2193. case TypeAttributeState::URL:
  2194. case TypeAttributeState::Email:
  2195. case TypeAttributeState::Password:
  2196. case TypeAttributeState::Date:
  2197. case TypeAttributeState::Month:
  2198. case TypeAttributeState::Week:
  2199. case TypeAttributeState::Time:
  2200. case TypeAttributeState::LocalDateAndTime:
  2201. case TypeAttributeState::Number:
  2202. case TypeAttributeState::Range:
  2203. case TypeAttributeState::Color:
  2204. return ValueAttributeMode::Value;
  2205. case TypeAttributeState::Hidden:
  2206. case TypeAttributeState::SubmitButton:
  2207. case TypeAttributeState::ImageButton:
  2208. case TypeAttributeState::ResetButton:
  2209. case TypeAttributeState::Button:
  2210. return ValueAttributeMode::Default;
  2211. case TypeAttributeState::Checkbox:
  2212. case TypeAttributeState::RadioButton:
  2213. return ValueAttributeMode::DefaultOn;
  2214. case TypeAttributeState::FileUpload:
  2215. return ValueAttributeMode::Filename;
  2216. }
  2217. VERIFY_NOT_REACHED();
  2218. }
  2219. HTMLInputElement::ValueAttributeMode HTMLInputElement::value_attribute_mode() const
  2220. {
  2221. return value_attribute_mode_for_type_state(type_state());
  2222. }
  2223. bool HTMLInputElement::is_focusable() const
  2224. {
  2225. return m_type != TypeAttributeState::Hidden && enabled();
  2226. }
  2227. }