HTMLTextAreaElement.cpp 19 KB

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