HTMLInputElement.cpp 54 KB

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