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        cx: &mut js::context::JSContext,
76        local_name: LocalName,
77        prefix: Option<Prefix>,
78        document: &Document,
79        proto: Option<HandleObject>,
80    ) -> DomRoot<HTMLOptionElement> {
81        Node::reflect_node_with_proto(
82            cx,
83            Box::new(HTMLOptionElement::new_inherited(
84                local_name, prefix, document,
85            )),
86            document,
87            proto,
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(cx, &self.owner_document());
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(cx, &child_clone);
235        }
236
237        // Step 3. Replace all with documentFragment within selectedcontent.
238        Node::replace_all(
239            cx,
240            Some(document_fragment.upcast()),
241            selectedcontent.upcast(),
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            cx,
259            QualName::new(None, ns!(html), local_name!("option")),
260            None,
261            &window.Document(),
262            ElementCreator::ScriptCreated,
263            CustomElementCreationMode::Synchronous,
264            proto,
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(cx, Some(text))
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, cx: &mut JSContext, value: DOMString) {
320        self.upcast::<Node>()
321            .set_text_content_for_element(cx, Some(value))
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(
396        &self,
397        cx: &mut js::context::JSContext,
398        attr: &Attr,
399        mutation: AttributeMutation,
400    ) {
401        self.super_type()
402            .unwrap()
403            .attribute_mutated(cx, attr, mutation);
404        match *attr.local_name() {
405            local_name!("disabled") => {
406                let el = self.upcast::<Element>();
407                match mutation {
408                    AttributeMutation::Set(..) => {
409                        el.set_disabled_state(true);
410                        el.set_enabled_state(false);
411                    },
412                    AttributeMutation::Removed => {
413                        el.set_disabled_state(false);
414                        el.set_enabled_state(true);
415                        el.check_parent_disabled_state_for_option();
416                    },
417                }
418                self.update_select_validity(CanGc::from_cx(cx));
419            },
420            local_name!("selected") => {
421                let mut selectedness_changed = false;
422                match mutation {
423                    AttributeMutation::Set(..) => {
424                        // https://html.spec.whatwg.org/multipage/#concept-option-selectedness
425                        if !self.dirtiness.get() && !self.selectedness.get() {
426                            self.set_selectedness(true);
427                            selectedness_changed = true;
428                        }
429                    },
430                    AttributeMutation::Removed => {
431                        // https://html.spec.whatwg.org/multipage/#concept-option-selectedness
432                        if !self.dirtiness.get() && self.selectedness.get() {
433                            self.set_selectedness(false);
434                            selectedness_changed = true;
435                        }
436                    },
437                }
438
439                if selectedness_changed {
440                    self.pick_if_selected_and_reset();
441
442                    if let Some(select_element) = self.owner_select_element() {
443                        select_element.update_shadow_tree(cx);
444                    }
445                }
446
447                self.update_select_validity(CanGc::from_cx(cx));
448            },
449            local_name!("label") => {
450                // The label of the selected option is displayed inside the select element, so we need to repaint
451                // when it changes
452                if let Some(select_element) = self.owner_select_element() {
453                    select_element.update_shadow_tree(cx);
454                }
455            },
456            _ => {},
457        }
458    }
459
460    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
461        if let Some(s) = self.super_type() {
462            s.bind_to_tree(cx, context);
463        }
464
465        self.upcast::<Element>()
466            .check_parent_disabled_state_for_option();
467
468        self.pick_if_selected_and_reset();
469        self.update_select_validity(CanGc::from_cx(cx));
470    }
471
472    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
473        self.super_type().unwrap().unbind_from_tree(context, can_gc);
474
475        if let Some(select) = context
476            .parent
477            .inclusive_ancestors(ShadowIncluding::No)
478            .find_map(DomRoot::downcast::<HTMLSelectElement>)
479        {
480            select
481                .validity_state(can_gc)
482                .perform_validation_and_update(ValidationFlags::all(), can_gc);
483            select.ask_for_reset();
484        }
485
486        let node = self.upcast::<Node>();
487        let el = self.upcast::<Element>();
488        if node.GetParentNode().is_some() {
489            el.check_parent_disabled_state_for_option();
490        } else {
491            el.check_disabled_attribute();
492        }
493    }
494
495    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
496        if let Some(super_type) = self.super_type() {
497            super_type.children_changed(cx, mutation);
498        }
499
500        // Changing the descendants of a selected option can change it's displayed label
501        // if it does not have a label attribute
502        if !self
503            .upcast::<Element>()
504            .has_attribute(&local_name!("label"))
505        {
506            if let Some(owner_select) = self.owner_select_element() {
507                if owner_select
508                    .selected_option()
509                    .is_some_and(|selected_option| self == &*selected_option)
510                {
511                    owner_select.update_shadow_tree(cx);
512                }
513            }
514        }
515    }
516
517    /// <https://html.spec.whatwg.org/multipage/#the-option-element:html-element-moving-steps>
518    fn moving_steps(&self, context: &MoveContext, can_gc: CanGc) {
519        if let Some(super_type) = self.super_type() {
520            super_type.moving_steps(context, can_gc);
521        }
522
523        // The option HTML element moving steps, given movedNode and oldParent, are to run update an
524        // option's nearest ancestor select given movedNode.
525        let element = self.upcast::<Element>();
526        if let Some(old_parent) = context.old_parent {
527            if let Some(select) = old_parent
528                .inclusive_ancestors(ShadowIncluding::No)
529                .find_map(DomRoot::downcast::<HTMLSelectElement>)
530            {
531                select
532                    .validity_state(can_gc)
533                    .perform_validation_and_update(ValidationFlags::all(), can_gc);
534                select.ask_for_reset();
535            }
536
537            if self.upcast::<Node>().GetParentNode().is_some() {
538                element.check_parent_disabled_state_for_option();
539            } else {
540                element.check_disabled_attribute();
541            }
542        }
543
544        element.check_parent_disabled_state_for_option();
545
546        self.pick_if_selected_and_reset();
547        self.update_select_validity(can_gc);
548    }
549}