HTMLSelectElement.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. set_prototype(&Bindings::ensure_web_prototype<Bindings::HTMLSelectElementPrototype>(realm, "HTMLSelectElement"_fly_string));
  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. JS::GCPtr<Layout::Node> HTMLSelectElement::create_layout_node(NonnullRefPtr<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. return Element::create_layout_node_for_display_type(document(), style->display(), style, this);
  50. }
  51. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-options
  52. JS::GCPtr<HTMLOptionsCollection> const& HTMLSelectElement::options()
  53. {
  54. if (!m_options) {
  55. m_options = HTMLOptionsCollection::create(*this, [](DOM::Element const& element) {
  56. // https://html.spec.whatwg.org/multipage/form-elements.html#concept-select-option-list
  57. // The list of options for a select element consists of all the option element children of
  58. // the select element, and all the option element children of all the optgroup element children
  59. // of the select element, in tree order.
  60. return is<HTMLOptionElement>(element);
  61. });
  62. }
  63. return m_options;
  64. }
  65. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-length
  66. size_t HTMLSelectElement::length()
  67. {
  68. // 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.
  69. return const_cast<HTMLOptionsCollection&>(*options()).length();
  70. }
  71. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-item
  72. DOM::Element* HTMLSelectElement::item(size_t index)
  73. {
  74. // 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.
  75. return const_cast<HTMLOptionsCollection&>(*options()).item(index);
  76. }
  77. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-nameditem
  78. DOM::Element* HTMLSelectElement::named_item(FlyString const& name)
  79. {
  80. // 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.
  81. return const_cast<HTMLOptionsCollection&>(*options()).named_item(name);
  82. }
  83. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-add
  84. WebIDL::ExceptionOr<void> HTMLSelectElement::add(HTMLOptionOrOptGroupElement element, Optional<HTMLElementOrElementIndex> before)
  85. {
  86. // Similarly, the add(element, before) method must act like its namesake method on that same options collection.
  87. return const_cast<HTMLOptionsCollection&>(*options()).add(move(element), move(before));
  88. }
  89. // https://html.spec.whatwg.org/multipage/form-elements.html#concept-select-option-list
  90. Vector<JS::Handle<HTMLOptionElement>> HTMLSelectElement::list_of_options() const
  91. {
  92. // The list of options for a select element consists of all the option element children of the select element,
  93. // and all the option element children of all the optgroup element children of the select element, in tree order.
  94. Vector<JS::Handle<HTMLOptionElement>> list;
  95. for_each_child_of_type<HTMLOptionElement>([&](HTMLOptionElement& option_element) {
  96. list.append(JS::make_handle(option_element));
  97. });
  98. for_each_child_of_type<HTMLOptGroupElement>([&](HTMLOptGroupElement const& optgroup_element) {
  99. optgroup_element.for_each_child_of_type<HTMLOptionElement>([&](HTMLOptionElement& option_element) {
  100. list.append(JS::make_handle(option_element));
  101. });
  102. });
  103. return list;
  104. }
  105. // https://html.spec.whatwg.org/multipage/form-elements.html#the-select-element:concept-form-reset-control
  106. void HTMLSelectElement::reset_algorithm()
  107. {
  108. // The reset algorithm for select elements is to go through all the option elements in the element's list of options,
  109. for (auto const& option_element : list_of_options()) {
  110. // set their selectedness to true if the option element has a selected attribute, and false otherwise,
  111. option_element->m_selected = option_element->has_attribute(AttributeNames::selected);
  112. // set their dirtiness to false,
  113. option_element->m_dirty = false;
  114. // and then have the option elements ask for a reset.
  115. option_element->ask_for_a_reset();
  116. }
  117. }
  118. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-selectedindex
  119. int HTMLSelectElement::selected_index() const
  120. {
  121. // The selectedIndex IDL attribute, on getting, must return the index of the first option element in the list of options
  122. // in tree order that has its selectedness set to true, if any. If there isn't one, then it must return −1.
  123. int index = 0;
  124. for (auto const& option_element : list_of_options()) {
  125. if (option_element->selected())
  126. return index;
  127. ++index;
  128. }
  129. return -1;
  130. }
  131. void HTMLSelectElement::set_selected_index(int index)
  132. {
  133. // On setting, the selectedIndex attribute must set the selectedness of all the option elements in the list of options to false,
  134. // and then the option element in the list of options whose index is the given new value,
  135. // if any, must have its selectedness set to true and its dirtiness set to true.
  136. auto options = list_of_options();
  137. for (auto& option : options)
  138. option->m_selected = false;
  139. if (index < 0 || index >= static_cast<int>(options.size()))
  140. return;
  141. auto& selected_option = options[index];
  142. selected_option->m_selected = true;
  143. selected_option->m_dirty = true;
  144. }
  145. // https://html.spec.whatwg.org/multipage/interaction.html#dom-tabindex
  146. i32 HTMLSelectElement::default_tab_index_value() const
  147. {
  148. // See the base function for the spec comments.
  149. return 0;
  150. }
  151. // https://html.spec.whatwg.org/multipage/form-elements.html#dom-select-type
  152. String const& HTMLSelectElement::type() const
  153. {
  154. // 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.
  155. static String const select_one = "select-one"_string;
  156. static String const select_multiple = "select-multiple"_string;
  157. if (!has_attribute(AttributeNames::multiple))
  158. return select_one;
  159. return select_multiple;
  160. }
  161. Optional<ARIA::Role> HTMLSelectElement::default_role() const
  162. {
  163. // https://www.w3.org/TR/html-aria/#el-select-multiple-or-size-greater-1
  164. if (has_attribute(AttributeNames::multiple))
  165. return ARIA::Role::listbox;
  166. if (has_attribute(AttributeNames::size)) {
  167. auto size_attribute = deprecated_attribute(AttributeNames::size).to_number<int>();
  168. if (size_attribute.has_value() && size_attribute.value() > 1)
  169. return ARIA::Role::listbox;
  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().browsing_context()->to_top_level_position(Web::CSSPixelPoint { rect->x(), rect->y() });
  260. document().browsing_context()->top_level_browsing_context()->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. update_inner_text_element();
  281. }
  282. }
  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. // Update inner text element to text content of selected option
  333. for (auto const& option_element : list_of_options()) {
  334. if (option_element->selected()) {
  335. m_inner_text_element->set_text_content(strip_newlines(option_element->text_content()));
  336. return;
  337. }
  338. }
  339. }
  340. }