HTMLInputElement.cpp 117 KB

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