HTMLInputElement.cpp 106 KB

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