HTMLInputElement.cpp 59 KB

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