HTMLInputElement.cpp 52 KB

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