HTMLInputElement.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  1. /*
  2. * Copyright (c) 2018-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Adam Hodgen <ant1441@gmail.com>
  4. * Copyright (c) 2022, Andrew Kaster <akaster@serenityos.org>
  5. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  10. #include <LibWeb/CSS/StyleValues/IdentifierStyleValue.h>
  11. #include <LibWeb/DOM/Document.h>
  12. #include <LibWeb/DOM/ElementFactory.h>
  13. #include <LibWeb/DOM/Event.h>
  14. #include <LibWeb/DOM/ShadowRoot.h>
  15. #include <LibWeb/HTML/BrowsingContext.h>
  16. #include <LibWeb/HTML/EventNames.h>
  17. #include <LibWeb/HTML/HTMLDivElement.h>
  18. #include <LibWeb/HTML/HTMLFormElement.h>
  19. #include <LibWeb/HTML/HTMLInputElement.h>
  20. #include <LibWeb/HTML/Scripting/Environments.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/Infra/CharacterTypes.h>
  23. #include <LibWeb/Layout/BlockContainer.h>
  24. #include <LibWeb/Layout/ButtonBox.h>
  25. #include <LibWeb/Layout/CheckBox.h>
  26. #include <LibWeb/Layout/RadioButton.h>
  27. #include <LibWeb/Namespace.h>
  28. #include <LibWeb/Page/Page.h>
  29. #include <LibWeb/WebIDL/DOMException.h>
  30. #include <LibWeb/WebIDL/ExceptionOr.h>
  31. namespace Web::HTML {
  32. JS_DEFINE_ALLOCATOR(HTMLInputElement);
  33. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  34. : HTMLElement(document, move(qualified_name))
  35. , m_value(DeprecatedString::empty())
  36. {
  37. }
  38. HTMLInputElement::~HTMLInputElement() = default;
  39. void HTMLInputElement::initialize(JS::Realm& realm)
  40. {
  41. Base::initialize(realm);
  42. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLInputElementPrototype>(realm, "HTMLInputElement"));
  43. }
  44. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  45. {
  46. Base::visit_edges(visitor);
  47. visitor.visit(m_inner_text_element);
  48. visitor.visit(m_text_node);
  49. visitor.visit(m_placeholder_element);
  50. visitor.visit(m_placeholder_text_node);
  51. visitor.visit(m_color_well_element);
  52. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group);
  53. visitor.visit(m_selected_files);
  54. }
  55. JS::GCPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  56. {
  57. if (type_state() == TypeAttributeState::Hidden)
  58. return nullptr;
  59. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton || type_state() == TypeAttributeState::FileUpload)
  60. return heap().allocate_without_realm<Layout::ButtonBox>(document(), *this, move(style));
  61. if (type_state() == TypeAttributeState::Checkbox)
  62. return heap().allocate_without_realm<Layout::CheckBox>(document(), *this, move(style));
  63. if (type_state() == TypeAttributeState::RadioButton)
  64. return heap().allocate_without_realm<Layout::RadioButton>(document(), *this, move(style));
  65. // AD-HOC: We rewrite `display: inline` to `display: inline-block`.
  66. // This is required for the internal shadow tree to work correctly in layout.
  67. if (style->display().is_inline_outside() && style->display().is_flow_inside())
  68. style->set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::InlineBlock)));
  69. return Element::create_layout_node_for_display_type(document(), style->display(), style, this);
  70. }
  71. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  72. {
  73. if (m_checked == checked)
  74. return;
  75. // The dirty checkedness flag must be initially set to false when the element is created,
  76. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  77. if (change_source == ChangeSource::User)
  78. m_dirty_checkedness = true;
  79. m_checked = checked;
  80. // This element's :checked pseudo-class could be used in a sibling's sibling-selector,
  81. // so we need to invalidate the style of all siblings.
  82. if (parent()) {
  83. parent()->for_each_child([&](auto& child) {
  84. child.invalidate_style();
  85. });
  86. }
  87. }
  88. void HTMLInputElement::set_checked_binding(bool checked)
  89. {
  90. if (type_state() == TypeAttributeState::RadioButton) {
  91. if (checked)
  92. set_checked_within_group();
  93. else
  94. set_checked(false, ChangeSource::Programmatic);
  95. } else {
  96. set_checked(checked, ChangeSource::Programmatic);
  97. }
  98. }
  99. // https://html.spec.whatwg.org/multipage/input.html#dom-input-indeterminate
  100. void HTMLInputElement::set_indeterminate(bool value)
  101. {
  102. // On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.
  103. m_indeterminate = value;
  104. }
  105. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  106. JS::GCPtr<FileAPI::FileList> HTMLInputElement::files()
  107. {
  108. // On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files.
  109. // The same object must be returned until the list of selected files changes.
  110. // If the IDL attribute does not apply, then it must instead return null.
  111. if (m_type != TypeAttributeState::FileUpload)
  112. return nullptr;
  113. if (!m_selected_files)
  114. m_selected_files = FileAPI::FileList::create(realm(), {});
  115. return m_selected_files;
  116. }
  117. // https://html.spec.whatwg.org/multipage/input.html#dom-input-files
  118. void HTMLInputElement::set_files(JS::GCPtr<FileAPI::FileList> files)
  119. {
  120. // 1. If the IDL attribute does not apply or the given value is null, then return.
  121. if (m_type != TypeAttributeState::FileUpload || files == nullptr)
  122. return;
  123. // 2. Replace the element's selected files with the given value.
  124. m_selected_files = files;
  125. }
  126. // https://html.spec.whatwg.org/multipage/input.html#update-the-file-selection
  127. void HTMLInputElement::update_the_file_selection(JS::NonnullGCPtr<FileAPI::FileList> files)
  128. {
  129. // 1. Queue an element task on the user interaction task source given element and the following steps:
  130. queue_an_element_task(Task::Source::UserInteraction, [this, files] {
  131. // 1. Update element's selected files so that it represents the user's selection.
  132. this->set_files(files.ptr());
  133. // 2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.
  134. auto input_event = DOM::Event::create(this->realm(), EventNames::input, { .bubbles = true, .composed = true });
  135. this->dispatch_event(input_event);
  136. // 3. Fire an event named change at the input element, with the bubbles attribute initialized to true.
  137. auto change_event = DOM::Event::create(this->realm(), EventNames::change, { .bubbles = true });
  138. this->dispatch_event(change_event);
  139. });
  140. }
  141. // https://html.spec.whatwg.org/multipage/input.html#show-the-picker,-if-applicable
  142. static void show_the_picker_if_applicable(HTMLInputElement& element)
  143. {
  144. // To show the picker, if applicable for an input element element:
  145. // 1. If element's relevant global object does not have transient activation, then return.
  146. auto& global_object = relevant_global_object(element);
  147. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation())
  148. return;
  149. // 2. If element is not mutable, then return.
  150. if (!element.is_mutable())
  151. return;
  152. // 3. If element's type attribute is in the File Upload state, then run these steps in parallel:
  153. if (element.type_state() == HTMLInputElement::TypeAttributeState::FileUpload) {
  154. // NOTE: These steps cannot be fully implemented here, and must be done in the PageClient when the response comes back from the PageHost
  155. // 1. Optionally, wait until any prior execution of this algorithm has terminated.
  156. // 2. Display a prompt to the user requesting that the user specify some files.
  157. // If the multiple attribute is not set on element, there must be no more than one file selected; otherwise, any number may be selected.
  158. // 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.
  159. // 3. Wait for the user to have made their selection.
  160. // 4. If the user dismissed the prompt without changing their selection,
  161. // then queue an element task on the user interaction task source given element to fire an event named cancel at element,
  162. // with the bubbles attribute initialized to true.
  163. // 5. Otherwise, update the file selection for element.
  164. bool const multiple = element.has_attribute(HTML::AttributeNames::multiple);
  165. auto weak_element = element.make_weak_ptr<DOM::EventTarget>();
  166. // FIXME: Pass along accept attribute information https://html.spec.whatwg.org/multipage/input.html#attr-input-accept
  167. // The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.
  168. element.document().browsing_context()->top_level_browsing_context()->page()->client().page_did_request_file_picker(weak_element, multiple);
  169. return;
  170. }
  171. // 4. Otherwise, the user agent should show any relevant user interface for selecting a value for element,
  172. // 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.)
  173. // If such a user interface is shown, it must respect the requirements stated in the relevant parts of the specification for how element
  174. // behaves given its type attribute state. (For example, various sections describe restrictions on the resulting value string.)
  175. // This step can have side effects, such as closing other pickers that were previously shown by this algorithm.
  176. // (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.)
  177. if (element.type_state() == HTMLInputElement::TypeAttributeState::Color) {
  178. auto weak_element = element.make_weak_ptr<HTMLInputElement>();
  179. element.document().browsing_context()->top_level_browsing_context()->page()->did_request_color_picker(weak_element, Color::from_string(MUST(String::from_deprecated_string(element.value()))).value_or(Color(0, 0, 0)));
  180. }
  181. }
  182. // https://html.spec.whatwg.org/multipage/input.html#dom-input-showpicker
  183. WebIDL::ExceptionOr<void> HTMLInputElement::show_picker()
  184. {
  185. // The showPicker() method steps are:
  186. // 1. If this is not mutable, then throw an "InvalidStateError" DOMException.
  187. if (!m_is_mutable)
  188. return WebIDL::InvalidStateError::create(realm(), "Element is not mutable"_fly_string);
  189. // 2. If this's relevant settings object's origin is not same origin with this's relevant settings object's top-level origin,
  190. // and this's type attribute is not in the File Upload state or Color state, then throw a "SecurityError" DOMException.
  191. // NOTE: File and Color inputs are exempted from this check for historical reason: their input activation behavior also shows their pickers,
  192. // and has never been guarded by an origin check.
  193. if (!relevant_settings_object(*this).origin().is_same_origin(relevant_settings_object(*this).top_level_origin)
  194. && m_type != TypeAttributeState::FileUpload && m_type != TypeAttributeState::Color) {
  195. return WebIDL::SecurityError::create(realm(), "Cross origin pickers are not allowed"_fly_string);
  196. }
  197. // 3. If this's relevant global object does not have transient activation, then throw a "NotAllowedError" DOMException.
  198. // FIXME: The global object we get here should probably not need casted to Window to check for transient activation
  199. auto& global_object = relevant_global_object(*this);
  200. if (!is<HTML::Window>(global_object) || !static_cast<HTML::Window&>(global_object).has_transient_activation()) {
  201. return WebIDL::NotAllowedError::create(realm(), "Too long since user activation to show picker"_fly_string);
  202. }
  203. // 4. Show the picker, if applicable, for this.
  204. show_the_picker_if_applicable(*this);
  205. return {};
  206. }
  207. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  208. WebIDL::ExceptionOr<void> HTMLInputElement::run_input_activation_behavior()
  209. {
  210. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  211. // 1. If the element is not connected, then return.
  212. if (!is_connected())
  213. return {};
  214. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  215. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  216. input_event->set_bubbles(true);
  217. input_event->set_composed(true);
  218. dispatch_event(input_event);
  219. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  220. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  221. change_event->set_bubbles(true);
  222. dispatch_event(*change_event);
  223. } else if (type_state() == TypeAttributeState::SubmitButton) {
  224. JS::GCPtr<HTMLFormElement> form;
  225. // 1. If the element does not have a form owner, then return.
  226. if (!(form = this->form()))
  227. return {};
  228. // 2. If the element's node document is not fully active, then return.
  229. if (!document().is_fully_active())
  230. return {};
  231. // 3. Submit the form owner from the element.
  232. TRY(form->submit_form(*this));
  233. } else if (type_state() == TypeAttributeState::FileUpload || type_state() == TypeAttributeState::Color) {
  234. show_the_picker_if_applicable(*this);
  235. } else {
  236. dispatch_event(DOM::Event::create(realm(), EventNames::change));
  237. }
  238. return {};
  239. }
  240. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  241. {
  242. // 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.
  243. m_value = value_sanitization_algorithm(m_text_node->data().to_deprecated_string());
  244. m_dirty_value = true;
  245. update_placeholder_visibility();
  246. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  247. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  248. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  249. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  250. input_event->set_bubbles(true);
  251. input_event->set_composed(true);
  252. dispatch_event(*input_event);
  253. });
  254. }
  255. void HTMLInputElement::did_pick_color(Optional<Color> picked_color)
  256. {
  257. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  258. // For input elements without a defined input activation behavior, but to which these events apply
  259. // and for which the user interface involves both interactive manipulation and an explicit commit action
  260. if (type_state() == TypeAttributeState::Color && picked_color.has_value()) {
  261. // then when the user changes the element's value
  262. m_value = value_sanitization_algorithm(picked_color.value().to_deprecated_string_without_alpha());
  263. m_dirty_value = true;
  264. if (m_color_well_element)
  265. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  266. // the user agent must queue an element task on the user interaction task source
  267. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  268. // given the input element to fire an event named input at the input element, with the bubbles and composed attributes initialized to true
  269. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  270. input_event->set_bubbles(true);
  271. input_event->set_composed(true);
  272. dispatch_event(*input_event);
  273. });
  274. // and any time the user commits the change, the user agent must queue an element task on the user interaction task source
  275. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  276. // given the input element
  277. // FIXME: to set its user interacted to true
  278. // and fire an event named change at the input element, with the bubbles attribute initialized to true.
  279. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  280. change_event->set_bubbles(true);
  281. dispatch_event(*change_event);
  282. });
  283. }
  284. }
  285. DeprecatedString HTMLInputElement::value() const
  286. {
  287. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  288. if (type_state() == TypeAttributeState::FileUpload) {
  289. // NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
  290. // NOTE: Since path components are not permitted in filenames in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.
  291. // On getting, return the string "C:\fakepath\" followed by the name of the first file in the list of selected files, if any, or the empty string if the list is empty.
  292. if (m_selected_files && m_selected_files->item(0))
  293. return DeprecatedString::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name());
  294. return DeprecatedString::empty();
  295. }
  296. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
  297. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  298. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the string "on".
  299. return get_attribute(AttributeNames::value).value_or("on"_string).to_deprecated_string();
  300. }
  301. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
  302. if (type_state() == TypeAttributeState::Hidden
  303. || type_state() == TypeAttributeState::SubmitButton
  304. || type_state() == TypeAttributeState::ImageButton
  305. || type_state() == TypeAttributeState::ResetButton
  306. || type_state() == TypeAttributeState::Button) {
  307. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the empty string.
  308. return get_attribute(AttributeNames::value).value_or(String {}).to_deprecated_string();
  309. }
  310. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  311. // Return the current value of the element.
  312. return m_value;
  313. }
  314. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(String const& value)
  315. {
  316. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  317. if (type_state() == TypeAttributeState::FileUpload) {
  318. // On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.
  319. if (!value.is_empty())
  320. return WebIDL::InvalidStateError::create(realm(), "Setting value of input type file to non-empty string"_fly_string);
  321. m_selected_files = nullptr;
  322. return {};
  323. }
  324. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  325. // 1. Let oldValue be the element's value.
  326. auto old_value = move(m_value);
  327. // 2. Set the element's value to the new value.
  328. // NOTE: For the TextNode this is done as part of step 4 below.
  329. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  330. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  331. // 3. Set the element's dirty value flag to true.
  332. m_dirty_value = true;
  333. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  334. m_value = value_sanitization_algorithm(value.to_deprecated_string());
  335. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  336. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  337. // text control, unselecting any selected text and resetting the selection direction to "none".
  338. if (m_text_node && (m_value != old_value)) {
  339. m_text_node->set_data(MUST(String::from_deprecated_string(m_value)));
  340. update_placeholder_visibility();
  341. }
  342. return {};
  343. }
  344. void HTMLInputElement::update_placeholder_visibility()
  345. {
  346. if (!m_placeholder_element)
  347. return;
  348. auto placeholder_text = this->placeholder_value();
  349. if (placeholder_text.has_value()) {
  350. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  351. } else {
  352. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  353. }
  354. }
  355. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  356. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  357. {
  358. switch (state) {
  359. case HTML::HTMLInputElement::TypeAttributeState::Text:
  360. case HTML::HTMLInputElement::TypeAttributeState::Search:
  361. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  362. case HTML::HTMLInputElement::TypeAttributeState::URL:
  363. case HTML::HTMLInputElement::TypeAttributeState::Email:
  364. case HTML::HTMLInputElement::TypeAttributeState::Password:
  365. case HTML::HTMLInputElement::TypeAttributeState::Date:
  366. case HTML::HTMLInputElement::TypeAttributeState::Month:
  367. case HTML::HTMLInputElement::TypeAttributeState::Week:
  368. case HTML::HTMLInputElement::TypeAttributeState::Time:
  369. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  370. case HTML::HTMLInputElement::TypeAttributeState::Number:
  371. return true;
  372. default:
  373. return false;
  374. }
  375. }
  376. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  377. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  378. {
  379. // 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.
  380. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  381. if (m_text_node)
  382. m_text_node->set_always_editable(m_is_mutable);
  383. }
  384. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  385. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  386. {
  387. switch (state) {
  388. case HTML::HTMLInputElement::TypeAttributeState::Text:
  389. case HTML::HTMLInputElement::TypeAttributeState::Search:
  390. case HTML::HTMLInputElement::TypeAttributeState::URL:
  391. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  392. case HTML::HTMLInputElement::TypeAttributeState::Email:
  393. case HTML::HTMLInputElement::TypeAttributeState::Password:
  394. case HTML::HTMLInputElement::TypeAttributeState::Number:
  395. return true;
  396. default:
  397. return false;
  398. }
  399. }
  400. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  401. Optional<DeprecatedString> HTMLInputElement::placeholder_value() const
  402. {
  403. if (!m_text_node || !m_text_node->data().is_empty())
  404. return {};
  405. if (!is_allowed_to_have_placeholder(type_state()))
  406. return {};
  407. if (!has_attribute(HTML::AttributeNames::placeholder))
  408. return {};
  409. auto placeholder = deprecated_attribute(HTML::AttributeNames::placeholder);
  410. if (placeholder.contains('\r') || placeholder.contains('\n')) {
  411. StringBuilder builder;
  412. for (auto ch : placeholder) {
  413. if (ch != '\r' && ch != '\n')
  414. builder.append(ch);
  415. }
  416. placeholder = builder.to_deprecated_string();
  417. }
  418. return placeholder;
  419. }
  420. class PlaceholderElement final : public HTMLDivElement {
  421. JS_CELL(PlaceholderElement, HTMLDivElement);
  422. JS_DECLARE_ALLOCATOR(PlaceholderElement);
  423. public:
  424. PlaceholderElement(DOM::Document& document)
  425. : HTMLDivElement(document, DOM::QualifiedName { HTML::TagNames::div, ""_fly_string, Namespace::HTML })
  426. {
  427. }
  428. virtual Optional<CSS::Selector::PseudoElement> pseudo_element() const override { return CSS::Selector::PseudoElement::Placeholder; }
  429. };
  430. JS_DEFINE_ALLOCATOR(PlaceholderElement);
  431. void HTMLInputElement::create_shadow_tree_if_needed()
  432. {
  433. if (shadow_root_internal())
  434. return;
  435. switch (type_state()) {
  436. case TypeAttributeState::Hidden:
  437. case TypeAttributeState::RadioButton:
  438. case TypeAttributeState::Checkbox:
  439. case TypeAttributeState::Button:
  440. case TypeAttributeState::SubmitButton:
  441. case TypeAttributeState::ResetButton:
  442. case TypeAttributeState::ImageButton:
  443. break;
  444. case TypeAttributeState::Color:
  445. create_color_input_shadow_tree();
  446. break;
  447. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  448. default:
  449. create_text_input_shadow_tree();
  450. break;
  451. }
  452. }
  453. void HTMLInputElement::create_text_input_shadow_tree()
  454. {
  455. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  456. auto initial_value = m_value;
  457. auto element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  458. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  459. display: flex;
  460. height: 100%;
  461. align-items: center;
  462. white-space: pre;
  463. border: none;
  464. padding: 1px 2px;
  465. )~~~"_string));
  466. m_placeholder_element = heap().allocate<PlaceholderElement>(realm(), document());
  467. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Height, "1lh"sv));
  468. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), MUST(String::from_deprecated_string(initial_value)));
  469. m_placeholder_text_node->set_data(attribute(HTML::AttributeNames::placeholder).value_or(String {}));
  470. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  471. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  472. MUST(element->append_child(*m_placeholder_element));
  473. m_inner_text_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  474. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Height, "1lh"sv));
  475. m_text_node = heap().allocate<DOM::Text>(realm(), document(), MUST(String::from_deprecated_string(initial_value)));
  476. if (m_type == TypeAttributeState::FileUpload) {
  477. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  478. m_text_node->set_always_editable(false);
  479. } else {
  480. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  481. }
  482. m_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  483. if (m_type == TypeAttributeState::Password)
  484. m_text_node->set_is_password_input({}, true);
  485. MUST(m_inner_text_element->append_child(*m_text_node));
  486. MUST(element->append_child(*m_inner_text_element));
  487. MUST(shadow_root->append_child(element));
  488. set_shadow_root(shadow_root);
  489. }
  490. void HTMLInputElement::create_color_input_shadow_tree()
  491. {
  492. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  493. auto color = value_sanitization_algorithm(m_value);
  494. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  495. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  496. width: fit-content;
  497. height: fit-content;
  498. padding: 4px;
  499. border: 1px solid ButtonBorder;
  500. background-color: ButtonFace;
  501. )~~~"_string));
  502. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  503. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  504. width: 24px;
  505. height: 24px;
  506. border: 1px solid ButtonBorder;
  507. box-sizing: border-box;
  508. )~~~"_string));
  509. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  510. MUST(border->append_child(*m_color_well_element));
  511. MUST(shadow_root->append_child(border));
  512. set_shadow_root(shadow_root);
  513. }
  514. void HTMLInputElement::did_receive_focus()
  515. {
  516. auto* browsing_context = document().browsing_context();
  517. if (!browsing_context)
  518. return;
  519. if (!m_text_node)
  520. return;
  521. browsing_context->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  522. }
  523. void HTMLInputElement::did_lose_focus()
  524. {
  525. // The change event fires when the value is committed, if that makes sense for the control,
  526. // or else when the control loses focus
  527. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  528. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  529. change_event->set_bubbles(true);
  530. dispatch_event(change_event);
  531. });
  532. }
  533. void HTMLInputElement::attribute_changed(FlyString const& name, Optional<String> const& value)
  534. {
  535. HTMLElement::attribute_changed(name, value);
  536. if (name == HTML::AttributeNames::checked) {
  537. if (!value.has_value()) {
  538. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  539. // the user agent must set the checkedness of the element to false.
  540. if (!m_dirty_checkedness)
  541. set_checked(false, ChangeSource::Programmatic);
  542. } else {
  543. // When the checked content attribute is added, if the control does not have dirty checkedness,
  544. // the user agent must set the checkedness of the element to true
  545. if (!m_dirty_checkedness)
  546. set_checked(true, ChangeSource::Programmatic);
  547. }
  548. } else if (name == HTML::AttributeNames::type) {
  549. m_type = parse_type_attribute(value.value_or(String {}));
  550. } else if (name == HTML::AttributeNames::value) {
  551. if (!value.has_value()) {
  552. if (!m_dirty_value) {
  553. m_value = DeprecatedString::empty();
  554. update_placeholder_visibility();
  555. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  556. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  557. }
  558. } else {
  559. if (!m_dirty_value) {
  560. m_value = value_sanitization_algorithm(value->to_deprecated_string());
  561. update_placeholder_visibility();
  562. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  563. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  564. }
  565. }
  566. } else if (name == HTML::AttributeNames::placeholder) {
  567. if (m_placeholder_text_node)
  568. m_placeholder_text_node->set_data(value.value_or(String {}));
  569. } else if (name == HTML::AttributeNames::readonly) {
  570. handle_readonly_attribute(value);
  571. }
  572. }
  573. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  574. {
  575. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  576. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  577. return HTMLInputElement::TypeAttributeState::state;
  578. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  579. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  580. // The missing value default and the invalid value default are the Text state.
  581. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  582. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  583. return HTMLInputElement::TypeAttributeState::Text;
  584. }
  585. StringView HTMLInputElement::type() const
  586. {
  587. // FIXME: This should probably be `Reflect` in the IDL.
  588. switch (m_type) {
  589. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  590. case TypeAttributeState::state: \
  591. return #keyword##sv;
  592. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  593. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  594. }
  595. VERIFY_NOT_REACHED();
  596. }
  597. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  598. {
  599. return set_attribute(HTML::AttributeNames::type, type);
  600. }
  601. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  602. static bool is_valid_simple_color(DeprecatedString const& value)
  603. {
  604. // if it is exactly seven characters long,
  605. if (value.length() != 7)
  606. return false;
  607. // and the first character is a U+0023 NUMBER SIGN character (#),
  608. if (!value.starts_with('#'))
  609. return false;
  610. // and the remaining six characters are all ASCII hex digits
  611. for (size_t i = 1; i < value.length(); i++)
  612. if (!is_ascii_hex_digit(value[i]))
  613. return false;
  614. return true;
  615. }
  616. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  617. static bool is_valid_time_string(DeprecatedString const& value)
  618. {
  619. // A string is a valid time string representing an hour hour, a minute minute, and a second second if it consists of the following components in the given order:
  620. // 1. Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23
  621. // 2. A U+003A COLON character (:)
  622. // 3. Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59
  623. // 4. If second is nonzero, or optionally if second is zero:
  624. // 1. A U+003A COLON character (:)
  625. // 2. Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59
  626. // 3. If second is not an integer, or optionally if second is an integer:
  627. // 1. A U+002E FULL STOP character (.)
  628. // 2. One, two, or three ASCII digits, representing the fractional part of second
  629. auto parts = value.split(':');
  630. if (parts.size() != 2 || parts.size() != 3)
  631. return false;
  632. if (parts[0].length() != 2)
  633. return false;
  634. auto hour = (parse_ascii_digit(parts[0][0]) * 10) + parse_ascii_digit(parts[0][1]);
  635. if (hour > 23)
  636. return false;
  637. if (parts[1].length() != 2)
  638. return false;
  639. auto minute = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  640. if (minute > 59)
  641. return false;
  642. if (parts.size() == 2)
  643. return true;
  644. if (parts[2].length() < 2)
  645. return false;
  646. auto second = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  647. if (second > 59)
  648. return false;
  649. if (parts[2].length() == 2)
  650. return true;
  651. auto second_parts = parts[2].split('.');
  652. if (second_parts.size() != 2)
  653. return false;
  654. if (second_parts[1].length() < 1 || second_parts[1].length() > 3)
  655. return false;
  656. for (auto digit : second_parts[1])
  657. if (!is_ascii_digit(digit))
  658. return false;
  659. return true;
  660. }
  661. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#week-number-of-the-last-day
  662. static u32 week_number_of_the_last_day(u64)
  663. {
  664. // FIXME: sometimes return 53 (!)
  665. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#weeks
  666. return 52;
  667. }
  668. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-week-string
  669. static bool is_valid_week_string(DeprecatedString const& value)
  670. {
  671. // A string is a valid week string representing a week-year year and week week if it consists of the following components in the given order:
  672. // 1. Four or more ASCII digits, representing year, where year > 0
  673. // 2. A U+002D HYPHEN-MINUS character (-)
  674. // 3. A U+0057 LATIN CAPITAL LETTER W character (W)
  675. // 4. Two ASCII digits, representing the week week, in the range 1 ≤ week ≤ maxweek, where maxweek is the week number of the last day of week-year year
  676. auto parts = value.split('-');
  677. if (parts.size() != 2)
  678. return false;
  679. if (parts[0].length() < 4)
  680. return false;
  681. for (auto digit : parts[0])
  682. if (!is_ascii_digit(digit))
  683. return false;
  684. if (parts[1].length() != 3)
  685. return false;
  686. if (!parts[1].starts_with('W'))
  687. return false;
  688. if (!is_ascii_digit(parts[1][1]))
  689. return false;
  690. if (!is_ascii_digit(parts[1][2]))
  691. return false;
  692. u64 year = 0;
  693. for (auto d : parts[0]) {
  694. year *= 10;
  695. year += parse_ascii_digit(d);
  696. }
  697. auto week = (parse_ascii_digit(parts[1][1]) * 10) + parse_ascii_digit(parts[1][2]);
  698. return week >= 1 && week <= week_number_of_the_last_day(year);
  699. }
  700. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string
  701. static bool is_valid_month_string(DeprecatedString const& value)
  702. {
  703. // A string is a valid month string representing a year year and month month if it consists of the following components in the given order:
  704. // 1. Four or more ASCII digits, representing year, where year > 0
  705. // 2. A U+002D HYPHEN-MINUS character (-)
  706. // 3. Two ASCII digits, representing the month month, in the range 1 ≤ month ≤ 12
  707. auto parts = value.split('-');
  708. if (parts.size() != 2)
  709. return false;
  710. if (parts[0].length() < 4)
  711. return false;
  712. for (auto digit : parts[0])
  713. if (!is_ascii_digit(digit))
  714. return false;
  715. if (parts[1].length() != 2)
  716. return false;
  717. if (!is_ascii_digit(parts[1][0]))
  718. return false;
  719. if (!is_ascii_digit(parts[1][1]))
  720. return false;
  721. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  722. return month >= 1 && month <= 12;
  723. }
  724. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  725. static bool is_valid_date_string(DeprecatedString const& value)
  726. {
  727. // A string is a valid date string representing a year year, month month, and day day if it consists of the following components in the given order:
  728. // 1. A valid month string, representing year and month
  729. // 2. A U+002D HYPHEN-MINUS character (-)
  730. // 3. Two ASCII digits, representing day, in the range 1 ≤ day ≤ maxday where maxday is the number of days in the month month and year year
  731. auto parts = value.split('-');
  732. if (parts.size() != 3)
  733. return false;
  734. if (!is_valid_month_string(DeprecatedString::formatted("{}-{}", parts[0], parts[1])))
  735. return false;
  736. if (parts[2].length() != 2)
  737. return false;
  738. i64 year = 0;
  739. for (auto d : parts[0]) {
  740. year *= 10;
  741. year += parse_ascii_digit(d);
  742. }
  743. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  744. i64 day = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  745. return day >= 1 && day <= AK::days_in_month(year, month);
  746. }
  747. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-local-date-and-time-string
  748. static bool is_valid_local_date_and_time_string(DeprecatedString const& value)
  749. {
  750. auto parts_split_by_T = value.split('T');
  751. if (parts_split_by_T.size() == 2)
  752. return is_valid_date_string(parts_split_by_T[0]) && is_valid_time_string(parts_split_by_T[1]);
  753. auto parts_split_by_space = value.split(' ');
  754. if (parts_split_by_space.size() == 2)
  755. return is_valid_date_string(parts_split_by_space[0]) && is_valid_time_string(parts_split_by_space[1]);
  756. return false;
  757. }
  758. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-normalised-local-date-and-time-string
  759. static DeprecatedString normalize_local_date_and_time_string(DeprecatedString const& value)
  760. {
  761. VERIFY(value.count(" "sv) == 1);
  762. return value.replace(" "sv, "T"sv, ReplaceMode::FirstOnly);
  763. }
  764. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  765. DeprecatedString HTMLInputElement::value_sanitization_algorithm(DeprecatedString value) const
  766. {
  767. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  768. // Strip newlines from the value.
  769. if (value.contains('\r') || value.contains('\n')) {
  770. StringBuilder builder;
  771. for (auto c : value) {
  772. if (!(c == '\r' || c == '\n'))
  773. builder.append(c);
  774. }
  775. return builder.to_deprecated_string();
  776. }
  777. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  778. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  779. if (value.contains('\r') || value.contains('\n')) {
  780. StringBuilder builder;
  781. for (auto c : value) {
  782. if (!(c == '\r' || c == '\n'))
  783. builder.append(c);
  784. }
  785. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  786. }
  787. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  788. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  789. // FIXME: handle the `multiple` attribute
  790. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  791. if (value.contains('\r') || value.contains('\n')) {
  792. StringBuilder builder;
  793. for (auto c : value) {
  794. if (!(c == '\r' || c == '\n'))
  795. builder.append(c);
  796. }
  797. return builder.string_view().trim(Infra::ASCII_WHITESPACE);
  798. }
  799. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  800. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  801. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values
  802. // 6. Skip ASCII whitespace within input given position.
  803. auto maybe_double = value.to_double(TrimWhitespace::Yes);
  804. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  805. return "";
  806. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  807. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  808. if (!is_valid_date_string(value))
  809. return "";
  810. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  811. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  812. if (!is_valid_month_string(value))
  813. return "";
  814. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  815. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  816. if (!is_valid_week_string(value))
  817. return "";
  818. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  819. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  820. if (!is_valid_time_string(value))
  821. return "";
  822. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  823. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  824. if (is_valid_local_date_and_time_string(value))
  825. return normalize_local_date_and_time_string(value);
  826. return "";
  827. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  828. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  829. auto maybe_double = value.to_double(TrimWhitespace::Yes);
  830. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  831. return JS::number_to_deprecated_string(maybe_double.value_or(0));
  832. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  833. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  834. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  835. if (is_valid_simple_color(value))
  836. return value.to_lowercase();
  837. // otherwise, set it to the string "#000000".
  838. return "#000000";
  839. }
  840. return value;
  841. }
  842. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  843. void HTMLInputElement::reset_algorithm()
  844. {
  845. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  846. m_dirty_value = false;
  847. m_dirty_checkedness = false;
  848. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  849. m_value = get_attribute(AttributeNames::value).value_or(String {}).to_deprecated_string();
  850. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  851. m_checked = has_attribute(AttributeNames::checked);
  852. // empty the list of selected files,
  853. m_selected_files = FileAPI::FileList::create(realm(), {});
  854. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  855. m_value = value_sanitization_algorithm(m_value);
  856. if (m_text_node) {
  857. m_text_node->set_data(MUST(String::from_deprecated_string(m_value)));
  858. update_placeholder_visibility();
  859. }
  860. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  861. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  862. }
  863. void HTMLInputElement::form_associated_element_was_inserted()
  864. {
  865. create_shadow_tree_if_needed();
  866. }
  867. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  868. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  869. {
  870. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  871. return !value_a.is_empty() && value_a == value_b;
  872. };
  873. // The radio button group that contains an input element a also contains all the
  874. // other input elements b that fulfill all of the following conditions:
  875. return (
  876. // - Both a and b are in the same tree.
  877. // - The input element b's type attribute is in the Radio Button state.
  878. a.type_state() == b.type_state()
  879. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  880. // - Either a and b have the same form owner, or they both have no form owner.
  881. && a.form() == b.form()
  882. // - They both have a name attribute, their name attributes are not empty, and the
  883. // value of a's name attribute equals the value of b's name attribute.
  884. && a.has_attribute(HTML::AttributeNames::name)
  885. && b.has_attribute(HTML::AttributeNames::name)
  886. && non_empty_equals(a.name(), b.name()));
  887. }
  888. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  889. void HTMLInputElement::set_checked_within_group()
  890. {
  891. if (checked())
  892. return;
  893. set_checked(true, ChangeSource::User);
  894. // No point iterating the tree if we have an empty name.
  895. auto name = this->name();
  896. if (name.is_empty())
  897. return;
  898. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  899. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  900. element.set_checked(false, ChangeSource::User);
  901. return IterationDecision::Continue;
  902. });
  903. }
  904. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  905. void HTMLInputElement::legacy_pre_activation_behavior()
  906. {
  907. m_before_legacy_pre_activation_behavior_checked = checked();
  908. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  909. // 1. If this element's type attribute is in the Checkbox state, then set
  910. // this element's checkedness to its opposite value (i.e. true if it is
  911. // false, false if it is true) and set this element's indeterminate IDL
  912. // attribute to false.
  913. if (type_state() == TypeAttributeState::Checkbox) {
  914. set_checked(!checked(), ChangeSource::User);
  915. set_indeterminate(false);
  916. }
  917. // 2. If this element's type attribute is in the Radio Button state, then
  918. // get a reference to the element in this element's radio button group that
  919. // has its checkedness set to true, if any, and then set this element's
  920. // checkedness to true.
  921. if (type_state() == TypeAttributeState::RadioButton) {
  922. DeprecatedString name = this->name();
  923. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  924. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  925. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  926. return IterationDecision::Break;
  927. }
  928. return IterationDecision::Continue;
  929. });
  930. set_checked_within_group();
  931. }
  932. }
  933. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  934. void HTMLInputElement::legacy_cancelled_activation_behavior()
  935. {
  936. // 1. If the element's type attribute is in the Checkbox state, then set the
  937. // element's checkedness and the element's indeterminate IDL attribute back
  938. // to the values they had before the legacy-pre-activation behavior was run.
  939. if (type_state() == TypeAttributeState::Checkbox) {
  940. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  941. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  942. }
  943. // 2. If this element 's type attribute is in the Radio Button state, then
  944. // if the element to which a reference was obtained in the
  945. // legacy-pre-activation behavior, if any, is still in what is now this
  946. // element' s radio button group, if it still has one, and if so, setting
  947. // that element 's checkedness to true; or else, if there was no such
  948. // element, or that element is no longer in this element' s radio button
  949. // group, or if this element no longer has a radio button group, setting
  950. // this element's checkedness to false.
  951. if (type_state() == TypeAttributeState::RadioButton) {
  952. bool did_reselect_previous_element = false;
  953. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  954. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  955. if (is_in_same_radio_button_group(*this, element_in_group)) {
  956. element_in_group.set_checked_within_group();
  957. did_reselect_previous_element = true;
  958. }
  959. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  960. }
  961. if (!did_reselect_previous_element)
  962. set_checked(false, ChangeSource::User);
  963. }
  964. }
  965. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  966. {
  967. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  968. }
  969. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  970. i32 HTMLInputElement::default_tab_index_value() const
  971. {
  972. // See the base function for the spec comments.
  973. return 0;
  974. }
  975. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  976. WebIDL::ExceptionOr<double> HTMLInputElement::value_as_number() const
  977. {
  978. // 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.
  979. if (type_state() != TypeAttributeState::Date || type_state() != TypeAttributeState::Month || type_state() != TypeAttributeState::Week || type_state() != TypeAttributeState::Time || type_state() != TypeAttributeState::LocalDateAndTime || type_state() != TypeAttributeState::Number || type_state() != TypeAttributeState::Range)
  980. return NAN;
  981. // Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value; if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.
  982. return value().to_double().value_or(NAN);
  983. }
  984. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  985. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  986. {
  987. // On setting, if the new value is infinite, then throw a TypeError exception.
  988. if (!isfinite(value))
  989. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  990. // 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.
  991. if (type_state() != TypeAttributeState::Date || type_state() != TypeAttributeState::Month || type_state() != TypeAttributeState::Week || type_state() != TypeAttributeState::Time || type_state() != TypeAttributeState::LocalDateAndTime || type_state() != TypeAttributeState::Number || type_state() != TypeAttributeState::Range)
  992. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
  993. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  994. if (value == NAN) {
  995. m_value = "";
  996. return {};
  997. }
  998. // 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.
  999. m_value = DeprecatedString::number(value);
  1000. return {};
  1001. }
  1002. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1003. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1004. {
  1005. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1006. return true;
  1007. }
  1008. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1009. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1010. {
  1011. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1012. return true;
  1013. }
  1014. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1015. void HTMLInputElement::set_custom_validity(String const& error)
  1016. {
  1017. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1018. return;
  1019. }
  1020. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  1021. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  1022. {
  1023. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  1024. return {};
  1025. }
  1026. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  1027. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, Optional<String> const& direction)
  1028. {
  1029. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  1030. return {};
  1031. }
  1032. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1033. {
  1034. // https://www.w3.org/TR/html-aria/#el-input-button
  1035. if (type_state() == TypeAttributeState::Button)
  1036. return ARIA::Role::button;
  1037. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1038. if (type_state() == TypeAttributeState::Checkbox)
  1039. return ARIA::Role::checkbox;
  1040. // https://www.w3.org/TR/html-aria/#el-input-email
  1041. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1042. return ARIA::Role::textbox;
  1043. // https://www.w3.org/TR/html-aria/#el-input-image
  1044. if (type_state() == TypeAttributeState::ImageButton)
  1045. return ARIA::Role::button;
  1046. // https://www.w3.org/TR/html-aria/#el-input-number
  1047. if (type_state() == TypeAttributeState::Number)
  1048. return ARIA::Role::spinbutton;
  1049. // https://www.w3.org/TR/html-aria/#el-input-radio
  1050. if (type_state() == TypeAttributeState::RadioButton)
  1051. return ARIA::Role::radio;
  1052. // https://www.w3.org/TR/html-aria/#el-input-range
  1053. if (type_state() == TypeAttributeState::Range)
  1054. return ARIA::Role::slider;
  1055. // https://www.w3.org/TR/html-aria/#el-input-reset
  1056. if (type_state() == TypeAttributeState::ResetButton)
  1057. return ARIA::Role::button;
  1058. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1059. if ((type_state() == TypeAttributeState::Text
  1060. || type_state() == TypeAttributeState::Search
  1061. || type_state() == TypeAttributeState::Telephone
  1062. || type_state() == TypeAttributeState::URL
  1063. || type_state() == TypeAttributeState::Email)
  1064. && has_attribute(AttributeNames::list))
  1065. return ARIA::Role::combobox;
  1066. // https://www.w3.org/TR/html-aria/#el-input-search
  1067. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1068. return ARIA::Role::textbox;
  1069. // https://www.w3.org/TR/html-aria/#el-input-submit
  1070. if (type_state() == TypeAttributeState::SubmitButton)
  1071. return ARIA::Role::button;
  1072. // https://www.w3.org/TR/html-aria/#el-input-tel
  1073. if (type_state() == TypeAttributeState::Telephone)
  1074. return ARIA::Role::textbox;
  1075. // https://www.w3.org/TR/html-aria/#el-input-text
  1076. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1077. return ARIA::Role::textbox;
  1078. // https://www.w3.org/TR/html-aria/#el-input-url
  1079. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1080. return ARIA::Role::textbox;
  1081. // https://www.w3.org/TR/html-aria/#el-input-color
  1082. // https://www.w3.org/TR/html-aria/#el-input-date
  1083. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1084. // https://www.w3.org/TR/html-aria/#el-input-file
  1085. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1086. // https://www.w3.org/TR/html-aria/#el-input-month
  1087. // https://www.w3.org/TR/html-aria/#el-input-password
  1088. // https://www.w3.org/TR/html-aria/#el-input-time
  1089. // https://www.w3.org/TR/html-aria/#el-input-week
  1090. return {};
  1091. }
  1092. bool HTMLInputElement::is_button() const
  1093. {
  1094. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1095. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1096. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1097. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1098. return type_state() == TypeAttributeState::SubmitButton
  1099. || type_state() == TypeAttributeState::ImageButton
  1100. || type_state() == TypeAttributeState::ResetButton
  1101. || type_state() == TypeAttributeState::Button;
  1102. }
  1103. bool HTMLInputElement::is_submit_button() const
  1104. {
  1105. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  1106. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  1107. return type_state() == TypeAttributeState::SubmitButton
  1108. || type_state() == TypeAttributeState::ImageButton;
  1109. }
  1110. bool HTMLInputElement::has_activation_behavior() const
  1111. {
  1112. return true;
  1113. }
  1114. void HTMLInputElement::activation_behavior(DOM::Event const&)
  1115. {
  1116. // The activation behavior for input elements are these steps:
  1117. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  1118. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  1119. run_input_activation_behavior().release_value_but_fixme_should_propagate_errors();
  1120. }
  1121. }