HTMLSelectElement.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
  4. * Copyright (c) 2023, Bastiaan van der Plaat <bastiaan.v.d.plaat@gmail.com>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/CSS/StyleValues/DisplayStyleValue.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/ElementFactory.h>
  12. #include <LibWeb/DOM/Event.h>
  13. #include <LibWeb/DOM/ShadowRoot.h>
  14. #include <LibWeb/HTML/EventNames.h>
  15. #include <LibWeb/HTML/HTMLFormElement.h>
  16. #include <LibWeb/HTML/HTMLHRElement.h>
  17. #include <LibWeb/HTML/HTMLOptGroupElement.h>
  18. #include <LibWeb/HTML/HTMLOptionElement.h>
  19. #include <LibWeb/HTML/HTMLSelectElement.h>
  20. #include <LibWeb/Infra/Strings.h>
  21. #include <LibWeb/Layout/Node.h>
  22. #include <LibWeb/Namespace.h>
  23. #include <LibWeb/Page/Page.h>
  24. namespace Web::HTML {
  25. JS_DEFINE_ALLOCATOR(HTMLSelectElement);
  26. HTMLSelectElement::HTMLSelectElement(DOM::Document& document, DOM::QualifiedName qualified_name)
  27. : HTMLElement(document, move(qualified_name))
  28. {
  29. }
  30. HTMLSelectElement::~HTMLSelectElement() = default;
  31. void HTMLSelectElement::initialize(JS::Realm& realm)
  32. {
  33. Base::initialize(realm);
  34. WEB_SET_PROTOTYPE_FOR_INTERFACE(HTMLSelectElement);
  35. }
  36. void HTMLSelectElement::visit_edges(Cell::Visitor& visitor)
  37. {
  38. Base::visit_edges(visitor);
  39. visitor.visit(m_options);
  40. visitor.visit(m_inner_text_element);
  41. visitor.visit(m_chevron_icon_element);
  42. }
  43. void HTMLSelectElement::adjust_computed_style(CSS::StyleProperties& style)
  44. {
  45. // AD-HOC: We rewrite `display: inline` to `display: inline-block`.
  46. // This is required for the internal shadow tree to work correctly in layout.
  47. if (style.display().is_inline_outside() && style.display().is_flow_inside())
  48. style.set_property(CSS::PropertyID::Display, CSS::DisplayStyleValue::create(CSS::Display::from_short(CSS::Display::Short::InlineBlock)));
  49. }
  50. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-options
  51. JS::GCPtr<HTMLOptionsCollection> const& HTMLSelectElement::options()
  52. {
  53. if (!m_options) {
  54. m_options = HTMLOptionsCollection::create(*this, [](DOM::Element const& element) {
  55. // https://html.spec.whatwg.org/multipage/form-elements.html#concept-select-option-list
  56. // The list of options for a select element consists of all the option element children of
  57. // the select element, and all the option element children of all the optgroup element children
  58. // of the select element, in tree order.
  59. return is<HTMLOptionElement>(element);
  60. });
  61. }
  62. return m_options;
  63. }
  64. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-length
  65. size_t HTMLSelectElement::length()
  66. {
  67. // The length IDL attribute must return the number of nodes represented by the options collection. On setting, it must act like the attribute of the same name on the options collection.
  68. return const_cast<HTMLOptionsCollection&>(*options()).length();
  69. }
  70. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-item
  71. DOM::Element* HTMLSelectElement::item(size_t index)
  72. {
  73. // The item(index) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.
  74. return const_cast<HTMLOptionsCollection&>(*options()).item(index);
  75. }
  76. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-nameditem
  77. DOM::Element* HTMLSelectElement::named_item(FlyString const& name)
  78. {
  79. // The namedItem(name) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.
  80. return const_cast<HTMLOptionsCollection&>(*options()).named_item(name);
  81. }
  82. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-add
  83. WebIDL::ExceptionOr<void> HTMLSelectElement::add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before)
  84. {
  85. // Similarly, the add(element, before) method must act like its namesake method on that same options collection.
  86. return const_cast<HTMLOptionsCollection&>(*options()).add(move(element), move(before));
  87. }
  88. // https://html.spec.whatwg.org/multipage/form-elements.html#concept-select-option-list
  89. Vector<JS::Handle<HTMLOptionElement>> HTMLSelectElement::list_of_options() const
  90. {
  91. // The list of options for a select element consists of all the option element children of the select element,
  92. // and all the option element children of all the optgroup element children of the select element, in tree order.
  93. Vector<JS::Handle<HTMLOptionElement>> list;
  94. for_each_child_of_type<HTMLOptionElement>([&](HTMLOptionElement& option_element) {
  95. list.append(JS::make_handle(option_element));
  96. });
  97. for_each_child_of_type<HTMLOptGroupElement>([&](HTMLOptGroupElement const& optgroup_element) {
  98. optgroup_element.for_each_child_of_type<HTMLOptionElement>([&](HTMLOptionElement& option_element) {
  99. list.append(JS::make_handle(option_element));
  100. });
  101. });
  102. return list;
  103. }
  104. // https://html.spec.whatwg.org/multipage/form-elements.html#the-select-element:concept-form-reset-control
  105. void HTMLSelectElement::reset_algorithm()
  106. {
  107. // The reset algorithm for select elements is to go through all the option elements in the element's list of options,
  108. for (auto const& option_element : list_of_options()) {
  109. // set their selectedness to true if the option element has a selected attribute, and false otherwise,
  110. option_element->m_selected = option_element->has_attribute(AttributeNames::selected);
  111. // set their dirtiness to false,
  112. option_element->m_dirty = false;
  113. // and then have the option elements ask for a reset.
  114. option_element->ask_for_a_reset();
  115. }
  116. }
  117. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-selectedindex
  118. int HTMLSelectElement::selected_index() const
  119. {
  120. // The selectedIndex IDL attribute, on getting, must return the index of the first option element in the list of options
  121. // in tree order that has its selectedness set to true, if any. If there isn't one, then it must return −1.
  122. int index = 0;
  123. for (auto const& option_element : list_of_options()) {
  124. if (option_element->selected())
  125. return index;
  126. ++index;
  127. }
  128. return -1;
  129. }
  130. void HTMLSelectElement::set_selected_index(int index)
  131. {
  132. // On setting, the selectedIndex attribute must set the selectedness of all the option elements in the list of options to false,
  133. // and then the option element in the list of options whose index is the given new value,
  134. // if any, must have its selectedness set to true and its dirtiness set to true.
  135. auto options = list_of_options();
  136. for (auto& option : options)
  137. option->m_selected = false;
  138. if (index < 0 || index >= static_cast<int>(options.size()))
  139. return;
  140. auto& selected_option = options[index];
  141. selected_option->m_selected = true;
  142. selected_option->m_dirty = true;
  143. }
  144. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  145. i32 HTMLSelectElement::default_tab_index_value() const
  146. {
  147. // See the base function for the spec comments.
  148. return 0;
  149. }
  150. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-type
  151. String const& HTMLSelectElement::type() const
  152. {
  153. // The type IDL attribute, on getting, must return the string "select-one" if the multiple attribute is absent, and the string "select-multiple" if the multiple attribute is present.
  154. static String const select_one = "select-one"_string;
  155. static String const select_multiple = "select-multiple"_string;
  156. if (!has_attribute(AttributeNames::multiple))
  157. return select_one;
  158. return select_multiple;
  159. }
  160. Optional<ARIA::Role> HTMLSelectElement::default_role() const
  161. {
  162. // https://www.w3.org/TR/html-aria/#el-select-multiple-or-size-greater-1
  163. if (has_attribute(AttributeNames::multiple))
  164. return ARIA::Role::listbox;
  165. if (has_attribute(AttributeNames::size)) {
  166. if (auto size_string = get_attribute(HTML::AttributeNames::size); size_string.has_value()) {
  167. if (auto size = size_string->to_number<int>(); size.has_value() && *size > 1)
  168. return ARIA::Role::listbox;
  169. }
  170. }
  171. // https://www.w3.org/TR/html-aria/#el-select
  172. return ARIA::Role::combobox;
  173. }
  174. String HTMLSelectElement::value() const
  175. {
  176. for (auto const& option_element : list_of_options())
  177. if (option_element->selected())
  178. return option_element->value();
  179. return ""_string;
  180. }
  181. WebIDL::ExceptionOr<void> HTMLSelectElement::set_value(String const& value)
  182. {
  183. for (auto const& option_element : list_of_options())
  184. option_element->set_selected(option_element->value() == value);
  185. update_inner_text_element();
  186. // When the user agent is to send select update notifications, queue an element task on the user interaction task source given the select element to run these steps:
  187. queue_an_element_task(HTML::Task::Source::UserInteraction, [this] {
  188. // FIXME: 1. Set the select element's user interacted to true.
  189. // 2. Fire an event named input at the select element, with the bubbles and composed attributes initialized to true.
  190. auto input_event = DOM::Event::create(realm(), HTML::EventNames::input);
  191. input_event->set_bubbles(true);
  192. input_event->set_composed(true);
  193. dispatch_event(input_event);
  194. // 3. Fire an event named change at the select element, with the bubbles attribute initialized to true.
  195. auto change_event = DOM::Event::create(realm(), HTML::EventNames::change);
  196. change_event->set_bubbles(true);
  197. dispatch_event(*change_event);
  198. });
  199. return {};
  200. }
  201. void HTMLSelectElement::set_is_open(bool open)
  202. {
  203. if (open == m_is_open)
  204. return;
  205. m_is_open = open;
  206. invalidate_style();
  207. }
  208. bool HTMLSelectElement::has_activation_behavior() const
  209. {
  210. return true;
  211. }
  212. static Optional<String> strip_newlines(Optional<String> string)
  213. {
  214. // FIXME: Move this to a more general function
  215. if (!string.has_value())
  216. return {};
  217. StringBuilder builder;
  218. for (auto c : string.value().bytes_as_string_view()) {
  219. if (c == '\r' || c == '\n') {
  220. builder.append(' ');
  221. } else {
  222. builder.append(c);
  223. }
  224. }
  225. return MUST(Infra::strip_and_collapse_whitespace(MUST(builder.to_string())));
  226. }
  227. void HTMLSelectElement::activation_behavior(DOM::Event const&)
  228. {
  229. // Populate select items
  230. Vector<SelectItem> items;
  231. for (auto const& child : children_as_vector()) {
  232. if (is<HTMLOptGroupElement>(*child)) {
  233. auto& opt_group_element = verify_cast<HTMLOptGroupElement>(*child);
  234. Vector<SelectItem> opt_group_items;
  235. for (auto const& child : opt_group_element.children_as_vector()) {
  236. if (is<HTMLOptionElement>(*child)) {
  237. auto& option_element = verify_cast<HTMLOptionElement>(*child);
  238. auto option_value = option_element.value();
  239. opt_group_items.append(SelectItem { SelectItem::Type::Option, strip_newlines(option_element.text_content()), option_value, {}, option_element.selected() });
  240. }
  241. if (is<HTMLHRElement>(*child)) {
  242. opt_group_items.append(SelectItem { SelectItem::Type::Separator });
  243. }
  244. }
  245. items.append(SelectItem { SelectItem::Type::OptionGroup, opt_group_element.get_attribute(AttributeNames::label), {}, opt_group_items });
  246. }
  247. if (is<HTMLOptionElement>(*child)) {
  248. auto& option_element = verify_cast<HTMLOptionElement>(*child);
  249. auto option_value = option_element.value();
  250. items.append(SelectItem { SelectItem::Type::Option, strip_newlines(option_element.text_content()), option_value, {}, option_element.selected() });
  251. }
  252. if (is<HTMLHRElement>(*child)) {
  253. items.append(SelectItem { SelectItem::Type::Separator });
  254. }
  255. }
  256. // Request select dropdown
  257. auto weak_element = make_weak_ptr<HTMLSelectElement>();
  258. auto rect = get_bounding_client_rect();
  259. auto position = document().navigable()->to_top_level_position(Web::CSSPixelPoint { rect->x(), rect->y() });
  260. document().page().did_request_select_dropdown(weak_element, position, CSSPixels(rect->width()), items);
  261. set_is_open(true);
  262. }
  263. void HTMLSelectElement::did_select_value(Optional<String> value)
  264. {
  265. set_is_open(false);
  266. if (value.has_value()) {
  267. MUST(set_value(*value));
  268. }
  269. }
  270. void HTMLSelectElement::form_associated_element_was_inserted()
  271. {
  272. create_shadow_tree_if_needed();
  273. // Wait until children are ready
  274. queue_an_element_task(HTML::Task::Source::Microtask, [this] {
  275. // Select first option when no other option is selected
  276. if (selected_index() == -1) {
  277. auto options = list_of_options();
  278. if (options.size() > 0) {
  279. options.at(0)->set_selected(true);
  280. }
  281. }
  282. update_inner_text_element();
  283. });
  284. }
  285. void HTMLSelectElement::form_associated_element_was_removed(DOM::Node*)
  286. {
  287. set_shadow_root(nullptr);
  288. }
  289. void HTMLSelectElement::computed_css_values_changed()
  290. {
  291. // Hide chevron icon when appearance is none
  292. if (m_chevron_icon_element) {
  293. auto appearance = computed_css_values()->appearance();
  294. if (appearance.has_value() && *appearance == CSS::Appearance::None) {
  295. MUST(m_chevron_icon_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "none"_string));
  296. } else {
  297. MUST(m_chevron_icon_element->style_for_bindings()->set_property(CSS::PropertyID::Display, "block"_string));
  298. }
  299. }
  300. }
  301. void HTMLSelectElement::create_shadow_tree_if_needed()
  302. {
  303. if (shadow_root_internal())
  304. return;
  305. auto shadow_root = heap().allocate<DOM::ShadowRoot>(realm(), document(), *this, Bindings::ShadowRootMode::Closed);
  306. set_shadow_root(shadow_root);
  307. auto border = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  308. MUST(border->set_attribute(HTML::AttributeNames::style, R"~~~(
  309. display: flex;
  310. align-items: center;
  311. height: 100%;
  312. )~~~"_string));
  313. MUST(shadow_root->append_child(border));
  314. m_inner_text_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  315. MUST(m_inner_text_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  316. flex: 1;
  317. )~~~"_string));
  318. MUST(border->append_child(*m_inner_text_element));
  319. // FIXME: Find better way to add chevron icon
  320. m_chevron_icon_element = DOM::create_element(document(), HTML::TagNames::div, Namespace::HTML).release_value_but_fixme_should_propagate_errors();
  321. MUST(m_chevron_icon_element->set_attribute(HTML::AttributeNames::style, R"~~~(
  322. width: 16px;
  323. height: 16px;
  324. margin-left: 4px;
  325. )~~~"_string));
  326. MUST(m_chevron_icon_element->set_inner_html("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path d=\"M7.41,8.58L12,13.17L16.59,8.58L18,10L12,16L6,10L7.41,8.58Z\" /></svg>"sv));
  327. MUST(border->append_child(*m_chevron_icon_element));
  328. update_inner_text_element();
  329. }
  330. void HTMLSelectElement::update_inner_text_element()
  331. {
  332. if (!m_inner_text_element)
  333. return;
  334. // Update inner text element to text content of selected option
  335. for (auto const& option_element : list_of_options()) {
  336. if (option_element->selected()) {
  337. m_inner_text_element->set_text_content(strip_newlines(option_element->text_content()));
  338. return;
  339. }
  340. }
  341. }
  342. }