script/dom/html/
htmloptionelement.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::cell::Cell;
6use std::convert::TryInto;
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix, QualName, local_name, ns};
10use js::context::JSContext;
11use js::rust::HandleObject;
12use style::str::{split_html_space_chars, str_join};
13use stylo_dom::ElementState;
14
15use crate::dom::attr::Attr;
16use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
17use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
18use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElement_Binding::HTMLSelectElementMethods;
19use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
20use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
21use crate::dom::bindings::error::Fallible;
22use crate::dom::bindings::inheritance::Castable;
23use crate::dom::bindings::root::DomRoot;
24use crate::dom::bindings::str::DOMString;
25use crate::dom::characterdata::CharacterData;
26use crate::dom::document::Document;
27use crate::dom::element::{AttributeMutation, CustomElementCreationMode, Element, ElementCreator};
28use crate::dom::html::htmlelement::HTMLElement;
29use crate::dom::html::htmlformelement::HTMLFormElement;
30use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
31use crate::dom::html::htmlscriptelement::HTMLScriptElement;
32use crate::dom::html::htmlselectelement::HTMLSelectElement;
33use crate::dom::node::{
34    BindContext, ChildrenMutation, CloneChildrenFlag, MoveContext, Node, NodeTraits,
35    ShadowIncluding, UnbindContext,
36};
37use crate::dom::text::Text;
38use crate::dom::types::DocumentFragment;
39use crate::dom::validation::Validatable;
40use crate::dom::validitystate::ValidationFlags;
41use crate::dom::virtualmethods::VirtualMethods;
42use crate::dom::window::Window;
43use crate::script_runtime::CanGc;
44
45#[dom_struct]
46pub(crate) struct HTMLOptionElement {
47    htmlelement: HTMLElement,
48
49    /// <https://html.spec.whatwg.org/multipage/#attr-option-selected>
50    selectedness: Cell<bool>,
51
52    /// <https://html.spec.whatwg.org/multipage/#concept-option-dirtiness>
53    dirtiness: Cell<bool>,
54}
55
56impl HTMLOptionElement {
57    fn new_inherited(
58        local_name: LocalName,
59        prefix: Option<Prefix>,
60        document: &Document,
61    ) -> HTMLOptionElement {
62        HTMLOptionElement {
63            htmlelement: HTMLElement::new_inherited_with_state(
64                ElementState::ENABLED,
65                local_name,
66                prefix,
67                document,
68            ),
69            selectedness: Cell::new(false),
70            dirtiness: Cell::new(false),
71        }
72    }
73
74    pub(crate) fn new(
75        local_name: LocalName,
76        prefix: Option<Prefix>,
77        document: &Document,
78        proto: Option<HandleObject>,
79        can_gc: CanGc,
80    ) -> DomRoot<HTMLOptionElement> {
81        Node::reflect_node_with_proto(
82            Box::new(HTMLOptionElement::new_inherited(
83                local_name, prefix, document,
84            )),
85            document,
86            proto,
87            can_gc,
88        )
89    }
90
91    pub(crate) fn set_selectedness(&self, selected: bool) {
92        self.selectedness.set(selected);
93        // Bump the tree version so that any live HTMLCollection (e.g. selectedOptions)
94        // rooted at an ancestor invalidates its cached length and cursor.
95        self.upcast::<Node>().rev_version();
96    }
97
98    pub(crate) fn set_dirtiness(&self, dirtiness: bool) {
99        self.dirtiness.set(dirtiness);
100    }
101
102    fn pick_if_selected_and_reset(&self) {
103        if let Some(select) = self.owner_select_element() {
104            if self.Selected() {
105                select.pick_option(self);
106            }
107            select.ask_for_reset();
108        }
109    }
110
111    /// <https://html.spec.whatwg.org/multipage/#concept-option-index>
112    fn index(&self) -> i32 {
113        let Some(owner_select) = self.owner_select_element() else {
114            return 0;
115        };
116
117        let Some(position) = owner_select.list_of_options().position(|n| &*n == self) else {
118            // An option should always be in it's owner's list of options, but it's not worth a browser panic
119            warn!("HTMLOptionElement called index_in_select at a select that did not contain it");
120            return 0;
121        };
122
123        position.try_into().unwrap_or(0)
124    }
125
126    fn owner_select_element(&self) -> Option<DomRoot<HTMLSelectElement>> {
127        let parent = self.upcast::<Node>().GetParentNode()?;
128
129        if parent.is::<HTMLOptGroupElement>() {
130            DomRoot::downcast::<HTMLSelectElement>(parent.GetParentNode()?)
131        } else {
132            DomRoot::downcast::<HTMLSelectElement>(parent)
133        }
134    }
135
136    fn update_select_validity(&self, can_gc: CanGc) {
137        if let Some(select) = self.owner_select_element() {
138            select
139                .validity_state(can_gc)
140                .perform_validation_and_update(ValidationFlags::all(), can_gc);
141        }
142    }
143
144    /// <https://html.spec.whatwg.org/multipage/#concept-option-label>
145    ///
146    /// Note that this is not equivalent to <https://html.spec.whatwg.org/multipage/#dom-option-label>.
147    pub(crate) fn displayed_label(&self) -> DOMString {
148        // > The label of an option element is the value of the label content attribute, if there is one
149        // > and its value is not the empty string, or, otherwise, the value of the element's text IDL attribute.
150        let label = self
151            .upcast::<Element>()
152            .get_string_attribute(&local_name!("label"));
153
154        if label.is_empty() {
155            return self.Text();
156        }
157
158        label
159    }
160
161    /// <https://html.spec.whatwg.org/multipage/#option-element-nearest-ancestor-select>
162    pub(crate) fn nearest_ancestor_select(&self) -> Option<DomRoot<HTMLSelectElement>> {
163        // Step 1. Let ancestorOptgroup be null.
164        // NOTE: We only care whether the value is non-null, so a boolean is enough
165        let mut did_see_ancestor_optgroup = false;
166
167        // Step 2. For each ancestor of option's ancestors, in reverse tree order:
168        for ancestor in self
169            .upcast::<Node>()
170            .ancestors()
171            .filter_map(DomRoot::downcast::<Element>)
172        {
173            // Step 2.1 If ancestor is a datalist, hr, or option element, then return null.
174            if matches!(
175                ancestor.local_name(),
176                &local_name!("datalist") | &local_name!("hr") | &local_name!("option")
177            ) {
178                return None;
179            }
180
181            // Step 2.2 If ancestor is an optgroup element
182            if ancestor.local_name() == &local_name!("optgroup") {
183                // Step 2.1 If ancestorOptgroup is not null, then return null.
184                if did_see_ancestor_optgroup {
185                    return None;
186                }
187
188                // Step 2.2 Set ancestorOptgroup to ancestor.
189                did_see_ancestor_optgroup = true;
190            }
191
192            // Step 2.3 If ancestor is a select, then return ancestor.
193            if let Some(select) = DomRoot::downcast::<HTMLSelectElement>(ancestor) {
194                return Some(select);
195            }
196        }
197
198        // Step 3. Return null.
199        None
200    }
201
202    /// <https://html.spec.whatwg.org/multipage/#maybe-clone-an-option-into-selectedcontent>
203    pub(crate) fn maybe_clone_an_option_into_selectedcontent(&self, cx: &mut JSContext) {
204        // Step 1. Let select be option's option element nearest ancestor select.
205        let select = self.nearest_ancestor_select();
206
207        // Step 2. If all of the following conditions are true:
208        // * select is not null;
209        // * option's selectedness is true; and
210        // * select's enabled selectedcontent is not null,
211        // * then run clone an option into a selectedcontent given option and select's enabled selectedcontent.
212        if self.selectedness.get() {
213            if let Some(selectedcontent) =
214                select.and_then(|select| select.get_enabled_selectedcontent())
215            {
216                self.clone_an_option_into_selectedcontent(cx, &selectedcontent);
217            }
218        }
219    }
220
221    /// <https://html.spec.whatwg.org/multipage/#clone-an-option-into-a-selectedcontent>
222    fn clone_an_option_into_selectedcontent(&self, cx: &mut JSContext, selectedcontent: &Element) {
223        // Step 1. Let documentFragment be a new DocumentFragment whose node document is option's node document.
224        let document_fragment = DocumentFragment::new(&self.owner_document(), CanGc::from_cx(cx));
225
226        // Step 2. For each child of option's children:
227        for child in self.upcast::<Node>().children() {
228            // Step 2.1 Let childClone be the result of running clone given child with subtree set to true.
229            let child_clone = Node::clone(cx, &child, None, CloneChildrenFlag::CloneChildren, None);
230
231            // Step 2.2 Append childClone to documentFragment.
232            let _ = document_fragment
233                .upcast::<Node>()
234                .AppendChild(&child_clone, CanGc::from_cx(cx));
235        }
236
237        // Step 3. Replace all with documentFragment within selectedcontent.
238        Node::replace_all(
239            Some(document_fragment.upcast()),
240            selectedcontent.upcast(),
241            CanGc::from_cx(cx),
242        );
243    }
244}
245
246impl HTMLOptionElementMethods<crate::DomTypeHolder> for HTMLOptionElement {
247    /// <https://html.spec.whatwg.org/multipage/#dom-option>
248    fn Option(
249        cx: &mut JSContext,
250        window: &Window,
251        proto: Option<HandleObject>,
252        text: DOMString,
253        value: Option<DOMString>,
254        default_selected: bool,
255        selected: bool,
256    ) -> Fallible<DomRoot<HTMLOptionElement>> {
257        let element = Element::create(
258            QualName::new(None, ns!(html), local_name!("option")),
259            None,
260            &window.Document(),
261            ElementCreator::ScriptCreated,
262            CustomElementCreationMode::Synchronous,
263            proto,
264            CanGc::from_cx(cx),
265        );
266
267        let option = DomRoot::downcast::<HTMLOptionElement>(element).unwrap();
268
269        if !text.is_empty() {
270            option
271                .upcast::<Node>()
272                .set_text_content_for_element(Some(text), CanGc::from_cx(cx))
273        }
274
275        if let Some(val) = value {
276            option.SetValue(val)
277        }
278
279        option.SetDefaultSelected(default_selected);
280        option.set_selectedness(selected);
281        option.update_select_validity(CanGc::from_cx(cx));
282        Ok(option)
283    }
284
285    // https://html.spec.whatwg.org/multipage/#dom-option-disabled
286    make_bool_getter!(Disabled, "disabled");
287
288    // https://html.spec.whatwg.org/multipage/#dom-option-disabled
289    make_bool_setter!(SetDisabled, "disabled");
290
291    /// <https://html.spec.whatwg.org/multipage/#dom-option-text>
292    fn Text(&self) -> DOMString {
293        let mut content = DOMString::new();
294
295        let mut iterator = self.upcast::<Node>().traverse_preorder(ShadowIncluding::No);
296        while let Some(node) = iterator.peek() {
297            if let Some(element) = node.downcast::<Element>() {
298                let html_script = element.is::<HTMLScriptElement>();
299                let svg_script = *element.namespace() == ns!(svg) &&
300                    element.local_name() == &local_name!("script");
301                if html_script || svg_script {
302                    iterator.next_skipping_children();
303                    continue;
304                }
305            }
306
307            if node.is::<Text>() {
308                let characterdata = node.downcast::<CharacterData>().unwrap();
309                content.push_str(&characterdata.Data().str());
310            }
311
312            iterator.next();
313        }
314
315        DOMString::from(str_join(split_html_space_chars(&content.str()), " "))
316    }
317
318    /// <https://html.spec.whatwg.org/multipage/#dom-option-text>
319    fn SetText(&self, value: DOMString, can_gc: CanGc) {
320        self.upcast::<Node>()
321            .set_text_content_for_element(Some(value), can_gc)
322    }
323
324    /// <https://html.spec.whatwg.org/multipage/#dom-option-form>
325    fn GetForm(&self) -> Option<DomRoot<HTMLFormElement>> {
326        let parent = self.upcast::<Node>().GetParentNode().and_then(|p| {
327            if p.is::<HTMLOptGroupElement>() {
328                p.upcast::<Node>().GetParentNode()
329            } else {
330                Some(p)
331            }
332        });
333
334        parent.and_then(|p| p.downcast::<HTMLSelectElement>().and_then(|s| s.GetForm()))
335    }
336
337    /// <https://html.spec.whatwg.org/multipage/#attr-option-value>
338    fn Value(&self) -> DOMString {
339        let element = self.upcast::<Element>();
340        let attr = &local_name!("value");
341        if element.has_attribute(attr) {
342            element.get_string_attribute(attr)
343        } else {
344            self.Text()
345        }
346    }
347
348    // https://html.spec.whatwg.org/multipage/#attr-option-value
349    make_setter!(SetValue, "value");
350
351    /// <https://html.spec.whatwg.org/multipage/#attr-option-label>
352    fn Label(&self) -> DOMString {
353        let element = self.upcast::<Element>();
354        let attr = &local_name!("label");
355        if element.has_attribute(attr) {
356            element.get_string_attribute(attr)
357        } else {
358            self.Text()
359        }
360    }
361
362    // https://html.spec.whatwg.org/multipage/#attr-option-label
363    make_setter!(SetLabel, "label");
364
365    // https://html.spec.whatwg.org/multipage/#dom-option-defaultselected
366    make_bool_getter!(DefaultSelected, "selected");
367
368    // https://html.spec.whatwg.org/multipage/#dom-option-defaultselected
369    make_bool_setter!(SetDefaultSelected, "selected");
370
371    /// <https://html.spec.whatwg.org/multipage/#dom-option-selected>
372    fn Selected(&self) -> bool {
373        self.selectedness.get()
374    }
375
376    /// <https://html.spec.whatwg.org/multipage/#dom-option-selected>
377    fn SetSelected(&self, selected: bool, can_gc: CanGc) {
378        self.dirtiness.set(true);
379        self.set_selectedness(selected);
380        self.pick_if_selected_and_reset();
381        self.update_select_validity(can_gc);
382    }
383
384    /// <https://html.spec.whatwg.org/multipage/#dom-option-index>
385    fn Index(&self) -> i32 {
386        self.index()
387    }
388}
389
390impl VirtualMethods for HTMLOptionElement {
391    fn super_type(&self) -> Option<&dyn VirtualMethods> {
392        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
393    }
394
395    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
396        self.super_type()
397            .unwrap()
398            .attribute_mutated(attr, mutation, can_gc);
399        match *attr.local_name() {
400            local_name!("disabled") => {
401                let el = self.upcast::<Element>();
402                match mutation {
403                    AttributeMutation::Set(..) => {
404                        el.set_disabled_state(true);
405                        el.set_enabled_state(false);
406                    },
407                    AttributeMutation::Removed => {
408                        el.set_disabled_state(false);
409                        el.set_enabled_state(true);
410                        el.check_parent_disabled_state_for_option();
411                    },
412                }
413                self.update_select_validity(can_gc);
414            },
415            local_name!("selected") => {
416                match mutation {
417                    AttributeMutation::Set(..) => {
418                        // https://html.spec.whatwg.org/multipage/#concept-option-selectedness
419                        if !self.dirtiness.get() {
420                            self.selectedness.set(true);
421                        }
422                    },
423                    AttributeMutation::Removed => {
424                        // https://html.spec.whatwg.org/multipage/#concept-option-selectedness
425                        if !self.dirtiness.get() {
426                            self.selectedness.set(false);
427                        }
428                    },
429                }
430                self.update_select_validity(can_gc);
431            },
432            local_name!("label") => {
433                // The label of the selected option is displayed inside the select element, so we need to repaint
434                // when it changes
435                if let Some(select_element) = self.owner_select_element() {
436                    select_element.update_shadow_tree(CanGc::note());
437                }
438            },
439            _ => {},
440        }
441    }
442
443    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
444        if let Some(s) = self.super_type() {
445            s.bind_to_tree(context, can_gc);
446        }
447
448        self.upcast::<Element>()
449            .check_parent_disabled_state_for_option();
450
451        self.pick_if_selected_and_reset();
452        self.update_select_validity(can_gc);
453    }
454
455    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
456        self.super_type().unwrap().unbind_from_tree(context, can_gc);
457
458        if let Some(select) = context
459            .parent
460            .inclusive_ancestors(ShadowIncluding::No)
461            .find_map(DomRoot::downcast::<HTMLSelectElement>)
462        {
463            select
464                .validity_state(can_gc)
465                .perform_validation_and_update(ValidationFlags::all(), can_gc);
466            select.ask_for_reset();
467        }
468
469        let node = self.upcast::<Node>();
470        let el = self.upcast::<Element>();
471        if node.GetParentNode().is_some() {
472            el.check_parent_disabled_state_for_option();
473        } else {
474            el.check_disabled_attribute();
475        }
476    }
477
478    fn children_changed(&self, mutation: &ChildrenMutation, can_gc: CanGc) {
479        if let Some(super_type) = self.super_type() {
480            super_type.children_changed(mutation, can_gc);
481        }
482
483        // Changing the descendants of a selected option can change it's displayed label
484        // if it does not have a label attribute
485        if !self
486            .upcast::<Element>()
487            .has_attribute(&local_name!("label"))
488        {
489            if let Some(owner_select) = self.owner_select_element() {
490                if owner_select
491                    .selected_option()
492                    .is_some_and(|selected_option| self == &*selected_option)
493                {
494                    owner_select.update_shadow_tree(can_gc);
495                }
496            }
497        }
498    }
499
500    /// <https://html.spec.whatwg.org/multipage/#the-option-element:html-element-moving-steps>
501    fn moving_steps(&self, context: &MoveContext, can_gc: CanGc) {
502        if let Some(super_type) = self.super_type() {
503            super_type.moving_steps(context, can_gc);
504        }
505
506        // The option HTML element moving steps, given movedNode and oldParent, are to run update an
507        // option's nearest ancestor select given movedNode.
508        let element = self.upcast::<Element>();
509        if let Some(old_parent) = context.old_parent {
510            if let Some(select) = old_parent
511                .inclusive_ancestors(ShadowIncluding::No)
512                .find_map(DomRoot::downcast::<HTMLSelectElement>)
513            {
514                select
515                    .validity_state(can_gc)
516                    .perform_validation_and_update(ValidationFlags::all(), can_gc);
517                select.ask_for_reset();
518            }
519
520            if self.upcast::<Node>().GetParentNode().is_some() {
521                element.check_parent_disabled_state_for_option();
522            } else {
523                element.check_disabled_attribute();
524            }
525        }
526
527        element.check_parent_disabled_state_for_option();
528
529        self.pick_if_selected_and_reset();
530        self.update_select_validity(can_gc);
531    }
532}