HTMLTextAreaElement.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2023, Sam Atkins <atkinssj@serenityos.org>
  4. * Copyright (c) 2024, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
  5. * Copyright (c) 2024, Jelle Raaijmakers <jelle@gmta.nl>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/Utf16View.h>
  10. #include <LibWeb/Bindings/HTMLTextAreaElementPrototype.h>
  11. #include <LibWeb/Bindings/Intrinsics.h>
  12. #include <LibWeb/CSS/StyleProperties.h>
  13. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  14. #include <LibWeb/CSS/StyleValues/LengthStyleValue.h>
  15. #include <LibWeb/DOM/Document.h>
  16. #include <LibWeb/DOM/ElementFactory.h>
  17. #include <LibWeb/DOM/Event.h>
  18. #include <LibWeb/DOM/ShadowRoot.h>
  19. #include <LibWeb/DOM/Text.h>
  20. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  21. #include <LibWeb/HTML/Numbers.h>
  22. #include <LibWeb/Infra/Strings.h>
  23. #include <LibWeb/Namespace.h>
  24. #include <LibWeb/Selection/Selection.h>
  25. namespace Web::HTML {
  26. JS_DEFINE_ALLOCATOR(HTMLTextAreaElement);
  27. HTMLTextAreaElement::HTMLTextAreaElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  28. : HTMLElement(document, move(qualified_name))
  29. , m_input_event_timer(Core::Timer::create_single_shot(0, [weak_this = make_weak_ptr()]() {
  30. if (!weak_this)
  31. return;
  32. static_cast<HTMLTextAreaElement*>(weak_this.ptr())->queue_firing_input_event();
  33. }))
  34. {
  35. }
  36. HTMLTextAreaElement::~HTMLTextAreaElement() = default;
  37. void HTMLTextAreaElement::adjust_computed_style(CSS::StyleProperties& style)
  38. {
  39. // AD-HOC: We rewrite `display: inline` to `display: inline-block`.
  40. // This is required for the internal shadow tree to work correctly in layout.
  41. if (style.display().is_inline_outside() && style.display().is_flow_inside())
  42. style.set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::InlineBlock)));
  43. if (style.property(CSS::PropertyID::Width)->has_auto())
  44. style.set_property(CSS::PropertyID::Width, CSS::LengthStyleValue::create(CSS::Length(cols(), CSS::Length::Type::Ch)));
  45. if (style.property(CSS::PropertyID::Height)->has_auto())
  46. style.set_property(CSS::PropertyID::Height, CSS::LengthStyleValue::create(CSS::Length(rows(), CSS::Length::Type::Lh)));
  47. }
  48. void HTMLTextAreaElement::initialize(JS::Realm& realm)
  49. {
  50. Base::initialize(realm);
  51. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLTextAreaElement);
  52. }
  53. void HTMLTextAreaElement::visit_edges(Cell::Visitor& visitor)
  54. {
  55. Base::visit_edges(visitor);
  56. visitor.visit(m_placeholder_element);
  57. visitor.visit(m_placeholder_text_node);
  58. visitor.visit(m_inner_text_element);
  59. visitor.visit(m_text_node);
  60. }
  61. void HTMLTextAreaElement::did_receive_focus()
  62. {
  63. if (!m_text_node)
  64. return;
  65. m_text_node->invalidate_style(DOM::StyleInvalidationReason::DidReceiveFocus);
  66. if (m_placeholder_text_node)
  67. m_placeholder_text_node->invalidate_style(DOM::StyleInvalidationReason::DidReceiveFocus);
  68. if (auto cursor = document().cursor_position(); !cursor || m_text_node != cursor->node())
  69. document().set_cursor_position(DOM::Position::create(realm(), *m_text_node, 0));
  70. }
  71. void HTMLTextAreaElement::did_lose_focus()
  72. {
  73. if (m_text_node)
  74. m_text_node->invalidate_style(DOM::StyleInvalidationReason::DidLoseFocus);
  75. if (m_placeholder_text_node)
  76. m_placeholder_text_node->invalidate_style(DOM::StyleInvalidationReason::DidLoseFocus);
  77. // The change event fires when the value is committed, if that makes sense for the control,
  78. // or else when the control loses focus
  79. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  80. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  81. change_event->set_bubbles(true);
  82. dispatch_event(change_event);
  83. });
  84. }
  85. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  86. i32 HTMLTextAreaElement::default_tab_index_value() const
  87. {
  88. // See the base function for the spec comments.
  89. return 0;
  90. }
  91. // https://html.spec.whatwg.org/multipage/form-elements.html#the-textarea-element:concept-form-reset-control
  92. void HTMLTextAreaElement::reset_algorithm()
  93. {
  94. // The reset algorithm for textarea elements is to set the dirty value flag back to false,
  95. m_dirty_value = false;
  96. // and set the raw value of element to its child text content.
  97. set_raw_value(child_text_content());
  98. if (m_text_node) {
  99. m_text_node->set_text_content(m_raw_value);
  100. update_placeholder_visibility();
  101. }
  102. }
  103. // https://w3c.github.io/webdriver/#dfn-clear-algorithm
  104. void HTMLTextAreaElement::clear_algorithm()
  105. {
  106. // The clear algorithm for textarea elements is to set the dirty value flag back to false,
  107. m_dirty_value = false;
  108. // and set the raw value of element to an empty string.
  109. set_raw_value(child_text_content());
  110. // Unlike their associated reset algorithms, changes made to form controls as part of these algorithms do count as
  111. // changes caused by the user (and thus, e.g. do cause input events to fire).
  112. queue_firing_input_event();
  113. }
  114. // https://html.spec.whatwg.org/multipage/forms.html#the-textarea-element:concept-node-clone-ext
  115. WebIDL::ExceptionOr<void> HTMLTextAreaElement::cloned(DOM::Node& copy, bool)
  116. {
  117. // The cloning steps for textarea elements must propagate the raw value and dirty value flag from the node being cloned to the copy.
  118. auto& textarea_copy = verify_cast<HTMLTextAreaElement>(copy);
  119. textarea_copy.m_raw_value = m_raw_value;
  120. textarea_copy.m_dirty_value = m_dirty_value;
  121. return {};
  122. }
  123. void HTMLTextAreaElement::form_associated_element_was_inserted()
  124. {
  125. create_shadow_tree_if_needed();
  126. }
  127. void HTMLTextAreaElement::form_associated_element_was_removed(DOM::Node*)
  128. {
  129. set_shadow_root(nullptr);
  130. }
  131. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-defaultvalue
  132. String HTMLTextAreaElement::default_value() const
  133. {
  134. // The defaultValue attribute's getter must return the element's child text content.
  135. return child_text_content();
  136. }
  137. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-defaultvalue
  138. void HTMLTextAreaElement::set_default_value(String const& default_value)
  139. {
  140. // The defaultValue attribute's setter must string replace all with the given value within this element.
  141. string_replace_all(default_value);
  142. }
  143. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-value
  144. String HTMLTextAreaElement::value() const
  145. {
  146. // The value IDL attribute must, on getting, return the element's API value.
  147. return api_value();
  148. }
  149. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-value
  150. void HTMLTextAreaElement::set_value(String const& value)
  151. {
  152. // 1. Let oldAPIValue be this element's API value.
  153. auto old_api_value = api_value();
  154. // 2. Set this element's raw value to the new value.
  155. set_raw_value(value);
  156. // 3. Set this element's dirty value flag to true.
  157. m_dirty_value = true;
  158. // 4. If the new API value is different from oldAPIValue, then move the text entry cursor position to the end of
  159. // the text control, unselecting any selected text and resetting the selection direction to "none".
  160. if (api_value() != old_api_value) {
  161. if (m_text_node) {
  162. m_text_node->set_data(m_raw_value);
  163. update_placeholder_visibility();
  164. set_the_selection_range(m_text_node->length(), m_text_node->length());
  165. }
  166. }
  167. }
  168. void HTMLTextAreaElement::set_raw_value(String value)
  169. {
  170. auto old_raw_value = move(m_raw_value);
  171. m_raw_value = move(value);
  172. m_api_value.clear();
  173. if (m_raw_value != old_raw_value)
  174. relevant_value_was_changed(m_text_node);
  175. }
  176. // https://html.spec.whatwg.org/multipage/form-elements.html#the-textarea-element:concept-fe-api-value-3
  177. String HTMLTextAreaElement::api_value() const
  178. {
  179. // The algorithm for obtaining the element's API value is to return the element's raw value, with newlines normalized.
  180. if (!m_api_value.has_value())
  181. m_api_value = Infra::normalize_newlines(m_raw_value);
  182. return *m_api_value;
  183. }
  184. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#concept-textarea/input-relevant-value
  185. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_relevant_value(String const& value)
  186. {
  187. set_value(value);
  188. return {};
  189. }
  190. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-textlength
  191. u32 HTMLTextAreaElement::text_length() const
  192. {
  193. // The textLength IDL attribute must return the length of the element's API value.
  194. return AK::utf16_code_unit_length_from_utf8(api_value());
  195. }
  196. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-checkvalidity
  197. bool HTMLTextAreaElement::check_validity()
  198. {
  199. dbgln("(STUBBED) HTMLTextAreaElement::check_validity(). Called on: {}", debug_description());
  200. return true;
  201. }
  202. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-reportvalidity
  203. bool HTMLTextAreaElement::report_validity()
  204. {
  205. dbgln("(STUBBED) HTMLTextAreaElement::report_validity(). Called on: {}", debug_description());
  206. return true;
  207. }
  208. // https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-cva-setcustomvalidity
  209. void HTMLTextAreaElement::set_custom_validity(String const& error)
  210. {
  211. dbgln("(STUBBED) HTMLTextAreaElement::set_custom_validity(\"{}\"). Called on: {}", error, debug_description());
  212. }
  213. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-maxlength
  214. WebIDL::Long HTMLTextAreaElement::max_length() const
  215. {
  216. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  217. if (auto maxlength_string = get_attribute(HTML::AttributeNames::maxlength); maxlength_string.has_value()) {
  218. if (auto maxlength = parse_non_negative_integer(*maxlength_string); maxlength.has_value())
  219. return *maxlength;
  220. }
  221. return -1;
  222. }
  223. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_max_length(WebIDL::Long value)
  224. {
  225. // The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers.
  226. return set_attribute(HTML::AttributeNames::maxlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  227. }
  228. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-minlength
  229. WebIDL::Long HTMLTextAreaElement::min_length() const
  230. {
  231. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  232. if (auto minlength_string = get_attribute(HTML::AttributeNames::minlength); minlength_string.has_value()) {
  233. if (auto minlength = parse_non_negative_integer(*minlength_string); minlength.has_value())
  234. return *minlength;
  235. }
  236. return -1;
  237. }
  238. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_min_length(WebIDL::Long value)
  239. {
  240. // The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.
  241. return set_attribute(HTML::AttributeNames::minlength, TRY(convert_non_negative_integer_to_string(realm(), value)));
  242. }
  243. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-cols
  244. unsigned HTMLTextAreaElement::cols() const
  245. {
  246. // The cols and rows attributes are limited to only positive numbers with fallback. The cols IDL attribute's default value is 20.
  247. if (auto cols_string = get_attribute(HTML::AttributeNames::cols); cols_string.has_value()) {
  248. if (auto cols = parse_non_negative_integer(*cols_string); cols.has_value())
  249. return *cols;
  250. }
  251. return 20;
  252. }
  253. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_cols(unsigned cols)
  254. {
  255. return set_attribute(HTML::AttributeNames::cols, String::number(cols));
  256. }
  257. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-rows
  258. unsigned HTMLTextAreaElement::rows() const
  259. {
  260. // The cols and rows attributes are limited to only positive numbers with fallback. The rows IDL attribute's default value is 2.
  261. if (auto rows_string = get_attribute(HTML::AttributeNames::rows); rows_string.has_value()) {
  262. if (auto rows = parse_non_negative_integer(*rows_string); rows.has_value())
  263. return *rows;
  264. }
  265. return 2;
  266. }
  267. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_rows(unsigned rows)
  268. {
  269. return set_attribute(HTML::AttributeNames::rows, String::number(rows));
  270. }
  271. WebIDL::UnsignedLong HTMLTextAreaElement::selection_start_binding() const
  272. {
  273. return selection_start().value();
  274. }
  275. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_selection_start_binding(WebIDL::UnsignedLong const& value)
  276. {
  277. return set_selection_start(value);
  278. }
  279. WebIDL::UnsignedLong HTMLTextAreaElement::selection_end_binding() const
  280. {
  281. return selection_end().value();
  282. }
  283. WebIDL::ExceptionOr<void> HTMLTextAreaElement::set_selection_end_binding(WebIDL::UnsignedLong const& value)
  284. {
  285. return set_selection_end(value);
  286. }
  287. String HTMLTextAreaElement::selection_direction_binding() const
  288. {
  289. return selection_direction().value();
  290. }
  291. void HTMLTextAreaElement::set_selection_direction_binding(String const& direction)
  292. {
  293. // NOTE: The selectionDirection setter never returns an error for textarea elements.
  294. MUST(static_cast<FormAssociatedTextControlElement&>(*this).set_selection_direction_binding(direction));
  295. }
  296. void HTMLTextAreaElement::create_shadow_tree_if_needed()
  297. {
  298. if (shadow_root())
  299. return;
  300. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  301. set_shadow_root(shadow_root);
  302. auto element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  303. MUST(shadow_root->append_child(element));
  304. m_placeholder_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  305. m_placeholder_element->set_use_pseudo_element(CSS::Selector::PseudoElement::Type::Placeholder);
  306. MUST(element->append_child(*m_placeholder_element));
  307. m_placeholder_text_node = heap().allocate<DOM::Text>(realm(), document(), String {});
  308. m_placeholder_text_node->set_data(get_attribute_value(HTML::AttributeNames::placeholder));
  309. m_placeholder_text_node->set_editable_text_node_owner(Badge<HTMLTextAreaElement> {}, *this);
  310. MUST(m_placeholder_element->append_child(*m_placeholder_text_node));
  311. m_inner_text_element = MUST(DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML));
  312. MUST(element->append_child(*m_inner_text_element));
  313. m_text_node = heap().allocate<DOM::Text>(realm(), document(), String {});
  314. handle_readonly_attribute(attribute(HTML::AttributeNames::readonly));
  315. m_text_node->set_editable_text_node_owner(Badge<HTMLTextAreaElement> {}, *this);
  316. // NOTE: If `children_changed()` was called before now, `m_raw_value` will hold the text content.
  317. // Otherwise, it will get filled in whenever that does get called.
  318. m_text_node->set_text_content(m_raw_value);
  319. handle_maxlength_attribute();
  320. MUST(m_inner_text_element->append_child(*m_text_node));
  321. update_placeholder_visibility();
  322. }
  323. // https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
  324. void HTMLTextAreaElement::handle_readonly_attribute(Optional<String> const& maybe_value)
  325. {
  326. // 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.
  327. m_is_mutable = !maybe_value.has_value();
  328. if (m_text_node)
  329. m_text_node->set_always_editable(m_is_mutable);
  330. }
  331. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-textarea-maxlength
  332. void HTMLTextAreaElement::handle_maxlength_attribute()
  333. {
  334. if (m_text_node) {
  335. auto max_length = this->max_length();
  336. if (max_length >= 0) {
  337. m_text_node->set_max_length(max_length);
  338. } else {
  339. m_text_node->set_max_length({});
  340. }
  341. }
  342. }
  343. void HTMLTextAreaElement::update_placeholder_visibility()
  344. {
  345. if (!m_placeholder_element)
  346. return;
  347. if (!m_text_node)
  348. return;
  349. auto placeholder_text = get_attribute(AttributeNames::placeholder);
  350. if (placeholder_text.has_value() && m_text_node->data().is_empty()) {
  351. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  352. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  353. } else {
  354. MUST(m_placeholder_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"sv));
  355. MUST(m_inner_text_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"sv));
  356. }
  357. }
  358. // https://html.spec.whatwg.org/multipage/form-elements.html#the-textarea-element:children-changed-steps
  359. void HTMLTextAreaElement::children_changed()
  360. {
  361. // The children changed steps for textarea elements must, if the element's dirty value flag is false,
  362. // set the element's raw value to its child text content.
  363. if (!m_dirty_value) {
  364. set_raw_value(child_text_content());
  365. if (m_text_node)
  366. m_text_node->set_text_content(m_raw_value);
  367. update_placeholder_visibility();
  368. }
  369. }
  370. void HTMLTextAreaElement::form_associated_element_attribute_changed(FlyString const& name, Optional<String> const& value)
  371. {
  372. if (name == HTML::AttributeNames::placeholder) {
  373. if (m_placeholder_text_node)
  374. m_placeholder_text_node->set_data(value.value_or(String {}));
  375. } else if (name == HTML::AttributeNames::readonly) {
  376. handle_readonly_attribute(value);
  377. } else if (name == HTML::AttributeNames::maxlength) {
  378. handle_maxlength_attribute();
  379. }
  380. }
  381. void HTMLTextAreaElement::did_edit_text_node(Badge<DOM::Document>)
  382. {
  383. VERIFY(m_text_node);
  384. set_raw_value(m_text_node->data());
  385. // Any time the user causes the element's raw value to change, the user agent must queue an element task on the user
  386. // interaction task source given the textarea element to fire an event named input at the textarea element, with the
  387. // bubbles and composed attributes initialized to true. User agents may wait for a suitable break in the user's
  388. // interaction before queuing the task; for example, a user agent could wait for the user to have not hit a key for
  389. // 100ms, so as to only fire the event when the user pauses, instead of continuously for each keystroke.
  390. m_input_event_timer->restart(100);
  391. // A textarea element's dirty value flag must be set to true whenever the user interacts with the control in a way that changes the raw value.
  392. m_dirty_value = true;
  393. update_placeholder_visibility();
  394. }
  395. void HTMLTextAreaElement::queue_firing_input_event()
  396. {
  397. queue_an_element_task(HTML::Task::Source::UserInteraction, [this]() {
  398. auto change_event = DOM::Event::create(realm(), HTML::EventNames::input, { .bubbles = true, .composed = true });
  399. dispatch_event(change_event);
  400. });
  401. }
  402. void HTMLTextAreaElement::selection_was_changed(size_t selection_start, size_t selection_end)
  403. {
  404. if (!m_text_node || !document().cursor_position() || document().cursor_position()->node() != m_text_node)
  405. return;
  406. document().set_cursor_position(DOM::Position::create(realm(), *m_text_node, selection_end));
  407. if (auto selection = document().get_selection())
  408. MUST(selection->set_base_and_extent(*m_text_node, selection_start, *m_text_node, selection_end));
  409. }
  410. }