HTMLInputElement.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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/Infra/Strings.h>
  24. #include <LibWeb/Layout/BlockContainer.h>
  25. #include <LibWeb/Layout/ButtonBox.h>
  26. #include <LibWeb/Layout/CheckBox.h>
  27. #include <LibWeb/Layout/RadioButton.h>
  28. #include <LibWeb/Namespace.h>
  29. #include <LibWeb/Page/Page.h>
  30. #include <LibWeb/WebIDL/DOMException.h>
  31. #include <LibWeb/WebIDL/ExceptionOr.h>
  32. namespace Web::HTML {
  33. JS_DEFINE_ALLOCATOR(HTMLInputElement);
  34. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  35. : HTMLElement(document, move(qualified_name))
  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"_fly_string));
  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(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. }
  236. return {};
  237. }
  238. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  239. {
  240. // 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.
  241. m_value = value_sanitization_algorithm(m_text_node->data());
  242. m_dirty_value = true;
  243. m_has_uncommitted_changes = true;
  244. update_placeholder_visibility();
  245. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  246. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  247. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  248. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  249. input_event->set_bubbles(true);
  250. input_event->set_composed(true);
  251. dispatch_event(*input_event);
  252. });
  253. }
  254. void HTMLInputElement::did_pick_color(Optional<Color> picked_color)
  255. {
  256. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  257. // For input elements without a defined input activation behavior, but to which these events apply
  258. // and for which the user interface involves both interactive manipulation and an explicit commit action
  259. if (type_state() == TypeAttributeState::Color && picked_color.has_value()) {
  260. // then when the user changes the element's value
  261. m_value = value_sanitization_algorithm(picked_color.value().to_string_without_alpha());
  262. m_dirty_value = true;
  263. if (m_color_well_element)
  264. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  265. // the user agent must queue an element task on the user interaction task source
  266. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  267. // given the input element to fire an event named input at the input element, with the bubbles and composed attributes initialized to true
  268. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  269. input_event->set_bubbles(true);
  270. input_event->set_composed(true);
  271. dispatch_event(*input_event);
  272. });
  273. // and any time the user commits the change, the user agent must queue an element task on the user interaction task source
  274. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  275. // given the input element
  276. // FIXME: to set its user interacted to true
  277. // and fire an event named change at the input element, with the bubbles attribute initialized to true.
  278. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  279. change_event->set_bubbles(true);
  280. dispatch_event(*change_event);
  281. });
  282. }
  283. }
  284. String HTMLInputElement::value() const
  285. {
  286. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-filename
  287. if (type_state() == TypeAttributeState::FileUpload) {
  288. // NOTE: This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.
  289. // NOTE: Since path components are not permitted in filenames in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.
  290. // 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.
  291. if (m_selected_files && m_selected_files->item(0))
  292. return MUST(String::formatted("C:\\fakepath\\{}", m_selected_files->item(0)->name()));
  293. return String {};
  294. }
  295. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default-on
  296. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  297. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the string "on".
  298. return get_attribute(AttributeNames::value).value_or("on"_string);
  299. }
  300. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-default
  301. if (type_state() == TypeAttributeState::Hidden
  302. || type_state() == TypeAttributeState::SubmitButton
  303. || type_state() == TypeAttributeState::ImageButton
  304. || type_state() == TypeAttributeState::ResetButton
  305. || type_state() == TypeAttributeState::Button) {
  306. // On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the empty string.
  307. return get_attribute(AttributeNames::value).value_or(String {});
  308. }
  309. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  310. // Return the current value of the element.
  311. return m_value;
  312. }
  313. WebIDL::ExceptionOr<void> HTMLInputElement::set_value(String const& value)
  314. {
  315. auto& realm = this->realm();
  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);
  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(m_value);
  340. update_placeholder_visibility();
  341. if (auto* browsing_context = document().browsing_context())
  342. browsing_context->set_cursor_position(DOM::Position::create(realm, *m_text_node, m_text_node->data().bytes().size()));
  343. }
  344. return {};
  345. }
  346. void HTMLInputElement::commit_pending_changes()
  347. {
  348. // The change event fires when the value is committed, if that makes sense for the control,
  349. // or else when the control loses focus
  350. switch (type_state()) {
  351. case TypeAttributeState::Email:
  352. case TypeAttributeState::Password:
  353. case TypeAttributeState::Search:
  354. case TypeAttributeState::Telephone:
  355. case TypeAttributeState::Text:
  356. case TypeAttributeState::URL:
  357. if (!m_has_uncommitted_changes)
  358. return;
  359. break;
  360. default:
  361. break;
  362. }
  363. m_has_uncommitted_changes = false;
  364. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  365. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change, { .bubbles = true });
  366. dispatch_event(change_event);
  367. });
  368. }
  369. void HTMLInputElement::update_placeholder_visibility()
  370. {
  371. if (!m_placeholder_element)
  372. return;
  373. auto placeholder_text = this->placeholder_value();
  374. if (placeholder_text.has_value()) {
  375. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  376. } else {
  377. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  378. }
  379. }
  380. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-readonly-3
  381. static bool is_allowed_to_be_readonly(HTML::HTMLInputElement::TypeAttributeState state)
  382. {
  383. switch (state) {
  384. case HTML::HTMLInputElement::TypeAttributeState::Text:
  385. case HTML::HTMLInputElement::TypeAttributeState::Search:
  386. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  387. case HTML::HTMLInputElement::TypeAttributeState::URL:
  388. case HTML::HTMLInputElement::TypeAttributeState::Email:
  389. case HTML::HTMLInputElement::TypeAttributeState::Password:
  390. case HTML::HTMLInputElement::TypeAttributeState::Date:
  391. case HTML::HTMLInputElement::TypeAttributeState::Month:
  392. case HTML::HTMLInputElement::TypeAttributeState::Week:
  393. case HTML::HTMLInputElement::TypeAttributeState::Time:
  394. case HTML::HTMLInputElement::TypeAttributeState::LocalDateAndTime:
  395. case HTML::HTMLInputElement::TypeAttributeState::Number:
  396. return true;
  397. default:
  398. return false;
  399. }
  400. }
  401. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  402. void HTMLInputElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  403. {
  404. // 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.
  405. m_is_mutable = !maybe_value.has_value() || !is_allowed_to_be_readonly(m_type);
  406. if (m_text_node)
  407. m_text_node->set_always_editable(m_is_mutable);
  408. }
  409. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:attr-input-placeholder-3
  410. static bool is_allowed_to_have_placeholder(HTML::HTMLInputElement::TypeAttributeState state)
  411. {
  412. switch (state) {
  413. case HTML::HTMLInputElement::TypeAttributeState::Text:
  414. case HTML::HTMLInputElement::TypeAttributeState::Search:
  415. case HTML::HTMLInputElement::TypeAttributeState::URL:
  416. case HTML::HTMLInputElement::TypeAttributeState::Telephone:
  417. case HTML::HTMLInputElement::TypeAttributeState::Email:
  418. case HTML::HTMLInputElement::TypeAttributeState::Password:
  419. case HTML::HTMLInputElement::TypeAttributeState::Number:
  420. return true;
  421. default:
  422. return false;
  423. }
  424. }
  425. // https://html.spec.whatwg.org/multipage/input.html#attr-input-placeholder
  426. Optional<DeprecatedString> HTMLInputElement::placeholder_value() const
  427. {
  428. if (!m_text_node || !m_text_node->data().is_empty())
  429. return {};
  430. if (!is_allowed_to_have_placeholder(type_state()))
  431. return {};
  432. if (!has_attribute(HTML::AttributeNames::placeholder))
  433. return {};
  434. auto placeholder = deprecated_attribute(HTML::AttributeNames::placeholder);
  435. if (placeholder.contains('\r') || placeholder.contains('\n')) {
  436. StringBuilder builder;
  437. for (auto ch : placeholder) {
  438. if (ch != '\r' && ch != '\n')
  439. builder.append(ch);
  440. }
  441. placeholder = builder.to_deprecated_string();
  442. }
  443. return placeholder;
  444. }
  445. class PlaceholderElement final : public HTMLDivElement {
  446. JS_CELL(PlaceholderElement, HTMLDivElement);
  447. JS_DECLARE_ALLOCATOR(PlaceholderElement);
  448. public:
  449. PlaceholderElement(DOM::Document& document)
  450. : HTMLDivElement(document, DOM::QualifiedName { HTML::TagNames::div, ""_fly_string, Namespace::HTML })
  451. {
  452. }
  453. virtual Optional<CSS::Selector::PseudoElement> pseudo_element() const override { return CSS::Selector::PseudoElement::Placeholder; }
  454. };
  455. JS_DEFINE_ALLOCATOR(PlaceholderElement);
  456. void HTMLInputElement::create_shadow_tree_if_needed()
  457. {
  458. if (shadow_root_internal())
  459. return;
  460. switch (type_state()) {
  461. case TypeAttributeState::Hidden:
  462. case TypeAttributeState::RadioButton:
  463. case TypeAttributeState::Checkbox:
  464. case TypeAttributeState::Button:
  465. case TypeAttributeState::SubmitButton:
  466. case TypeAttributeState::ResetButton:
  467. case TypeAttributeState::ImageButton:
  468. break;
  469. case TypeAttributeState::Color:
  470. create_color_input_shadow_tree();
  471. break;
  472. // FIXME: This could be better factored. Everything except the above types becomes a text input.
  473. default:
  474. create_text_input_shadow_tree();
  475. break;
  476. }
  477. }
  478. void HTMLInputElement::create_text_input_shadow_tree()
  479. {
  480. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  481. auto initial_value = m_value;
  482. auto element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  483. MUST(element->set_attribute(HTML::AttributeNames::style, R"~~~(
  484. display: flex;
  485. height: 100%;
  486. align-items: center;
  487. white-space: pre;
  488. border: none;
  489. padding: 1px 2px;
  490. )~~~"_string));
  491. m_placeholder_element = heap().allocate<PlaceholderElement>(realm(), document());
  492. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Height, "1lh"sv));
  493. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), initial_value);
  494. m_placeholder_text_node->set_data(attribute(HTML::AttributeNames::placeholder).value_or(String {}));
  495. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  496. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  497. MUST(element->append_child(*m_placeholder_element));
  498. m_inner_text_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  499. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Height, "1lh"sv));
  500. m_text_node = heap().allocate<DOM::Text>(realm(), document(), move(initial_value));
  501. if (m_type == TypeAttributeState::FileUpload) {
  502. // NOTE: file upload state is mutable, but we don't allow the text node to be modifed
  503. m_text_node->set_always_editable(false);
  504. } else {
  505. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  506. }
  507. m_text_node->set_editable_text_node_owner(Badge<HTMLInputElement> {}, *this);
  508. if (m_type == TypeAttributeState::Password)
  509. m_text_node->set_is_password_input({}, true);
  510. MUST(m_inner_text_element->append_child(*m_text_node));
  511. MUST(element->append_child(*m_inner_text_element));
  512. MUST(shadow_root->append_child(element));
  513. set_shadow_root(shadow_root);
  514. }
  515. void HTMLInputElement::create_color_input_shadow_tree()
  516. {
  517. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  518. auto color = value_sanitization_algorithm(m_value);
  519. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  520. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  521. width: fit-content;
  522. height: fit-content;
  523. padding: 4px;
  524. border: 1px solid ButtonBorder;
  525. background-color: ButtonFace;
  526. )~~~"_string));
  527. m_color_well_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  528. MUST(m_color_well_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  529. width: 24px;
  530. height: 24px;
  531. border: 1px solid ButtonBorder;
  532. box-sizing: border-box;
  533. )~~~"_string));
  534. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, color));
  535. MUST(border->append_child(*m_color_well_element));
  536. MUST(shadow_root->append_child(border));
  537. set_shadow_root(shadow_root);
  538. }
  539. void HTMLInputElement::did_receive_focus()
  540. {
  541. auto* browsing_context = document().browsing_context();
  542. if (!browsing_context)
  543. return;
  544. if (!m_text_node)
  545. return;
  546. browsing_context->set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  547. }
  548. void HTMLInputElement::did_lose_focus()
  549. {
  550. commit_pending_changes();
  551. }
  552. void HTMLInputElement::attribute_changed(FlyString const& name, Optional<String> const& value)
  553. {
  554. HTMLElement::attribute_changed(name, value);
  555. if (name == HTML::AttributeNames::checked) {
  556. if (!value.has_value()) {
  557. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  558. // the user agent must set the checkedness of the element to false.
  559. if (!m_dirty_checkedness)
  560. set_checked(false, ChangeSource::Programmatic);
  561. } else {
  562. // When the checked content attribute is added, if the control does not have dirty checkedness,
  563. // the user agent must set the checkedness of the element to true
  564. if (!m_dirty_checkedness)
  565. set_checked(true, ChangeSource::Programmatic);
  566. }
  567. } else if (name == HTML::AttributeNames::type) {
  568. m_type = parse_type_attribute(value.value_or(String {}));
  569. } else if (name == HTML::AttributeNames::value) {
  570. if (!value.has_value()) {
  571. if (!m_dirty_value) {
  572. m_value = String {};
  573. update_placeholder_visibility();
  574. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  575. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  576. }
  577. } else {
  578. if (!m_dirty_value) {
  579. m_value = value_sanitization_algorithm(*value);
  580. update_placeholder_visibility();
  581. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  582. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  583. }
  584. }
  585. } else if (name == HTML::AttributeNames::placeholder) {
  586. if (m_placeholder_text_node)
  587. m_placeholder_text_node->set_data(value.value_or(String {}));
  588. } else if (name == HTML::AttributeNames::readonly) {
  589. handle_readonly_attribute(value);
  590. }
  591. }
  592. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  593. {
  594. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  595. if (type.equals_ignoring_ascii_case(#keyword##sv)) \
  596. return HTMLInputElement::TypeAttributeState::state;
  597. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  598. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  599. // The missing value default and the invalid value default are the Text state.
  600. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  601. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  602. return HTMLInputElement::TypeAttributeState::Text;
  603. }
  604. StringView HTMLInputElement::type() const
  605. {
  606. // FIXME: This should probably be `Reflect` in the IDL.
  607. switch (m_type) {
  608. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  609. case TypeAttributeState::state: \
  610. return #keyword##sv;
  611. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  612. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  613. }
  614. VERIFY_NOT_REACHED();
  615. }
  616. WebIDL::ExceptionOr<void> HTMLInputElement::set_type(String const& type)
  617. {
  618. return set_attribute(HTML::AttributeNames::type, type);
  619. }
  620. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-simple-colour
  621. static bool is_valid_simple_color(StringView value)
  622. {
  623. // if it is exactly seven characters long,
  624. if (value.length() != 7)
  625. return false;
  626. // and the first character is a U+0023 NUMBER SIGN character (#),
  627. if (!value.starts_with('#'))
  628. return false;
  629. // and the remaining six characters are all ASCII hex digits
  630. for (size_t i = 1; i < value.length(); i++)
  631. if (!is_ascii_hex_digit(value[i]))
  632. return false;
  633. return true;
  634. }
  635. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-time-string
  636. static bool is_valid_time_string(StringView value)
  637. {
  638. // 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:
  639. // 1. Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23
  640. // 2. A U+003A COLON character (:)
  641. // 3. Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59
  642. // 4. If second is nonzero, or optionally if second is zero:
  643. // 1. A U+003A COLON character (:)
  644. // 2. Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59
  645. // 3. If second is not an integer, or optionally if second is an integer:
  646. // 1. A U+002E FULL STOP character (.)
  647. // 2. One, two, or three ASCII digits, representing the fractional part of second
  648. auto parts = value.split_view(':');
  649. if (parts.size() != 2 || parts.size() != 3)
  650. return false;
  651. if (parts[0].length() != 2)
  652. return false;
  653. auto hour = (parse_ascii_digit(parts[0][0]) * 10) + parse_ascii_digit(parts[0][1]);
  654. if (hour > 23)
  655. return false;
  656. if (parts[1].length() != 2)
  657. return false;
  658. auto minute = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  659. if (minute > 59)
  660. return false;
  661. if (parts.size() == 2)
  662. return true;
  663. if (parts[2].length() < 2)
  664. return false;
  665. auto second = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  666. if (second > 59)
  667. return false;
  668. if (parts[2].length() == 2)
  669. return true;
  670. auto second_parts = parts[2].split_view('.');
  671. if (second_parts.size() != 2)
  672. return false;
  673. if (second_parts[1].length() < 1 || second_parts[1].length() > 3)
  674. return false;
  675. for (auto digit : second_parts[1])
  676. if (!is_ascii_digit(digit))
  677. return false;
  678. return true;
  679. }
  680. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#week-number-of-the-last-day
  681. static u32 week_number_of_the_last_day(u64)
  682. {
  683. // FIXME: sometimes return 53 (!)
  684. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#weeks
  685. return 52;
  686. }
  687. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-week-string
  688. static bool is_valid_week_string(StringView value)
  689. {
  690. // 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:
  691. // 1. Four or more ASCII digits, representing year, where year > 0
  692. // 2. A U+002D HYPHEN-MINUS character (-)
  693. // 3. A U+0057 LATIN CAPITAL LETTER W character (W)
  694. // 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
  695. auto parts = value.split_view('-');
  696. if (parts.size() != 2)
  697. return false;
  698. if (parts[0].length() < 4)
  699. return false;
  700. for (auto digit : parts[0])
  701. if (!is_ascii_digit(digit))
  702. return false;
  703. if (parts[1].length() != 3)
  704. return false;
  705. if (!parts[1].starts_with('W'))
  706. return false;
  707. if (!is_ascii_digit(parts[1][1]))
  708. return false;
  709. if (!is_ascii_digit(parts[1][2]))
  710. return false;
  711. u64 year = 0;
  712. for (auto d : parts[0]) {
  713. year *= 10;
  714. year += parse_ascii_digit(d);
  715. }
  716. auto week = (parse_ascii_digit(parts[1][1]) * 10) + parse_ascii_digit(parts[1][2]);
  717. return week >= 1 && week <= week_number_of_the_last_day(year);
  718. }
  719. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-month-string
  720. static bool is_valid_month_string(StringView value)
  721. {
  722. // 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:
  723. // 1. Four or more ASCII digits, representing year, where year > 0
  724. // 2. A U+002D HYPHEN-MINUS character (-)
  725. // 3. Two ASCII digits, representing the month month, in the range 1 ≤ month ≤ 12
  726. auto parts = value.split_view('-');
  727. if (parts.size() != 2)
  728. return false;
  729. if (parts[0].length() < 4)
  730. return false;
  731. for (auto digit : parts[0])
  732. if (!is_ascii_digit(digit))
  733. return false;
  734. if (parts[1].length() != 2)
  735. return false;
  736. if (!is_ascii_digit(parts[1][0]))
  737. return false;
  738. if (!is_ascii_digit(parts[1][1]))
  739. return false;
  740. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  741. return month >= 1 && month <= 12;
  742. }
  743. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-date-string
  744. static bool is_valid_date_string(StringView value)
  745. {
  746. // 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:
  747. // 1. A valid month string, representing year and month
  748. // 2. A U+002D HYPHEN-MINUS character (-)
  749. // 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
  750. auto parts = value.split_view('-');
  751. if (parts.size() != 3)
  752. return false;
  753. if (!is_valid_month_string(DeprecatedString::formatted("{}-{}", parts[0], parts[1])))
  754. return false;
  755. if (parts[2].length() != 2)
  756. return false;
  757. i64 year = 0;
  758. for (auto d : parts[0]) {
  759. year *= 10;
  760. year += parse_ascii_digit(d);
  761. }
  762. auto month = (parse_ascii_digit(parts[1][0]) * 10) + parse_ascii_digit(parts[1][1]);
  763. i64 day = (parse_ascii_digit(parts[2][0]) * 10) + parse_ascii_digit(parts[2][1]);
  764. return day >= 1 && day <= AK::days_in_month(year, month);
  765. }
  766. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-local-date-and-time-string
  767. static bool is_valid_local_date_and_time_string(StringView value)
  768. {
  769. auto parts_split_by_T = value.split_view('T');
  770. if (parts_split_by_T.size() == 2)
  771. return is_valid_date_string(parts_split_by_T[0]) && is_valid_time_string(parts_split_by_T[1]);
  772. auto parts_split_by_space = value.split_view(' ');
  773. if (parts_split_by_space.size() == 2)
  774. return is_valid_date_string(parts_split_by_space[0]) && is_valid_time_string(parts_split_by_space[1]);
  775. return false;
  776. }
  777. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#valid-normalised-local-date-and-time-string
  778. static String normalize_local_date_and_time_string(String const& value)
  779. {
  780. VERIFY(value.count(" "sv) == 1);
  781. return MUST(value.replace(" "sv, "T"sv, ReplaceMode::FirstOnly));
  782. }
  783. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  784. String HTMLInputElement::value_sanitization_algorithm(String const& value) const
  785. {
  786. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  787. // Strip newlines from the value.
  788. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  789. StringBuilder builder;
  790. for (auto c : value.bytes_as_string_view()) {
  791. if (c != '\r' && c != '\n')
  792. builder.append(c);
  793. }
  794. return MUST(builder.to_string());
  795. }
  796. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  797. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  798. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  799. StringBuilder builder;
  800. for (auto c : value.bytes_as_string_view()) {
  801. if (c != '\r' && c != '\n')
  802. builder.append(c);
  803. }
  804. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  805. }
  806. } else if (type_state() == HTMLInputElement::TypeAttributeState::Email) {
  807. // https://html.spec.whatwg.org/multipage/input.html#email-state-(type=email):value-sanitization-algorithm
  808. // FIXME: handle the `multiple` attribute
  809. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  810. if (value.bytes_as_string_view().contains('\r') || value.bytes_as_string_view().contains('\n')) {
  811. StringBuilder builder;
  812. for (auto c : value.bytes_as_string_view()) {
  813. if (c != '\r' && c != '\n')
  814. builder.append(c);
  815. }
  816. return MUST(String::from_utf8(builder.string_view().trim(Infra::ASCII_WHITESPACE)));
  817. }
  818. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  819. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  820. // https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values
  821. // 6. Skip ASCII whitespace within input given position.
  822. auto maybe_double = value.bytes_as_string_view().to_double(TrimWhitespace::Yes);
  823. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  824. return String {};
  825. } else if (type_state() == HTMLInputElement::TypeAttributeState::Date) {
  826. // https://html.spec.whatwg.org/multipage/input.html#date-state-(type=date):value-sanitization-algorithm
  827. if (!is_valid_date_string(value))
  828. return String {};
  829. } else if (type_state() == HTMLInputElement::TypeAttributeState::Month) {
  830. // https://html.spec.whatwg.org/multipage/input.html#month-state-(type=month):value-sanitization-algorithm
  831. if (!is_valid_month_string(value))
  832. return String {};
  833. } else if (type_state() == HTMLInputElement::TypeAttributeState::Week) {
  834. // https://html.spec.whatwg.org/multipage/input.html#week-state-(type=week):value-sanitization-algorithm
  835. if (!is_valid_week_string(value))
  836. return String {};
  837. } else if (type_state() == HTMLInputElement::TypeAttributeState::Time) {
  838. // https://html.spec.whatwg.org/multipage/input.html#time-state-(type=time):value-sanitization-algorithm
  839. if (!is_valid_time_string(value))
  840. return String {};
  841. } else if (type_state() == HTMLInputElement::TypeAttributeState::LocalDateAndTime) {
  842. // https://html.spec.whatwg.org/multipage/input.html#local-date-and-time-state-(type=datetime-local):value-sanitization-algorithm
  843. if (is_valid_local_date_and_time_string(value))
  844. return normalize_local_date_and_time_string(value);
  845. return String {};
  846. } else if (type_state() == HTMLInputElement::TypeAttributeState::Range) {
  847. // https://html.spec.whatwg.org/multipage/input.html#range-state-(type=range):value-sanitization-algorithm
  848. auto maybe_double = value.bytes_as_string_view().to_double(TrimWhitespace::Yes);
  849. if (!maybe_double.has_value() || !isfinite(maybe_double.value()))
  850. return JS::number_to_string(maybe_double.value_or(0));
  851. } else if (type_state() == HTMLInputElement::TypeAttributeState::Color) {
  852. // https://html.spec.whatwg.org/multipage/input.html#color-state-(type=color):value-sanitization-algorithm
  853. // If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase;
  854. if (is_valid_simple_color(value))
  855. return MUST(Infra::to_ascii_lowercase(value));
  856. // otherwise, set it to the string "#000000".
  857. return "#000000"_string;
  858. }
  859. return value;
  860. }
  861. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:concept-form-reset-control
  862. void HTMLInputElement::reset_algorithm()
  863. {
  864. // The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false,
  865. m_dirty_value = false;
  866. m_dirty_checkedness = false;
  867. // set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise,
  868. m_value = get_attribute(AttributeNames::value).value_or(String {});
  869. // set the checkedness of the element to true if the element has a checked content attribute and false if it does not,
  870. m_checked = has_attribute(AttributeNames::checked);
  871. // empty the list of selected files,
  872. m_selected_files = FileAPI::FileList::create(realm(), {});
  873. // and then invoke the value sanitization algorithm, if the type attribute's current state defines one.
  874. m_value = value_sanitization_algorithm(m_value);
  875. if (m_text_node) {
  876. m_text_node->set_data(m_value);
  877. update_placeholder_visibility();
  878. }
  879. if (type_state() == TypeAttributeState::Color && m_color_well_element)
  880. MUST(m_color_well_element->style_for_bindings()->set_property(CSS::PropertyID::BackgroundColor, m_value));
  881. }
  882. void HTMLInputElement::form_associated_element_was_inserted()
  883. {
  884. create_shadow_tree_if_needed();
  885. }
  886. void HTMLInputElement::form_associated_element_was_removed(DOM::Node*)
  887. {
  888. set_shadow_root(nullptr);
  889. }
  890. // https://html.spec.whatwg.org/multipage/input.html#radio-button-group
  891. static bool is_in_same_radio_button_group(HTML::HTMLInputElement const& a, HTML::HTMLInputElement const& b)
  892. {
  893. auto non_empty_equals = [](auto const& value_a, auto const& value_b) {
  894. return !value_a.is_empty() && value_a == value_b;
  895. };
  896. // The radio button group that contains an input element a also contains all the
  897. // other input elements b that fulfill all of the following conditions:
  898. return (
  899. // - Both a and b are in the same tree.
  900. // - The input element b's type attribute is in the Radio Button state.
  901. a.type_state() == b.type_state()
  902. && b.type_state() == HTMLInputElement::TypeAttributeState::RadioButton
  903. // - Either a and b have the same form owner, or they both have no form owner.
  904. && a.form() == b.form()
  905. // - They both have a name attribute, their name attributes are not empty, and the
  906. // value of a's name attribute equals the value of b's name attribute.
  907. && a.has_attribute(HTML::AttributeNames::name)
  908. && b.has_attribute(HTML::AttributeNames::name)
  909. && non_empty_equals(a.name(), b.name()));
  910. }
  911. // https://html.spec.whatwg.org/multipage/input.html#radio-button-state-(type=radio)
  912. void HTMLInputElement::set_checked_within_group()
  913. {
  914. if (checked())
  915. return;
  916. set_checked(true, ChangeSource::User);
  917. // No point iterating the tree if we have an empty name.
  918. auto name = this->name();
  919. if (name.is_empty())
  920. return;
  921. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  922. if (element.checked() && &element != this && is_in_same_radio_button_group(*this, element))
  923. element.set_checked(false, ChangeSource::User);
  924. return IterationDecision::Continue;
  925. });
  926. }
  927. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  928. void HTMLInputElement::legacy_pre_activation_behavior()
  929. {
  930. m_before_legacy_pre_activation_behavior_checked = checked();
  931. m_before_legacy_pre_activation_behavior_indeterminate = indeterminate();
  932. // 1. If this element's type attribute is in the Checkbox state, then set
  933. // this element's checkedness to its opposite value (i.e. true if it is
  934. // false, false if it is true) and set this element's indeterminate IDL
  935. // attribute to false.
  936. if (type_state() == TypeAttributeState::Checkbox) {
  937. set_checked(!checked(), ChangeSource::User);
  938. set_indeterminate(false);
  939. }
  940. // 2. If this element's type attribute is in the Radio Button state, then
  941. // get a reference to the element in this element's radio button group that
  942. // has its checkedness set to true, if any, and then set this element's
  943. // checkedness to true.
  944. if (type_state() == TypeAttributeState::RadioButton) {
  945. DeprecatedString name = this->name();
  946. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  947. if (element.checked() && is_in_same_radio_button_group(*this, element)) {
  948. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  949. return IterationDecision::Break;
  950. }
  951. return IterationDecision::Continue;
  952. });
  953. set_checked_within_group();
  954. }
  955. }
  956. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  957. void HTMLInputElement::legacy_cancelled_activation_behavior()
  958. {
  959. // 1. If the element's type attribute is in the Checkbox state, then set the
  960. // element's checkedness and the element's indeterminate IDL attribute back
  961. // to the values they had before the legacy-pre-activation behavior was run.
  962. if (type_state() == TypeAttributeState::Checkbox) {
  963. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  964. set_indeterminate(m_before_legacy_pre_activation_behavior_indeterminate);
  965. }
  966. // 2. If this element 's type attribute is in the Radio Button state, then
  967. // if the element to which a reference was obtained in the
  968. // legacy-pre-activation behavior, if any, is still in what is now this
  969. // element' s radio button group, if it still has one, and if so, setting
  970. // that element 's checkedness to true; or else, if there was no such
  971. // element, or that element is no longer in this element' s radio button
  972. // group, or if this element no longer has a radio button group, setting
  973. // this element's checkedness to false.
  974. if (type_state() == TypeAttributeState::RadioButton) {
  975. bool did_reselect_previous_element = false;
  976. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  977. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  978. if (is_in_same_radio_button_group(*this, element_in_group)) {
  979. element_in_group.set_checked_within_group();
  980. did_reselect_previous_element = true;
  981. }
  982. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  983. }
  984. if (!did_reselect_previous_element)
  985. set_checked(false, ChangeSource::User);
  986. }
  987. }
  988. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  989. {
  990. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  991. }
  992. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  993. i32 HTMLInputElement::default_tab_index_value() const
  994. {
  995. // See the base function for the spec comments.
  996. return 0;
  997. }
  998. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  999. WebIDL::ExceptionOr<double> HTMLInputElement::value_as_number() const
  1000. {
  1001. // 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.
  1002. 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)
  1003. return NAN;
  1004. // 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.
  1005. return value().bytes_as_string_view().to_double().value_or(NAN);
  1006. }
  1007. // https://html.spec.whatwg.org/multipage/input.html#dom-input-valueasnumber
  1008. WebIDL::ExceptionOr<void> HTMLInputElement::set_value_as_number(double value)
  1009. {
  1010. // On setting, if the new value is infinite, then throw a TypeError exception.
  1011. if (!isfinite(value))
  1012. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "valueAsNumber: Value is infinite"sv };
  1013. // 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.
  1014. 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)
  1015. return WebIDL::InvalidStateError::create(realm(), "valueAsNumber: Invalid input type used"_fly_string);
  1016. // Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string.
  1017. if (value == NAN) {
  1018. m_value = String {};
  1019. return {};
  1020. }
  1021. // 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.
  1022. m_value = MUST(String::number(value));
  1023. return {};
  1024. }
  1025. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  1026. WebIDL::ExceptionOr<bool> HTMLInputElement::check_validity()
  1027. {
  1028. dbgln("(STUBBED) HTMLInputElement::check_validity(). Called on: {}", debug_description());
  1029. return true;
  1030. }
  1031. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  1032. WebIDL::ExceptionOr<bool> HTMLInputElement::report_validity()
  1033. {
  1034. dbgln("(STUBBED) HTMLInputElement::report_validity(). Called on: {}", debug_description());
  1035. return true;
  1036. }
  1037. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  1038. void HTMLInputElement::set_custom_validity(String const& error)
  1039. {
  1040. dbgln("(STUBBED) HTMLInputElement::set_custom_validity(error={}). Called on: {}", error, debug_description());
  1041. return;
  1042. }
  1043. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-select
  1044. WebIDL::ExceptionOr<void> HTMLInputElement::select()
  1045. {
  1046. dbgln("(STUBBED) HTMLInputElement::select(). Called on: {}", debug_description());
  1047. return {};
  1048. }
  1049. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-textarea/input-setselectionrange
  1050. WebIDL::ExceptionOr<void> HTMLInputElement::set_selection_range(u32 start, u32 end, Optional<String> const& direction)
  1051. {
  1052. dbgln("(STUBBED) HTMLInputElement::set_selection_range(start={}, end={}, direction='{}'). Called on: {}", start, end, direction, debug_description());
  1053. return {};
  1054. }
  1055. Optional<ARIA::Role> HTMLInputElement::default_role() const
  1056. {
  1057. // https://www.w3.org/TR/html-aria/#el-input-button
  1058. if (type_state() == TypeAttributeState::Button)
  1059. return ARIA::Role::button;
  1060. // https://www.w3.org/TR/html-aria/#el-input-checkbox
  1061. if (type_state() == TypeAttributeState::Checkbox)
  1062. return ARIA::Role::checkbox;
  1063. // https://www.w3.org/TR/html-aria/#el-input-email
  1064. if (type_state() == TypeAttributeState::Email && !has_attribute(AttributeNames::list))
  1065. return ARIA::Role::textbox;
  1066. // https://www.w3.org/TR/html-aria/#el-input-image
  1067. if (type_state() == TypeAttributeState::ImageButton)
  1068. return ARIA::Role::button;
  1069. // https://www.w3.org/TR/html-aria/#el-input-number
  1070. if (type_state() == TypeAttributeState::Number)
  1071. return ARIA::Role::spinbutton;
  1072. // https://www.w3.org/TR/html-aria/#el-input-radio
  1073. if (type_state() == TypeAttributeState::RadioButton)
  1074. return ARIA::Role::radio;
  1075. // https://www.w3.org/TR/html-aria/#el-input-range
  1076. if (type_state() == TypeAttributeState::Range)
  1077. return ARIA::Role::slider;
  1078. // https://www.w3.org/TR/html-aria/#el-input-reset
  1079. if (type_state() == TypeAttributeState::ResetButton)
  1080. return ARIA::Role::button;
  1081. // https://www.w3.org/TR/html-aria/#el-input-text-list
  1082. if ((type_state() == TypeAttributeState::Text
  1083. || type_state() == TypeAttributeState::Search
  1084. || type_state() == TypeAttributeState::Telephone
  1085. || type_state() == TypeAttributeState::URL
  1086. || type_state() == TypeAttributeState::Email)
  1087. && has_attribute(AttributeNames::list))
  1088. return ARIA::Role::combobox;
  1089. // https://www.w3.org/TR/html-aria/#el-input-search
  1090. if (type_state() == TypeAttributeState::Search && !has_attribute(AttributeNames::list))
  1091. return ARIA::Role::textbox;
  1092. // https://www.w3.org/TR/html-aria/#el-input-submit
  1093. if (type_state() == TypeAttributeState::SubmitButton)
  1094. return ARIA::Role::button;
  1095. // https://www.w3.org/TR/html-aria/#el-input-tel
  1096. if (type_state() == TypeAttributeState::Telephone)
  1097. return ARIA::Role::textbox;
  1098. // https://www.w3.org/TR/html-aria/#el-input-text
  1099. if (type_state() == TypeAttributeState::Text && !has_attribute(AttributeNames::list))
  1100. return ARIA::Role::textbox;
  1101. // https://www.w3.org/TR/html-aria/#el-input-url
  1102. if (type_state() == TypeAttributeState::URL && !has_attribute(AttributeNames::list))
  1103. return ARIA::Role::textbox;
  1104. // https://www.w3.org/TR/html-aria/#el-input-color
  1105. // https://www.w3.org/TR/html-aria/#el-input-date
  1106. // https://www.w3.org/TR/html-aria/#el-input-datetime-local
  1107. // https://www.w3.org/TR/html-aria/#el-input-file
  1108. // https://www.w3.org/TR/html-aria/#el-input-hidden
  1109. // https://www.w3.org/TR/html-aria/#el-input-month
  1110. // https://www.w3.org/TR/html-aria/#el-input-password
  1111. // https://www.w3.org/TR/html-aria/#el-input-time
  1112. // https://www.w3.org/TR/html-aria/#el-input-week
  1113. return {};
  1114. }
  1115. bool HTMLInputElement::is_button() const
  1116. {
  1117. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-button
  1118. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-button
  1119. // https://html.spec.whatwg.org/multipage/input.html#reset-button-state-(type=reset):concept-button
  1120. // https://html.spec.whatwg.org/multipage/input.html#button-state-(type=button):concept-button
  1121. return type_state() == TypeAttributeState::SubmitButton
  1122. || type_state() == TypeAttributeState::ImageButton
  1123. || type_state() == TypeAttributeState::ResetButton
  1124. || type_state() == TypeAttributeState::Button;
  1125. }
  1126. bool HTMLInputElement::is_submit_button() const
  1127. {
  1128. // https://html.spec.whatwg.org/multipage/input.html#submit-button-state-(type=submit):concept-submit-button
  1129. // https://html.spec.whatwg.org/multipage/input.html#image-button-state-(type=image):concept-submit-button
  1130. return type_state() == TypeAttributeState::SubmitButton
  1131. || type_state() == TypeAttributeState::ImageButton;
  1132. }
  1133. bool HTMLInputElement::has_activation_behavior() const
  1134. {
  1135. return true;
  1136. }
  1137. void HTMLInputElement::activation_behavior(DOM::Event const&)
  1138. {
  1139. // The activation behavior for input elements are these steps:
  1140. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  1141. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  1142. run_input_activation_behavior().release_value_but_fixme_should_propagate_errors();
  1143. }
  1144. }