Skip to main content

script/dom/html/
htmlelement.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/. */
4use std::default::Default;
5use std::rc::Rc;
6
7use dom_struct::dom_struct;
8use html5ever::{LocalName, Prefix, QualName, local_name, ns};
9use js::context::{JSContext, NoGC};
10use js::rust::HandleObject;
11use layout_api::{QueryMsg, ScrollContainerQueryFlags, ScrollContainerResponse};
12use rustc_hash::FxHashSet;
13use script_bindings::callback::RootedCallback;
14use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
15use script_bindings::codegen::GenericBindings::DocumentFragmentBinding::DocumentFragmentMethods;
16use script_bindings::codegen::GenericBindings::ElementBinding::ScrollLogicalPosition;
17use script_bindings::codegen::GenericBindings::WindowBinding::ScrollBehavior;
18use script_bindings::dom::UnrootedDom;
19use style::attr::AttrValue;
20use stylo_dom::ElementState;
21
22use crate::dom::NodeFlags;
23use crate::dom::activation::Activatable;
24use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterData_Binding::CharacterDataMethods;
25use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::{
26    EventHandlerNonNull, OnErrorEventHandlerNonNull,
27};
28use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::{
29    HTMLElementMethods, ShowPopoverOptions,
30};
31use crate::dom::bindings::codegen::Bindings::HTMLLabelElementBinding::HTMLLabelElementMethods;
32use crate::dom::bindings::codegen::Bindings::HTMLOrSVGOrMathMLElementBinding::FocusOptions;
33use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
34use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
35use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
36use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
37use crate::dom::bindings::codegen::UnionTypes::TogglePopoverOptionsOrBoolean;
38use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
39use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
40use crate::dom::bindings::refcounted::Trusted;
41use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
42use crate::dom::bindings::str::DOMString;
43use crate::dom::characterdata::CharacterData;
44use crate::dom::closewatcher::internalclosewatcher::{
45    InternalCloseWatcher, InternalCloseWatcherOwner,
46};
47use crate::dom::css::cssstyledeclaration::{
48    CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner,
49};
50use crate::dom::customelementregistry::{CustomElementRegistry, CustomElementState};
51use crate::dom::document::Document;
52use crate::dom::document::focus::FocusableArea;
53use crate::dom::document_event_handler::character_to_code;
54use crate::dom::documentfragment::DocumentFragment;
55use crate::dom::domstringmap::DOMStringMap;
56use crate::dom::element::attributes::storage::AttrRef;
57use crate::dom::element::{
58    AttributeMutation, CustomElementCreationMode, Element, ElementCreator,
59    is_element_affected_by_legacy_background_presentational_hint,
60};
61use crate::dom::event::{Event, EventBubbles, EventCancelable};
62use crate::dom::eventtarget::EventTarget;
63use crate::dom::html::form_controls::htmlbuttonelement::HTMLButtonElement;
64use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
65use crate::dom::html::form_controls::input_type::InputType;
66use crate::dom::html::htmlbodyelement::HTMLBodyElement;
67use crate::dom::html::htmldetailselement::HTMLDetailsElement;
68use crate::dom::html::htmlformelement::{FormControl, HTMLFormElement};
69use crate::dom::html::htmlframesetelement::HTMLFrameSetElement;
70use crate::dom::html::htmlhtmlelement::HTMLHtmlElement;
71use crate::dom::html::htmllabelelement::HTMLLabelElement;
72use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
73use crate::dom::html::interactive::htmldialogelement::HTMLDialogElement;
74use crate::dom::html::internals::elementinternals::ElementInternals;
75use crate::dom::htmlelement::PopoverState::NoPopover;
76use crate::dom::htmlformelement::FormControlElementHelpers;
77use crate::dom::iterators::ShadowIncluding;
78use crate::dom::medialist::MediaList;
79use crate::dom::node::focus::FocusTrigger;
80use crate::dom::node::virtualmethods::VirtualMethods;
81use crate::dom::node::{
82    BindContext, MoveContext, Node, NodeDamage, NodeTraits, UnbindContext,
83    from_untrusted_node_address,
84};
85use crate::dom::shadowroot::shadowroot::ShadowRoot;
86use crate::dom::text::Text;
87use crate::dom::toggleevent::ToggleEvent;
88use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollRequirement};
89
90/// <https://html.spec.whatwg.org/multipage/#attr-popover>
91#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
92pub(crate) enum PopoverState {
93    Auto,
94    Manual,
95    Hint,
96    NoPopover,
97}
98
99impl PopoverState {
100    /// <https://html.spec.whatwg.org/multipage/#the-popover-attribute:attr-popover-4>
101    fn from_attribute_value(value: Option<String>) -> Self {
102        // > The popover attribute is an enumerated attribute with the following keywords and states:
103        // > - auto: Auto
104        // > - manual: Manual
105        // > - hint: Hint
106        // > The attribute's missing value default is the No Popover state, its invalid value
107        // > default is the Manual state, and its empty value default is the Auto state.
108        let Some(value) = value else {
109            return PopoverState::NoPopover;
110        };
111
112        if value.is_empty() || value.eq_ignore_ascii_case("auto") {
113            PopoverState::Auto
114        } else if value.eq_ignore_ascii_case("hint") {
115            PopoverState::Hint
116        } else {
117            PopoverState::Manual
118        }
119    }
120
121    /// <https://html.spec.whatwg.org/multipage/#dom-popover>
122    fn reflect_attribute(&self) -> Option<DOMString> {
123        // > The popover IDL attribute must reflect the popover attribute, limited to only known values.
124        match self {
125            PopoverState::Auto => Some(DOMString::from_static("auto")),
126            PopoverState::Manual => Some(DOMString::from_static("manual")),
127            PopoverState::Hint => Some(DOMString::from_static("hint")),
128            PopoverState::NoPopover => None,
129        }
130    }
131}
132
133#[dom_struct]
134pub(crate) struct HTMLElement {
135    element: Element,
136    style_decl: MutNullableDom<CSSStyleDeclaration>,
137    dataset: MutNullableDom<DOMStringMap>,
138}
139
140impl HTMLElement {
141    pub(crate) fn new_inherited(
142        tag_name: LocalName,
143        prefix: Option<Prefix>,
144        document: &Document,
145    ) -> HTMLElement {
146        HTMLElement::new_inherited_with_state(ElementState::empty(), tag_name, prefix, document)
147    }
148
149    pub(crate) fn new_inherited_with_state(
150        state: ElementState,
151        tag_name: LocalName,
152        prefix: Option<Prefix>,
153        document: &Document,
154    ) -> HTMLElement {
155        HTMLElement {
156            element: Element::new_inherited_with_state(
157                state,
158                tag_name,
159                ns!(html),
160                prefix,
161                document,
162            ),
163            style_decl: Default::default(),
164            dataset: Default::default(),
165        }
166    }
167
168    pub(crate) fn new(
169        cx: &mut js::context::JSContext,
170        local_name: LocalName,
171        prefix: Option<Prefix>,
172        document: &Document,
173        proto: Option<HandleObject>,
174    ) -> DomRoot<HTMLElement> {
175        Node::reflect_node_with_proto(
176            cx,
177            Box::new(HTMLElement::new_inherited(local_name, prefix, document)),
178            document,
179            proto,
180        )
181    }
182
183    fn is_body_or_frameset(&self) -> bool {
184        let eventtarget = self.upcast::<EventTarget>();
185        eventtarget.is::<HTMLBodyElement>() || eventtarget.is::<HTMLFrameSetElement>()
186    }
187
188    /// Calls into the layout engine to generate a plain text representation
189    /// of a [`HTMLElement`] as specified when getting the `.innerText` or
190    /// `.outerText` in JavaScript.`
191    ///
192    /// <https://html.spec.whatwg.org/multipage/#get-the-text-steps>
193    pub(crate) fn get_inner_outer_text(&self, cx: &mut JSContext) -> DOMString {
194        let node = self.upcast::<Node>();
195        let window = node.owner_window();
196        let element = self.as_element();
197
198        // Step 1.
199        let element_not_rendered =
200            !node.is_connected() || !element.has_css_layout_box_deprecated(cx);
201        if element_not_rendered {
202            return node.GetTextContent().unwrap();
203        }
204
205        window.layout_reflow(cx, QueryMsg::ElementInnerOuterTextQuery);
206        let text = window
207            .layout()
208            .query_element_inner_outer_text(node.to_trusted_node_address());
209
210        DOMString::from(text)
211    }
212
213    /// <https://html.spec.whatwg.org/multipage/#set-the-inner-text-steps>
214    pub(crate) fn set_inner_text(&self, cx: &mut JSContext, input: DOMString) {
215        // Step 1: Let fragment be the rendered text fragment for value given element's node
216        // document.
217        let fragment = self.rendered_text_fragment(cx, input);
218
219        // Step 2: Replace all with fragment within element.
220        Node::replace_all(cx, Some(fragment.upcast()), self.upcast::<Node>());
221    }
222
223    /// <https://html.spec.whatwg.org/multipage/#matches-the-environment>
224    pub(crate) fn media_attribute_matches_media_environment(&self) -> bool {
225        // A string matches the environment of the user if it is the empty string,
226        // a string consisting of only ASCII whitespace, or is a media query list that
227        // matches the user's environment according to the definitions given in Media Queries. [MQ]
228        self.element
229            .get_attribute_string_ref(&local_name!("media"))
230            .is_none_or(|media| {
231                let media = media.as_attr_ref();
232                MediaList::matches_environment(&self.owner_document(), &media.value())
233            })
234    }
235
236    /// <https://html.spec.whatwg.org/multipage/#editing-host>
237    pub(crate) fn is_editing_host(&self) -> bool {
238        // > An editing host is either an HTML element with its contenteditable attribute in the true state or plaintext-only state,
239        matches!(&*self.ContentEditable().str(), "true" | "plaintext-only")
240        // > or a child HTML element of a Document whose design mode enabled is true.
241        // TODO
242    }
243
244    pub(crate) fn previously_focused_element(&self, no_gc: &NoGC) -> Option<DomRoot<Element>> {
245        self.upcast::<Element>()
246            .ensure_rare_data(no_gc)
247            .previously_focused_element
248            .get()
249    }
250
251    pub(crate) fn set_previously_focused_element(&self, element: Option<&Element>, no_gc: &NoGC) {
252        self.upcast::<Element>()
253            .ensure_rare_data(no_gc)
254            .previously_focused_element
255            .set(element);
256    }
257
258    pub(crate) fn ensure_element_internals(&self, cx: &mut JSContext) -> DomRoot<ElementInternals> {
259        let element = self.upcast::<Element>();
260        let Some(element_internals) = element.get_element_internals() else {
261            let internals = ElementInternals::new(cx, self);
262            element.ensure_rare_data(cx.no_gc()).element_internals =
263                Some(Dom::from_ref(&*internals));
264            return internals;
265        };
266        element_internals
267    }
268
269    pub(crate) fn is_disableable_form_control(&self) -> bool {
270        match self.upcast::<Node>().type_id() {
271            NodeTypeId::Element(ElementTypeId::HTMLElement(
272                HTMLElementTypeId::HTMLButtonElement |
273                HTMLElementTypeId::HTMLInputElement |
274                HTMLElementTypeId::HTMLSelectElement |
275                HTMLElementTypeId::HTMLTextAreaElement,
276            )) => true,
277            NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLElement)) => {
278                self.is_form_associated_custom_element()
279            },
280            _ => false,
281        }
282    }
283
284    /// <https://html.spec.whatwg.org/multipage/#concept-fe-disabled>
285    pub(crate) fn is_form_element_disabled(&self, no_gc: &NoGC) -> bool {
286        // > A form control is disabled if any of the following are true:
287        // > - The element is a button, input, select, textarea, or form-associated custom
288        // > element, and the disabled attribute is specified on this element (regardless of
289        // > its value).
290        // > - The element is a descendant of a fieldset element whose disabled attribute is
291        // > specified, and is not a descendant of that fieldset element's first legend element
292        // > child, if any.
293        let element = self.as_element();
294        self.is_disableable_form_control() &&
295            (element.has_attribute(&local_name!("disabled")) ||
296                element.is_disabled_by_ancestor_fieldset(no_gc))
297    }
298
299    /// <https://html.spec.whatwg.org/multipage/#attr-popover>
300    pub(crate) fn popover_state(&self) -> PopoverState {
301        let attribute_value = self
302            .upcast::<Element>()
303            .get_attribute_string_value(&local_name!("popover"));
304        PopoverState::from_attribute_value(attribute_value)
305    }
306
307    /// <https://html.spec.whatwg.org/multipage/#show-popover>
308    pub(crate) fn show_popover(
309        &self,
310        cx: &mut JSContext,
311        throw_exceptions: bool,
312        source: Option<&HTMLElement>,
313    ) -> Fallible<()> {
314        let element = self.upcast::<Element>();
315
316        // Step 1. Let document be element's node document.
317        let document = self.owner_document();
318        let overlay_handler = document.overlay_handler();
319
320        // Step 2. If document's showing popover is true or document's hiding popover nesting
321        // count is not 0:
322        if overlay_handler.showing_popover() || overlay_handler.hiding_popover_nesting_count() != 0
323        {
324            // Step 2.1. If throwExceptions is true, then throw a "InvalidStateError" DOMException.
325            if throw_exceptions {
326                return Err(Error::InvalidState(Some(
327                    "Cannot show a popover while another popover is being shown or hidden.".into(),
328                )));
329            }
330
331            // Step 2.2. Return.
332            return Ok(());
333        }
334
335        // Step 3. Let validityResult be the result of running check popover validity given element,
336        // false, and null. If this throws an exception, catch it, and set validityResult to that
337        // exception.
338        let validity_result = self.check_popover_validity(false, None);
339
340        // Step 4. If validityResult is not true:
341        if !matches!(validity_result, Ok(true)) {
342            // Step 4.1. If throwExceptions is true and validityResult is a DOMException, then throw
343            // validityResult.
344            if throw_exceptions && let Err(error) = validity_result {
345                return Err(error);
346            }
347
348            // Step 4.2. Return.
349            return Ok(());
350        }
351
352        // Step 5. Assert: element's popover trigger is null.
353        assert!(self.popover_trigger().is_none());
354
355        // Step 6. Assert: element is not in document's top layer.
356        assert!(!overlay_handler.is_in_the_top_layer(element));
357
358        // Step 7. Set document's showing popover to true.
359        overlay_handler.set_showing_popover(true);
360
361        // Step 8. Let cleanupShowingSteps be the following step:
362        let cleanup_showing_steps = || {
363            // Step 8.1. Set document's showing popover to false.
364            overlay_handler.set_showing_popover(false);
365        };
366
367        // Step 9. If the result of firing an event named beforetoggle, using ToggleEvent, with the
368        // cancelable attribute initialized to true, the oldState attribute initialized to "closed",
369        // the newState attribute initialized to "open", and the source attribute initialized to
370        // source at element is false, then run cleanupShowingSteps and return.
371        let event = ToggleEvent::new(
372            cx,
373            &self.owner_window(),
374            atom!("beforetoggle"),
375            EventBubbles::DoesNotBubble,
376            EventCancelable::Cancelable,
377            DOMString::from_static("closed"),
378            DOMString::from_static("open"),
379            source.map(|source| source.upcast::<Element>()),
380        );
381        if !event
382            .upcast::<Event>()
383            .fire(cx, self.upcast::<EventTarget>())
384        {
385            cleanup_showing_steps();
386            return Ok(());
387        }
388
389        // Step 10. Set validityResult to the result of running check popover validity given
390        // element, false, and document. If this throws an exception, catch it, and set
391        // validityResult to that exception.
392        let validity_result = self.check_popover_validity(false, Some(&document));
393
394        // Step 11. If validityResult is not true:
395        if !matches!(validity_result, Ok(true)) {
396            // Step 11.1. Run cleanupShowingSteps.
397            cleanup_showing_steps();
398
399            // Step 11.2. If throwExceptions is true and validityResult is a DOMException, then
400            // throw validityResult.
401            if throw_exceptions && let Err(error) = validity_result {
402                return Err(error);
403            }
404
405            // Step 11.3. Return.
406            return Ok(());
407        }
408
409        // Step 12. Let shouldRestoreFocus be false.
410        let mut should_restore_focus = false;
411
412        // Step 13. Let originalType be the current state of element's popover attribute.
413        let original_type = self.popover_state();
414
415        // Step 14. Let effectiveType be originalType.
416        let mut effective_type = original_type;
417
418        let mut ancestor = None;
419
420        // Step 15. If originalType is Auto or Hint, then:
421        if matches!(original_type, PopoverState::Auto | PopoverState::Hint) {
422            // Step 15.1. Let ancestor be the result of running topmost popover ancestor given
423            // element, source, and true.
424            ancestor = element.topmost_popover_ancestor(cx.no_gc(), source, true);
425
426            // Step 15.2. If all of the following are true:
427            // - ancestor is not null;
428            // - ancestor's opened in popover mode is "hint"; and
429            // - effectiveType is the Auto state,
430            // then set effectiveType to the Hint state.
431            if ancestor.as_ref().is_some_and(|ancestor| {
432                ancestor.opened_in_popover_mode() == Some(PopoverState::Hint)
433            }) && effective_type == PopoverState::Auto
434            {
435                effective_type = PopoverState::Hint;
436            }
437
438            // Step 15.3. Run hide popover stack until given document, ancestor, Hint,
439            // shouldRestoreFocus, and true.
440            overlay_handler.hide_popover_stack_until(
441                cx,
442                ancestor.as_deref(),
443                PopoverState::Hint,
444                should_restore_focus,
445                true,
446            );
447
448            // Step 15.4. If effectiveType is Auto, then run hide popover stack until given
449            // document, ancestor, Auto, shouldRestoreFocus, and true.
450            if effective_type == PopoverState::Auto {
451                overlay_handler.hide_popover_stack_until(
452                    cx,
453                    ancestor.as_deref(),
454                    PopoverState::Auto,
455                    should_restore_focus,
456                    true,
457                );
458            }
459
460            // Step 15.5. If originalType is not equal to the value of element's popover attribute:
461            if original_type != self.popover_state() {
462                // Step 15.5.1. Run cleanupShowingSteps.
463                cleanup_showing_steps();
464
465                // Step 15.5.2. If throwExceptions is true, then throw an "InvalidStateError" DOMException.
466                if throw_exceptions {
467                    return Err(Error::InvalidState(Some(
468                        "The popover attribute changed while showing the popover.".into(),
469                    )));
470                }
471
472                // Step 15.5.3. Return.
473                return Ok(());
474            }
475
476            // Step 15.6. Set validityResult to the result of running check popover validity given
477            // element, false, and document. If this throws an exception, catch it, and set
478            // validityResult to that exception.
479            let validity_result = self.check_popover_validity(false, Some(&document));
480
481            // Step 15.7. If validityResult is not true:
482            if !matches!(validity_result, Ok(true)) {
483                // Step 15.7.1. Run cleanupShowingSteps.
484                cleanup_showing_steps();
485
486                // Step 15.7.2. If throwExceptions is true and validityResult is a DOMException,
487                // then throw validityResult.
488                if throw_exceptions && let Err(error) = validity_result {
489                    return Err(error);
490                }
491
492                // Step 15.7.3. Return.
493                return Ok(());
494            }
495
496            // Step 15.8. If the result of running topmost auto or hint popover on document is null,
497            // then set shouldRestoreFocus to true.
498            if overlay_handler
499                .find_the_topmost_auto_or_hint_popover(cx.no_gc())
500                .is_none()
501            {
502                should_restore_focus = true;
503            }
504
505            // Step 15.9. If effectiveType is Auto:
506            if effective_type == PopoverState::Auto {
507                // Step 15.9.1. Assert: document's showing auto popover list does not contain element.
508                debug_assert!(!overlay_handler.showing_popover_list_contains(
509                    cx.no_gc(),
510                    PopoverState::Auto,
511                    self
512                ));
513
514                // Step 15.9.2. Set element's opened in popover mode to "auto".
515                self.set_opened_in_popover_mode(cx.no_gc(), Some(PopoverState::Auto));
516            }
517            // Otherwise:
518            else {
519                // Step 15.9.1. Assert: effectiveType is Hint.
520                debug_assert!(effective_type == PopoverState::Hint);
521
522                // Step 15.9.2. Assert: document's showing hint popover list does not contain element.
523                debug_assert!(!overlay_handler.showing_popover_list_contains(
524                    cx.no_gc(),
525                    PopoverState::Hint,
526                    self
527                ));
528
529                // Step 15.9.3. Set element's opened in popover mode to "hint".
530                self.set_opened_in_popover_mode(cx.no_gc(), Some(PopoverState::Hint));
531            }
532
533            // Step 15.10. Set element's popover close watcher to the result of establishing a close
534            // watcher given element's relevant global object, with:
535            // - cancelAction being to return true.
536            // - closeAction being to hide a popover given element, true, true, false, and null.
537            // - getEnabledState being to return true.
538            let close_watcher = InternalCloseWatcher::establish(
539                cx.no_gc(),
540                document.window(),
541                &InternalCloseWatcherOwner::Popover(Dom::from_ref(self)),
542            );
543            self.set_popover_close_watcher(cx.no_gc(), close_watcher);
544        }
545
546        // Step 16. Set element's previously focused element to null.
547        self.set_previously_focused_element(None, cx.no_gc());
548
549        // Step 17. Let originallyFocusedElement be document's focused area of the document's DOM
550        // anchor.
551        let originally_focused_element = document
552            .focus_handler()
553            .focused_area()
554            .element()
555            .map(DomRoot::from_ref);
556
557        // Step 18. Add an element to the top layer given element.
558        overlay_handler.add_an_element_to_the_top_layer(element, cx.no_gc());
559
560        // Step 19. If effectiveType is Hint and ancestor's opened in popover mode is "auto", then
561        // set document's hint stack parent to ancestor.
562        if effective_type == PopoverState::Hint &&
563            let Some(ancestor) = &ancestor &&
564            ancestor.opened_in_popover_mode() == Some(PopoverState::Auto)
565        {
566            overlay_handler.set_hint_stack_parent(Some(ancestor));
567        }
568
569        // Step 20. Set element's popover visibility state to showing.
570        element.set_popover_visibility_state_showing(cx.no_gc(), true);
571
572        // Step 21. Set element's popover trigger to source.
573        self.set_popover_trigger(cx.no_gc(), source);
574
575        // TODO: Step 22. Set element's implicit anchor element to source.
576
577        // Step 23. Run the popover focusing steps given element.
578        self.run_popover_focusing_steps(cx);
579
580        // Step 24. If shouldRestoreFocus is true and element's popover attribute is not in the No
581        // Popover state, then set element's previously focused element to
582        // originallyFocusedElement.
583        if should_restore_focus && self.popover_state() != PopoverState::NoPopover {
584            self.set_previously_focused_element(originally_focused_element.as_deref(), cx.no_gc());
585        }
586
587        // Step 25. Run cleanupShowingSteps.
588        cleanup_showing_steps();
589
590        // Step 26. Queue a popover toggle event task given element, "closed", "open", and source.
591        self.queue_a_popover_toggle_event_task("closed", "open", source);
592        Ok(())
593    }
594
595    /// <https://html.spec.whatwg.org/multipage/#queue-a-popover-toggle-event-task>
596    fn queue_a_popover_toggle_event_task(
597        &self,
598        old_state: &'static str,
599        new_state: &'static str,
600        source: Option<&HTMLElement>,
601    ) {
602        // TODO: Step 1. If element's popover toggle task tracker is not null, then:
603        // TODO: Step 1.1. Set oldState to element's popover toggle task tracker's old state.
604        // TODO: Step 1.2. Remove element's popover toggle task tracker's task from its task queue.
605        // TODO: Step 1.3. Set element's popover toggle task tracker to null.
606
607        // Step 2. Queue an element task given the DOM manipulation task source and element to run
608        // the following steps:
609        let this = Trusted::new(self);
610        let trusted_source = source.map(|source| Trusted::new(source.upcast::<Element>()));
611        self.owner_global()
612            .task_manager()
613            .dom_manipulation_task_source()
614            .queue(task!(fire_popover_toggle_event: move |cx| {
615                let this = this.root();
616                let source = trusted_source.map(|source| source.root());
617
618                // Step 2.1. Fire an event named toggle at element, using ToggleEvent, with the
619                // oldState attribute initialized to oldState, the newState attribute initialized to
620                // newState, and the source attribute initialized to source.
621                let event = ToggleEvent::new(
622                    cx,
623                    &this.owner_window(),
624                    atom!("toggle"),
625                    EventBubbles::DoesNotBubble,
626                    EventCancelable::NotCancelable,
627                    DOMString::from_static(old_state),
628                    DOMString::from_static(new_state),
629                    source.as_deref(),
630                );
631                event.upcast::<Event>().fire(cx, this.upcast::<EventTarget>());
632
633                // TODO: Step 2.2. Set element's popover toggle task tracker to null.
634            }));
635
636        // TODO: Step 3. Set element's popover toggle task tracker to a struct with task set to the
637        // just-queued task and old state set to oldState.
638    }
639
640    /// <https://html.spec.whatwg.org/multipage/#hide-popover-algorithm>
641    pub(crate) fn hide_popover(
642        &self,
643        cx: &mut JSContext,
644        focus_previous_element: bool,
645        mut fire_events: bool,
646        throw_exceptions: bool,
647        source: Option<&HTMLElement>,
648    ) -> Fallible<()> {
649        let element = self.upcast::<Element>();
650
651        // Step 1. Let validityResult be the result of running check popover validity given element,
652        // true, and null. If this throws an exception, catch it, and let validityResult be that
653        // exception.
654        let validity_result = self.check_popover_validity(true, None);
655
656        // Step 2. If validityResult is not true:
657        if !matches!(validity_result, Ok(true)) {
658            // Step 2.1. If throwExceptions is true and validityResult is a DOMException, then throw
659            // validityResult.
660            if throw_exceptions && let Err(error) = validity_result {
661                return Err(error);
662            }
663
664            // Step 2.2. Return.
665            return Ok(());
666        }
667
668        // Step 3. Let document be element's node document.
669        let document = self.owner_document();
670        let overlay_handler = document.overlay_handler();
671
672        // Step 4. Let nestedHide be element's popover hiding.
673        let nested_hide = self.popover_hiding();
674
675        // Step 5. Set element's popover hiding to true.
676        self.set_popover_hiding(cx.no_gc(), true);
677
678        // Step 6. If nestedHide is true, then set fireEvents to false.
679        if nested_hide {
680            fire_events = false;
681        }
682
683        // Step 7. Increment document's hiding popover nesting count.
684        overlay_handler.increment_hiding_popover_nesting_count();
685
686        // Step 8. Let cleanupSteps be the following steps:
687        let cleanup_steps = |no_gc: &NoGC| {
688            // Step 8.1. If nestedHide is false, then set element's popover hiding to false.
689            if !nested_hide {
690                self.set_popover_hiding(no_gc, false);
691            }
692
693            // Step 8.2. Decrement document's hiding popover nesting count.
694            overlay_handler.decrement_hiding_popover_nesting_count();
695        };
696
697        // Step 9. Let autoPopoverListContainsElement be true if document's showing auto popover
698        // list contains element; otherwise false.
699        let auto_popover_list_contains_element =
700            overlay_handler.showing_popover_list_contains(cx.no_gc(), PopoverState::Auto, self);
701
702        // Step 10. Let hintPopoverListContainsElement be true if document's showing hint popover
703        // list contains element; otherwise false.
704        let hint_popover_list_contains_element =
705            overlay_handler.showing_popover_list_contains(cx.no_gc(), PopoverState::Hint, self);
706
707        // Step 11. If element's opened in popover mode is "auto" or "hint", then:
708        if matches!(
709            self.opened_in_popover_mode(),
710            Some(PopoverState::Auto) | Some(PopoverState::Hint)
711        ) {
712            // Step 11.1. If hintPopoverListContainsElement is true, then run hide popover stack
713            // until given document, element, Hint, focusPreviousElement, and fireEvents.
714            if hint_popover_list_contains_element {
715                overlay_handler.hide_popover_stack_until(
716                    cx,
717                    Some(self),
718                    PopoverState::Hint,
719                    focus_previous_element,
720                    fire_events,
721                );
722            }
723
724            // Step 11.2. If element is document's hint stack parent, then run hide popover stack
725            // until given document, null, Hint, focusPreviousElement, and fireEvents.
726            if overlay_handler.is_hint_stack_parent(self) {
727                overlay_handler.hide_popover_stack_until(
728                    cx,
729                    None,
730                    PopoverState::Hint,
731                    focus_previous_element,
732                    fire_events,
733                );
734            }
735
736            // Step 11.3. If autoPopoverListContainsElement is true, then run hide popover stack
737            // until given document, element, Auto, focusPreviousElement, and fireEvents.
738            if auto_popover_list_contains_element {
739                overlay_handler.hide_popover_stack_until(
740                    cx,
741                    Some(self),
742                    PopoverState::Auto,
743                    focus_previous_element,
744                    fire_events,
745                );
746            }
747
748            // Step 11.4. Set validityResult to the result of running check popover validity given
749            // element, true, and document. If this throws an exception, catch it, and set
750            // validityResult to that exception.
751            let validity_result = self.check_popover_validity(true, Some(&document));
752
753            // Step 11.5. If validityResult is not true:
754            if !matches!(validity_result, Ok(true)) {
755                // Step 11.5.1. Run cleanupSteps.
756                cleanup_steps(cx);
757
758                // Step 11.5.2. If throwExceptions is true and validityResult is a DOMException,
759                // then throw validityResult.
760                if throw_exceptions && let Err(error) = validity_result {
761                    return Err(error);
762                }
763
764                // Step 11.5.3. Return.
765                return Ok(());
766            }
767        }
768
769        // Step 12. If fireEvents is true:
770        if fire_events {
771            // Step 12.1. Fire an event named beforetoggle, using ToggleEvent, with the oldState
772            // attribute initialized to "open", the newState attribute initialized to "closed", and
773            // the source attribute set to source at element.
774            let event = ToggleEvent::new(
775                cx,
776                &self.owner_window(),
777                atom!("beforetoggle"),
778                EventBubbles::DoesNotBubble,
779                EventCancelable::NotCancelable,
780                DOMString::from_static("open"),
781                DOMString::from_static("closed"),
782                source.map(|source| source.upcast::<Element>()),
783            );
784            event
785                .upcast::<Event>()
786                .fire(cx, self.upcast::<EventTarget>());
787
788            // Step 12.2. Set validityResult to the result of running check popover validity given
789            // element, true, and document, catching any exceptions.
790            let validity_result = self.check_popover_validity(true, Some(&document));
791
792            // Step 12.2. If validityResult is not true:
793            if !matches!(validity_result, Ok(true)) {
794                // Step 12.2.1. Run cleanupSteps.
795                cleanup_steps(cx);
796
797                // Step 12.2.2. If throwExceptions is true and validityResult is a DOMException,
798                // then throw validityResult.
799                if throw_exceptions && let Err(error) = validity_result {
800                    return Err(error);
801                }
802
803                // Step 12.2.3. Return.
804                return Ok(());
805            }
806
807            // Step 12.4. Request an element to be removed from the top layer given element.
808            overlay_handler
809                .request_an_element_to_be_removed_from_the_top_layer(element, cx.no_gc());
810
811            // TODO: Step 12.5. Set element's implicit anchor element to null.
812        }
813        // Step 13. Otherwise, remove an element from the top layer immediately given element.
814        else {
815            overlay_handler.remove_an_element_from_the_top_layer_immediately(element, cx.no_gc());
816        }
817
818        // Step 14. Set element's popover trigger to null.
819        self.set_popover_trigger(cx.no_gc(), None);
820
821        // Step 15. Set element's opened in popover mode to null.
822        self.set_opened_in_popover_mode(cx.no_gc(), None);
823
824        // Step 16. Set element's popover visibility state to hidden.
825        element.set_popover_visibility_state_showing(cx.no_gc(), false);
826
827        // Step 17. If element is document's hint stack parent, or document's showing hint popover
828        // list is empty, then set document's hint stack parent to null.
829        if overlay_handler.is_hint_stack_parent(self) ||
830            overlay_handler
831                .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Hint)
832                .is_empty()
833        {
834            overlay_handler.set_hint_stack_parent(None);
835        }
836
837        // Step 18. If fireEvents is true, then queue a popover toggle event task given element,
838        // "open", "closed", and source.
839        if fire_events {
840            self.queue_a_popover_toggle_event_task("open", "closed", source);
841        }
842
843        // Step 19. Let previouslyFocusedElement be element's previously focused element.
844        // Step 20. If previouslyFocusedElement is not null, then:
845        if let Some(previously_focused_element) = self.previously_focused_element(cx.no_gc()) {
846            // Step 20.1. Set element's previously focused element to null.
847            self.set_previously_focused_element(None, cx.no_gc());
848
849            // Step 20.2. If focusPreviousElement is true and document's focused area of the
850            // document's DOM anchor is a shadow-including inclusive descendant of element, then
851            // run the focusing steps for previouslyFocusedElement; the viewport should not be
852            // scrolled by doing this step.
853            if focus_previous_element &&
854                document
855                    .focus_handler()
856                    .focused_area()
857                    .dom_anchor(&document)
858                    .inclusive_ancestors(ShadowIncluding::Yes)
859                    .any(|node| &*node == self.upcast::<Node>())
860            {
861                previously_focused_element
862                    .upcast::<Node>()
863                    .run_the_focusing_steps(cx, None, FocusTrigger::Script);
864            }
865        }
866
867        // Step 21. If element's popover close watcher is not null:
868        // Step 21.1. Destroy element's popover close watcher.
869        // Step 21.2. Set element's popover close watcher to null.
870        if let Some(close_watcher) = self.take_popover_close_watcher(cx.no_gc()) {
871            close_watcher.destroy(cx.no_gc());
872        }
873
874        // Step 22. Run cleanupSteps.
875        cleanup_steps(cx.no_gc());
876        Ok(())
877    }
878
879    /// <https://html.spec.whatwg.org/multipage/#popover-focusing-steps>
880    fn run_popover_focusing_steps(&self, cx: &mut JSContext) {
881        // TODO: Step 1. If the allow focus steps given subject's node document return false, then
882        // return.
883
884        // Step 2. If subject is a dialog element, then run the dialog focusing steps given subject
885        // and return.
886        if let Some(dialog) = self.downcast::<HTMLDialogElement>() {
887            dialog.run_dialog_focusing_steps(cx);
888            return;
889        }
890
891        // Step 3. If subject has the autofocus attribute, then let control be subject.
892        let node = self.upcast::<Node>();
893        rooted!(&in(cx) let control = if self.Autofocus() {
894            node.get_the_focusable_area(cx, FocusTrigger::Script)
895        }
896        // Step 4. Otherwise, let control be the autofocus delegate for subject given "other".
897        else {
898            node.autofocus_delegate(cx, FocusTrigger::Script)
899        });
900
901        // Step 5. If control is null, then return.
902        let Some(control) = &*control else {
903            return;
904        };
905
906        // Step 6. Run the focusing steps given control.
907        // FIXME: Use the focusing steps once they support a focusable area as an argument.
908        self.owner_document()
909            .focus_handler()
910            .focus(cx, control, FocusTrigger::Script);
911
912        // TODO: Step 7. Let topDocument be the active document of control's node document's
913        // node navigable's top-level traversable.
914        // TODO: Step 8. If control's node document's origin is not the same as the origin of
915        // topDocument, then return.
916        // TODO: Step 9. Empty topDocument's autofocus candidates.
917        // TODO: Step 10. Set topDocument's autofocus processed flag to true.
918    }
919
920    /// <https://html.spec.whatwg.org/multipage/#check-popover-validity>
921    pub(crate) fn check_popover_validity(
922        &self,
923        expected_to_be_showing: bool,
924        expected_document: Option<&Document>,
925    ) -> Fallible<bool> {
926        // Step 1. If element's popover attribute is in the No Popover state, then throw a
927        // "NotSupportedError" DOMException.
928        if self.popover_state() == NoPopover {
929            return Err(Error::NotSupported(Some(
930                "Element does not have a popover attribute.".into(),
931            )));
932        }
933
934        // Step 2. If any of the following are true:
935        // - expectedToBeShowing is true and element's popover visibility state is not showing; or
936        // - expectedToBeShowing is false and element's popover visibility state is not hidden,
937        // then return false.
938        let element = self.upcast::<Element>();
939        if expected_to_be_showing != element.popover_visibility_state_showing() {
940            return Ok(false);
941        }
942
943        // Step 3. If any of the following are true:
944        // - expectedToBeShowing is false and element is not connected;
945        // - expectedToBeShowing is false and element's node document is not fully active;
946        // - expectedDocument is not null and element's node document is not expectedDocument;
947        // - element is a dialog element and its is modal is set to true; or
948        // - element's fullscreen flag is set.
949        // then throw an "InvalidStateError" DOMException.
950        let document = self.owner_document();
951        if (!expected_to_be_showing &&
952            (!self.upcast::<Node>().is_connected() || !document.is_fully_active())) ||
953            expected_document.is_some_and(|expected| *expected != *document) ||
954            (self.is::<HTMLDialogElement>() && element.state().contains(ElementState::MODAL)) ||
955            element.state().contains(ElementState::FULLSCREEN)
956        {
957            return Err(Error::InvalidState(Some(
958                "Element is not in a valid state to show or hide a popover.".into(),
959            )));
960        }
961
962        // Step 4. Return true.
963        Ok(true)
964    }
965
966    /// <https://html.spec.whatwg.org/multipage/#popover-target-attribute-activation-behavior>
967    pub(crate) fn popover_target_attribute_activation_behavior(
968        &self,
969        cx: &mut JSContext,
970        event_target: &Node,
971    ) {
972        // 1. Let popover be node's popover target element.
973        let popover = self.popover_target_element(cx);
974
975        // 2. If popover is null, then return.
976        let Some(popover) = popover else {
977            return;
978        };
979
980        // 3. If eventTarget is a shadow-including inclusive descendant of popover and popover
981        // is a shadow-including descendant of node, then return.
982        let popover_node = popover.upcast::<Node>();
983        if popover_node.is_shadow_including_inclusive_ancestor_of(event_target) &&
984            self.upcast::<Node>()
985                .is_shadow_including_inclusive_ancestor_of(popover_node)
986        {
987            return;
988        }
989
990        let popover_showing = popover
991            .upcast::<Element>()
992            .popover_visibility_state_showing();
993        let popover_target_action = self
994            .upcast::<Element>()
995            .get_string_attribute(&local_name!("popovertargetaction"))
996            .to_ascii_lowercase();
997
998        // 4. If node's popovertargetaction attribute is in the show state and popover's popover
999        // visibility state is showing, then return.
1000        if popover_target_action == "show" && popover_showing {
1001            return;
1002        }
1003
1004        // 5. If node's popovertargetaction attribute is in the hide state and popover's popover
1005        // visibility state is hidden, then return.
1006        if popover_target_action == "hide" && !popover_showing {
1007            return;
1008        }
1009
1010        // 6. If popover's popover visibility state is showing, then run the hide popover algorithm
1011        // given popover, true, true, false, and node.
1012        if popover_showing {
1013            popover
1014                .hide_popover(cx, true, true, false, Some(self))
1015                .expect("This shouldn't fail in this codepath");
1016        }
1017        // 7. Otherwise:
1018        else {
1019            // 7.1. Let validity be the result of running check popover validity given popover,
1020            // false, and null. If this throws an exception, catch it, and let validity be false.
1021            let validity = popover.check_popover_validity(false, None);
1022
1023            // 7.2. If validity is true, then run show popover given popover, false, and node.
1024            if matches!(validity, Ok(true)) {
1025                popover
1026                    .show_popover(cx, false, Some(self))
1027                    .expect("This shouldn't fail in this codepath");
1028            }
1029        }
1030    }
1031
1032    /// <https://html.spec.whatwg.org/multipage/#popover-target-element>
1033    pub(crate) fn popover_target_element(
1034        &self,
1035        cx: &mut JSContext,
1036    ) -> Option<DomRoot<HTMLElement>> {
1037        // 1. If node is not a button, then return null.
1038        if !self.is_a_button() {
1039            return None;
1040        }
1041
1042        // 2. If node is disabled, then return null.
1043        if self.is_form_element_disabled(cx.no_gc()) {
1044            return None;
1045        }
1046
1047        // 3. If node has a form owner and node is a submit button, then return null.
1048        if self
1049            .downcast::<HTMLButtonElement>()
1050            .is_some_and(|button| button.form_owner().is_some() && button.is_submit_button()) ||
1051            self.downcast::<HTMLInputElement>()
1052                .is_some_and(|input| input.form_owner().is_some() && input.is_submit_button())
1053        {
1054            return None;
1055        }
1056
1057        // 4. Let popoverElement be the result of running node's get the popovertarget-associated element.
1058        let popover_target_value = self
1059            .upcast::<Element>()
1060            .get_attribute_string_value(&local_name!("popovertarget"))?
1061            .into();
1062
1063        let root_node = self
1064            .upcast::<Node>()
1065            .GetRootNode(&GetRootNodeOptions::empty());
1066
1067        let popover_element = if let Some(document) = root_node.downcast::<Document>() {
1068            document.GetElementById(cx, popover_target_value)
1069        } else if let Some(document_fragment) = root_node.downcast::<DocumentFragment>() {
1070            document_fragment.GetElementById(cx, popover_target_value)
1071        } else {
1072            unreachable!("Element must be in a document or document fragment")
1073        };
1074
1075        // 5. If popoverElement is null, then return null.
1076        let popover_element = DomRoot::downcast::<HTMLElement>(popover_element?)?;
1077
1078        // 6. If popoverElement's popover attribute is in the No Popover state, then return null.
1079        if popover_element.popover_state() == PopoverState::NoPopover {
1080            return None;
1081        }
1082
1083        // 7. Return popoverElement.
1084        Some(popover_element)
1085    }
1086
1087    /// <https://html.spec.whatwg.org/multipage/#get-the-popover-stack-position>
1088    pub(crate) fn popover_stack_position(&self, cx: &mut JSContext) -> usize {
1089        let document = self.upcast::<Element>().owner_document();
1090
1091        // Step 1. Let hintList be popover's node document's showing hint popover list.
1092        let hint_list = document
1093            .overlay_handler()
1094            .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Hint);
1095
1096        // Step 2. Let autoList be popover's node document's showing auto popover list.
1097        let auto_list = document
1098            .overlay_handler()
1099            .showing_popover_list_unrooted(cx.no_gc(), PopoverState::Auto);
1100
1101        // Step 3. If popover is in hintList, then return the index of popover in hintList + the
1102        // size of autoList + 1.
1103        if let Some(hint_list_index) = hint_list.iter().position(|popover| popover == self) {
1104            return hint_list_index + auto_list.len() + 1;
1105        }
1106
1107        // Step 4. If popover is in autoList, then return the index of popover in autoList + 1.
1108        if let Some(auto_list_index) = auto_list.iter().position(|popover| popover == self) {
1109            return auto_list_index + 1;
1110        }
1111
1112        // Step 5. Return 0.
1113        0
1114    }
1115
1116    /// <https://html.spec.whatwg.org/multipage/#concept-button>
1117    fn is_a_button(&self) -> bool {
1118        self.is::<HTMLButtonElement>() ||
1119            self.downcast::<HTMLInputElement>().is_some_and(|input| {
1120                matches!(
1121                    *input.input_type(),
1122                    InputType::Submit(_) |
1123                        InputType::Reset(_) |
1124                        InputType::Image(_) |
1125                        InputType::Button(_)
1126                )
1127            })
1128    }
1129
1130    pub(crate) fn opened_in_popover_mode(&self) -> Option<PopoverState> {
1131        self.upcast::<Element>()
1132            .rare_data()
1133            .as_ref()?
1134            .opened_in_popover_mode
1135    }
1136
1137    fn set_opened_in_popover_mode(&self, no_gc: &NoGC, mode: Option<PopoverState>) {
1138        self.upcast::<Element>()
1139            .ensure_rare_data(no_gc)
1140            .opened_in_popover_mode = mode;
1141    }
1142
1143    fn popover_trigger(&self) -> Option<DomRoot<HTMLElement>> {
1144        self.upcast::<Element>()
1145            .rare_data()
1146            .as_ref()?
1147            .popover_trigger
1148            .get()
1149    }
1150
1151    fn set_popover_trigger(&self, no_gc: &NoGC, trigger: Option<&HTMLElement>) {
1152        self.upcast::<Element>()
1153            .ensure_rare_data(no_gc)
1154            .popover_trigger
1155            .set(trigger);
1156    }
1157
1158    fn popover_hiding(&self) -> bool {
1159        self.upcast::<Element>()
1160            .rare_data()
1161            .as_ref()
1162            .is_some_and(|rare_data| rare_data.popover_hiding)
1163    }
1164
1165    fn set_popover_hiding(&self, no_gc: &NoGC, value: bool) {
1166        self.upcast::<Element>()
1167            .ensure_rare_data(no_gc)
1168            .popover_hiding = value;
1169    }
1170
1171    fn set_popover_close_watcher(&self, no_gc: &NoGC, close_watcher: Rc<InternalCloseWatcher>) {
1172        self.upcast::<Element>()
1173            .ensure_rare_data(no_gc)
1174            .popover_close_watcher
1175            .safe_borrow_mut(no_gc)
1176            .replace(close_watcher);
1177    }
1178
1179    fn take_popover_close_watcher(&self, no_gc: &NoGC) -> Option<Rc<InternalCloseWatcher>> {
1180        self.upcast::<Element>()
1181            .rare_data()
1182            .as_ref()?
1183            .popover_close_watcher
1184            .safe_borrow_mut(no_gc)
1185            .take()
1186    }
1187}
1188
1189impl HTMLElementMethods<crate::DomTypeHolder> for HTMLElement {
1190    /// <https://html.spec.whatwg.org/multipage/#the-style-attribute>
1191    fn Style(&self, cx: &mut JSContext) -> DomRoot<CSSStyleDeclaration> {
1192        self.style_decl.or_init(|| {
1193            let global = self.owner_window();
1194            CSSStyleDeclaration::new(
1195                cx,
1196                &global,
1197                CSSStyleOwner::Element(Dom::from_ref(self.upcast())),
1198                None,
1199                CSSModificationAccess::ReadWrite,
1200            )
1201        })
1202    }
1203
1204    // https://html.spec.whatwg.org/multipage/#attr-title
1205    make_getter!(Title, "title");
1206    // https://html.spec.whatwg.org/multipage/#attr-title
1207    make_setter!(SetTitle, "title");
1208
1209    // https://html.spec.whatwg.org/multipage/#attr-lang
1210    make_getter!(Lang, "lang");
1211    // https://html.spec.whatwg.org/multipage/#attr-lang
1212    make_setter!(SetLang, "lang");
1213
1214    // https://html.spec.whatwg.org/multipage/#the-dir-attribute
1215    make_enumerated_getter!(
1216        Dir,
1217        "dir",
1218        "ltr" | "rtl" | "auto",
1219        missing => "",
1220        invalid => ""
1221    );
1222
1223    // https://html.spec.whatwg.org/multipage/#the-dir-attribute
1224    make_setter!(SetDir, "dir");
1225
1226    // https://html.spec.whatwg.org/multipage/#dom-hidden
1227    make_bool_getter!(Hidden, "hidden");
1228    // https://html.spec.whatwg.org/multipage/#dom-hidden
1229    make_bool_setter!(SetHidden, "hidden");
1230
1231    // https://html.spec.whatwg.org/multipage/#the-inert-attribute
1232    make_bool_getter!(Inert, "inert");
1233    make_bool_setter!(SetInert, "inert");
1234
1235    // https://html.spec.whatwg.org/multipage/#globaleventhandlers
1236    global_event_handlers!(NoOnload);
1237
1238    /// <https://html.spec.whatwg.org/multipage/#dom-dataset>
1239    fn Dataset(&self, cx: &mut JSContext) -> DomRoot<DOMStringMap> {
1240        self.dataset
1241            .or_init(|| DOMStringMap::new(cx, self.upcast()))
1242    }
1243
1244    /// <https://html.spec.whatwg.org/multipage/#handler-onerror>
1245    fn GetOnerror(&self, cx: &mut JSContext) -> Option<RootedCallback<OnErrorEventHandlerNonNull>> {
1246        if self.is_body_or_frameset() {
1247            let document = self.owner_document();
1248            if document.has_browsing_context() {
1249                document.window().GetOnerror(cx)
1250            } else {
1251                None
1252            }
1253        } else {
1254            self.upcast::<EventTarget>()
1255                .get_event_handler_common(cx, "error")
1256        }
1257    }
1258
1259    /// <https://html.spec.whatwg.org/multipage/#handler-onerror>
1260    fn SetOnerror(
1261        &self,
1262        cx: &mut JSContext,
1263        listener: Option<RootedCallback<OnErrorEventHandlerNonNull>>,
1264    ) {
1265        if self.is_body_or_frameset() {
1266            let document = self.owner_document();
1267            if document.has_browsing_context() {
1268                document.window().SetOnerror(cx, listener)
1269            }
1270        } else {
1271            // special setter for error
1272            self.upcast::<EventTarget>()
1273                .set_error_event_handler(cx, "error", listener)
1274        }
1275    }
1276
1277    /// <https://html.spec.whatwg.org/multipage/#handler-onload>
1278    fn GetOnload(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1279        if self.is_body_or_frameset() {
1280            let document = self.owner_document();
1281            if document.has_browsing_context() {
1282                document.window().GetOnload(cx)
1283            } else {
1284                None
1285            }
1286        } else {
1287            self.upcast::<EventTarget>()
1288                .get_event_handler_common(cx, "load")
1289        }
1290    }
1291
1292    /// <https://html.spec.whatwg.org/multipage/#handler-onload>
1293    fn SetOnload(&self, cx: &mut JSContext, listener: Option<RootedCallback<EventHandlerNonNull>>) {
1294        if self.is_body_or_frameset() {
1295            let document = self.owner_document();
1296            if document.has_browsing_context() {
1297                document.window().SetOnload(cx, listener)
1298            }
1299        } else {
1300            self.upcast::<EventTarget>()
1301                .set_event_handler_common(cx, "load", listener)
1302        }
1303    }
1304
1305    /// <https://html.spec.whatwg.org/multipage/#handler-onblur>
1306    fn GetOnblur(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1307        if self.is_body_or_frameset() {
1308            let document = self.owner_document();
1309            if document.has_browsing_context() {
1310                document.window().GetOnblur(cx)
1311            } else {
1312                None
1313            }
1314        } else {
1315            self.upcast::<EventTarget>()
1316                .get_event_handler_common(cx, "blur")
1317        }
1318    }
1319
1320    /// <https://html.spec.whatwg.org/multipage/#handler-onblur>
1321    fn SetOnblur(&self, cx: &mut JSContext, listener: Option<RootedCallback<EventHandlerNonNull>>) {
1322        if self.is_body_or_frameset() {
1323            let document = self.owner_document();
1324            if document.has_browsing_context() {
1325                document.window().SetOnblur(cx, listener)
1326            }
1327        } else {
1328            self.upcast::<EventTarget>()
1329                .set_event_handler_common(cx, "blur", listener)
1330        }
1331    }
1332
1333    /// <https://html.spec.whatwg.org/multipage/#handler-onfocus>
1334    fn GetOnfocus(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1335        if self.is_body_or_frameset() {
1336            let document = self.owner_document();
1337            if document.has_browsing_context() {
1338                document.window().GetOnfocus(cx)
1339            } else {
1340                None
1341            }
1342        } else {
1343            self.upcast::<EventTarget>()
1344                .get_event_handler_common(cx, "focus")
1345        }
1346    }
1347
1348    /// <https://html.spec.whatwg.org/multipage/#handler-onfocus>
1349    fn SetOnfocus(
1350        &self,
1351        cx: &mut JSContext,
1352        listener: Option<RootedCallback<EventHandlerNonNull>>,
1353    ) {
1354        if self.is_body_or_frameset() {
1355            let document = self.owner_document();
1356            if document.has_browsing_context() {
1357                document.window().SetOnfocus(cx, listener)
1358            }
1359        } else {
1360            self.upcast::<EventTarget>()
1361                .set_event_handler_common(cx, "focus", listener)
1362        }
1363    }
1364
1365    /// <https://html.spec.whatwg.org/multipage/#handler-onresize>
1366    fn GetOnresize(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1367        if self.is_body_or_frameset() {
1368            let document = self.owner_document();
1369            if document.has_browsing_context() {
1370                document.window().GetOnresize(cx)
1371            } else {
1372                None
1373            }
1374        } else {
1375            self.upcast::<EventTarget>()
1376                .get_event_handler_common(cx, "resize")
1377        }
1378    }
1379
1380    /// <https://html.spec.whatwg.org/multipage/#handler-onresize>
1381    fn SetOnresize(
1382        &self,
1383        cx: &mut JSContext,
1384        listener: Option<RootedCallback<EventHandlerNonNull>>,
1385    ) {
1386        if self.is_body_or_frameset() {
1387            let document = self.owner_document();
1388            if document.has_browsing_context() {
1389                document.window().SetOnresize(cx, listener)
1390            }
1391        } else {
1392            self.upcast::<EventTarget>()
1393                .set_event_handler_common(cx, "resize", listener)
1394        }
1395    }
1396
1397    /// <https://html.spec.whatwg.org/multipage/#handler-onscroll>
1398    fn GetOnscroll(&self, cx: &mut JSContext) -> Option<RootedCallback<EventHandlerNonNull>> {
1399        if self.is_body_or_frameset() {
1400            let document = self.owner_document();
1401            if document.has_browsing_context() {
1402                document.window().GetOnscroll(cx)
1403            } else {
1404                None
1405            }
1406        } else {
1407            self.upcast::<EventTarget>()
1408                .get_event_handler_common(cx, "scroll")
1409        }
1410    }
1411
1412    /// <https://html.spec.whatwg.org/multipage/#handler-onscroll>
1413    fn SetOnscroll(
1414        &self,
1415        cx: &mut JSContext,
1416        listener: Option<RootedCallback<EventHandlerNonNull>>,
1417    ) {
1418        if self.is_body_or_frameset() {
1419            let document = self.owner_document();
1420            if document.has_browsing_context() {
1421                document.window().SetOnscroll(cx, listener)
1422            }
1423        } else {
1424            self.upcast::<EventTarget>()
1425                .set_event_handler_common(cx, "scroll", listener)
1426        }
1427    }
1428
1429    /// <https://html.spec.whatwg.org/multipage/#attr-itemtype>
1430    fn Itemtypes(&self) -> Option<Vec<DOMString>> {
1431        let atoms = self
1432            .element
1433            .get_tokenlist_attribute(&local_name!("itemtype"));
1434
1435        if atoms.is_empty() {
1436            return None;
1437        }
1438
1439        Some(
1440            FxHashSet::from_iter(
1441                atoms
1442                    .iter()
1443                    .map(|attr_value| DOMString::from(String::from(attr_value.trim()))),
1444            )
1445            .into_iter()
1446            .collect(),
1447        )
1448    }
1449
1450    /// <https://html.spec.whatwg.org/multipage/#names:-the-itemprop-attribute>
1451    fn PropertyNames(&self) -> Option<Vec<DOMString>> {
1452        let atoms = self
1453            .element
1454            .get_tokenlist_attribute(&local_name!("itemprop"));
1455
1456        if atoms.is_empty() {
1457            return None;
1458        }
1459
1460        Some(
1461            FxHashSet::from_iter(
1462                atoms
1463                    .iter()
1464                    .map(|attr_value| DOMString::from(String::from(attr_value.trim()))),
1465            )
1466            .into_iter()
1467            .collect(),
1468        )
1469    }
1470
1471    /// <https://html.spec.whatwg.org/multipage/#dom-click>
1472    fn Click(&self, cx: &mut JSContext) {
1473        // 1. If this element is a form control that is disabled, then return.
1474        if self.is_form_element_disabled(cx.no_gc()) {
1475            return;
1476        }
1477
1478        // 2. If this element's click in progress flag is set, then return.
1479        let element = self.as_element();
1480        if element.click_in_progress() {
1481            return;
1482        }
1483
1484        // 3. Set this element's click in progress flag.
1485        element.set_click_in_progress(true);
1486
1487        // 4. Fire a synthetic pointer event named click at this element, with the not trusted flag set.
1488        self.upcast::<Node>()
1489            .fire_synthetic_pointer_event_not_trusted(cx, atom!("click"));
1490
1491        // 5. Unset this element's click in progress flag.
1492        element.set_click_in_progress(false);
1493    }
1494
1495    /// <https://html.spec.whatwg.org/multipage/#dom-focus>
1496    fn Focus(&self, cx: &mut JSContext, options: &FocusOptions) {
1497        // 1. If the allow focus steps given this's node document return false, then return.
1498        // TODO: Implement this.
1499
1500        // 2. Run the focusing steps for this.
1501        if !self
1502            .upcast::<Node>()
1503            .run_the_focusing_steps(cx, None, FocusTrigger::Script)
1504        {
1505            // The specification seems to imply we should scroll into view even if this element
1506            // is not a focusable area. No browser does this, so we return early in that case.
1507            // See https://github.com/whatwg/html/issues/12231.
1508            return;
1509        }
1510
1511        // > 3. If options["focusVisible"] is true, or does not exist but in an
1512        // >    implementation-defined  way the user agent determines it would be best to do so,
1513        // >    then indicate focus. TODO: Implement this.
1514
1515        // > 4. If options["preventScroll"] is false, then scroll a target into view given this,
1516        // >    "auto", "center", and "center".
1517        if !options.preventScroll {
1518            let scroll_axis = ScrollAxisState {
1519                position: ScrollLogicalPosition::Center,
1520                requirement: ScrollRequirement::IfNotVisible,
1521            };
1522            self.upcast::<Element>().scroll_into_view_with_options(
1523                cx,
1524                ScrollBehavior::Smooth,
1525                scroll_axis,
1526                scroll_axis,
1527                None,
1528                None,
1529            );
1530        }
1531    }
1532
1533    /// <https://html.spec.whatwg.org/multipage/#dom-blur>
1534    fn Blur(&self, cx: &mut JSContext) {
1535        // TODO: Run the unfocusing steps. Focus the top-level document, not
1536        //       the current document.
1537        if !self.as_element().focus_state() {
1538            return;
1539        }
1540        // <https://html.spec.whatwg.org/multipage/#unfocusing-steps>
1541        self.owner_document().focus_handler().focus(
1542            cx,
1543            &FocusableArea::Viewport,
1544            FocusTrigger::Script,
1545        );
1546    }
1547
1548    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-scrollparent>
1549    #[expect(unsafe_code)]
1550    fn ScrollParent(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1551        self.owner_window()
1552            .scroll_container_query(
1553                Some(self.upcast()),
1554                ScrollContainerQueryFlags::ForScrollParent,
1555            )
1556            .and_then(|response| match response {
1557                ScrollContainerResponse::Viewport(..) => {
1558                    self.owner_document().GetScrollingElement(cx)
1559                },
1560                ScrollContainerResponse::Element(parent_node_address, ..) => {
1561                    let node = unsafe { from_untrusted_node_address(parent_node_address) };
1562                    DomRoot::downcast(node)
1563                },
1564            })
1565    }
1566
1567    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetparent>
1568    fn GetOffsetParent(&self, cx: &mut JSContext) -> Option<DomRoot<Element>> {
1569        if self.is::<HTMLBodyElement>() || self.element.is_root() {
1570            return None;
1571        }
1572
1573        let node = self.upcast::<Node>();
1574        let window = self.owner_window();
1575        let (element, _) = window.offset_parent_query(cx, node);
1576
1577        element
1578    }
1579
1580    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsettop>
1581    fn OffsetTop(&self, cx: &mut JSContext) -> i32 {
1582        if self.is_body_element() {
1583            return 0;
1584        }
1585
1586        let node = self.upcast::<Node>();
1587        let window = self.owner_window();
1588        let (_, rect) = window.offset_parent_query(cx, node);
1589
1590        rect.origin.y.to_nearest_px()
1591    }
1592
1593    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetleft>
1594    fn OffsetLeft(&self, cx: &mut JSContext) -> i32 {
1595        if self.is_body_element() {
1596            return 0;
1597        }
1598
1599        let node = self.upcast::<Node>();
1600        let window = self.owner_window();
1601        let (_, rect) = window.offset_parent_query(cx, node);
1602
1603        rect.origin.x.to_nearest_px()
1604    }
1605
1606    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetwidth>
1607    fn OffsetWidth(&self, cx: &mut JSContext) -> i32 {
1608        let node = self.upcast::<Node>();
1609        let window = self.owner_window();
1610        let (_, rect) = window.offset_parent_query(cx, node);
1611
1612        rect.size.width.to_nearest_px()
1613    }
1614
1615    /// <https://drafts.csswg.org/cssom-view/#dom-htmlelement-offsetheight>
1616    fn OffsetHeight(&self, cx: &mut JSContext) -> i32 {
1617        let node = self.upcast::<Node>();
1618        let window = self.owner_window();
1619        let (_, rect) = window.offset_parent_query(cx, node);
1620
1621        rect.size.height.to_nearest_px()
1622    }
1623
1624    /// <https://html.spec.whatwg.org/multipage/#the-innertext-idl-attribute>
1625    fn InnerText(&self, cx: &mut JSContext) -> DOMString {
1626        self.get_inner_outer_text(cx)
1627    }
1628
1629    /// <https://html.spec.whatwg.org/multipage/#set-the-inner-text-steps>
1630    fn SetInnerText(&self, cx: &mut JSContext, input: DOMString) {
1631        self.set_inner_text(cx, input)
1632    }
1633
1634    /// <https://html.spec.whatwg.org/multipage/#dom-outertext>
1635    fn GetOuterText(&self, cx: &mut JSContext) -> Fallible<DOMString> {
1636        Ok(self.get_inner_outer_text(cx))
1637    }
1638
1639    /// <https://html.spec.whatwg.org/multipage/#the-innertext-idl-attribute:dom-outertext-2>
1640    fn SetOuterText(&self, cx: &mut JSContext, input: DOMString) -> Fallible<()> {
1641        // Step 1: If this's parent is null, then throw a "NoModificationAllowedError" DOMException.
1642        let Some(parent) = self.upcast::<Node>().GetParentNode() else {
1643            return Err(Error::NoModificationAllowed(Some(
1644                "Cannot modify HTML element as its parent element is null".into(),
1645            )));
1646        };
1647
1648        let node = self.upcast::<Node>();
1649        let document = self.owner_document();
1650
1651        // Step 2: Let next be this's next sibling.
1652        let next = node.GetNextSibling();
1653
1654        // Step 3: Let previous be this's previous sibling.
1655        let previous = node.GetPreviousSibling();
1656
1657        // Step 4: Let fragment be the rendered text fragment for the given value given this's node
1658        // document.
1659        let fragment = self.rendered_text_fragment(cx, input);
1660
1661        // Step 5: If fragment has no children, then append a new Text node whose data is the empty
1662        // string and node document is this's node document to fragment.
1663        if fragment.upcast::<Node>().children_count() == 0 {
1664            let text_node = Text::new(cx, DOMString::new(), &document);
1665
1666            fragment
1667                .upcast::<Node>()
1668                .AppendChild(cx, text_node.upcast())?;
1669        }
1670
1671        // Step 6: Replace this with fragment within this's parent.
1672        parent.ReplaceChild(cx, fragment.upcast(), node)?;
1673
1674        // Step 7: If next is non-null and next's previous sibling is a Text node, then merge with
1675        // the next text node given next's previous sibling.
1676        if let Some(next_sibling) = next &&
1677            let Some(node) = next_sibling.GetPreviousSibling()
1678        {
1679            Self::merge_with_the_next_text_node(cx, &node);
1680        }
1681
1682        // Step 8: If previous is a Text node, then merge with the next text node given previous.
1683        if let Some(previous) = previous {
1684            Self::merge_with_the_next_text_node(cx, &previous)
1685        }
1686
1687        Ok(())
1688    }
1689
1690    /// <https://html.spec.whatwg.org/multipage/#dom-translate>
1691    fn Translate(&self) -> bool {
1692        self.as_element().is_translate_enabled()
1693    }
1694
1695    /// <https://html.spec.whatwg.org/multipage/#dom-translate>
1696    fn SetTranslate(&self, cx: &mut JSContext, yesno: bool) {
1697        self.as_element().set_string_attribute(
1698            cx,
1699            &html5ever::local_name!("translate"),
1700            match yesno {
1701                true => DOMString::from_static("yes"),
1702                false => DOMString::from_static("no"),
1703            },
1704        );
1705    }
1706
1707    // https://html.spec.whatwg.org/multipage/#dom-contenteditable
1708    make_enumerated_getter!(
1709        ContentEditable,
1710        "contenteditable",
1711        "true" | "false" | "plaintext-only",
1712        missing => "inherit",
1713        invalid => "inherit",
1714        empty => "true"
1715    );
1716
1717    /// <https://html.spec.whatwg.org/multipage/#dom-contenteditable>
1718    fn SetContentEditable(&self, cx: &mut JSContext, value: DOMString) -> ErrorResult {
1719        let attr_name = &local_name!("contenteditable");
1720        if value.eq_ignore_ascii_case("inherit") {
1721            // > On setting, if the new value is an ASCII case-insensitive match for the string "inherit", then the content attribute must be removed,
1722            self.element.remove_attribute_by_name(cx, attr_name);
1723        } else if value.eq_ignore_ascii_case("true") ||
1724            value.eq_ignore_ascii_case("false") ||
1725            value.eq_ignore_ascii_case("plaintext-only")
1726        {
1727            // > if the new value is an ASCII case-insensitive match for the string "true", then the content attribute must be set to the string "true",
1728            // > if the new value is an ASCII case-insensitive match for the string "plaintext-only", then the content attribute must be set to the string "plaintext-only",
1729            // > if the new value is an ASCII case-insensitive match for the string "false", then the content attribute must be set to the string "false",
1730            let lower_value = value.to_ascii_lowercase();
1731            self.element
1732                .set_attribute(cx, attr_name, AttrValue::String(lower_value));
1733        } else {
1734            // > and otherwise the attribute setter must throw a "SyntaxError" DOMException.
1735            return Err(Error::Syntax(Some(
1736                "Invalid attribute for HTML element".into(),
1737            )));
1738        };
1739        Ok(())
1740    }
1741
1742    /// <https://html.spec.whatwg.org/multipage/#dom-iscontenteditable>
1743    fn IsContentEditable(&self) -> bool {
1744        // > The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or editable, and false otherwise.
1745        self.upcast::<Node>().is_editable_or_editing_host()
1746    }
1747
1748    /// <https://html.spec.whatwg.org/multipage#dom-attachinternals>
1749    fn AttachInternals(&self, cx: &mut JSContext) -> Fallible<DomRoot<ElementInternals>> {
1750        // Step 1: If this's is value is not null, then throw a "NotSupportedError" DOMException
1751        if self.element.get_is().is_some() {
1752            return Err(Error::NotSupported(Some(
1753                "Local name of HTML element must not be set".into(),
1754            )));
1755        }
1756
1757        // Step 2: Let definition be the result of looking up a custom element definition
1758        let lookup_registry = {
1759            // TODO: Remove this fallback when Node::adopt is aligned according to specs.
1760            //       Currently elements carry stale global registry from another document.
1761            let registry = self.as_element().custom_element_registry();
1762            if registry
1763                .as_ref()
1764                .is_some_and(|registry| registry.is_scoped())
1765            {
1766                registry
1767            } else {
1768                self.upcast::<Node>().owner_doc().custom_element_registry()
1769            }
1770        };
1771        let definition = CustomElementRegistry::lookup_custom_element_definition(
1772            lookup_registry.as_deref(),
1773            self.upcast::<Element>().namespace(),
1774            self.as_element().local_name(),
1775            None,
1776        );
1777
1778        // Step 3: If definition is null, then throw an "NotSupportedError" DOMException
1779        let definition = match definition {
1780            Some(definition) => definition,
1781            None => {
1782                return Err(Error::NotSupported(Some(
1783                    "Custom element definition is missing".into(),
1784                )));
1785            },
1786        };
1787
1788        // Step 4: If definition's disable internals is true, then throw a "NotSupportedError" DOMException
1789        if definition.disable_internals {
1790            return Err(Error::NotSupported(Some(
1791                "Custom element definition's `disabledFeatures` must not include \"internals\""
1792                    .into(),
1793            )));
1794        }
1795
1796        // Step 5: If this's attached internals is non-null, then throw an "NotSupportedError" DOMException
1797        let internals = self.ensure_element_internals(cx);
1798        if internals.attached() {
1799            return Err(Error::NotSupported(Some(
1800                "HTML element's internals are already attached".into(),
1801            )));
1802        }
1803
1804        // Step 6: If this's custom element state is not "precustomized" or "custom",
1805        // then throw a "NotSupportedError" DOMException.
1806        if !matches!(
1807            self.element.get_custom_element_state(),
1808            CustomElementState::Precustomized | CustomElementState::Custom
1809        ) {
1810            return Err(Error::NotSupported(Some(
1811                "HTML element is not yet upgraded".into(),
1812            )));
1813        }
1814
1815        if self.is_form_associated_custom_element() {
1816            self.element.init_state_for_internals(cx.no_gc());
1817        }
1818
1819        // Step 6-7: Set this's attached internals to a new ElementInternals instance
1820        internals.set_attached();
1821        Ok(internals)
1822    }
1823
1824    /// <https://html.spec.whatwg.org/multipage/#dom-showpopover>
1825    fn ShowPopover(&self, cx: &mut JSContext, options: &ShowPopoverOptions) -> Fallible<()> {
1826        // Step 1. Let source be options["source"] if it exists; otherwise, null.
1827        // Step 2. Run show popover given this, true, and source.
1828        self.show_popover(cx, true, options.source.as_deref())
1829    }
1830
1831    /// <https://html.spec.whatwg.org/multipage/#dom-hidepopover>
1832    fn HidePopover(&self, cx: &mut JSContext) -> Fallible<()> {
1833        // 1. Run the hide popover algorithm given this, true, true, true, and null.
1834        self.hide_popover(cx, true, true, true, None)
1835    }
1836
1837    /// <https://html.spec.whatwg.org/multipage/#dom-togglepopover>
1838    fn TogglePopover(
1839        &self,
1840        cx: &mut JSContext,
1841        options: TogglePopoverOptionsOrBoolean,
1842    ) -> Fallible<bool> {
1843        // Step 1. Let force be null.
1844        let (force, source) = match &options {
1845            // Step 2. If options is a boolean, set force to options.
1846            TogglePopoverOptionsOrBoolean::Boolean(options) => (Some(*options), None),
1847            // Step 3. Otherwise, if options["force"] exists, set force to options["force"].
1848            // Step 4. Let source be options["source"] if it exists; otherwise, null.
1849            TogglePopoverOptionsOrBoolean::TogglePopoverOptions(options) => {
1850                (options.force, options.parent.source.as_deref())
1851            },
1852        };
1853
1854        // Step 5. If this's popover visibility state is showing, and force is null or false, then
1855        // run the hide popover algorithm given this, true, true, true, and null.
1856        if self.upcast::<Element>().popover_visibility_state_showing() &&
1857            force.is_none_or(|force| !force)
1858        {
1859            self.hide_popover(cx, true, true, true, None)?
1860        }
1861        // Step 6. Otherwise, if force is null or true, then run show popover given this, true, and source.
1862        else if force.is_none_or(|force| force) {
1863            self.show_popover(cx, true, source)?;
1864        }
1865        // Step 7. Otherwise:
1866        else {
1867            // Step 7.1. Let expectedToBeShowing be true if this's popover visibility state is
1868            // showing; otherwise false.
1869            let expected_to_be_showing =
1870                self.upcast::<Element>().popover_visibility_state_showing();
1871
1872            // Step 7.2. Run check popover validity given expectedToBeShowing, true, and null.
1873            self.check_popover_validity(expected_to_be_showing, None)?;
1874        }
1875
1876        // Step 8. Return true if this's popover visibility state is showing; otherwise false.
1877        Ok(self.upcast::<Element>().popover_visibility_state_showing())
1878    }
1879
1880    /// <https://html.spec.whatwg.org/multipage/#dom-popover>
1881    fn GetPopover(&self) -> Option<DOMString> {
1882        self.popover_state().reflect_attribute()
1883    }
1884
1885    // https://html.spec.whatwg.org/multipage/#dom-popover
1886    fn SetPopover(&self, cx: &mut JSContext, value: Option<DOMString>) {
1887        let element = self.upcast::<Element>();
1888        if let Some(value) = value {
1889            element.set_string_attribute(cx, &local_name!("popover"), value);
1890        } else {
1891            element.remove_attribute_by_name(cx, &local_name!("popover"));
1892        }
1893    }
1894
1895    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
1896    fn Nonce(&self) -> DOMString {
1897        self.as_element().nonce_value().into()
1898    }
1899
1900    /// <https://html.spec.whatwg.org/multipage/#dom-noncedelement-nonce>
1901    fn SetNonce(&self, cx: &mut JSContext, value: DOMString) {
1902        self.as_element()
1903            .update_nonce_internal_slot(String::from(value), cx.no_gc())
1904    }
1905
1906    /// <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
1907    fn Autofocus(&self) -> bool {
1908        self.element.has_attribute(&local_name!("autofocus"))
1909    }
1910
1911    /// <https://html.spec.whatwg.org/multipage/#dom-fe-autofocus>
1912    fn SetAutofocus(&self, cx: &mut JSContext, autofocus: bool) {
1913        self.element
1914            .set_bool_attribute(cx, &local_name!("autofocus"), autofocus);
1915    }
1916
1917    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
1918    fn TabIndex(&self) -> i32 {
1919        self.element.tab_index()
1920    }
1921
1922    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
1923    fn SetTabIndex(&self, cx: &mut JSContext, tab_index: i32) {
1924        self.element
1925            .set_attribute(cx, &local_name!("tabindex"), tab_index.into());
1926    }
1927
1928    // https://html.spec.whatwg.org/multipage/#dom-accesskey
1929    make_getter!(AccessKey, "accesskey");
1930
1931    // https://html.spec.whatwg.org/multipage/#dom-accesskey
1932    make_setter!(SetAccessKey, "accesskey");
1933
1934    /// <https://html.spec.whatwg.org/multipage/#dom-accesskeylabel>
1935    fn AccessKeyLabel(&self) -> DOMString {
1936        // The accessKeyLabel IDL attribute must return a string that represents the element's
1937        // assigned access key, if any. If the element does not have one, then the IDL attribute
1938        // must return the empty string.
1939        if !self.element.has_attribute(&local_name!("accesskey")) {
1940            return Default::default();
1941        }
1942
1943        let access_key_string =
1944            String::from(self.element.get_string_attribute(&local_name!("accesskey")));
1945
1946        #[cfg(target_os = "macos")]
1947        let access_key_label = format!("⌃⌥{access_key_string}");
1948        #[cfg(not(target_os = "macos"))]
1949        let access_key_label = format!("Alt+Shift+{access_key_string}");
1950
1951        access_key_label.into()
1952    }
1953}
1954
1955fn append_text_node_to_fragment(
1956    cx: &mut JSContext,
1957    document: &Document,
1958    fragment: &DocumentFragment,
1959    text: String,
1960) {
1961    let text = Text::new(cx, DOMString::from(text), document);
1962    fragment
1963        .upcast::<Node>()
1964        .AppendChild(cx, text.upcast())
1965        .unwrap();
1966}
1967
1968impl HTMLElement {
1969    /// <https://html.spec.whatwg.org/multipage/#category-label>
1970    pub(crate) fn is_labelable_element(&self) -> bool {
1971        match self.upcast::<Node>().type_id() {
1972            NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
1973                HTMLElementTypeId::HTMLInputElement => !matches!(
1974                    *self.downcast::<HTMLInputElement>().unwrap().input_type(),
1975                    InputType::Hidden(_)
1976                ),
1977                HTMLElementTypeId::HTMLButtonElement |
1978                HTMLElementTypeId::HTMLMeterElement |
1979                HTMLElementTypeId::HTMLOutputElement |
1980                HTMLElementTypeId::HTMLProgressElement |
1981                HTMLElementTypeId::HTMLSelectElement |
1982                HTMLElementTypeId::HTMLTextAreaElement => true,
1983                _ => self.is_form_associated_custom_element(),
1984            },
1985            _ => false,
1986        }
1987    }
1988
1989    /// <https://html.spec.whatwg.org/multipage/#form-associated-custom-element>
1990    pub(crate) fn is_form_associated_custom_element(&self) -> bool {
1991        if let Some(definition) = self.as_element().get_custom_element_definition() {
1992            definition.is_autonomous() && definition.form_associated
1993        } else {
1994            false
1995        }
1996    }
1997
1998    /// <https://html.spec.whatwg.org/multipage/#category-listed>
1999    pub(crate) fn is_listed_element(&self) -> bool {
2000        match self.upcast::<Node>().type_id() {
2001            NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
2002                HTMLElementTypeId::HTMLButtonElement |
2003                HTMLElementTypeId::HTMLFieldSetElement |
2004                HTMLElementTypeId::HTMLInputElement |
2005                HTMLElementTypeId::HTMLObjectElement |
2006                HTMLElementTypeId::HTMLOutputElement |
2007                HTMLElementTypeId::HTMLSelectElement |
2008                HTMLElementTypeId::HTMLTextAreaElement => true,
2009                _ => self.is_form_associated_custom_element(),
2010            },
2011            _ => false,
2012        }
2013    }
2014
2015    /// <https://html.spec.whatwg.org/multipage/#the-body-element-2>
2016    pub(crate) fn is_body_element(&self) -> bool {
2017        let self_node = self.upcast::<Node>();
2018        self_node.GetParentNode().is_some_and(|parent| {
2019            let parent_node = parent.upcast::<Node>();
2020            (self_node.is::<HTMLBodyElement>() || self_node.is::<HTMLFrameSetElement>()) &&
2021                parent_node.is::<HTMLHtmlElement>() &&
2022                self_node
2023                    .preceding_siblings()
2024                    .all(|n| !n.is::<HTMLBodyElement>() && !n.is::<HTMLFrameSetElement>())
2025        })
2026    }
2027
2028    /// <https://html.spec.whatwg.org/multipage/#category-submit>
2029    pub(crate) fn is_submittable_element(&self) -> bool {
2030        match self.upcast::<Node>().type_id() {
2031            NodeTypeId::Element(ElementTypeId::HTMLElement(type_id)) => match type_id {
2032                HTMLElementTypeId::HTMLButtonElement |
2033                HTMLElementTypeId::HTMLInputElement |
2034                HTMLElementTypeId::HTMLSelectElement |
2035                HTMLElementTypeId::HTMLTextAreaElement => true,
2036                _ => self.is_form_associated_custom_element(),
2037            },
2038            _ => false,
2039        }
2040    }
2041
2042    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
2043    // This gets the nth label in tree order.
2044    pub(crate) fn label_at<'a>(
2045        &self,
2046        no_gc: &'a NoGC,
2047        index: u32,
2048    ) -> Option<UnrootedDom<'a, Node>> {
2049        let element = self.as_element();
2050
2051        // Traverse entire tree for <label> elements that have
2052        // this as their control.
2053        // There is room for performance optimization, as we don't need
2054        // the actual result of GetControl, only whether the result
2055        // would match self.
2056        // (Even more room for performance optimization: do what
2057        // nodelist ChildrenList does and keep a mutation-aware cursor
2058        // around; this may be hard since labels need to keep working
2059        // even as they get detached into a subtree and reattached to
2060        // a document.)
2061        let root_element = element.root_element();
2062        let root_node = root_element.upcast::<Node>();
2063        root_node
2064            .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
2065            .filter_map(UnrootedDom::downcast::<HTMLLabelElement>)
2066            .filter(|elem| match elem.GetControl(no_gc) {
2067                Some(control) => &*control == self,
2068                _ => false,
2069            })
2070            .nth(index as usize)
2071            .map(UnrootedDom::upcast)
2072    }
2073
2074    // https://html.spec.whatwg.org/multipage/#dom-lfe-labels
2075    // This counts the labels of the element, to support NodeList::Length
2076    pub(crate) fn labels_count(&self, no_gc: &NoGC) -> u32 {
2077        // see label_at comments about performance
2078        let element = self.as_element();
2079        let root_element = element.root_element();
2080        let root_node = root_element.upcast::<Node>();
2081        root_node
2082            .traverse_preorder_unrooted(no_gc, ShadowIncluding::No)
2083            .filter_map(UnrootedDom::downcast::<HTMLLabelElement>)
2084            .filter(|elem| match elem.GetControl(no_gc) {
2085                Some(control) => &*control == self,
2086                _ => false,
2087            })
2088            .count() as u32
2089    }
2090
2091    // https://html.spec.whatwg.org/multipage/#the-directionality.
2092    // returns Some if can infer direction by itself or from child nodes
2093    // returns None if requires to go up to parent
2094    pub(crate) fn directionality(&self) -> Option<String> {
2095        let element_direction = &self.Dir();
2096
2097        if element_direction == "ltr" {
2098            return Some("ltr".to_owned());
2099        }
2100
2101        if element_direction == "rtl" {
2102            return Some("rtl".to_owned());
2103        }
2104
2105        if let Some(input) = self.downcast::<HTMLInputElement>() &&
2106            matches!(*input.input_type(), InputType::Tel(_))
2107        {
2108            return Some("ltr".to_owned());
2109        }
2110
2111        if element_direction == "auto" {
2112            if let Some(directionality) = self
2113                .downcast::<HTMLInputElement>()
2114                .and_then(|input| input.auto_directionality())
2115            {
2116                return Some(directionality);
2117            }
2118
2119            if let Some(area) = self.downcast::<HTMLTextAreaElement>() {
2120                return Some(area.auto_directionality());
2121            }
2122        }
2123
2124        // TODO(NeverHappened): Implement condition
2125        // If the element's dir attribute is in the auto state OR
2126        // If the element is a bdi element and the dir attribute is not in a defined state
2127        // (i.e. it is not present or has an invalid value)
2128        // Requires bdi element implementation (https://html.spec.whatwg.org/multipage/#the-bdi-element)
2129
2130        None
2131    }
2132
2133    /// <https://html.spec.whatwg.org/multipage/#the-summary-element:activation-behaviour>
2134    pub(crate) fn summary_activation_behavior(&self, cx: &mut js::context::JSContext) {
2135        debug_assert!(self.as_element().local_name() == &local_name!("summary"));
2136
2137        // Step 1. If this summary element is not the summary for its parent details, then return.
2138        let is_implicit_summary_element = self.is_implicit_summary_element();
2139        if !is_implicit_summary_element && !self.is_a_summary_for_its_parent_details() {
2140            return;
2141        }
2142
2143        // Step 2. Let parent be this summary element's parent.
2144        let parent = if is_implicit_summary_element {
2145            DomRoot::downcast::<HTMLDetailsElement>(self.containing_shadow_root().unwrap().Host())
2146                .unwrap()
2147        } else {
2148            self.upcast::<Node>()
2149                .GetParentNode()
2150                .and_then(DomRoot::downcast::<HTMLDetailsElement>)
2151                .unwrap()
2152        };
2153
2154        // Step 3. If the open attribute is present on parent, then remove it.
2155        // Otherwise, set parent's open attribute to the empty string.
2156        parent.toggle(cx);
2157    }
2158
2159    /// <https://html.spec.whatwg.org/multipage/#summary-for-its-parent-details>
2160    pub(crate) fn is_a_summary_for_its_parent_details(&self) -> bool {
2161        // Step 1. If this summary element has no parent, then return false.
2162        // Step 2. Let parent be this summary element's parent.
2163        let Some(parent) = self.upcast::<Node>().GetParentNode() else {
2164            return false;
2165        };
2166
2167        // Step 3. If parent is not a details element, then return false.
2168        let Some(details) = parent.downcast::<HTMLDetailsElement>() else {
2169            return false;
2170        };
2171
2172        // Step 4. If parent's first summary element child is not this summary
2173        // element, then return false.
2174        // Step 5. Return true.
2175        details
2176            .find_corresponding_summary_element()
2177            .is_some_and(|summary| &*summary == self.upcast())
2178    }
2179
2180    /// Whether or not this is an implicitly generated `<summary>`
2181    /// element for a UA `<details>` shadow tree
2182    fn is_implicit_summary_element(&self) -> bool {
2183        // Note that non-implicit summary elements are not actually inside
2184        // the UA shadow tree, they're only assigned to a slot inside it.
2185        // Therefore they don't cause false positives here
2186        self.containing_shadow_root()
2187            .as_deref()
2188            .map(ShadowRoot::Host)
2189            .is_some_and(|host| host.is::<HTMLDetailsElement>())
2190    }
2191
2192    /// <https://html.spec.whatwg.org/multipage/#rendered-text-fragment>
2193    fn rendered_text_fragment(
2194        &self,
2195        cx: &mut JSContext,
2196        input: DOMString,
2197    ) -> DomRoot<DocumentFragment> {
2198        // Step 1: Let fragment be a new DocumentFragment whose node document is document.
2199        let document = self.owner_document();
2200        let fragment = DocumentFragment::new(cx, &document);
2201
2202        // Step 2: Let position be a position variable for input, initially pointing at the start
2203        // of input.
2204        let input = input.str();
2205        let mut position = input.chars().peekable();
2206
2207        // Step 3: Let text be the empty string.
2208        let mut text = String::new();
2209
2210        // Step 4
2211        while let Some(ch) = position.next() {
2212            match ch {
2213                // While position is not past the end of input, and the code point at position is
2214                // either U+000A LF or U+000D CR:
2215                '\u{000A}' | '\u{000D}' => {
2216                    if ch == '\u{000D}' && position.peek() == Some(&'\u{000A}') {
2217                        // a \r\n pair should only generate one <br>,
2218                        // so just skip the \r.
2219                        position.next();
2220                    }
2221
2222                    if !text.is_empty() {
2223                        append_text_node_to_fragment(cx, &document, &fragment, text);
2224                        text = String::new();
2225                    }
2226
2227                    let br = Element::create(
2228                        cx,
2229                        QualName::new(None, ns!(html), local_name!("br")),
2230                        None,
2231                        &document,
2232                        ElementCreator::ScriptCreated,
2233                        CustomElementCreationMode::Asynchronous,
2234                        None,
2235                    );
2236                    fragment
2237                        .upcast::<Node>()
2238                        .AppendChild(cx, br.upcast())
2239                        .unwrap();
2240                },
2241                _ => {
2242                    // Collect a sequence of code points that are not U+000A LF or U+000D CR from
2243                    // input given position, and set text to the result.
2244                    text.push(ch);
2245                },
2246            }
2247        }
2248
2249        // If text is not the empty string, then append a new Text node whose data is text and node
2250        // document is document to fragment.
2251        if !text.is_empty() {
2252            append_text_node_to_fragment(cx, &document, &fragment, text);
2253        }
2254
2255        fragment
2256    }
2257
2258    /// Checks whether a given [`DomRoot<Node>`] and its next sibling are
2259    /// of type [`Text`], and if so merges them into a single [`Text`]
2260    /// node.
2261    ///
2262    /// <https://html.spec.whatwg.org/multipage/#merge-with-the-next-text-node>
2263    fn merge_with_the_next_text_node(cx: &mut JSContext, node: &Node) {
2264        // Make sure node is a Text node
2265        if !node.is::<Text>() {
2266            return;
2267        }
2268
2269        // Step 1: Let next be node's next sibling.
2270        let next = match node.GetNextSibling() {
2271            Some(next) => next,
2272            None => return,
2273        };
2274
2275        // Step 2: If next is not a Text node, then return.
2276        if !next.is::<Text>() {
2277            return;
2278        }
2279        // Step 3: Replace data with node, node's data's length, 0, and next's data.
2280        let node_chars = node.downcast::<CharacterData>().expect("Node is Text");
2281        let next_chars = next.downcast::<CharacterData>().expect("Next node is Text");
2282        node_chars
2283            .ReplaceData(cx, node_chars.Length(), 0, next_chars.Data())
2284            .expect("Got chars from Text");
2285
2286        // Step 4:Remove next.
2287        next.remove_self(cx);
2288    }
2289
2290    /// <https://html.spec.whatwg.org/multipage/#keyboard-shortcuts-processing-model>
2291    /// > Whenever an element's accesskey attribute is set, changed, or removed, the user agent must
2292    /// > update the element's assigned access key by running the following steps:
2293    fn update_assigned_access_key(&self) {
2294        // 1. If the element has no accesskey attribute, then skip to the fallback step below.
2295        if !self.element.has_attribute(&local_name!("accesskey")) {
2296            // This is the same as steps 4 and 5 below.
2297            self.owner_document()
2298                .event_handler()
2299                .unassign_access_key(self);
2300        }
2301
2302        // 2. Otherwise, split the attribute's value on ASCII whitespace, and let keys be the resulting tokens.
2303        let attribute_value = self.element.get_string_attribute(&local_name!("accesskey"));
2304        let string_view = attribute_value.str();
2305        let values = string_view.split_html_space_characters();
2306
2307        // 3. For each value in keys in turn, in the order the tokens appeared in the attribute's
2308        //    value, run the following substeps:
2309        for value in values {
2310            // 1. If the value is not a string exactly one code point in length, then skip the
2311            //    remainder of these steps for this value.
2312            let mut characters = value.chars();
2313            let Some(character) = characters.next() else {
2314                continue;
2315            };
2316            if characters.count() > 0 {
2317                continue;
2318            }
2319
2320            // 2. If the value does not correspond to a key on the system's keyboard, then skip the
2321            //    remainder of these steps for this value.
2322            let Some(code) = character_to_code(character) else {
2323                continue;
2324            };
2325
2326            // 3. If the user agent can find a mix of zero or more modifier keys that, combined with
2327            //    the key that corresponds to the value given in the attribute, can be used as the
2328            //    access key, then the user agent may assign that combination of keys as the element's
2329            //    assigned access key and return.
2330            self.owner_document()
2331                .event_handler()
2332                .assign_access_key(self, code);
2333            return;
2334        }
2335
2336        // 4. Fallback: Optionally, the user agent may assign a key combination of its choosing as
2337        //    the element's assigned access key and then return.
2338        // We do not do this.
2339
2340        // 5. If this step is reached, the element has no assigned access key.
2341        self.owner_document()
2342            .event_handler()
2343            .unassign_access_key(self);
2344    }
2345}
2346
2347impl VirtualMethods for HTMLElement {
2348    fn super_type(&self) -> Option<&dyn VirtualMethods> {
2349        Some(self.as_element() as &dyn VirtualMethods)
2350    }
2351
2352    fn attribute_mutated(
2353        &self,
2354        cx: &mut JSContext,
2355        attr: AttrRef<'_>,
2356        mutation: AttributeMutation,
2357    ) {
2358        self.super_type()
2359            .unwrap()
2360            .attribute_mutated(cx, attr, mutation);
2361        let element = self.as_element();
2362        match (attr.local_name(), mutation) {
2363            (&local_name!("accesskey"), ..) => {
2364                self.update_assigned_access_key();
2365            },
2366            // https://html.spec.whatwg.org/multipage/#the-popover-attribute
2367            (&local_name!("popover"), mutation) => {
2368                // > If element's popover visibility state is in the showing state and oldValue and
2369                // > value are in different states, then run the hide popover algorithm given
2370                // > element, true, true, false, and null.
2371                let old_state = PopoverState::from_attribute_value(mutation.old_value(attr));
2372                if element.popover_visibility_state_showing() && old_state != self.popover_state() {
2373                    let _ = self.hide_popover(cx, true, true, false, None);
2374                }
2375            },
2376            // <https://html.spec.whatwg.org/multipage/#the-inert-attribute>
2377            (&local_name!("inert"), mutation) => {
2378                // https://html.spec.whatwg.org/multipage/#blocked-by-a-modal-dialog
2379                // > While document is so blocked, every node that is connected to document, with the
2380                // > exception of the subject element and its flat tree descendants, must become inert.
2381                let is_blocked_document = element.is_document_element() &&
2382                    element
2383                        .owner_document()
2384                        .overlay_handler()
2385                        .is_blocked_by_a_modal_dialog();
2386
2387                element.set_state(
2388                    cx.no_gc(),
2389                    ElementState::INERT,
2390                    is_blocked_document || !matches!(mutation, AttributeMutation::Removed),
2391                );
2392            },
2393            (&local_name!("form"), mutation) if self.is_form_associated_custom_element() => {
2394                self.form_attribute_mutated(cx, mutation);
2395            },
2396            // Adding or removing a "contenteditable" attribute might make a 0-size selection
2397            // render its caret or not.
2398            (&local_name!("contenteditable"), ..) => {
2399                if let Some(selection) = self.owner_document().selection() &&
2400                    self.upcast::<Node>()
2401                        .get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION)
2402                {
2403                    selection.set_visible_selection_dirty();
2404                }
2405            },
2406            (&local_name!("disabled"), _) => {
2407                element.invalidate_disabled_state(cx);
2408            },
2409            (&local_name!("readonly"), mutation) if self.is_form_associated_custom_element() => {
2410                match mutation {
2411                    AttributeMutation::Set(_) => {
2412                        element.set_read_write_state(cx.no_gc(), true);
2413                    },
2414                    AttributeMutation::Removed => {
2415                        element.set_read_write_state(cx.no_gc(), false);
2416                    },
2417                }
2418            },
2419            (&local_name!("nonce"), mutation) => match mutation {
2420                AttributeMutation::Set(_) => {
2421                    let nonce = &**attr.value();
2422                    element.update_nonce_internal_slot(nonce.to_owned(), cx.no_gc());
2423                },
2424                AttributeMutation::Removed => {
2425                    element.update_nonce_internal_slot(String::new(), cx.no_gc());
2426                },
2427            },
2428            // containertiming is not in html5ever, so for now we check manually
2429            // Layout records these attributes as fragment flags when it builds this element's
2430            // boxes, so the boxes have to be rebuilt when they change.
2431            (name, _) if &**name == "containertiming" || &**name == "containertimingignore" => {
2432                self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
2433            },
2434            _ => {},
2435        }
2436    }
2437
2438    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
2439        if let Some(super_type) = self.super_type() {
2440            super_type.bind_to_tree(cx, context);
2441        }
2442        self.element.invalidate_disabled_state(cx);
2443        if self.element.has_attribute(&local_name!("accesskey")) {
2444            self.update_assigned_access_key();
2445        }
2446    }
2447
2448    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
2449        if let Some(super_type) = self.super_type() {
2450            super_type.unbind_from_tree(cx, context);
2451        }
2452        self.element.invalidate_disabled_state(cx);
2453        if self.as_element().has_attribute(&local_name!("accesskey")) {
2454            self.owner_document()
2455                .event_handler()
2456                .unassign_access_key(self);
2457        }
2458
2459        // https://html.spec.whatwg.org/multipage/#dom-trees
2460        // > If removedNode's popover attribute is not in the No Popover state, then run the hide
2461        // > popover algorithm given removedNode, false, false, false, and null.
2462        if self.popover_state() != PopoverState::NoPopover {
2463            let _ = self.hide_popover(cx, false, false, false, None);
2464        }
2465    }
2466
2467    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
2468        if is_element_affected_by_legacy_background_presentational_hint(
2469            self.element.namespace(),
2470            self.element.local_name(),
2471        ) && attr.local_name() == &local_name!("background")
2472        {
2473            return true;
2474        }
2475
2476        self.super_type()
2477            .unwrap()
2478            .attribute_affects_presentational_hints(attr)
2479    }
2480
2481    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
2482        match *name {
2483            local_name!("itemprop") => AttrValue::from_serialized_tokenlist(value.into()),
2484            local_name!("itemtype") => AttrValue::from_serialized_tokenlist(value.into()),
2485            local_name!("background")
2486                if is_element_affected_by_legacy_background_presentational_hint(
2487                    self.element.namespace(),
2488                    self.element.local_name(),
2489                ) =>
2490            {
2491                AttrValue::from_resolved_url(
2492                    &self.owner_document().base_url().get_arc(),
2493                    value.into(),
2494                )
2495            },
2496            _ => self
2497                .super_type()
2498                .unwrap()
2499                .parse_plain_attribute(name, value),
2500        }
2501    }
2502
2503    /// <https://html.spec.whatwg.org/multipage/#dom-trees:html-element-moving-steps>
2504    fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
2505        // Step 1. If movedNode is an element whose namespace is the HTML namespace, and this
2506        // standard defines HTML element moving steps for movedNode's local name, then run the
2507        // corresponding HTML element moving steps given movedNode.
2508        if let Some(super_type) = self.super_type() {
2509            super_type.moving_steps(cx, context);
2510        }
2511
2512        // Step 2. If movedNode is a form-associated element with a non-null form owner and
2513        // movedNode and its form owner are no longer in the same tree, then reset the form owner of
2514        // movedNode.
2515        if let Some(form_control) = self.element.as_maybe_form_control() {
2516            form_control.moving_steps(cx);
2517        }
2518
2519        self.element.invalidate_disabled_state(cx);
2520    }
2521}
2522
2523impl Activatable for HTMLElement {
2524    fn as_element(&self) -> &Element {
2525        &self.element
2526    }
2527
2528    fn is_instance_activatable(&self) -> bool {
2529        self.element.local_name() == &local_name!("summary")
2530    }
2531
2532    // Basically used to make the HTMLSummaryElement activatable (which has no IDL definition)
2533    fn activation_behavior(
2534        &self,
2535        cx: &mut js::context::JSContext,
2536        _event: &Event,
2537        _target: &EventTarget,
2538    ) {
2539        self.summary_activation_behavior(cx);
2540    }
2541}
2542
2543// Form-associated custom elements are the same interface type as
2544// normal HTMLElements, so HTMLElement needs to have the FormControl trait
2545// even though it's usually more specific trait implementations, like the
2546// HTMLInputElement one, that we really want. (Alternately we could put
2547// the FormControl trait on ElementInternals, but that raises lifetime issues.)
2548impl FormControl for HTMLElement {
2549    fn form_owner(&self) -> Option<DomRoot<HTMLFormElement>> {
2550        debug_assert!(self.is_form_associated_custom_element());
2551        self.element
2552            .get_element_internals()
2553            .and_then(|e| e.form_owner())
2554    }
2555
2556    fn set_form_owner(&self, cx: &mut JSContext, form: Option<&HTMLFormElement>) {
2557        debug_assert!(self.is_form_associated_custom_element());
2558        self.ensure_element_internals(cx).set_form_owner(form);
2559    }
2560
2561    fn to_html_element(&self) -> &HTMLElement {
2562        self
2563    }
2564}