Skip to main content

script/dom/html/form_controls/
htmlselectelement.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::default::Default;
6use std::iter;
7
8use dom_struct::dom_struct;
9use embedder_traits::{EmbedderControlRequest, MouseButton, SelectElementRequest};
10use embedder_traits::{SelectElementOption, SelectElementOptionOrOptgroup};
11use html5ever::{local_name, LocalName, Prefix};
12use js::context::{JSContext, NoGC};
13use js::rust::HandleObject;
14use script_bindings::cell::{DomRefCell, Ref};
15use script_bindings::dom::UnrootedDom;
16use style::attr::AttrValue;
17use stylo_dom::ElementState;
18
19use crate::dom::element::attributes::storage::AttrRef;
20use crate::dom::iterators::ShadowIncluding;
21use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods;
22use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
23use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
24use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
25use crate::dom::bindings::codegen::Bindings::HTMLOptionsCollectionBinding::HTMLOptionsCollectionMethods;
26use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
27use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
28use crate::dom::bindings::codegen::GenericBindings::CharacterDataBinding::CharacterData_Binding::CharacterDataMethods;
29use crate::dom::bindings::codegen::GenericBindings::HTMLOptGroupElementBinding::HTMLOptGroupElement_Binding::HTMLOptGroupElementMethods;
30use crate::dom::bindings::codegen::UnionTypes::{
31    HTMLElementOrLong, HTMLOptionElementOrHTMLOptGroupElement,
32};
33use crate::dom::bindings::error::ErrorResult;
34use crate::dom::bindings::inheritance::Castable;
35use crate::dom::bindings::refcounted::Trusted;
36use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
37use crate::dom::bindings::str::DOMString;
38use crate::dom::characterdata::CharacterData;
39use crate::dom::document::Document;
40use crate::dom::document_embedder_controls::ControlElement;
41use crate::dom::element::{AttributeMutation, Element};
42use crate::dom::event::Event;
43use crate::dom::event::{EventBubbles, EventCancelable, EventComposed};
44use crate::dom::eventtarget::EventTarget;
45use crate::dom::html::htmlcollection::{CollectionFilter, CollectionSource, HTMLCollection};
46use crate::dom::html::htmlelement::HTMLElement;
47use crate::dom::html::htmlformelement::{FormControl, FormDatum, FormDatumValue, HTMLFormElement};
48use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
49use crate::dom::html::htmloptionelement::HTMLOptionElement;
50use crate::dom::html::htmlhrelement::HTMLHRElement;
51use crate::dom::html::htmloptionscollection::HTMLOptionsCollection;
52use crate::dom::node::{ChildrenMutation, Node, NodeTraits,  UnbindContext};
53use crate::dom::nodelist::NodeList;
54use crate::dom::shadowroot::ShadowRoot;
55use crate::dom::shadowroot::ua_shadowroot::{CreateUAShadowRootForSelf, UAShadowRoot};
56use crate::dom::text::Text;
57use crate::dom::types::{FocusEvent, HTMLDataListElement, MouseEvent};
58use crate::dom::validation::{is_barred_by_datalist_ancestor, Validatable};
59use crate::dom::validitystate::{ValidationFlags, ValidityState};
60use crate::dom::node::virtualmethods::VirtualMethods;
61
62const DEFAULT_SELECT_SIZE: u32 = 0;
63
64const SELECT_BOX_STYLE: &str = "
65    display: flex;
66    align-items: center;
67    height: 100%;
68    gap: 4px;
69";
70
71const TEXT_CONTAINER_STYLE: &str = "flex: 1;";
72
73const CHEVRON_CONTAINER_STYLE: &str = "
74    background-image: url('data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"180\" height=\"180\" viewBox=\"0 0 180 180\"> <path d=\"M10 50h160L90 130z\" style=\"fill:currentcolor\"/> </svg>');
75    background-size: 100%;
76    background-repeat: no-repeat;
77    background-position: center;
78
79    vertical-align: middle;
80    line-height: 1;
81    display: inline-block;
82    width: 0.75em;
83    height: 0.75em;
84";
85
86#[derive(JSTraceable, MallocSizeOf)]
87struct OptionsFilter;
88impl CollectionFilter for OptionsFilter {
89    fn filter<'a>(&self, element: &'a Element, root: &'a Node) -> bool {
90        let Some(option) = element.downcast::<HTMLOptionElement>() else {
91            return false;
92        };
93        let Some(select) = option.cached_nearest_ancestor_select() else {
94            return false;
95        };
96        root == select.upcast()
97    }
98}
99
100/// Provides selected options directly via [`HTMLSelectElement::list_of_options`].
101#[derive(JSTraceable, MallocSizeOf)]
102struct SelectedOptionsSource;
103
104impl CollectionSource for SelectedOptionsSource {
105    fn iter<'b>(
106        &'b self,
107        no_gc: &'b NoGC,
108        root: &'b Node,
109    ) -> Box<dyn Iterator<Item = UnrootedDom<'b, Element>> + 'b> {
110        let select = root
111            .downcast::<HTMLSelectElement>()
112            .expect("SelectedOptionsSource must be rooted on an HTMLSelectElement");
113        Box::new(
114            select
115                .list_of_options(no_gc)
116                .filter(|option| option.Selected())
117                .map(UnrootedDom::upcast::<Element>),
118        )
119    }
120}
121
122#[dom_struct]
123pub(crate) struct HTMLSelectElement {
124    htmlelement: HTMLElement,
125    options: MutNullableDom<HTMLOptionsCollection>,
126    selected_options: MutNullableDom<HTMLCollection>,
127    form_owner: MutNullableDom<HTMLFormElement>,
128    labels_node_list: MutNullableDom<NodeList>,
129    validity_state: MutNullableDom<ValidityState>,
130    shadow_tree: DomRefCell<Option<ShadowTree>>,
131}
132
133/// Holds handles to all elements in the UA shadow tree
134#[derive(Clone, JSTraceable, MallocSizeOf)]
135#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
136struct ShadowTree {
137    selected_option: Dom<Text>,
138}
139
140impl UAShadowRoot<ShadowTree> for HTMLSelectElement {
141    fn store_for_shadow_tree(&self, cx: &mut JSContext, shadow_root: DomRoot<ShadowRoot>) {
142        let document = self.owner_document();
143
144        let select_box = self.create_element_in_ua_shadowroot(cx, local_name!("div"));
145        select_box.set_string_attribute(cx, &local_name!("style"), SELECT_BOX_STYLE.into());
146        shadow_root
147            .upcast::<Node>()
148            .AppendChild(cx, select_box.upcast::<Node>())
149            .unwrap();
150
151        let text_container = self.create_element_in_ua_shadowroot(cx, local_name!("div"));
152        text_container.set_string_attribute(cx, &local_name!("style"), TEXT_CONTAINER_STYLE.into());
153        select_box
154            .upcast::<Node>()
155            .AppendChild(cx, text_container.upcast::<Node>())
156            .unwrap();
157
158        let text = Text::new(cx, DOMString::new(), &document);
159        text_container
160            .upcast::<Node>()
161            .AppendChild(cx, text.upcast::<Node>())
162            .unwrap();
163
164        let chevron_container = self.create_element_in_ua_shadowroot(cx, local_name!("div"));
165        chevron_container.set_string_attribute(
166            cx,
167            &local_name!("style"),
168            CHEVRON_CONTAINER_STYLE.into(),
169        );
170        select_box
171            .upcast::<Node>()
172            .AppendChild(cx, chevron_container.upcast::<Node>())
173            .unwrap();
174
175        let _ = self
176            .shadow_tree
177            .safe_borrow_mut(cx.no_gc())
178            .insert(ShadowTree {
179                selected_option: text.as_traced(),
180            });
181    }
182
183    fn borrow_for_shadow_tree(&self) -> Ref<'_, Option<ShadowTree>> {
184        self.shadow_tree.borrow()
185    }
186}
187
188impl HTMLSelectElement {
189    fn new_inherited(
190        local_name: LocalName,
191        prefix: Option<Prefix>,
192        document: &Document,
193    ) -> HTMLSelectElement {
194        HTMLSelectElement {
195            htmlelement: HTMLElement::new_inherited_with_state(
196                ElementState::ENABLED | ElementState::VALID | ElementState::OPTIONAL_,
197                local_name,
198                prefix,
199                document,
200            ),
201            options: Default::default(),
202            selected_options: Default::default(),
203            form_owner: Default::default(),
204            labels_node_list: Default::default(),
205            validity_state: Default::default(),
206            shadow_tree: Default::default(),
207        }
208    }
209
210    pub(crate) fn new(
211        cx: &mut js::context::JSContext,
212        local_name: LocalName,
213        prefix: Option<Prefix>,
214        document: &Document,
215        proto: Option<HandleObject>,
216    ) -> DomRoot<HTMLSelectElement> {
217        let n = Node::reflect_node_with_proto(
218            cx,
219            Box::new(HTMLSelectElement::new_inherited(
220                local_name, prefix, document,
221            )),
222            document,
223            proto,
224        );
225
226        n.upcast::<Node>().set_weird_parser_insertion_mode();
227        n
228    }
229
230    /// <https://html.spec.whatwg.org/multipage/#concept-select-option-list>
231    pub(crate) fn list_of_options<'b>(
232        &self,
233        no_gc: &'b NoGC,
234    ) -> impl Iterator<Item = UnrootedDom<'b, HTMLOptionElement>> + use<'b> {
235        let self_node = self.upcast::<Node>();
236
237        // Step 1. Let options be « ».
238        let mut iterator = self_node.traverse_preorder_unrooted(no_gc, ShadowIncluding::No);
239
240        // Step 2. Let node be the first child of select in tree order.
241        iterator.next();
242
243        // Step 3. While node is not null:
244        iter::from_fn(move || {
245            loop {
246                let node = iterator.peek()?.clone();
247
248                // Step 3.2. If any of the following conditions are true:
249                //   - node is a select element;
250                //   - node is an hr element;
251                //   - node is an option element;
252                //   - node is a datalist element;
253                //   - node is an optgroup element and node has an ancestor optgroup in between itself
254                //     and select,
255                // then set node to the next descendant of select in tree order, excluding node's
256                // descendants, if any such node exists; otherwise null.
257                if skip_descendants_for_list_of_options(no_gc, &node) {
258                    iterator.next_skipping_children();
259                } else {
260                    // Step 3.3. Otherwise, set node to the next descendant of select in tree order, if any
261                    // such node exists; otherwise null.
262                    iterator.next();
263                }
264
265                // Step 3.1. If node is an option element, then append node to options.
266                if let Some(option) = UnrootedDom::downcast::<HTMLOptionElement>(node) {
267                    return Some(option);
268                }
269            }
270        })
271    }
272
273    /// <https://html.spec.whatwg.org/multipage/#placeholder-label-option>
274    /// > If a select element has a required attribute specified, and has a display size of 1; and
275    /// > if the value of the first option element in the select element's list of options (if any) is
276    /// > the empty string, and that option element does not have an ancestor optgroup in between
277    /// > itself and the select element, then that option is the select element's placeholder label
278    /// > option.
279    /// >
280    /// > If a select element has a required attribute specified, does not have a multiple attribute
281    /// > specified, and has a display size of 1, then the select element must have a placeholder label
282    /// > option.
283    fn get_placeholder_label_option(&self, no_gc: &NoGC) -> Option<DomRoot<HTMLOptionElement>> {
284        if self.Required() && !self.Multiple() && self.display_size() == 1 {
285            self.list_of_options(no_gc)
286                .next()
287                .filter(|node| {
288                    node.Value().is_empty() &&
289                        !has_ancestor_optgroup_between_self_and_select(no_gc, node.upcast())
290                })
291                .map(|node| node.as_rooted())
292        } else {
293            None
294        }
295    }
296
297    /// <https://html.spec.whatwg.org/multipage/#the-select-element:concept-form-reset-control>
298    pub(crate) fn reset(&self, no_gc: &NoGC) {
299        for opt in self.list_of_options(no_gc) {
300            opt.set_selectedness(no_gc, opt.DefaultSelected());
301            opt.set_dirtiness(false);
302        }
303        self.selectedness_setting_algorithm(no_gc);
304    }
305
306    /// <https://html.spec.whatwg.org/multipage/#selectedness-setting-algorithm>
307    pub(crate) fn selectedness_setting_algorithm(&self, no_gc: &NoGC) -> bool {
308        // Step 1. If select has the multiple attribute, then return false.
309        if self.Multiple() {
310            return false;
311        }
312
313        // Step 2. Let hasChanged be false.
314        let mut has_changed = false;
315        // Step 3. Let firstEnabledOption be null.
316        let mut first_enabled: Option<DomRoot<HTMLOptionElement>> = None;
317        // Step 4. Let lastSelectedOption be null.
318        let mut last_selected: Option<DomRoot<HTMLOptionElement>> = None;
319
320        // Step 5. For each option of select's list of options:
321        for option in self.list_of_options(no_gc) {
322            // Step 5.1. If option's selectedness is true:
323            if option.Selected() {
324                // Step 5.1.1. If lastSelectedOption is not null:
325                if let Some(last_selected) = &last_selected {
326                    // Step 5.1.1.1. Set lastSelectedOption's selectedness to false.
327                    last_selected.set_selectedness(no_gc, false);
328                    // Step 5.1.1.2. Set hasChanged to true.
329                    has_changed = true;
330                }
331                // Step 5.1.2. Set lastSelectedOption to option.
332                last_selected = Some(option.as_rooted());
333            }
334            // Step 5.2 If firstEnabledOption is null and option is not disabled, then set
335            // firstEnabledOption to option.
336            let element = option.upcast::<Element>();
337            if first_enabled.is_none() && !element.disabled_state() {
338                first_enabled = Some(option.as_rooted());
339            }
340        }
341
342        // Step 6. If lastSelectedOption is null, firstEnabledOption is not null, and select's
343        // display size is 1:
344        if last_selected.is_none() &&
345            let Some(first_enabled) = first_enabled &&
346            self.display_size() == 1
347        {
348            // Step 6.1. Set firstEnabledOption's selectedness to true.
349            first_enabled.set_selectedness(no_gc, true);
350            // Step 6.2 Set hasChanged to true.
351            has_changed = true;
352        }
353
354        // Step 7. Return hasChanged.
355        has_changed
356    }
357
358    pub(crate) fn push_form_data(&self, no_gc: &NoGC, data_set: &mut Vec<FormDatum>) {
359        if self.Name().is_empty() {
360            return;
361        }
362        for opt in self.list_of_options(no_gc) {
363            let element = opt.upcast::<Element>();
364            if opt.Selected() && element.enabled_state() {
365                data_set.push(FormDatum {
366                    ty: self.Type(),
367                    name: self.Name(),
368                    value: FormDatumValue::String(opt.Value()),
369                });
370            }
371        }
372    }
373
374    /// <https://html.spec.whatwg.org/multipage/#concept-select-pick>
375    pub(crate) fn pick_option(&self, no_gc: &NoGC, picked: &HTMLOptionElement) {
376        if !self.Multiple() {
377            let picked = picked.upcast();
378            for opt in self.list_of_options(no_gc) {
379                if opt.upcast::<HTMLElement>() != picked {
380                    opt.set_selectedness(no_gc, false);
381                }
382            }
383        }
384    }
385
386    /// <https://html.spec.whatwg.org/multipage/#concept-select-size>
387    fn display_size(&self) -> u32 {
388        if self.Size() == 0 {
389            if self.Multiple() { 4 } else { 1 }
390        } else {
391            self.Size()
392        }
393    }
394
395    pub(crate) fn update_shadow_tree(&self, cx: &mut JSContext) {
396        let shadow_tree = self.shadow_tree(cx);
397
398        let selected_options = self.selected_options(cx.no_gc());
399        let selected_options_count = selected_options.len();
400
401        let displayed_text = if selected_options_count == 1 {
402            let first_selected_option = self
403                .selected_option(cx.no_gc())
404                .or_else(|| self.list_of_options(cx.no_gc()).next());
405
406            let first_selected_option_text = first_selected_option
407                .map(|option| option.displayed_label())
408                .unwrap_or_default();
409
410            // Replace newlines with whitespace, then collapse and trim whitespace
411            itertools::join(first_selected_option_text.str().split_whitespace(), " ")
412        } else {
413            format!("{selected_options_count} selected")
414        };
415
416        shadow_tree
417            .selected_option
418            .upcast::<CharacterData>()
419            .SetData(cx, displayed_text.trim().into());
420    }
421
422    pub(crate) fn selected_option<'b>(
423        &self,
424        no_gc: &'b NoGC,
425    ) -> Option<UnrootedDom<'b, HTMLOptionElement>> {
426        self.list_of_options(no_gc)
427            .find(|opt_elem| opt_elem.Selected())
428            .or_else(|| self.list_of_options(no_gc).next())
429    }
430
431    pub(crate) fn selected_options<'b>(
432        &self,
433        no_gc: &'b NoGC,
434    ) -> Vec<UnrootedDom<'b, HTMLOptionElement>> {
435        self.list_of_options(no_gc)
436            .filter(|opt_elem| opt_elem.Selected())
437            .collect()
438    }
439
440    pub(crate) fn show_menu(&self, cx: &mut JSContext) {
441        // Collect list of optgroups and options
442        let mut index = 0;
443        let mut embedder_option_from_option = |option: &HTMLOptionElement| {
444            let embedder_option = SelectElementOption {
445                id: index,
446                label: option.displayed_label().into(),
447                is_disabled: option.Disabled(),
448            };
449            index += 1;
450            embedder_option
451        };
452        let options = self
453            .upcast::<Node>()
454            .children()
455            .flat_map(|child| {
456                if let Some(option) = child.downcast::<HTMLOptionElement>() {
457                    return Some(embedder_option_from_option(option).into());
458                }
459
460                if let Some(optgroup) = child.downcast::<HTMLOptGroupElement>() {
461                    let options = optgroup
462                        .upcast::<Node>()
463                        .children()
464                        .flat_map(DomRoot::downcast::<HTMLOptionElement>)
465                        .map(|option| embedder_option_from_option(&option))
466                        .collect();
467                    let label = optgroup.Label().into();
468
469                    return Some(SelectElementOptionOrOptgroup::Optgroup { label, options });
470                }
471
472                None
473            })
474            .collect();
475
476        let selected_options = self
477            .list_of_options(cx.no_gc())
478            .enumerate()
479            .filter(|(_, option)| option.Selected())
480            .map(|(index, _)| index)
481            .collect();
482
483        self.owner_document()
484            .embedder_controls()
485            .show_embedder_control(
486                cx,
487                ControlElement::Select(Dom::from_ref(self)),
488                EmbedderControlRequest::SelectElement(SelectElementRequest {
489                    options,
490                    selected_options,
491                    allow_select_multiple: self.Multiple(),
492                }),
493                None,
494            );
495        self.upcast::<Element>().set_open_state(cx.no_gc(), true);
496    }
497
498    pub(crate) fn handle_embedder_response(&self, cx: &mut JSContext, selected_values: Vec<usize>) {
499        self.upcast::<Element>().set_open_state(cx.no_gc(), false);
500
501        let selected_values = if self.Multiple() {
502            selected_values
503        } else {
504            selected_values.into_iter().take(1).collect()
505        };
506
507        let mut selection_did_change = false;
508        for (index, option) in self.list_of_options(cx.no_gc()).enumerate() {
509            let should_be_selected = selected_values.contains(&index);
510            let option_selected_did_change = option.Selected() != should_be_selected;
511
512            if option_selected_did_change {
513                selection_did_change = true;
514            }
515
516            option.set_selectedness(cx.no_gc(), should_be_selected);
517
518            if option_selected_did_change {
519                option.set_dirtiness(true);
520            }
521        }
522
523        if selection_did_change {
524            self.update_shadow_tree(cx);
525            self.send_update_notifications();
526        }
527    }
528
529    fn multiple_attribute_mutated(&self, cx: &mut JSContext, mutation: AttributeMutation) {
530        if mutation.is_removal() {
531            let mut first_enabled: Option<DomRoot<HTMLOptionElement>> = None;
532            let mut first_selected: Option<DomRoot<HTMLOptionElement>> = None;
533
534            for option in self.list_of_options(cx.no_gc()) {
535                if first_selected.is_none() && option.Selected() {
536                    first_selected = Some(DomRoot::from_ref(&option));
537                }
538                option.set_selectedness(cx.no_gc(), false);
539                let element = option.upcast::<Element>();
540                if first_enabled.is_none() && !element.disabled_state() {
541                    first_enabled = Some(DomRoot::from_ref(&option));
542                }
543            }
544
545            if let Some(first_selected) = first_selected {
546                first_selected.set_selectedness(cx.no_gc(), true);
547            } else if self.display_size() == 1 &&
548                let Some(first_enabled) = first_enabled
549            {
550                first_enabled.set_selectedness(cx.no_gc(), true);
551            }
552
553            self.update_shadow_tree(cx);
554        }
555    }
556
557    /// <https://html.spec.whatwg.org/multipage/#send-select-update-notifications>
558    fn send_update_notifications(&self) {
559        // > When the user agent is to send select update notifications, queue an element task on the
560        // > user interaction task source given the select element to run these steps:
561        let this = Trusted::new(self);
562        self.owner_global()
563            .task_manager()
564            .user_interaction_task_source()
565            .queue(task!(send_select_update_notification: move |cx| {
566                let this = this.root();
567
568                // TODO: Step 1. Set the select element's user validity to true.
569
570                // Step 2. Fire an event named input at the select element, with the bubbles and composed
571                // attributes initialized to true.
572                this.upcast::<EventTarget>()
573                    .fire_event_with_params(
574                        cx,
575                        atom!("input"),
576                        EventBubbles::Bubbles,
577                        EventCancelable::NotCancelable,
578                        EventComposed::Composed,
579                    );
580
581                // Step 3. Fire an event named change at the select element, with the bubbles attribute initialized
582                // to true.
583                this.upcast::<EventTarget>()
584                    .fire_bubbling_event(cx, atom!("change"));
585            }));
586    }
587
588    fn may_have_embedder_control(&self) -> bool {
589        let el = self.upcast::<Element>();
590        !el.disabled_state()
591    }
592
593    /// <https://html.spec.whatwg.org/multipage/#select-enabled-selectedcontent>
594    pub(crate) fn get_enabled_selectedcontent(&self) -> Option<DomRoot<Element>> {
595        // Step 1. If select has the multiple attribute, then return null.
596        if self.Multiple() {
597            return None;
598        }
599
600        // Step 2. Let selectedcontent be the first selectedcontent element descendant
601        // of select in tree order if any such element exists; otherwise return null.
602        // TODO: Step 3. If selectedcontent's disabled is true, then return null.
603        // NOTE: We don't actually implement selectedcontent yet
604        // Step 4. Return selectedcontent.
605        self.upcast::<Node>()
606            .traverse_preorder(ShadowIncluding::No)
607            .skip(1)
608            .filter_map(DomRoot::downcast::<Element>)
609            .find(|element| element.local_name() == &local_name!("selectedcontent"))
610    }
611
612    /// <https://html.spec.whatwg.org/multipage/#update-a-select's-descendant-selectedcontent-elements>
613    pub(crate) fn update_a_selects_descendant_selectedcontent_elements(&self, cx: &mut JSContext) {
614        // Step 1. If select has the multiple attribute, then return.
615        if self.Multiple() {
616            return;
617        }
618
619        // Step 2. Let descendantSelectedcontents be a list of select's descendants, in tree order,
620        // that are selectedcontent elements whose disabled is false.
621        let descendant_selected_contents = self.get_enabled_selectedcontent();
622
623        // Step 3. For each selectedcontent of descendantSelectedcontents: update a selectedcontent
624        // given select and selectedcontent.
625        //
626        // Note: This is a bit different than the specification, because we do not yet support
627        // `selectedcontent`.
628        if let Some(selected_content) = descendant_selected_contents {
629            self.update_a_selected_content(cx, &selected_content);
630        }
631    }
632
633    /// <https://html.spec.whatwg.org/multipage/#update-a-selectedcontent>
634    fn update_a_selected_content(&self, cx: &mut JSContext, selected_content: &Element) {
635        // Step 1. If selectedcontent's disabled is true, then return.
636        // TODO: We do not yet calculate the selectedcontent's disabledness and it is
637        // different than the form control disabled state.
638
639        // Step 2. Let option be the first option in select's list of options whose selectedness is
640        // true, if any such option exists; otherwise null.
641        let option = self
642            .list_of_options(cx.no_gc())
643            .find(|option| option.Selected())
644            .map(|option| option.as_rooted());
645
646        match option {
647            None => {
648                // Step 3. If option is null, then clear a selectedcontent given selectedcontent.
649                // This is <https://html.spec.whatwg.org/multipage/#clear-a-selectedcontent>
650                // Step 1. Replace all with null within selectedcontent.
651                Node::replace_all(cx, None, selected_content.upcast());
652            },
653            Some(option) => {
654                // Step 4. Otherwise, clone an option into a selectedcontent given option and
655                // selectedcontent.
656                option.clone_an_option_into_selectedcontent(cx, selected_content);
657            },
658        }
659    }
660}
661
662impl HTMLSelectElementMethods<crate::DomTypeHolder> for HTMLSelectElement {
663    /// <https://html.spec.whatwg.org/multipage/#dom-select-add>
664    fn Add(
665        &self,
666        cx: &mut JSContext,
667        element: HTMLOptionElementOrHTMLOptGroupElement,
668        before: Option<HTMLElementOrLong>,
669    ) -> ErrorResult {
670        self.Options(cx).Add(cx, element, before)
671    }
672
673    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
674    make_bool_getter!(Disabled, "disabled");
675
676    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
677    make_bool_setter!(SetDisabled, "disabled");
678
679    /// <https://html.spec.whatwg.org/multipage/#dom-fae-form>
680    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
681        self.form_owner()
682    }
683
684    // https://html.spec.whatwg.org/multipage/#dom-select-multiple
685    make_bool_getter!(Multiple, "multiple");
686
687    // https://html.spec.whatwg.org/multipage/#dom-select-multiple
688    make_bool_setter!(SetMultiple, "multiple");
689
690    // https://html.spec.whatwg.org/multipage/#dom-fe-name
691    make_getter!(Name, "name");
692
693    // https://html.spec.whatwg.org/multipage/#dom-fe-name
694    make_atomic_setter!(SetName, "name");
695
696    // https://html.spec.whatwg.org/multipage/#dom-select-required
697    make_bool_getter!(Required, "required");
698
699    // https://html.spec.whatwg.org/multipage/#dom-select-required
700    make_bool_setter!(SetRequired, "required");
701
702    // https://html.spec.whatwg.org/multipage/#dom-select-size
703    make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
704
705    // https://html.spec.whatwg.org/multipage/#dom-select-size
706    make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
707
708    /// <https://html.spec.whatwg.org/multipage/#dom-select-type>
709    fn Type(&self) -> DOMString {
710        DOMString::from(if self.Multiple() {
711            "select-multiple"
712        } else {
713            "select-one"
714        })
715    }
716
717    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
718    make_labels_getter!(Labels, labels_node_list);
719
720    /// <https://html.spec.whatwg.org/multipage/#dom-select-options>
721    fn Options(&self, cx: &mut JSContext) -> DomRoot<HTMLOptionsCollection> {
722        self.options.or_init(|| {
723            let window = self.owner_window();
724            HTMLOptionsCollection::new(cx, &window, self, Box::new(OptionsFilter))
725        })
726    }
727
728    /// <https://html.spec.whatwg.org/multipage/#dom-select-selectedoptions>
729    fn SelectedOptions(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
730        self.selected_options.or_init(|| {
731            let window = self.owner_window();
732            HTMLCollection::new_with_source(
733                cx,
734                &window,
735                self.upcast(),
736                Box::new(SelectedOptionsSource),
737            )
738        })
739    }
740
741    /// <https://html.spec.whatwg.org/multipage/#dom-select-length>
742    fn Length(&self, cx: &mut JSContext) -> u32 {
743        self.Options(cx).Length(cx)
744    }
745
746    /// <https://html.spec.whatwg.org/multipage/#dom-select-length>
747    fn SetLength(&self, cx: &mut JSContext, length: u32) {
748        self.Options(cx).SetLength(cx, length)
749    }
750
751    /// <https://html.spec.whatwg.org/multipage/#dom-select-item>
752    fn Item(&self, cx: &mut JSContext, index: u32) -> Option<DomRoot<Element>> {
753        self.Options(cx).upcast().Item(cx, index)
754    }
755
756    /// <https://html.spec.whatwg.org/multipage/#dom-select-item>
757    fn IndexedGetter(&self, cx: &mut JSContext, index: u32) -> Option<DomRoot<Element>> {
758        self.Options(cx).IndexedGetter(cx, index)
759    }
760
761    /// <https://html.spec.whatwg.org/multipage/#dom-select-setter>
762    fn IndexedSetter(
763        &self,
764        cx: &mut JSContext,
765        index: u32,
766        value: Option<&HTMLOptionElement>,
767    ) -> ErrorResult {
768        self.Options(cx).IndexedSetter(cx, index, value)
769    }
770
771    /// <https://html.spec.whatwg.org/multipage/#dom-select-nameditem>
772    fn NamedItem(&self, cx: &mut JSContext, name: DOMString) -> Option<DomRoot<HTMLOptionElement>> {
773        self.Options(cx)
774            .NamedGetter(cx, name)
775            .and_then(DomRoot::downcast::<HTMLOptionElement>)
776    }
777
778    /// <https://html.spec.whatwg.org/multipage/#dom-select-remove>
779    fn Remove_(&self, cx: &mut JSContext, index: i32) {
780        self.Options(cx).Remove(cx, index)
781    }
782
783    /// <https://html.spec.whatwg.org/multipage/#dom-select-remove>
784    fn Remove(&self, cx: &mut JSContext) {
785        self.upcast::<Element>().Remove(cx)
786    }
787
788    /// <https://html.spec.whatwg.org/multipage/#dom-select-value>
789    fn Value(&self, cx: &JSContext) -> DOMString {
790        self.list_of_options(cx.no_gc())
791            .find(|opt_elem| opt_elem.Selected())
792            .map(|opt_elem| opt_elem.Value())
793            .unwrap_or_default()
794    }
795
796    /// <https://html.spec.whatwg.org/multipage/#dom-select-value>
797    fn SetValue(&self, cx: &mut JSContext, value: DOMString) {
798        let mut opt_iter = self.list_of_options(cx.no_gc());
799        // Reset until we find an <option> with a matching value
800        for opt in opt_iter.by_ref() {
801            if opt.Value() == value {
802                opt.set_selectedness(cx.no_gc(), true);
803                opt.set_dirtiness(true);
804                break;
805            }
806            opt.set_selectedness(cx.no_gc(), false);
807        }
808        // Reset remaining <option> elements
809        for opt in opt_iter {
810            opt.set_selectedness(cx.no_gc(), false);
811        }
812
813        self.validity_state(cx)
814            .perform_validation_and_update(cx, ValidationFlags::VALUE_MISSING);
815
816        self.update_shadow_tree(cx);
817    }
818
819    /// <https://html.spec.whatwg.org/multipage/#dom-select-selectedindex>
820    fn SelectedIndex(&self, cx: &JSContext) -> i32 {
821        self.list_of_options(cx.no_gc())
822            .enumerate()
823            .filter(|(_, opt_elem)| opt_elem.Selected())
824            .map(|(i, _)| i as i32)
825            .next()
826            .unwrap_or(-1)
827    }
828
829    /// <https://html.spec.whatwg.org/multipage/#dom-select-selectedindex>
830    fn SetSelectedIndex(&self, cx: &mut JSContext, index: i32) {
831        let mut selection_did_change = false;
832
833        {
834            let mut opt_iter = self.list_of_options(cx.no_gc());
835            for opt in opt_iter.by_ref().take(index as usize) {
836                selection_did_change |= opt.Selected();
837                opt.set_selectedness(cx.no_gc(), false);
838            }
839            if let Some(selected_option) = opt_iter.next() {
840                selection_did_change |= !selected_option.Selected();
841                selected_option.set_selectedness(cx.no_gc(), true);
842                selected_option.set_dirtiness(true);
843
844                // Reset remaining <option> elements
845                for opt in opt_iter {
846                    selection_did_change |= opt.Selected();
847                    opt.set_selectedness(cx.no_gc(), false);
848                }
849            }
850        }
851
852        if selection_did_change {
853            self.update_shadow_tree(cx);
854        }
855    }
856
857    /// <https://html.spec.whatwg.org/multipage/#dom-cva-willvalidate>
858    fn WillValidate(&self, no_gc: &NoGC) -> bool {
859        self.is_instance_validatable(no_gc)
860    }
861
862    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
863    fn Validity(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
864        self.validity_state(cx)
865    }
866
867    /// <https://html.spec.whatwg.org/multipage/#dom-cva-checkvalidity>
868    fn CheckValidity(&self, cx: &mut JSContext) -> bool {
869        self.check_validity(cx)
870    }
871
872    /// <https://html.spec.whatwg.org/multipage/#dom-cva-reportvalidity>
873    fn ReportValidity(&self, cx: &mut JSContext) -> bool {
874        self.report_validity(cx)
875    }
876
877    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
878    fn ValidationMessage(&self, cx: &mut JSContext) -> DOMString {
879        self.validation_message(cx)
880    }
881
882    /// <https://html.spec.whatwg.org/multipage/#dom-cva-setcustomvalidity>
883    fn SetCustomValidity(&self, cx: &mut JSContext, error: DOMString) {
884        self.validity_state(cx).set_custom_error_message(cx, error);
885    }
886}
887
888impl VirtualMethods for HTMLSelectElement {
889    fn super_type(&self) -> Option<&dyn VirtualMethods> {
890        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
891    }
892
893    fn attribute_mutated(
894        &self,
895        cx: &mut js::context::JSContext,
896        attr: AttrRef<'_>,
897        mutation: AttributeMutation,
898    ) {
899        let could_have_had_embedder_control = self.may_have_embedder_control();
900        self.super_type()
901            .unwrap()
902            .attribute_mutated(cx, attr, mutation);
903        match *attr.local_name() {
904            local_name!("multiple") => {
905                self.multiple_attribute_mutated(cx, mutation);
906            },
907            local_name!("required") => {
908                self.validity_state(cx)
909                    .perform_validation_and_update(cx, ValidationFlags::VALUE_MISSING);
910
911                // https://html.spec.whatwg.org/multipage/#selector-required
912                // > The :required pseudo-class must match any element falling into one of the following categories:
913                // > - select elements that have a required attribute
914                let element = self.upcast::<Element>();
915                let required = matches!(mutation, AttributeMutation::Set(_));
916                element.set_state(cx.no_gc(), ElementState::REQUIRED, required);
917
918                // https://html.spec.whatwg.org/multipage/#selector-optional
919                // > The :optional pseudo-class must match any element falling into one of the following categories:
920                // > - select elements that do not have a required attribute
921                element.set_state(cx.no_gc(), ElementState::OPTIONAL_, !required);
922            },
923            local_name!("disabled") => {
924                self.validity_state(cx)
925                    .perform_validation_and_update(cx, ValidationFlags::VALUE_MISSING);
926            },
927            local_name!("form") => {
928                self.form_attribute_mutated(cx, mutation);
929            },
930            _ => {},
931        }
932        if could_have_had_embedder_control && !self.may_have_embedder_control() {
933            self.owner_document()
934                .embedder_controls()
935                .hide_embedder_control(self.upcast());
936        }
937    }
938
939    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
940        self.super_type().unwrap().unbind_from_tree(cx, context);
941        self.owner_document_unrooted(cx.no_gc())
942            .embedder_controls()
943            .hide_embedder_control(self.upcast());
944    }
945
946    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
947        if let Some(s) = self.super_type() {
948            s.children_changed(cx, mutation);
949        }
950
951        self.update_shadow_tree(cx);
952    }
953
954    fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
955        match *local_name {
956            local_name!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
957            _ => self
958                .super_type()
959                .unwrap()
960                .parse_plain_attribute(local_name, value),
961        }
962    }
963
964    fn handle_event(&self, cx: &mut js::context::JSContext, event: &Event) {
965        self.super_type().unwrap().handle_event(cx, event);
966        if let Some(event) = event.downcast::<FocusEvent>() &&
967            *event.upcast::<Event>().type_() != *"blur"
968        {
969            self.owner_document()
970                .embedder_controls()
971                .hide_embedder_control(self.upcast());
972        }
973
974        // https://html.spec.whatwg.org/multipage/#select-open-picker
975        if event.IsTrusted() &&
976            !self.upcast::<Element>().disabled_state() &&
977            let Some(mouse_event) = event.downcast::<MouseEvent>() &&
978            mouse_event.button() == MouseButton::Primary &&
979            *event.type_() == *"mousedown"
980        {
981            self.show_menu(cx);
982        }
983    }
984}
985
986impl FormControl for HTMLSelectElement {
987    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
988        self.form_owner.get()
989    }
990
991    fn set_form_owner(&self, _cx: &mut JSContext, form: Option<&HTMLFormElement>) {
992        self.form_owner.set(form);
993    }
994
995    fn to_html_element(&self) -> &HTMLElement {
996        self.upcast::<HTMLElement>()
997    }
998}
999
1000impl Validatable for HTMLSelectElement {
1001    fn as_element(&self) -> &Element {
1002        self.upcast()
1003    }
1004
1005    fn validity_state(&self, cx: &mut JSContext) -> DomRoot<ValidityState> {
1006        self.validity_state
1007            .or_init(|| ValidityState::new(cx, &self.owner_window(), self.upcast()))
1008    }
1009
1010    fn satisfies_constraints(&self) -> bool {
1011        let Some(validity_state) = self.validity_state.get() else {
1012            return true;
1013        };
1014        validity_state.invalid_flags().is_empty()
1015    }
1016
1017    fn is_instance_validatable(&self, no_gc: &NoGC) -> bool {
1018        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls%3A-the-disabled-attribute%3Abarred-from-constraint-validation
1019        // https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation
1020        !self.upcast::<Element>().disabled_state() &&
1021            !is_barred_by_datalist_ancestor(no_gc, self.upcast())
1022    }
1023
1024    fn perform_validation(
1025        &self,
1026        cx: &mut JSContext,
1027        validate_flags: ValidationFlags,
1028    ) -> ValidationFlags {
1029        let mut failed_flags = ValidationFlags::empty();
1030
1031        // https://html.spec.whatwg.org/multipage/#suffering-from-being-missing
1032        // https://html.spec.whatwg.org/multipage/#the-select-element%3Asuffering-from-being-missing
1033        if validate_flags.contains(ValidationFlags::VALUE_MISSING) && self.Required() {
1034            let placeholder = self.get_placeholder_label_option(cx.no_gc());
1035            let is_value_missing = !self.list_of_options(cx.no_gc()).any(|e| {
1036                e.Selected() &&
1037                    placeholder
1038                        .as_ref()
1039                        .map(|placeholder| **placeholder != **e)
1040                        .unwrap_or(true)
1041            });
1042            failed_flags.set(ValidationFlags::VALUE_MISSING, is_value_missing);
1043        }
1044
1045        failed_flags
1046    }
1047}
1048
1049/// Implements Step 3.2 of <https://html.spec.whatwg.org/multipage/#concept-select-option-list>.
1050fn skip_descendants_for_list_of_options(no_gc: &NoGC, node: &Node) -> bool {
1051    // Step 3.2. If any of the following conditions are true:
1052    //   - node is a select element;
1053    //   - node is an hr element;
1054    //   - node is an option element;
1055    //   - node is a datalist element;
1056    if node.is::<HTMLSelectElement>() ||
1057        node.is::<HTMLHRElement>() ||
1058        node.is::<HTMLOptionElement>() ||
1059        node.is::<HTMLDataListElement>()
1060    {
1061        return true;
1062    }
1063
1064    //   - node is an optgroup element and node has an ancestor optgroup in between itself
1065    //     and select,
1066    //
1067    // We shouldn't recurse into them because of the check above and `select` here is the
1068    // originating select element of this call.
1069    if node.is::<HTMLOptGroupElement>() &&
1070        has_ancestor_optgroup_between_self_and_select(no_gc, node)
1071    {
1072        return true;
1073    }
1074
1075    false
1076}
1077
1078fn has_ancestor_optgroup_between_self_and_select(no_gc: &NoGC, node: &Node) -> bool {
1079    for ancestor in node.ancestors_unrooted(no_gc) {
1080        if ancestor.is::<HTMLSelectElement>() {
1081            return false;
1082        }
1083        if ancestor.is::<HTMLOptGroupElement>() {
1084            return true;
1085        }
1086    }
1087    false
1088}