HTMLInputElement.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. * Copyright (c) 2018-2022, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, Adam Hodgen <ant1441@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibWeb/Bindings/HTMLInputElementPrototype.h>
  8. #include <LibWeb/DOM/Document.h>
  9. #include <LibWeb/DOM/Event.h>
  10. #include <LibWeb/DOM/ShadowRoot.h>
  11. #include <LibWeb/DOM/Text.h>
  12. #include <LibWeb/HTML/BrowsingContext.h>
  13. #include <LibWeb/HTML/EventNames.h>
  14. #include <LibWeb/HTML/HTMLFormElement.h>
  15. #include <LibWeb/HTML/HTMLInputElement.h>
  16. #include <LibWeb/Layout/BlockContainer.h>
  17. #include <LibWeb/Layout/ButtonBox.h>
  18. #include <LibWeb/Layout/CheckBox.h>
  19. #include <LibWeb/Layout/RadioButton.h>
  20. namespace Web::HTML {
  21. HTMLInputElement::HTMLInputElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  22. : HTMLElement(document, move(qualified_name))
  23. , m_value(String::empty())
  24. {
  25. set_prototype(&window().ensure_web_prototype<Bindings::HTMLInputElementPrototype>("HTMLInputElement"));
  26. activation_behavior = [this](auto&) {
  27. // The activation behavior for input elements are these steps:
  28. // FIXME: 1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.
  29. // 2. Run this element's input activation behavior, if any, and do nothing otherwise.
  30. run_input_activation_behavior();
  31. };
  32. }
  33. HTMLInputElement::~HTMLInputElement() = default;
  34. void HTMLInputElement::visit_edges(Cell::Visitor& visitor)
  35. {
  36. Base::visit_edges(visitor);
  37. visitor.visit(m_text_node.ptr());
  38. visitor.visit(m_legacy_pre_activation_behavior_checked_element_in_group.ptr());
  39. }
  40. RefPtr<Layout::Node> HTMLInputElement::create_layout_node(NonnullRefPtr<CSS::StyleProperties> style)
  41. {
  42. if (type_state() == TypeAttributeState::Hidden)
  43. return nullptr;
  44. if (type_state() == TypeAttributeState::SubmitButton || type_state() == TypeAttributeState::Button || type_state() == TypeAttributeState::ResetButton)
  45. return adopt_ref(*new Layout::ButtonBox(document(), *this, move(style)));
  46. if (type_state() == TypeAttributeState::Checkbox)
  47. return adopt_ref(*new Layout::CheckBox(document(), *this, move(style)));
  48. if (type_state() == TypeAttributeState::RadioButton)
  49. return adopt_ref(*new Layout::RadioButton(document(), *this, move(style)));
  50. auto layout_node = adopt_ref(*new Layout::BlockContainer(document(), this, move(style)));
  51. layout_node->set_inline(true);
  52. return layout_node;
  53. }
  54. void HTMLInputElement::set_checked(bool checked, ChangeSource change_source)
  55. {
  56. if (m_checked == checked)
  57. return;
  58. // The dirty checkedness flag must be initially set to false when the element is created,
  59. // and must be set to true whenever the user interacts with the control in a way that changes the checkedness.
  60. if (change_source == ChangeSource::User)
  61. m_dirty_checkedness = true;
  62. m_checked = checked;
  63. set_needs_style_update(true);
  64. }
  65. void HTMLInputElement::set_checked_binding(bool checked)
  66. {
  67. if (type_state() == TypeAttributeState::RadioButton) {
  68. if (checked)
  69. set_checked_within_group();
  70. else
  71. set_checked(false, ChangeSource::Programmatic);
  72. } else {
  73. set_checked(checked, ChangeSource::Programmatic);
  74. }
  75. }
  76. // https://html.spec.whatwg.org/multipage/input.html#input-activation-behavior
  77. void HTMLInputElement::run_input_activation_behavior()
  78. {
  79. if (type_state() == TypeAttributeState::Checkbox || type_state() == TypeAttributeState::RadioButton) {
  80. // 1. If the element is not connected, then return.
  81. if (!is_connected())
  82. return;
  83. // 2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.
  84. auto input_event = DOM::Event::create(document().window(), HTML::EventNames::input);
  85. input_event->set_bubbles(true);
  86. input_event->set_composed(true);
  87. dispatch_event(*input_event);
  88. // 3. Fire an event named change at the element with the bubbles attribute initialized to true.
  89. auto change_event = DOM::Event::create(document().window(), HTML::EventNames::change);
  90. change_event->set_bubbles(true);
  91. dispatch_event(*change_event);
  92. } else if (type_state() == TypeAttributeState::SubmitButton) {
  93. JS::GCPtr<HTMLFormElement> form;
  94. // 1. If the element does not have a form owner, then return.
  95. if (!(form = this->form()))
  96. return;
  97. // 2. If the element's node document is not fully active, then return.
  98. if (!document().is_fully_active())
  99. return;
  100. // 3. Submit the form owner from the element.
  101. form->submit_form(this);
  102. } else {
  103. dispatch_event(*DOM::Event::create(document().window(), EventNames::change));
  104. }
  105. }
  106. void HTMLInputElement::did_edit_text_node(Badge<BrowsingContext>)
  107. {
  108. // 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.
  109. m_value = value_sanitization_algorithm(m_text_node->data());
  110. m_dirty_value = true;
  111. // NOTE: This is a bit ad-hoc, but basically implements part of "4.10.5.5 Common event behaviors"
  112. // https://html.spec.whatwg.org/multipage/input.html#common-input-element-events
  113. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  114. auto input_event = DOM::Event::create(document().window(), HTML::EventNames::input);
  115. input_event->set_bubbles(true);
  116. input_event->set_composed(true);
  117. dispatch_event(*input_event);
  118. // FIXME: This should only fire when the input is "committed", whatever that means.
  119. auto change_event = DOM::Event::create(document().window(), HTML::EventNames::change);
  120. change_event->set_bubbles(true);
  121. dispatch_event(*change_event);
  122. });
  123. }
  124. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  125. String HTMLInputElement::value() const
  126. {
  127. // Return the current value of the element.
  128. return m_value;
  129. }
  130. // https://html.spec.whatwg.org/multipage/input.html#dom-input-value-value
  131. void HTMLInputElement::set_value(String value)
  132. {
  133. // 1. Let oldValue be the element's value.
  134. auto old_value = move(m_value);
  135. // 2. Set the element's value to the new value.
  136. // NOTE: This is done as part of step 4 below.
  137. // 3. Set the element's dirty value flag to true.
  138. m_dirty_value = true;
  139. // 4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.
  140. m_value = value_sanitization_algorithm(move(value));
  141. // 5. If the element's value (after applying the value sanitization algorithm) is different from oldValue,
  142. // and the element has a text entry cursor position, move the text entry cursor position to the end of the
  143. // text control, unselecting any selected text and resetting the selection direction to "none".
  144. if (m_text_node && (m_value != old_value))
  145. m_text_node->set_data(m_value);
  146. }
  147. void HTMLInputElement::create_shadow_tree_if_needed()
  148. {
  149. if (shadow_root())
  150. return;
  151. // FIXME: This could be better factored. Everything except the below types becomes a text input.
  152. switch (type_state()) {
  153. case TypeAttributeState::RadioButton:
  154. case TypeAttributeState::Checkbox:
  155. case TypeAttributeState::Button:
  156. case TypeAttributeState::SubmitButton:
  157. case TypeAttributeState::ResetButton:
  158. case TypeAttributeState::ImageButton:
  159. return;
  160. default:
  161. break;
  162. }
  163. auto* shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this);
  164. auto initial_value = m_value;
  165. if (initial_value.is_null())
  166. initial_value = String::empty();
  167. auto element = document().create_element(HTML::TagNames::div).release_value();
  168. element->set_attribute(HTML::AttributeNames::style, "white-space: pre; padding-top: 1px; padding-bottom: 1px; padding-left: 2px; padding-right: 2px");
  169. m_text_node = heap().allocate<DOM::Text>(realm(), document(), initial_value);
  170. m_text_node->set_always_editable(true);
  171. m_text_node->set_owner_input_element({}, *this);
  172. element->append_child(*m_text_node);
  173. shadow_root->append_child(move(element));
  174. set_shadow_root(move(shadow_root));
  175. }
  176. void HTMLInputElement::did_receive_focus()
  177. {
  178. auto* browsing_context = document().browsing_context();
  179. if (!browsing_context)
  180. return;
  181. if (!m_text_node)
  182. return;
  183. browsing_context->set_cursor_position(DOM::Position { *m_text_node, 0 });
  184. }
  185. void HTMLInputElement::parse_attribute(FlyString const& name, String const& value)
  186. {
  187. HTMLElement::parse_attribute(name, value);
  188. if (name == HTML::AttributeNames::checked) {
  189. // When the checked content attribute is added, if the control does not have dirty checkedness,
  190. // the user agent must set the checkedness of the element to true
  191. if (!m_dirty_checkedness)
  192. set_checked(true, ChangeSource::Programmatic);
  193. } else if (name == HTML::AttributeNames::type) {
  194. m_type = parse_type_attribute(value);
  195. } else if (name == HTML::AttributeNames::value) {
  196. if (!m_dirty_value)
  197. m_value = value_sanitization_algorithm(value);
  198. }
  199. }
  200. HTMLInputElement::TypeAttributeState HTMLInputElement::parse_type_attribute(StringView type)
  201. {
  202. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  203. if (type.equals_ignoring_case(#keyword##sv)) \
  204. return HTMLInputElement::TypeAttributeState::state;
  205. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  206. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  207. // The missing value default and the invalid value default are the Text state.
  208. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:missing-value-default
  209. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:invalid-value-default
  210. return HTMLInputElement::TypeAttributeState::Text;
  211. }
  212. void HTMLInputElement::did_remove_attribute(FlyString const& name)
  213. {
  214. HTMLElement::did_remove_attribute(name);
  215. if (name == HTML::AttributeNames::checked) {
  216. // When the checked content attribute is removed, if the control does not have dirty checkedness,
  217. // the user agent must set the checkedness of the element to false.
  218. if (!m_dirty_checkedness)
  219. set_checked(false, ChangeSource::Programmatic);
  220. } else if (name == HTML::AttributeNames::value) {
  221. if (!m_dirty_value)
  222. m_value = String::empty();
  223. }
  224. }
  225. String HTMLInputElement::type() const
  226. {
  227. switch (m_type) {
  228. #define __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE(keyword, state) \
  229. case TypeAttributeState::state: \
  230. return #keyword##sv;
  231. ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTES
  232. #undef __ENUMERATE_HTML_INPUT_TYPE_ATTRIBUTE
  233. }
  234. VERIFY_NOT_REACHED();
  235. }
  236. void HTMLInputElement::set_type(String const& type)
  237. {
  238. set_attribute(HTML::AttributeNames::type, type);
  239. }
  240. // https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
  241. String HTMLInputElement::value_sanitization_algorithm(String value) const
  242. {
  243. if (type_state() == HTMLInputElement::TypeAttributeState::Text || type_state() == HTMLInputElement::TypeAttributeState::Search || type_state() == HTMLInputElement::TypeAttributeState::Telephone || type_state() == HTMLInputElement::TypeAttributeState::Password) {
  244. // Strip newlines from the value.
  245. if (value.contains('\r') || value.contains('\n')) {
  246. StringBuilder builder;
  247. for (auto c : value) {
  248. if (!(c == '\r' || c == '\n'))
  249. builder.append(c);
  250. }
  251. return builder.to_string();
  252. }
  253. } else if (type_state() == HTMLInputElement::TypeAttributeState::URL) {
  254. // Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.
  255. if (value.contains('\r') || value.contains('\n')) {
  256. StringBuilder builder;
  257. for (auto c : value) {
  258. if (!(c == '\r' || c == '\n'))
  259. builder.append(c);
  260. }
  261. return builder.to_string().trim_whitespace();
  262. }
  263. } else if (type_state() == HTMLInputElement::TypeAttributeState::Number) {
  264. // If the value of the element is not a valid floating-point number, then set it to the empty string instead.
  265. char* end_ptr;
  266. auto val = strtod(value.characters(), &end_ptr);
  267. if (!isfinite(val) || *end_ptr)
  268. return "";
  269. }
  270. // FIXME: Implement remaining value sanitation algorithms
  271. return value;
  272. }
  273. void HTMLInputElement::form_associated_element_was_inserted()
  274. {
  275. create_shadow_tree_if_needed();
  276. }
  277. void HTMLInputElement::set_checked_within_group()
  278. {
  279. if (checked())
  280. return;
  281. set_checked(true, ChangeSource::User);
  282. String name = this->name();
  283. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  284. if (element.checked() && &element != this && element.name() == name)
  285. element.set_checked(false, ChangeSource::User);
  286. return IterationDecision::Continue;
  287. });
  288. }
  289. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-pre-activation-behavior
  290. void HTMLInputElement::legacy_pre_activation_behavior()
  291. {
  292. m_before_legacy_pre_activation_behavior_checked = checked();
  293. // 1. If this element's type attribute is in the Checkbox state, then set
  294. // this element's checkedness to its opposite value (i.e. true if it is
  295. // false, false if it is true) and set this element's indeterminate IDL
  296. // attribute to false.
  297. // FIXME: Set indeterminate to false when that exists.
  298. if (type_state() == TypeAttributeState::Checkbox) {
  299. set_checked(!checked(), ChangeSource::User);
  300. }
  301. // 2. If this element's type attribute is in the Radio Button state, then
  302. // get a reference to the element in this element's radio button group that
  303. // has its checkedness set to true, if any, and then set this element's
  304. // checkedness to true.
  305. if (type_state() == TypeAttributeState::RadioButton) {
  306. String name = this->name();
  307. document().for_each_in_inclusive_subtree_of_type<HTML::HTMLInputElement>([&](auto& element) {
  308. if (element.checked() && element.name() == name) {
  309. m_legacy_pre_activation_behavior_checked_element_in_group = &element;
  310. return IterationDecision::Break;
  311. }
  312. return IterationDecision::Continue;
  313. });
  314. set_checked_within_group();
  315. }
  316. }
  317. // https://html.spec.whatwg.org/multipage/input.html#the-input-element:legacy-canceled-activation-behavior
  318. void HTMLInputElement::legacy_cancelled_activation_behavior()
  319. {
  320. // 1. If the element's type attribute is in the Checkbox state, then set the
  321. // element's checkedness and the element's indeterminate IDL attribute back
  322. // to the values they had before the legacy-pre-activation behavior was run.
  323. if (type_state() == TypeAttributeState::Checkbox) {
  324. set_checked(m_before_legacy_pre_activation_behavior_checked, ChangeSource::Programmatic);
  325. }
  326. // 2. If this element 's type attribute is in the Radio Button state, then
  327. // if the element to which a reference was obtained in the
  328. // legacy-pre-activation behavior, if any, is still in what is now this
  329. // element' s radio button group, if it still has one, and if so, setting
  330. // that element 's checkedness to true; or else, if there was no such
  331. // element, or that element is no longer in this element' s radio button
  332. // group, or if this element no longer has a radio button group, setting
  333. // this element's checkedness to false.
  334. if (type_state() == TypeAttributeState::RadioButton) {
  335. String name = this->name();
  336. bool did_reselect_previous_element = false;
  337. if (m_legacy_pre_activation_behavior_checked_element_in_group) {
  338. auto& element_in_group = *m_legacy_pre_activation_behavior_checked_element_in_group;
  339. if (name == element_in_group.name()) {
  340. element_in_group.set_checked_within_group();
  341. did_reselect_previous_element = true;
  342. }
  343. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  344. }
  345. if (!did_reselect_previous_element)
  346. set_checked(false, ChangeSource::User);
  347. }
  348. }
  349. void HTMLInputElement::legacy_cancelled_activation_behavior_was_not_called()
  350. {
  351. m_legacy_pre_activation_behavior_checked_element_in_group = nullptr;
  352. }
  353. }