script/dom/html/
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::{FormControlRequest as EmbedderFormControl};
10use embedder_traits::{SelectElementOption, SelectElementOptionOrOptgroup};
11use euclid::{Point2D, Rect, Size2D};
12use html5ever::{LocalName, Prefix, QualName, local_name, ns};
13use js::rust::HandleObject;
14use style::attr::AttrValue;
15use stylo_dom::ElementState;
16use webrender_api::units::DeviceIntRect;
17use crate::dom::bindings::refcounted::Trusted;
18use crate::dom::document_embedder_controls::ControlElement;
19use crate::dom::event::{EventBubbles, EventCancelable, EventComposed};
20use crate::dom::bindings::codegen::GenericBindings::HTMLOptGroupElementBinding::HTMLOptGroupElement_Binding::HTMLOptGroupElementMethods;
21use crate::dom::activation::Activatable;
22use crate::dom::attr::Attr;
23use crate::dom::bindings::cell::{DomRefCell, Ref};
24use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods;
25use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
26use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
27use crate::dom::bindings::codegen::Bindings::HTMLOptionsCollectionBinding::HTMLOptionsCollectionMethods;
28use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
29use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
30use crate::dom::bindings::codegen::GenericBindings::CharacterDataBinding::CharacterData_Binding::CharacterDataMethods;
31use crate::dom::bindings::codegen::UnionTypes::{
32    HTMLElementOrLong, HTMLOptionElementOrHTMLOptGroupElement,
33};
34use crate::dom::bindings::error::ErrorResult;
35use crate::dom::bindings::inheritance::Castable;
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::element::{AttributeMutation, CustomElementCreationMode, Element, ElementCreator};
41use crate::dom::event::Event;
42use crate::dom::eventtarget::EventTarget;
43use crate::dom::html::htmlcollection::CollectionFilter;
44use crate::dom::html::htmlelement::HTMLElement;
45use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
46use crate::dom::html::htmlformelement::{FormControl, FormDatum, FormDatumValue, HTMLFormElement};
47use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
48use crate::dom::html::htmloptionelement::HTMLOptionElement;
49use crate::dom::html::htmloptionscollection::HTMLOptionsCollection;
50use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
51use crate::dom::nodelist::NodeList;
52use crate::dom::text::Text;
53use crate::dom::validation::{Validatable, is_barred_by_datalist_ancestor};
54use crate::dom::validitystate::{ValidationFlags, ValidityState};
55use crate::dom::virtualmethods::VirtualMethods;
56use crate::script_runtime::CanGc;
57
58const DEFAULT_SELECT_SIZE: u32 = 0;
59
60const SELECT_BOX_STYLE: &str = "
61    display: flex;
62    align-items: center;
63    height: 100%;
64";
65
66const TEXT_CONTAINER_STYLE: &str = "flex: 1;";
67
68const CHEVRON_CONTAINER_STYLE: &str = "
69    font-size: 16px;
70    margin: 4px;
71";
72
73#[derive(JSTraceable, MallocSizeOf)]
74struct OptionsFilter;
75impl CollectionFilter for OptionsFilter {
76    fn filter<'a>(&self, elem: &'a Element, root: &'a Node) -> bool {
77        if !elem.is::<HTMLOptionElement>() {
78            return false;
79        }
80
81        let node = elem.upcast::<Node>();
82        if root.is_parent_of(node) {
83            return true;
84        }
85
86        match node.GetParentNode() {
87            Some(optgroup) => optgroup.is::<HTMLOptGroupElement>() && root.is_parent_of(&optgroup),
88            None => false,
89        }
90    }
91}
92
93#[dom_struct]
94pub(crate) struct HTMLSelectElement {
95    htmlelement: HTMLElement,
96    options: MutNullableDom<HTMLOptionsCollection>,
97    form_owner: MutNullableDom<HTMLFormElement>,
98    labels_node_list: MutNullableDom<NodeList>,
99    validity_state: MutNullableDom<ValidityState>,
100    shadow_tree: DomRefCell<Option<ShadowTree>>,
101}
102
103/// Holds handles to all elements in the UA shadow tree
104#[derive(Clone, JSTraceable, MallocSizeOf)]
105#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
106struct ShadowTree {
107    selected_option: Dom<Text>,
108}
109
110impl HTMLSelectElement {
111    fn new_inherited(
112        local_name: LocalName,
113        prefix: Option<Prefix>,
114        document: &Document,
115    ) -> HTMLSelectElement {
116        HTMLSelectElement {
117            htmlelement: HTMLElement::new_inherited_with_state(
118                ElementState::ENABLED | ElementState::VALID,
119                local_name,
120                prefix,
121                document,
122            ),
123            options: Default::default(),
124            form_owner: Default::default(),
125            labels_node_list: Default::default(),
126            validity_state: Default::default(),
127            shadow_tree: Default::default(),
128        }
129    }
130
131    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
132    pub(crate) fn new(
133        local_name: LocalName,
134        prefix: Option<Prefix>,
135        document: &Document,
136        proto: Option<HandleObject>,
137        can_gc: CanGc,
138    ) -> DomRoot<HTMLSelectElement> {
139        let n = Node::reflect_node_with_proto(
140            Box::new(HTMLSelectElement::new_inherited(
141                local_name, prefix, document,
142            )),
143            document,
144            proto,
145            can_gc,
146        );
147
148        n.upcast::<Node>().set_weird_parser_insertion_mode();
149        n
150    }
151
152    /// <https://html.spec.whatwg.org/multipage/#concept-select-option-list>
153    pub(crate) fn list_of_options(
154        &self,
155    ) -> impl Iterator<Item = DomRoot<HTMLOptionElement>> + use<'_> {
156        self.upcast::<Node>().children().flat_map(|node| {
157            if node.is::<HTMLOptionElement>() {
158                let node = DomRoot::downcast::<HTMLOptionElement>(node).unwrap();
159                Choice3::First(iter::once(node))
160            } else if node.is::<HTMLOptGroupElement>() {
161                Choice3::Second(node.children().filter_map(DomRoot::downcast))
162            } else {
163                Choice3::Third(iter::empty())
164            }
165        })
166    }
167
168    // https://html.spec.whatwg.org/multipage/#placeholder-label-option
169    fn get_placeholder_label_option(&self) -> Option<DomRoot<HTMLOptionElement>> {
170        if self.Required() && !self.Multiple() && self.display_size() == 1 {
171            self.list_of_options().next().filter(|node| {
172                let parent = node.upcast::<Node>().GetParentNode();
173                node.Value().is_empty() && parent.as_deref() == Some(self.upcast())
174            })
175        } else {
176            None
177        }
178    }
179
180    // https://html.spec.whatwg.org/multipage/#the-select-element:concept-form-reset-control
181    pub(crate) fn reset(&self) {
182        for opt in self.list_of_options() {
183            opt.set_selectedness(opt.DefaultSelected());
184            opt.set_dirtiness(false);
185        }
186        self.ask_for_reset();
187    }
188
189    // https://html.spec.whatwg.org/multipage/#ask-for-a-reset
190    pub(crate) fn ask_for_reset(&self) {
191        if self.Multiple() {
192            return;
193        }
194
195        let mut first_enabled: Option<DomRoot<HTMLOptionElement>> = None;
196        let mut last_selected: Option<DomRoot<HTMLOptionElement>> = None;
197
198        for opt in self.list_of_options() {
199            if opt.Selected() {
200                opt.set_selectedness(false);
201                last_selected = Some(DomRoot::from_ref(&opt));
202            }
203            let element = opt.upcast::<Element>();
204            if first_enabled.is_none() && !element.disabled_state() {
205                first_enabled = Some(DomRoot::from_ref(&opt));
206            }
207        }
208
209        if let Some(last_selected) = last_selected {
210            last_selected.set_selectedness(true);
211        } else if self.display_size() == 1 {
212            if let Some(first_enabled) = first_enabled {
213                first_enabled.set_selectedness(true);
214            }
215        }
216    }
217
218    pub(crate) fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
219        if self.Name().is_empty() {
220            return;
221        }
222        for opt in self.list_of_options() {
223            let element = opt.upcast::<Element>();
224            if opt.Selected() && element.enabled_state() {
225                data_set.push(FormDatum {
226                    ty: self.Type(),
227                    name: self.Name(),
228                    value: FormDatumValue::String(opt.Value()),
229                });
230            }
231        }
232    }
233
234    // https://html.spec.whatwg.org/multipage/#concept-select-pick
235    pub(crate) fn pick_option(&self, picked: &HTMLOptionElement) {
236        if !self.Multiple() {
237            let picked = picked.upcast();
238            for opt in self.list_of_options() {
239                if opt.upcast::<HTMLElement>() != picked {
240                    opt.set_selectedness(false);
241                }
242            }
243        }
244    }
245
246    // https://html.spec.whatwg.org/multipage/#concept-select-size
247    fn display_size(&self) -> u32 {
248        if self.Size() == 0 {
249            if self.Multiple() { 4 } else { 1 }
250        } else {
251            self.Size()
252        }
253    }
254
255    fn create_shadow_tree(&self, can_gc: CanGc) {
256        let document = self.owner_document();
257        let root = self.upcast::<Element>().attach_ua_shadow_root(true, can_gc);
258
259        let select_box = Element::create(
260            QualName::new(None, ns!(html), local_name!("div")),
261            None,
262            &document,
263            ElementCreator::ScriptCreated,
264            CustomElementCreationMode::Asynchronous,
265            None,
266            can_gc,
267        );
268        select_box.set_string_attribute(&local_name!("style"), SELECT_BOX_STYLE.into(), can_gc);
269
270        let text_container = Element::create(
271            QualName::new(None, ns!(html), local_name!("div")),
272            None,
273            &document,
274            ElementCreator::ScriptCreated,
275            CustomElementCreationMode::Asynchronous,
276            None,
277            can_gc,
278        );
279        text_container.set_string_attribute(
280            &local_name!("style"),
281            TEXT_CONTAINER_STYLE.into(),
282            can_gc,
283        );
284        select_box
285            .upcast::<Node>()
286            .AppendChild(text_container.upcast::<Node>(), can_gc)
287            .unwrap();
288
289        let text = Text::new(DOMString::new(), &document, can_gc);
290        let _ = self.shadow_tree.borrow_mut().insert(ShadowTree {
291            selected_option: text.as_traced(),
292        });
293        text_container
294            .upcast::<Node>()
295            .AppendChild(text.upcast::<Node>(), can_gc)
296            .unwrap();
297
298        let chevron_container = Element::create(
299            QualName::new(None, ns!(html), local_name!("div")),
300            None,
301            &document,
302            ElementCreator::ScriptCreated,
303            CustomElementCreationMode::Asynchronous,
304            None,
305            can_gc,
306        );
307        chevron_container.set_string_attribute(
308            &local_name!("style"),
309            CHEVRON_CONTAINER_STYLE.into(),
310            can_gc,
311        );
312        chevron_container
313            .upcast::<Node>()
314            .set_text_content_for_element(Some("▾".into()), can_gc);
315        select_box
316            .upcast::<Node>()
317            .AppendChild(chevron_container.upcast::<Node>(), can_gc)
318            .unwrap();
319
320        root.upcast::<Node>()
321            .AppendChild(select_box.upcast::<Node>(), can_gc)
322            .unwrap();
323    }
324
325    fn shadow_tree(&self, can_gc: CanGc) -> Ref<'_, ShadowTree> {
326        if !self.upcast::<Element>().is_shadow_host() {
327            self.create_shadow_tree(can_gc);
328        }
329
330        Ref::filter_map(self.shadow_tree.borrow(), Option::as_ref)
331            .ok()
332            .expect("UA shadow tree was not created")
333    }
334
335    pub(crate) fn update_shadow_tree(&self, can_gc: CanGc) {
336        let shadow_tree = self.shadow_tree(can_gc);
337
338        let selected_option_text = self
339            .selected_option()
340            .or_else(|| self.list_of_options().next())
341            .map(|option| option.displayed_label())
342            .unwrap_or_default();
343
344        // Replace newlines with whitespace, then collapse and trim whitespace
345        let displayed_text = itertools::join(selected_option_text.str().split_whitespace(), " ");
346
347        shadow_tree
348            .selected_option
349            .upcast::<CharacterData>()
350            .SetData(displayed_text.trim().into());
351    }
352
353    pub(crate) fn selected_option(&self) -> Option<DomRoot<HTMLOptionElement>> {
354        self.list_of_options()
355            .find(|opt_elem| opt_elem.Selected())
356            .or_else(|| self.list_of_options().next())
357    }
358
359    pub(crate) fn show_menu(&self) {
360        // Collect list of optgroups and options
361        let mut index = 0;
362        let mut embedder_option_from_option = |option: &HTMLOptionElement| {
363            let embedder_option = SelectElementOption {
364                id: index,
365                label: option.displayed_label().into(),
366                is_disabled: option.Disabled(),
367            };
368            index += 1;
369            embedder_option
370        };
371        let options = self
372            .upcast::<Node>()
373            .children()
374            .flat_map(|child| {
375                if let Some(option) = child.downcast::<HTMLOptionElement>() {
376                    return Some(embedder_option_from_option(option).into());
377                }
378
379                if let Some(optgroup) = child.downcast::<HTMLOptGroupElement>() {
380                    let options = optgroup
381                        .upcast::<Node>()
382                        .children()
383                        .flat_map(DomRoot::downcast::<HTMLOptionElement>)
384                        .map(|option| embedder_option_from_option(&option))
385                        .collect();
386                    let label = optgroup.Label().into();
387
388                    return Some(SelectElementOptionOrOptgroup::Optgroup { label, options });
389                }
390
391                None
392            })
393            .collect();
394
395        let rect = self.upcast::<Node>().border_box().unwrap_or_default();
396        let rect = Rect::new(
397            Point2D::new(rect.origin.x.to_px(), rect.origin.y.to_px()),
398            Size2D::new(rect.size.width.to_px(), rect.size.height.to_px()),
399        );
400
401        let selected_index = self.list_of_options().position(|option| option.Selected());
402
403        self.owner_document().embedder_controls().show_form_control(
404            ControlElement::Select(DomRoot::from_ref(self)),
405            DeviceIntRect::from_untyped(&rect.to_box2d()),
406            EmbedderFormControl::SelectElement(options, selected_index),
407        );
408    }
409
410    pub(crate) fn handle_menu_response(&self, response: Option<usize>, can_gc: CanGc) {
411        let Some(selected_value) = response else {
412            return;
413        };
414
415        self.SetSelectedIndex(selected_value as i32, can_gc);
416        self.send_update_notifications();
417    }
418
419    /// <https://html.spec.whatwg.org/multipage/#send-select-update-notifications>
420    fn send_update_notifications(&self) {
421        // > When the user agent is to send select update notifications, queue an element task on the
422        // > user interaction task source given the select element to run these steps:
423        let this = Trusted::new(self);
424        self.owner_global()
425            .task_manager()
426            .user_interaction_task_source()
427            .queue(task!(send_select_update_notification: move || {
428                let this = this.root();
429
430                // TODO: Step 1. Set the select element's user validity to true.
431
432                // Step 2. Fire an event named input at the select element, with the bubbles and composed
433                // attributes initialized to true.
434                this.upcast::<EventTarget>()
435                    .fire_event_with_params(
436                        atom!("input"),
437                        EventBubbles::Bubbles,
438                        EventCancelable::NotCancelable,
439                        EventComposed::Composed,
440                        CanGc::note(),
441                    );
442
443                // Step 3. Fire an event named change at the select element, with the bubbles attribute initialized
444                // to true.
445                this.upcast::<EventTarget>()
446                    .fire_bubbling_event(atom!("change"), CanGc::note());
447            }));
448    }
449}
450
451impl HTMLSelectElementMethods<crate::DomTypeHolder> for HTMLSelectElement {
452    /// <https://html.spec.whatwg.org/multipage/#dom-select-add>
453    fn Add(
454        &self,
455        element: HTMLOptionElementOrHTMLOptGroupElement,
456        before: Option<HTMLElementOrLong>,
457    ) -> ErrorResult {
458        self.Options().Add(element, before)
459    }
460
461    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
462    make_bool_getter!(Disabled, "disabled");
463
464    // https://html.spec.whatwg.org/multipage/#dom-fe-disabled
465    make_bool_setter!(SetDisabled, "disabled");
466
467    /// <https://html.spec.whatwg.org/multipage/#dom-fae-form>
468    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
469        self.form_owner()
470    }
471
472    // https://html.spec.whatwg.org/multipage/#dom-select-multiple
473    make_bool_getter!(Multiple, "multiple");
474
475    // https://html.spec.whatwg.org/multipage/#dom-select-multiple
476    make_bool_setter!(SetMultiple, "multiple");
477
478    // https://html.spec.whatwg.org/multipage/#dom-fe-name
479    make_getter!(Name, "name");
480
481    // https://html.spec.whatwg.org/multipage/#dom-fe-name
482    make_atomic_setter!(SetName, "name");
483
484    // https://html.spec.whatwg.org/multipage/#dom-select-required
485    make_bool_getter!(Required, "required");
486
487    // https://html.spec.whatwg.org/multipage/#dom-select-required
488    make_bool_setter!(SetRequired, "required");
489
490    // https://html.spec.whatwg.org/multipage/#dom-select-size
491    make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
492
493    // https://html.spec.whatwg.org/multipage/#dom-select-size
494    make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
495
496    /// <https://html.spec.whatwg.org/multipage/#dom-select-type>
497    fn Type(&self) -> DOMString {
498        DOMString::from(if self.Multiple() {
499            "select-multiple"
500        } else {
501            "select-one"
502        })
503    }
504
505    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
506    make_labels_getter!(Labels, labels_node_list);
507
508    /// <https://html.spec.whatwg.org/multipage/#dom-select-options>
509    fn Options(&self) -> DomRoot<HTMLOptionsCollection> {
510        self.options.or_init(|| {
511            let window = self.owner_window();
512            HTMLOptionsCollection::new(&window, self, Box::new(OptionsFilter), CanGc::note())
513        })
514    }
515
516    /// <https://html.spec.whatwg.org/multipage/#dom-select-length>
517    fn Length(&self) -> u32 {
518        self.Options().Length()
519    }
520
521    /// <https://html.spec.whatwg.org/multipage/#dom-select-length>
522    fn SetLength(&self, length: u32, can_gc: CanGc) {
523        self.Options().SetLength(length, can_gc)
524    }
525
526    /// <https://html.spec.whatwg.org/multipage/#dom-select-item>
527    fn Item(&self, index: u32) -> Option<DomRoot<Element>> {
528        self.Options().upcast().Item(index)
529    }
530
531    /// <https://html.spec.whatwg.org/multipage/#dom-select-item>
532    fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Element>> {
533        self.Options().IndexedGetter(index)
534    }
535
536    /// <https://html.spec.whatwg.org/multipage/#dom-select-setter>
537    fn IndexedSetter(
538        &self,
539        index: u32,
540        value: Option<&HTMLOptionElement>,
541        can_gc: CanGc,
542    ) -> ErrorResult {
543        self.Options().IndexedSetter(index, value, can_gc)
544    }
545
546    /// <https://html.spec.whatwg.org/multipage/#dom-select-nameditem>
547    fn NamedItem(&self, name: DOMString) -> Option<DomRoot<HTMLOptionElement>> {
548        self.Options()
549            .NamedGetter(name)
550            .and_then(DomRoot::downcast::<HTMLOptionElement>)
551    }
552
553    /// <https://html.spec.whatwg.org/multipage/#dom-select-remove>
554    fn Remove_(&self, index: i32) {
555        self.Options().Remove(index)
556    }
557
558    /// <https://html.spec.whatwg.org/multipage/#dom-select-remove>
559    fn Remove(&self) {
560        self.upcast::<Element>().Remove(CanGc::note())
561    }
562
563    /// <https://html.spec.whatwg.org/multipage/#dom-select-value>
564    fn Value(&self) -> DOMString {
565        self.list_of_options()
566            .find(|opt_elem| opt_elem.Selected())
567            .map(|opt_elem| opt_elem.Value())
568            .unwrap_or_default()
569    }
570
571    /// <https://html.spec.whatwg.org/multipage/#dom-select-value>
572    fn SetValue(&self, value: DOMString) {
573        let mut opt_iter = self.list_of_options();
574        // Reset until we find an <option> with a matching value
575        for opt in opt_iter.by_ref() {
576            if opt.Value() == value {
577                opt.set_selectedness(true);
578                opt.set_dirtiness(true);
579                break;
580            }
581            opt.set_selectedness(false);
582        }
583        // Reset remaining <option> elements
584        for opt in opt_iter {
585            opt.set_selectedness(false);
586        }
587
588        self.validity_state()
589            .perform_validation_and_update(ValidationFlags::VALUE_MISSING, CanGc::note());
590    }
591
592    /// <https://html.spec.whatwg.org/multipage/#dom-select-selectedindex>
593    fn SelectedIndex(&self) -> i32 {
594        self.list_of_options()
595            .enumerate()
596            .filter(|(_, opt_elem)| opt_elem.Selected())
597            .map(|(i, _)| i as i32)
598            .next()
599            .unwrap_or(-1)
600    }
601
602    /// <https://html.spec.whatwg.org/multipage/#dom-select-selectedindex>
603    fn SetSelectedIndex(&self, index: i32, can_gc: CanGc) {
604        let mut selection_did_change = false;
605
606        let mut opt_iter = self.list_of_options();
607        for opt in opt_iter.by_ref().take(index as usize) {
608            selection_did_change |= opt.Selected();
609            opt.set_selectedness(false);
610        }
611        if let Some(selected_option) = opt_iter.next() {
612            selection_did_change |= !selected_option.Selected();
613            selected_option.set_selectedness(true);
614            selected_option.set_dirtiness(true);
615
616            // Reset remaining <option> elements
617            for opt in opt_iter {
618                selection_did_change |= opt.Selected();
619                opt.set_selectedness(false);
620            }
621        }
622
623        if selection_did_change {
624            self.update_shadow_tree(can_gc);
625        }
626    }
627
628    /// <https://html.spec.whatwg.org/multipage/#dom-cva-willvalidate>
629    fn WillValidate(&self) -> bool {
630        self.is_instance_validatable()
631    }
632
633    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validity>
634    fn Validity(&self) -> DomRoot<ValidityState> {
635        self.validity_state()
636    }
637
638    /// <https://html.spec.whatwg.org/multipage/#dom-cva-checkvalidity>
639    fn CheckValidity(&self, can_gc: CanGc) -> bool {
640        self.check_validity(can_gc)
641    }
642
643    /// <https://html.spec.whatwg.org/multipage/#dom-cva-reportvalidity>
644    fn ReportValidity(&self, can_gc: CanGc) -> bool {
645        self.report_validity(can_gc)
646    }
647
648    /// <https://html.spec.whatwg.org/multipage/#dom-cva-validationmessage>
649    fn ValidationMessage(&self) -> DOMString {
650        self.validation_message()
651    }
652
653    /// <https://html.spec.whatwg.org/multipage/#dom-cva-setcustomvalidity>
654    fn SetCustomValidity(&self, error: DOMString) {
655        self.validity_state().set_custom_error_message(error);
656    }
657}
658
659impl VirtualMethods for HTMLSelectElement {
660    fn super_type(&self) -> Option<&dyn VirtualMethods> {
661        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
662    }
663
664    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
665        self.super_type()
666            .unwrap()
667            .attribute_mutated(attr, mutation, can_gc);
668        match *attr.local_name() {
669            local_name!("required") => {
670                self.validity_state()
671                    .perform_validation_and_update(ValidationFlags::VALUE_MISSING, can_gc);
672            },
673            local_name!("disabled") => {
674                let el = self.upcast::<Element>();
675                match mutation {
676                    AttributeMutation::Set(_) => {
677                        el.set_disabled_state(true);
678                        el.set_enabled_state(false);
679                    },
680                    AttributeMutation::Removed => {
681                        el.set_disabled_state(false);
682                        el.set_enabled_state(true);
683                        el.check_ancestors_disabled_state_for_form_control();
684                    },
685                }
686
687                self.validity_state()
688                    .perform_validation_and_update(ValidationFlags::VALUE_MISSING, can_gc);
689            },
690            local_name!("form") => {
691                self.form_attribute_mutated(mutation, can_gc);
692            },
693            _ => {},
694        }
695    }
696
697    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
698        if let Some(s) = self.super_type() {
699            s.bind_to_tree(context, can_gc);
700        }
701
702        self.upcast::<Element>()
703            .check_ancestors_disabled_state_for_form_control();
704    }
705
706    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
707        self.super_type().unwrap().unbind_from_tree(context, can_gc);
708
709        let node = self.upcast::<Node>();
710        let el = self.upcast::<Element>();
711        if node
712            .ancestors()
713            .any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
714        {
715            el.check_ancestors_disabled_state_for_form_control();
716        } else {
717            el.check_disabled_attribute();
718        }
719    }
720
721    fn children_changed(&self, mutation: &ChildrenMutation) {
722        if let Some(s) = self.super_type() {
723            s.children_changed(mutation);
724        }
725
726        self.update_shadow_tree(CanGc::note());
727    }
728
729    fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
730        match *local_name {
731            local_name!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
732            _ => self
733                .super_type()
734                .unwrap()
735                .parse_plain_attribute(local_name, value),
736        }
737    }
738}
739
740impl FormControl for HTMLSelectElement {
741    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
742        self.form_owner.get()
743    }
744
745    fn set_form_owner(&self, form: Option<&HTMLFormElement>) {
746        self.form_owner.set(form);
747    }
748
749    fn to_element(&self) -> &Element {
750        self.upcast::<Element>()
751    }
752}
753
754impl Validatable for HTMLSelectElement {
755    fn as_element(&self) -> &Element {
756        self.upcast()
757    }
758
759    fn validity_state(&self) -> DomRoot<ValidityState> {
760        self.validity_state
761            .or_init(|| ValidityState::new(&self.owner_window(), self.upcast(), CanGc::note()))
762    }
763
764    fn is_instance_validatable(&self) -> bool {
765        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls%3A-the-disabled-attribute%3Abarred-from-constraint-validation
766        // https://html.spec.whatwg.org/multipage/#the-datalist-element%3Abarred-from-constraint-validation
767        !self.upcast::<Element>().disabled_state() && !is_barred_by_datalist_ancestor(self.upcast())
768    }
769
770    fn perform_validation(
771        &self,
772        validate_flags: ValidationFlags,
773        _can_gc: CanGc,
774    ) -> ValidationFlags {
775        let mut failed_flags = ValidationFlags::empty();
776
777        // https://html.spec.whatwg.org/multipage/#suffering-from-being-missing
778        // https://html.spec.whatwg.org/multipage/#the-select-element%3Asuffering-from-being-missing
779        if validate_flags.contains(ValidationFlags::VALUE_MISSING) && self.Required() {
780            let placeholder = self.get_placeholder_label_option();
781            let is_value_missing = !self
782                .list_of_options()
783                .any(|e| e.Selected() && placeholder != Some(e));
784            failed_flags.set(ValidationFlags::VALUE_MISSING, is_value_missing);
785        }
786
787        failed_flags
788    }
789}
790
791impl Activatable for HTMLSelectElement {
792    fn as_element(&self) -> &Element {
793        self.upcast()
794    }
795
796    fn is_instance_activatable(&self) -> bool {
797        true
798    }
799
800    fn activation_behavior(&self, _event: &Event, _target: &EventTarget, _can_gc: CanGc) {
801        self.show_menu();
802    }
803}
804
805enum Choice3<I, J, K> {
806    First(I),
807    Second(J),
808    Third(K),
809}
810
811impl<I, J, K, T> Iterator for Choice3<I, J, K>
812where
813    I: Iterator<Item = T>,
814    J: Iterator<Item = T>,
815    K: Iterator<Item = T>,
816{
817    type Item = T;
818
819    fn next(&mut self) -> Option<T> {
820        match *self {
821            Choice3::First(ref mut i) => i.next(),
822            Choice3::Second(ref mut j) => j.next(),
823            Choice3::Third(ref mut k) => k.next(),
824        }
825    }
826
827    fn size_hint(&self) -> (usize, Option<usize>) {
828        match *self {
829            Choice3::First(ref i) => i.size_hint(),
830            Choice3::Second(ref j) => j.size_hint(),
831            Choice3::Third(ref k) => k.size_hint(),
832        }
833    }
834}