Skip to main content

script/dom/element/
element.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Element nodes.
6
7#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
8
9use std::borrow::Cow;
10use std::cell::{Cell, LazyCell, RefCell};
11use std::default::Default;
12use std::rc::Rc;
13use std::str::FromStr;
14use std::sync::atomic::{AtomicUsize, Ordering};
15use std::{fmt, mem};
16
17use app_units::Au;
18use atomic_refcell::{AtomicRef, AtomicRefCell};
19use cssparser::match_ignore_ascii_case;
20use dom_struct::dom_struct;
21use embedder_traits::EmbedderMsg;
22use euclid::Rect;
23use hashlink::LruCache;
24use html5ever::serialize::TraversalScope;
25use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode};
26use html5ever::{LocalName, Namespace, Prefix, QualName, local_name, namespace_prefix, ns};
27use js::context::{JSContext, NoGC};
28use js::jsapi::{Heap, JSObject};
29use js::jsval::JSVal;
30use js::realm::CurrentRealm;
31use js::rust::HandleObject;
32use layout_api::{
33    ACCESSKIT_ROLE_TO_ARIA_ROLE, AccessibilityDamage, LayoutDamage, QueryMsg,
34    ScrollContainerQueryFlags, StyleData, with_layout_state,
35};
36use net_traits::ReferrerPolicy;
37use net_traits::request::{CorsSettings, CredentialsMode};
38use rustc_hash::FxBuildHasher;
39use script_bindings::callback::RootedCallback;
40use script_bindings::cell::{DomRefCell, Ref, RefMut};
41use script_bindings::codegen::GenericBindings::AnimationBinding::AnimationMethods;
42use script_bindings::codegen::GenericBindings::KeyframeEffectBinding::KeyframeEffectMethods;
43use script_bindings::dom::UnrootedDom;
44use script_bindings::domstring::TracedDOMString;
45use script_bindings::reflector::DomObject;
46use selectors::attr::CaseSensitivity;
47use selectors::matching::ElementSelectorFlags;
48use selectors::sink::Push;
49use servo_arc::{Arc as ServoArc, ArcBorrow as ServoArcBorrow};
50use style::applicable_declarations::ApplicableDeclarationBlock;
51use style::attr::{AttrValue, LengthOrPercentageOrAuto};
52use style::context::QuirksMode;
53use style::invalidation::element::restyle_hints::RestyleHint;
54use style::properties::longhands::{
55    self, background_image, border_spacing, font_family, font_size,
56};
57use style::properties::{
58    ComputedValues, Importance, PropertyDeclaration, PropertyDeclarationBlock,
59    parse_style_attribute,
60};
61use style::rule_tree::{CascadeLevel, CascadeOrigin, StyleSourceBorrow};
62use style::selector_parser::{RestyleDamage, SelectorParser, Snapshot};
63use style::shared_lock::Locked;
64use style::str::string_as_ascii_lowercase;
65use style::stylesheets::layer_rule::LayerOrder;
66use style::stylesheets::{CssRuleType, UrlExtraData};
67use style::values::computed::{Overflow, UserSelect};
68use style::values::generics::NonNegative;
69use style::values::generics::position::PreferredRatio;
70use style::values::generics::ratio::Ratio;
71use style::values::{AtomIdent, AtomString, computed, specified};
72use style::{ArcSlice, CaseSensitivityExt, dom_apis, thread_state};
73use style_traits::CSSPixel;
74use stylo_atoms::Atom;
75use stylo_dom::ElementState;
76use xml5ever::serialize::TraversalScope::{
77    ChildrenOnly as XmlChildrenOnly, IncludeNode as XmlIncludeNode,
78};
79
80use crate::conversions::Convert;
81use crate::css::stylesheet_loader::StylesheetOwner;
82use crate::dom::accessors::AttrStrRef;
83use crate::dom::activation::Activatable;
84use crate::dom::animation::Animation;
85use crate::dom::animations::keyframeeffect::KeyframeEffect;
86use crate::dom::attr::{Attr, is_relevant_attribute};
87use crate::dom::bindings::cell::AtomicSafeBorrowMut;
88use crate::dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
89use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
90use crate::dom::bindings::codegen::Bindings::ElementBinding::{
91    ElementMethods, FullscreenOptions, GetHTMLOptions, ScrollIntoViewContainer,
92    ScrollLogicalPosition, ShadowRootInit,
93};
94use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
95use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function;
96use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods;
97use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
98use crate::dom::bindings::codegen::Bindings::SanitizerBinding::{
99    SetHTMLOptions, SetHTMLUnsafeOptions,
100};
101use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
102    ShadowRootMethods, ShadowRootMode, SlotAssignmentMode,
103};
104use crate::dom::bindings::codegen::Bindings::WindowBinding::{
105    ScrollBehavior, ScrollToOptions, WindowMethods,
106};
107use crate::dom::bindings::codegen::UnionTypes::{
108    BooleanOrScrollIntoViewOptions, NodeOrString, TrustedHTMLOrNullIsEmptyString,
109    TrustedHTMLOrString,
110    TrustedHTMLOrTrustedScriptOrTrustedScriptURLOrString as TrustedTypeOrString,
111    UnrestrictedDoubleOrKeyframeAnimationOptions, UnrestrictedDoubleOrKeyframeEffectOptions,
112};
113use crate::dom::bindings::conversions::DerivedFrom;
114use crate::dom::bindings::domname::{
115    self, is_valid_attribute_local_name, namespace_from_domstring,
116};
117use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
118use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
119use crate::dom::bindings::num::Finite;
120use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
121use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, ToLayout};
122use crate::dom::bindings::str::DOMString;
123use crate::dom::csp::{CspReporting, InlineCheckType, SourcePosition};
124use crate::dom::customelementregistry::{
125    CallbackReaction, CustomElementDefinition, CustomElementReaction, CustomElementRegistry,
126    CustomElementState, is_valid_custom_element_name,
127};
128use crate::dom::document::Document;
129use crate::dom::document::focus::FocusableArea;
130use crate::dom::documentfragment::DocumentFragment;
131use crate::dom::domrect::DOMRect;
132use crate::dom::domrectlist::DOMRectList;
133use crate::dom::domtokenlist::DOMTokenList;
134use crate::dom::element::attributes::storage::{
135    AttrName, AttrRef, AttrValueRef, AttributeEntry, AttributeStorage, ContentAttributeData,
136};
137use crate::dom::element::create::create_element;
138use crate::dom::eventtarget::EventTarget;
139use crate::dom::globalscope::GlobalScope;
140use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement;
141use crate::dom::html::htmlanchorelement::HTMLAnchorElement;
142use crate::dom::html::htmlareaelement::HTMLAreaElement;
143use crate::dom::html::htmlbodyelement::HTMLBodyElement;
144use crate::dom::html::htmlbuttonelement::HTMLButtonElement;
145use crate::dom::html::htmlcollection::HTMLCollection;
146use crate::dom::html::htmlelement::{HTMLElement, PopoverState};
147use crate::dom::html::htmlembedelement::HTMLEmbedElement;
148use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement;
149use crate::dom::html::htmlfontelement::HTMLFontElement;
150use crate::dom::html::htmlformelement::FormControlElementHelpers;
151use crate::dom::html::htmlhrelement::{HTMLHRElement, SizePresentationalHint};
152use crate::dom::html::htmliframeelement::HTMLIFrameElement;
153use crate::dom::html::htmlimageelement::HTMLImageElement;
154use crate::dom::html::htmllabelelement::HTMLLabelElement;
155use crate::dom::html::htmllegendelement::HTMLLegendElement;
156use crate::dom::html::htmllinkelement::HTMLLinkElement;
157use crate::dom::html::htmlmarqueeelement::HTMLMarqueeElement;
158use crate::dom::html::htmlobjectelement::HTMLObjectElement;
159use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement;
160use crate::dom::html::htmloptionelement::HTMLOptionElement;
161use crate::dom::html::htmloutputelement::HTMLOutputElement;
162use crate::dom::html::htmlscriptelement::HTMLScriptElement;
163use crate::dom::html::htmlselectelement::HTMLSelectElement;
164use crate::dom::html::htmlslotelement::{HTMLSlotElement, Slottable};
165use crate::dom::html::htmlstyleelement::HTMLStyleElement;
166use crate::dom::html::htmltablecellelement::HTMLTableCellElement;
167use crate::dom::html::htmltablecolelement::HTMLTableColElement;
168use crate::dom::html::htmltableelement::HTMLTableElement;
169use crate::dom::html::htmltablerowelement::HTMLTableRowElement;
170use crate::dom::html::htmltablesectionelement::HTMLTableSectionElement;
171use crate::dom::html::htmltemplateelement::HTMLTemplateElement;
172use crate::dom::html::htmltextareaelement::HTMLTextAreaElement;
173use crate::dom::html::htmlvideoelement::HTMLVideoElement;
174use crate::dom::html::interactive::htmldialogelement::HTMLDialogElement;
175use crate::dom::html::internals::elementinternals::ElementInternals;
176use crate::dom::intersectionobserver::{IntersectionObserver, IntersectionObserverRegistration};
177use crate::dom::iterators::ShadowIncluding;
178use crate::dom::mathmlelement::MathMLElement;
179use crate::dom::mutationobserver::{Mutation, MutationObserver};
180use crate::dom::namednodemap::NamedNodeMap;
181use crate::dom::node::virtualmethods::{VirtualMethods, vtable_for};
182use crate::dom::node::{
183    BindContext, ChildrenMutation, CloneChildrenFlag, IsShadowTree, MoveContext, Node, NodeDamage,
184    NodeFlags, NodeTraits, UnbindContext,
185};
186use crate::dom::nodelist::NodeList;
187use crate::dom::range::Range;
188use crate::dom::raredata::ElementRareData;
189use crate::dom::sanitizer::Sanitizer;
190use crate::dom::servoparser::ServoParser;
191use crate::dom::shadowroot::shadowroot::{IsUserAgentWidget, ShadowRoot};
192use crate::dom::svg::svgelement::SVGElement;
193use crate::dom::text::Text;
194use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
195use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
196use crate::dom::validation::Validatable;
197use crate::dom::validitystate::ValidationFlags;
198use crate::dom::window::Window;
199use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollingBox};
200use crate::dom::{Promise, RootedPromise};
201use crate::event_loop::script_thread::ScriptThread;
202use crate::layout_dom::ServoDangerousStyleElement;
203use crate::realms::enter_auto_realm;
204
205// TODO: Update focus state when the top-level browsing context gains or loses system focus,
206// and when the element enters or leaves a browsing context container.
207// https://html.spec.whatwg.org/multipage/#selector-focus
208
209/// <https://dom.spec.whatwg.org/#element>
210#[dom_struct]
211pub struct Element {
212    node: Node,
213    #[no_trace]
214    local_name: LocalName,
215    #[no_trace]
216    namespace: Namespace,
217    #[no_trace]
218    prefix: DomRefCell<Option<Prefix>>,
219    attrs: AttributeStorage,
220    #[no_trace]
221    id_attribute: AtomicRefCell<Option<Atom>>,
222    #[conditional_malloc_size_of]
223    #[no_trace]
224    style_attribute: DomRefCell<Option<ServoArc<Locked<PropertyDeclarationBlock>>>>,
225    attr_list: MutNullableDom<NamedNodeMap>,
226    class_list: MutNullableDom<DOMTokenList>,
227    #[no_trace]
228    state: Cell<ElementState>,
229    /// These flags are set by the style system to indicate the that certain
230    /// operations may require restyling this element or its descendants.
231    selector_flags: AtomicUsize,
232    rare_data: DomRefCell<Option<Box<ElementRareData>>>,
233
234    /// Style data for this node. This is accessed and mutated by style
235    /// passes and is used to lay out this node and populate layout data.
236    #[no_trace]
237    style_data: DomRefCell<Option<Box<StyleData>>>,
238}
239
240impl fmt::Debug for Element {
241    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
242        write!(f, "<{}", self.local_name)?;
243        if let Some(ref id) = *self.id_attribute.borrow() {
244            write!(f, " id={}", id)?;
245        }
246        write!(f, ">")
247    }
248}
249
250#[derive(MallocSizeOf, PartialEq)]
251pub(crate) enum ElementCreator {
252    ParserCreated(u64),
253    ScriptCreated,
254}
255
256pub(crate) enum CustomElementCreationMode {
257    Synchronous,
258    Asynchronous,
259}
260
261impl ElementCreator {
262    pub(crate) fn is_parser_created(&self) -> bool {
263        match *self {
264            ElementCreator::ParserCreated(_) => true,
265            ElementCreator::ScriptCreated => false,
266        }
267    }
268    pub(crate) fn return_line_number(&self) -> u64 {
269        match *self {
270            ElementCreator::ParserCreated(l) => l,
271            ElementCreator::ScriptCreated => 1,
272        }
273    }
274}
275
276pub(crate) enum AdjacentPosition {
277    BeforeBegin,
278    AfterEnd,
279    AfterBegin,
280    BeforeEnd,
281}
282
283impl FromStr for AdjacentPosition {
284    type Err = Error;
285
286    fn from_str(position: &str) -> Result<Self, Self::Err> {
287        match_ignore_ascii_case! { position,
288            "beforebegin" => Ok(AdjacentPosition::BeforeBegin),
289            "afterbegin"  => Ok(AdjacentPosition::AfterBegin),
290            "beforeend"   => Ok(AdjacentPosition::BeforeEnd),
291            "afterend"    => Ok(AdjacentPosition::AfterEnd),
292            _             => Err(Error::Syntax(Some("Invalid position".into())))
293        }
294    }
295}
296
297//
298// Element methods
299//
300impl Element {
301    pub(crate) fn create(
302        cx: &mut JSContext,
303        name: QualName,
304        is: Option<LocalName>,
305        document: &Document,
306        creator: ElementCreator,
307        mode: CustomElementCreationMode,
308        proto: Option<HandleObject>,
309    ) -> DomRoot<Element> {
310        create_element(cx, name, is, document, creator, mode, proto)
311    }
312
313    pub(crate) fn new_inherited(
314        local_name: LocalName,
315        namespace: Namespace,
316        prefix: Option<Prefix>,
317        document: &Document,
318    ) -> Element {
319        Element::new_inherited_with_state(
320            ElementState::empty(),
321            local_name,
322            namespace,
323            prefix,
324            document,
325        )
326    }
327
328    pub(crate) fn new_inherited_with_state(
329        state: ElementState,
330        local_name: LocalName,
331        namespace: Namespace,
332        prefix: Option<Prefix>,
333        document: &Document,
334    ) -> Element {
335        Element {
336            node: Node::new_inherited(document),
337            local_name,
338            namespace,
339            prefix: DomRefCell::new(prefix),
340            attrs: Default::default(),
341            id_attribute: Default::default(),
342            style_attribute: DomRefCell::new(None),
343            attr_list: Default::default(),
344            class_list: Default::default(),
345            state: Cell::new(state),
346            selector_flags: Default::default(),
347            rare_data: Default::default(),
348            style_data: Default::default(),
349        }
350    }
351
352    pub(crate) fn set_had_duplicate_attributes(&self, no_gc: &NoGC) {
353        self.ensure_rare_data(no_gc).had_duplicate_attributes = true;
354    }
355
356    pub(crate) fn new(
357        cx: &mut JSContext,
358        local_name: LocalName,
359        namespace: Namespace,
360        prefix: Option<Prefix>,
361        document: &Document,
362        proto: Option<HandleObject>,
363    ) -> DomRoot<Element> {
364        Node::reflect_node_with_proto(
365            cx,
366            Box::new(Element::new_inherited(
367                local_name, namespace, prefix, document,
368            )),
369            document,
370            proto,
371        )
372    }
373
374    pub(crate) fn rare_data(&self) -> Ref<'_, Option<Box<ElementRareData>>> {
375        self.rare_data.borrow()
376    }
377
378    fn rare_data_mut(&self) -> RefMut<'_, Option<Box<ElementRareData>>> {
379        self.rare_data.borrow_mut()
380    }
381
382    pub(crate) fn ensure_rare_data<'a: 'b, 'b>(
383        &'a self,
384        no_gc: &'b NoGC,
385    ) -> RefMut<'b, Box<ElementRareData>> {
386        let mut rare_data = self.rare_data.safe_borrow_mut(no_gc);
387        if rare_data.is_none() {
388            *rare_data = Some(Default::default());
389        }
390        RefMut::map(rare_data, |rare_data| rare_data.as_mut().unwrap())
391    }
392
393    pub(crate) fn clean_up_style_data(&self) {
394        self.style_data.borrow_mut().take();
395    }
396
397    pub(crate) fn restyle(&self, no_gc: &NoGC, damage: NodeDamage) {
398        let doc = self.node.owner_document_unrooted(no_gc);
399        let mut restyle = doc.ensure_pending_restyle(self);
400
401        // FIXME(bholley): I think we should probably only do this for
402        // NodeStyleDamaged, but I'm preserving existing behavior.
403        restyle.hint.insert(RestyleHint::RESTYLE_SELF);
404
405        match damage {
406            NodeDamage::Style => {},
407            NodeDamage::ContentOrHeritage => {
408                doc.note_dirty_element(no_gc, self);
409                restyle
410                    .damage
411                    .insert(RestyleDamage::from(LayoutDamage::DescendantHasBoxDamage));
412            },
413            NodeDamage::Other => {
414                doc.note_dirty_element(no_gc, self);
415                restyle.damage.insert(RestyleDamage::reconstruct());
416            },
417        }
418    }
419
420    pub(crate) fn has_dirty_descendants(&self) -> bool {
421        self.upcast::<Node>()
422            .get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS)
423    }
424
425    pub(crate) fn note_dirty_descendants(&self, no_gc: &NoGC) {
426        self.upcast::<Node>()
427            .owner_doc_unrooted(no_gc)
428            .note_dirty_element(no_gc, self);
429    }
430
431    pub(crate) fn set_is(&self, is: LocalName, no_gc: &NoGC) {
432        self.ensure_rare_data(no_gc).is_value = Some(is);
433    }
434
435    /// <https://dom.spec.whatwg.org/#concept-element-is-value>
436    pub(crate) fn get_is(&self) -> Option<LocalName> {
437        self.rare_data().as_ref()?.is_value.clone()
438    }
439
440    /// This is a performance optimization. `Element::create` can simply call
441    /// `element.set_custom_element_state(CustomElementState::Uncustomized)` to initialize
442    /// uncustomized, built-in elements with the right state, which currently just means that the
443    /// `DEFINED` state should be `true` for styling. However `set_custom_element_state` has a high
444    /// performance cost and it is unnecessary if the element is being created as an uncustomized
445    /// built-in element.
446    ///
447    /// See <https://github.com/servo/servo/issues/37745> for more details.
448    pub(crate) fn set_initial_custom_element_state_to_uncustomized(&self) {
449        let mut state = self.state.get();
450        state.insert(ElementState::DEFINED);
451        self.state.set(state);
452    }
453
454    /// <https://dom.spec.whatwg.org/#concept-element-custom-element-state>
455    pub(crate) fn set_custom_element_state(&self, state: CustomElementState, no_gc: &NoGC) {
456        // no need to inflate rare data for uncustomized
457        if state != CustomElementState::Uncustomized {
458            self.ensure_rare_data(no_gc).custom_element_state = state;
459        }
460
461        let in_defined_state = matches!(
462            state,
463            CustomElementState::Uncustomized | CustomElementState::Custom
464        );
465        self.set_state(no_gc, ElementState::DEFINED, in_defined_state)
466    }
467
468    pub(crate) fn get_custom_element_state(&self) -> CustomElementState {
469        if let Some(rare_data) = self.rare_data().as_ref() {
470            return rare_data.custom_element_state;
471        }
472        CustomElementState::Uncustomized
473    }
474
475    /// <https://dom.spec.whatwg.org/#concept-element-custom>
476    pub(crate) fn is_custom(&self) -> bool {
477        self.get_custom_element_state() == CustomElementState::Custom
478    }
479
480    pub(crate) fn set_custom_element_definition(
481        &self,
482        definition: Rc<CustomElementDefinition>,
483        no_gc: &NoGC,
484    ) {
485        self.ensure_rare_data(no_gc).custom_element_definition = Some(definition);
486    }
487
488    pub(crate) fn get_custom_element_definition(&self) -> Option<Rc<CustomElementDefinition>> {
489        self.rare_data().as_ref()?.custom_element_definition.clone()
490    }
491
492    pub(crate) fn clear_custom_element_definition(&self, no_gc: &NoGC) {
493        self.ensure_rare_data(no_gc).custom_element_definition = None;
494    }
495
496    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
497    pub(crate) fn push_callback_reaction(
498        &self,
499        function: RootedCallback<Function>,
500        args: Box<[Heap<JSVal>]>,
501        no_gc: &NoGC,
502    ) {
503        self.ensure_rare_data(no_gc)
504            .custom_element_reaction_queue
505            .push(CustomElementReaction::Callback(function.to_traced(), args));
506    }
507
508    pub(crate) fn push_upgrade_reaction(
509        &self,
510        definition: Rc<CustomElementDefinition>,
511        no_gc: &NoGC,
512    ) {
513        self.ensure_rare_data(no_gc)
514            .custom_element_reaction_queue
515            .push(CustomElementReaction::Upgrade(definition));
516    }
517
518    pub(crate) fn clear_reaction_queue(&self) {
519        if let Some(ref mut rare_data) = *self.rare_data_mut() {
520            rare_data.custom_element_reaction_queue.clear();
521        }
522    }
523
524    pub(crate) fn invoke_reactions(&self, cx: &mut JSContext) {
525        loop {
526            rooted_vec!(let mut reactions);
527            match *self.rare_data_mut() {
528                Some(ref mut data) => {
529                    mem::swap(&mut *reactions, &mut data.custom_element_reaction_queue)
530                },
531                None => break,
532            };
533
534            if reactions.is_empty() {
535                break;
536            }
537
538            for reaction in reactions.iter() {
539                reaction.invoke(cx, self);
540            }
541
542            reactions.clear();
543        }
544    }
545
546    /// <https://drafts.csswg.org/css-display-4/#box>
547    ///
548    /// This version is deprecated because it's not specification compliant. It only checks whether
549    /// the element is styled and isn't `display: none`. Callers should be examined to see if they
550    /// should really be calling `Self::has_css_layout_box` instead.
551    pub(crate) fn has_css_layout_box_deprecated(&self, cx: &mut JSContext) -> bool {
552        self.style(cx).is_some_and(|s| !s.get_display().is_none())
553    }
554
555    /// <https://drafts.csswg.org/css-display-4/#box>
556    pub(crate) fn has_css_layout_box(&self) -> bool {
557        // TODO: This isn't always the same. For example, SVG elements are rendered
558        // but do not necessarily have a CSS layout box. Later, when we fully support
559        // SVG, this needs to be re-examined.
560        self.upcast::<Node>().is_being_rendered(None)
561    }
562
563    /// <https://drafts.csswg.org/cssom-view/#potentially-scrollable>
564    pub(crate) fn is_potentially_scrollable_body(&self, cx: &mut JSContext) -> bool {
565        self.is_potentially_scrollable_body_shared_logic(cx, false)
566    }
567
568    /// <https://drafts.csswg.org/cssom-view/#potentially-scrollable>
569    pub(crate) fn is_potentially_scrollable_body_for_scrolling_element(
570        &self,
571        cx: &mut JSContext,
572    ) -> bool {
573        self.is_potentially_scrollable_body_shared_logic(cx, true)
574    }
575
576    /// <https://drafts.csswg.org/cssom-view/#potentially-scrollable>
577    fn is_potentially_scrollable_body_shared_logic(
578        &self,
579        cx: &mut JSContext,
580        treat_overflow_clip_on_parent_as_hidden: bool,
581    ) -> bool {
582        let node = self.upcast::<Node>();
583        debug_assert!(
584            node.owner_doc().GetBody().as_deref() == self.downcast::<HTMLElement>(),
585            "Called is_potentially_scrollable_body on element that is not the <body>"
586        );
587
588        // "An element body (which will be the body element) is potentially
589        // scrollable if all of the following conditions are true:
590        //  - body has an associated box."
591        if !self.has_css_layout_box_deprecated(cx) {
592            return false;
593        }
594
595        // " - body’s parent element’s computed value of the overflow-x or
596        //     overflow-y properties is neither visible nor clip."
597        if let Some(parent) = node.GetParentElement() &&
598            let Some(style) = parent.style(cx)
599        {
600            let mut overflow_x = style.get_box().get_overflow_x();
601            let mut overflow_y = style.get_box().get_overflow_y();
602
603            // This fulfills the 'treat parent element overflow:clip as overflow:hidden' stipulation
604            // from the document.scrollingElement specification.
605            if treat_overflow_clip_on_parent_as_hidden {
606                if overflow_x == &Overflow::Clip {
607                    overflow_x = &Overflow::Hidden;
608                }
609                if overflow_y == &Overflow::Clip {
610                    overflow_y = &Overflow::Hidden;
611                }
612            }
613
614            if !overflow_x.is_scrollable() && !overflow_y.is_scrollable() {
615                return false;
616            }
617        };
618
619        // " - body’s computed value of the overflow-x or overflow-y properties
620        //     is neither visible nor clip."
621        if let Some(style) = self.style(cx) &&
622            !style.get_box().get_overflow_x().is_scrollable() &&
623            !style.get_box().get_overflow_y().is_scrollable()
624        {
625            return false;
626        };
627
628        true
629    }
630
631    /// Whether this element is styled such that it establishes a scroll container.
632    /// <https://www.w3.org/TR/css-overflow-3/#scroll-container>
633    pub(crate) fn establishes_scroll_container(&self, cx: &mut JSContext) -> bool {
634        // The CSS computed value has made sure that either both axes are scrollable or none are scrollable.
635        self.upcast::<Node>()
636            .effective_overflow(cx)
637            .is_some_and(|overflow| overflow.establishes_scroll_container())
638    }
639
640    /// Like [`Self::establishes_scroll_container`], but without forcing a reflow.
641    pub(crate) fn establishes_scroll_container_without_reflow(&self) -> bool {
642        self.upcast::<Node>()
643            .effective_overflow_without_reflow()
644            .is_some_and(|overflow| overflow.establishes_scroll_container())
645    }
646
647    pub(crate) fn has_overflow(&self, cx: &mut JSContext) -> bool {
648        self.ScrollHeight(cx) > self.ClientHeight(cx) || self.ScrollWidth(cx) > self.ClientWidth(cx)
649    }
650
651    /// Whether or not this element has a scrolling box according to
652    /// <https://drafts.csswg.org/cssom-view/#scrolling-box>.
653    ///
654    /// This is true if:
655    ///  1. The element has a layout box.
656    ///  2. The style specifies that overflow should be scrollable (`auto`, `hidden` or `scroll`).
657    ///  3. The fragment actually has content that overflows the box.
658    fn has_scrolling_box(&self, cx: &mut JSContext) -> bool {
659        self.has_css_layout_box_deprecated(cx) &&
660            self.establishes_scroll_container(cx) &&
661            self.has_overflow(cx)
662    }
663
664    pub(crate) fn shadow_root(&self) -> Option<DomRoot<ShadowRoot>> {
665        self.rare_data()
666            .as_ref()?
667            .shadow_root
668            .as_ref()
669            .map(|sr| DomRoot::from_ref(&**sr))
670    }
671
672    pub(crate) fn shadow_root_unrooted<'a>(
673        &self,
674        no_gc: &'a NoGC,
675    ) -> Option<UnrootedDom<'a, ShadowRoot>> {
676        self.rare_data()
677            .as_ref()?
678            .shadow_root
679            .as_ref()
680            .map(|shadow_root| shadow_root.as_unrooted(no_gc))
681    }
682
683    pub(crate) fn is_shadow_host(&self) -> bool {
684        self.shadow_root().is_some()
685    }
686
687    /// <https://dom.spec.whatwg.org/#dom-element-attachshadow>
688    #[expect(clippy::too_many_arguments)]
689    pub(crate) fn attach_shadow(
690        &self,
691        cx: &mut JSContext,
692        is_ua_widget: IsUserAgentWidget,
693        mode: ShadowRootMode,
694        clonable: bool,
695        serializable: bool,
696        delegates_focus: bool,
697        slot_assignment_mode: SlotAssignmentMode,
698    ) -> Fallible<DomRoot<ShadowRoot>> {
699        // Step 1. If element’s namespace is not the HTML namespace,
700        // then throw a "NotSupportedError" DOMException.
701        if self.namespace != ns!(html) {
702            return Err(Error::NotSupported(Some(
703                "Cannot attach shadow roots to elements with non-HTML namespaces".to_owned(),
704            )));
705        }
706
707        // Step 2. If element’s local name is not a valid shadow host name,
708        // then throw a "NotSupportedError" DOMException.
709        if !is_valid_shadow_host_name(self.local_name()) {
710            // UA shadow roots may be attached to anything
711            if is_ua_widget != IsUserAgentWidget::Yes {
712                let error_message = format!(
713                    "Cannot attach shadow roots to <{}> elements",
714                    *self.local_name()
715                );
716                return Err(Error::NotSupported(Some(error_message)));
717            }
718        }
719
720        // Step 3. If element’s local name is a valid custom element name,
721        // or element’s is value is non-null
722        if is_valid_custom_element_name(self.local_name()) || self.get_is().is_some() {
723            // Step 3.1. Let definition be the result of looking up a custom element definition
724            // given element’s node document, its namespace, its local name, and its is value.
725
726            let definition = self.get_custom_element_definition();
727            // Step 3.2. If definition is not null and definition’s disable shadow
728            //  is true, then throw a "NotSupportedError" DOMException.
729            if definition.is_some_and(|definition| definition.disable_shadow) {
730                let error_message = format!(
731                    "The custom element constructor of <{}> disabled attachment of shadow roots",
732                    self.local_name()
733                );
734                return Err(Error::NotSupported(Some(error_message)));
735            }
736        }
737
738        // Step 4. If element is a shadow host:
739        // Step 4.1. Let currentShadowRoot be element’s shadow root.
740        if let Some(current_shadow_root) = self.shadow_root() {
741            // Step 4.2. If currentShadowRoot’s declarative is false
742            // or currentShadowRoot’s mode is not mode
743            // then throw a "NotSupportedError" DOMException.
744            if !current_shadow_root.is_declarative() ||
745                current_shadow_root.shadow_root_mode() != mode
746            {
747                return Err(Error::NotSupported(Some(
748                    "Cannot attach a second shadow root to the same element".into(),
749                )));
750            }
751
752            // Step 4.3.1. Remove all of currentShadowRoot’s children, in tree order.
753            for child in current_shadow_root.upcast::<Node>().children() {
754                child.remove_self(cx);
755            }
756
757            // Step 4.3.2. Set currentShadowRoot’s declarative to false.
758            current_shadow_root.set_declarative(false);
759
760            // Step 4.3.3. Return
761            return Ok(current_shadow_root);
762        }
763
764        // Step 5. Let shadow be a new shadow root whose node document
765        // is element’s node document, host is element, and mode is mode
766        //
767        // Step 8. Set shadow’s slot assignment to slotAssignment
768        //
769        // Step 10. Set shadow’s clonable to clonable
770        let document = self.node.owner_doc();
771        let shadow_root = ShadowRoot::new(
772            cx,
773            self,
774            &document,
775            mode,
776            slot_assignment_mode,
777            clonable,
778            is_ua_widget,
779        );
780
781        // This is not in the specification, but this is where we ensure that the
782        // non-shadow-tree children of `self` no longer have layout boxes as they are no
783        // longer in the flat tree.
784        let node = self.upcast::<Node>();
785        if node.is_connected() {
786            document.remove_style_and_layout_data_from_subtree(cx.no_gc(), node);
787        }
788        if let Some(selection) = self.owner_document().selection() &&
789            node.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION)
790        {
791            selection.set_visible_selection_dirty();
792        }
793
794        // Step 6. Set shadow's delegates focus to delegatesFocus
795        shadow_root.set_delegates_focus(delegates_focus);
796
797        // Step 7. If element’s custom element state is "precustomized" or "custom",
798        // then set shadow’s available to element internals to true.
799        if matches!(
800            self.get_custom_element_state(),
801            CustomElementState::Precustomized | CustomElementState::Custom
802        ) {
803            shadow_root.set_available_to_element_internals(true);
804        }
805
806        // Step 9. Set shadow's declarative to false
807        shadow_root.set_declarative(false);
808
809        // Step 11. Set shadow's serializable to serializable
810        shadow_root.set_serializable(serializable);
811
812        // Step 12. Set element’s shadow root to shadow
813        self.ensure_rare_data(cx.no_gc()).shadow_root = Some(Dom::from_ref(&*shadow_root));
814        shadow_root
815            .upcast::<Node>()
816            .set_containing_shadow_root(Some(&shadow_root));
817
818        let bind_context = BindContext::new(self.upcast(), IsShadowTree::Yes);
819        shadow_root.bind_to_tree(cx, &bind_context);
820
821        node.dirty(cx.no_gc(), NodeDamage::Other);
822
823        Ok(shadow_root)
824    }
825
826    /// <https://html.spec.whatwg.org/multipage/#translation-mode>
827    pub(crate) fn is_translate_enabled(&self) -> bool {
828        let name = &local_name!("translate");
829        if self.has_attribute(name) {
830            let attribute = self.get_string_attribute(name);
831            match_ignore_ascii_case! { &*attribute.str(),
832                "yes" | "" => return true,
833                "no" => return false,
834                _ => {},
835            }
836        }
837        if let Some(parent) = self.upcast::<Node>().GetParentNode() &&
838            let Some(elem) = parent.downcast::<Element>()
839        {
840            return elem.is_translate_enabled();
841        }
842        true
843    }
844
845    /// <https://html.spec.whatwg.org/multipage/#the-directionality>
846    pub(crate) fn directionality(&self) -> String {
847        self.downcast::<HTMLElement>()
848            .and_then(|html_element| html_element.directionality())
849            .unwrap_or_else(|| {
850                let node = self.upcast::<Node>();
851                node.parent_directionality()
852            })
853    }
854
855    pub(crate) fn is_root(&self) -> bool {
856        match self.node.GetParentNode() {
857            None => false,
858            Some(node) => node.is::<Document>(),
859        }
860    }
861
862    /// Return all IntersectionObserverRegistration for this element.
863    /// Lazily initialize the raredata if it does not exist.
864    pub(crate) fn registered_intersection_observers_mut<'a: 'b, 'b>(
865        &'a self,
866        no_gc: &'b NoGC,
867    ) -> RefMut<'b, Vec<IntersectionObserverRegistration>> {
868        RefMut::map(self.ensure_rare_data(no_gc), |rare_data| {
869            &mut rare_data.registered_intersection_observers
870        })
871    }
872
873    pub(crate) fn registered_intersection_observers(
874        &self,
875    ) -> Option<Ref<'_, Vec<IntersectionObserverRegistration>>> {
876        let rare_data: Ref<'_, _> = self.rare_data.borrow();
877
878        if rare_data.is_none() {
879            return None;
880        }
881        Some(Ref::map(rare_data, |rare_data| {
882            &rare_data
883                .as_ref()
884                .unwrap()
885                .registered_intersection_observers
886        }))
887    }
888
889    pub(crate) fn get_intersection_observer_registration(
890        &self,
891        observer: &IntersectionObserver,
892    ) -> Option<Ref<'_, IntersectionObserverRegistration>> {
893        if let Some(registrations) = self.registered_intersection_observers() {
894            registrations
895                .iter()
896                .position(|reg_obs| reg_obs.observer == observer)
897                .map(|index| Ref::map(registrations, |registrations| &registrations[index]))
898        } else {
899            None
900        }
901    }
902
903    /// Add a new IntersectionObserverRegistration with initial value to the element.
904    pub(crate) fn add_initial_intersection_observer_registration(
905        &self,
906        observer: &IntersectionObserver,
907        no_gc: &NoGC,
908    ) {
909        self.ensure_rare_data(no_gc)
910            .registered_intersection_observers
911            .push(IntersectionObserverRegistration::new_initial(observer));
912    }
913
914    /// Removes a certain IntersectionObserver.
915    pub(crate) fn remove_intersection_observer(
916        &self,
917        observer: &IntersectionObserver,
918        no_gc: &NoGC,
919    ) {
920        self.ensure_rare_data(no_gc)
921            .registered_intersection_observers
922            .retain(|reg_obs| *reg_obs.observer != *observer)
923    }
924
925    /// Get the [`ScrollingBox`] that contains this element, if one does. `position:
926    /// fixed` elements do not have a containing [`ScrollingBox`].
927    pub(crate) fn scrolling_box(&self, flags: ScrollContainerQueryFlags) -> Option<ScrollingBox> {
928        self.owner_window()
929            .scrolling_box_query(Some(self.upcast()), flags)
930    }
931
932    /// <https://drafts.csswg.org/cssom-view/#scroll-a-target-into-view>
933    pub(crate) fn scroll_into_view_with_options(
934        &self,
935        cx: &mut JSContext,
936        behavior: ScrollBehavior,
937        block: ScrollAxisState,
938        inline: ScrollAxisState,
939        container: Option<&Element>,
940        inner_target_rect: Option<Rect<Au, CSSPixel>>,
941    ) {
942        let get_target_rect = |cx: &mut JSContext| match inner_target_rect {
943            None => self.upcast::<Node>().border_box(cx).unwrap_or_default(),
944            Some(inner_target_rect) => inner_target_rect.translate(
945                self.upcast::<Node>()
946                    .content_box(cx)
947                    .unwrap_or_default()
948                    .origin
949                    .to_vector(),
950            ),
951        };
952
953        // Step 1: For each ancestor element or viewport that establishes a scrolling box `scrolling
954        // box`, in order of innermost to outermost scrolling box, run these substeps:
955        let mut parent_scrolling_box = self.scrolling_box(ScrollContainerQueryFlags::empty());
956        while let Some(scrolling_box) = parent_scrolling_box {
957            parent_scrolling_box = scrolling_box.parent();
958
959            // Step 1.1: If the Document associated with `target` is not same origin with the
960            // Document associated with the element or viewport associated with `scrolling box`,
961            // terminate these steps.
962            //
963            // TODO: Handle this. We currently do not chain up to parent Documents.
964
965            // Step 1.2 Let `position` be the scroll position resulting from running the steps to
966            // determine the scroll-into-view position of `target` with `behavior` as the scroll
967            // behavior, `block` as the block flow position, `inline` as the inline base direction
968            // position and `scrolling box` as the scrolling box.
969            let target_rect = get_target_rect(cx);
970            let position =
971                scrolling_box.determine_scroll_into_view_position(cx, block, inline, target_rect);
972
973            // Step 1.3: If `position` is not the same as `scrolling box`’s current scroll position, or
974            // `scrolling box` has an ongoing smooth scroll,
975            //
976            // TODO: Handle smooth scrolling.
977            if position != scrolling_box.scroll_position(cx) {
978                //  ↪ If `scrolling box` is associated with an element
979                //    Perform a scroll of the element’s scrolling box to `position`,
980                //    with the `element` as the associated element and `behavior` as the
981                //    scroll behavior.
982                //  ↪ If `scrolling box` is associated with a viewport
983                //    Step 1: Let `document` be the viewport’s associated Document.
984                //    Step 2: Let `root element` be document’s root element, if there is one, or
985                //    null otherwise.
986                //    Step 3: Perform a scroll of the viewport to `position`, with `root element`
987                //    as the associated element and `behavior` as the scroll behavior.
988                scrolling_box.scroll_to(cx, position, behavior);
989            }
990
991            // Step 1.4: If `container` is not null and either `scrolling box` is a shadow-including
992            // inclusive ancestor of `container` or is a viewport whose document is a shadow-including
993            // inclusive ancestor of `container`, abort the rest of these steps.
994            if container.is_some_and(|container| {
995                let container_node = container.upcast::<Node>();
996                scrolling_box
997                    .node()
998                    .is_shadow_including_inclusive_ancestor_of(container_node)
999            }) {
1000                return;
1001            }
1002        }
1003
1004        let window_proxy = self.owner_window_unrooted(cx.no_gc()).window_proxy();
1005        let Some(frame_element) = window_proxy.frame_element() else {
1006            return;
1007        };
1008
1009        let inner_target_rect = Some(get_target_rect(cx));
1010        let mut realm = enter_auto_realm(cx, frame_element);
1011        let cx = &mut realm;
1012        frame_element.scroll_into_view_with_options(
1013            cx,
1014            behavior,
1015            block,
1016            inline,
1017            None,
1018            inner_target_rect,
1019        )
1020    }
1021
1022    pub(crate) fn ensure_contenteditable_selection_range(
1023        &self,
1024        cx: &mut JSContext,
1025        document: &Document,
1026    ) -> DomRoot<Range> {
1027        let Some(selection_range) = self
1028            .rare_data()
1029            .as_ref()
1030            .and_then(|data| data.contenteditable_selection_range.get())
1031        else {
1032            let range = Range::new_with_doc(cx, document, None);
1033            self.ensure_rare_data(cx.no_gc())
1034                .contenteditable_selection_range
1035                .set(Some(&*range));
1036            return range;
1037        };
1038        selection_range
1039    }
1040
1041    /// <https://drafts.csswg.org/cssom-view/#scrolling-events>
1042    ///
1043    /// > Whenever an element gets scrolled (whether in response to user interaction or
1044    /// > by an API), the user agent must run these steps:
1045    pub(crate) fn handle_scroll_event(&self) {
1046        // Step 1: Let doc be the element’s node document.
1047        let document = self.owner_document();
1048
1049        // Step 2: If the element is a snap container, run the steps to update
1050        // scrollsnapchanging targets for the element with the element’s eventual
1051        // snap target in the block axis as newBlockTarget and the element’s eventual
1052        // snap target in the inline axis as newInlineTarget.
1053        //
1054        // TODO(#7673): Implement scroll snapping
1055
1056        // Steps 3 and 4 are shared with other scroll targets.
1057        document.finish_handle_scroll_event(self.upcast());
1058    }
1059
1060    pub(crate) fn style(&self, cx: &mut JSContext) -> Option<ServoArc<ComputedValues>> {
1061        self.owner_window().layout_reflow(cx, QueryMsg::StyleQuery);
1062        self.style_without_reflow()
1063    }
1064
1065    /// Do the same kind of query as [`Self::style`], but do not force a reflow. This is for
1066    /// callers that have just run another query and know the style data is already current.
1067    pub(crate) fn style_without_reflow(&self) -> Option<ServoArc<ComputedValues>> {
1068        self.style_data
1069            .borrow()
1070            .as_ref()
1071            .map(|data| data.element_data.borrow().styles.primary().clone())
1072    }
1073
1074    pub(crate) fn is_styled(&self) -> bool {
1075        self.style_data.borrow().is_some()
1076    }
1077
1078    pub(crate) fn is_display_none(&self) -> bool {
1079        self.style_data.borrow().as_ref().is_none_or(|data| {
1080            data.element_data
1081                .borrow()
1082                .styles
1083                .primary()
1084                .get_box()
1085                .display
1086                .is_none()
1087        })
1088    }
1089
1090    /// Returns the computed value of the [`user-select`] property. Returns `None` if the
1091    /// element is unstyled.
1092    ///
1093    /// [`user-select`]: <https://drafts.csswg.org/css-ui-4/#propdef-user-select>
1094    pub(crate) fn computed_user_select(&self) -> Option<UserSelect> {
1095        Some(
1096            self.style_data
1097                .borrow()
1098                .as_ref()?
1099                .element_data
1100                .borrow()
1101                .styles
1102                .primary()
1103                .get_ui()
1104                .user_select,
1105        )
1106    }
1107
1108    pub(crate) fn check_style_on_self_or_eager_pseudos(
1109        &self,
1110        check_styles_fn: impl Fn(&ComputedValues) -> bool,
1111    ) -> bool {
1112        let style_data = self.style_data.borrow();
1113        let Some(data) = style_data.as_ref().map(|data| data.element_data.borrow()) else {
1114            return false;
1115        };
1116
1117        if check_styles_fn(data.styles.primary()) {
1118            return true;
1119        }
1120
1121        let mut pseudo_styles = data.styles.pseudos.as_array().iter();
1122        pseudo_styles.any(|style| style.as_deref().is_some_and(&check_styles_fn))
1123    }
1124
1125    #[inline]
1126    pub(crate) fn dirty_presentational_hints(&self) {
1127        self.upcast::<Node>()
1128            .set_flag(NodeFlags::HAS_RESOLVED_PRESENTATIONAL_HINTS, false);
1129    }
1130
1131    /// <https://fullscreen.spec.whatwg.org/#fullscreen-element-ready-check>
1132    pub(crate) fn fullscreen_element_ready_check(&self) -> bool {
1133        // > A fullscreen element ready check for an element element returns true if all of the
1134        // > following are true, and false otherwise:
1135        // > - element is connected.
1136        // > - element’s node document is allowed to use the "fullscreen" feature.
1137        // > - element namespace is not the HTML namespace, or element's popover visibility state is hidden.
1138        self.is_connected() &&
1139            self.owner_document()
1140                .overlay_handler()
1141                .is_allowed_to_use_fullscreen() &&
1142            (*self.namespace() != ns!(html) || !self.popover_visibility_state_showing())
1143    }
1144}
1145
1146/// <https://dom.spec.whatwg.org/#valid-shadow-host-name>
1147#[inline]
1148pub(crate) fn is_valid_shadow_host_name(name: &LocalName) -> bool {
1149    // > A valid shadow host name is:
1150    // > - a valid custom element name
1151    if is_valid_custom_element_name(name) {
1152        return true;
1153    }
1154
1155    // > - "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3",
1156    // >   "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span"
1157    matches!(
1158        name,
1159        &local_name!("article") |
1160            &local_name!("aside") |
1161            &local_name!("blockquote") |
1162            &local_name!("body") |
1163            &local_name!("div") |
1164            &local_name!("footer") |
1165            &local_name!("h1") |
1166            &local_name!("h2") |
1167            &local_name!("h3") |
1168            &local_name!("h4") |
1169            &local_name!("h5") |
1170            &local_name!("h6") |
1171            &local_name!("header") |
1172            &local_name!("main") |
1173            &local_name!("nav") |
1174            &local_name!("p") |
1175            &local_name!("section") |
1176            &local_name!("span")
1177    )
1178}
1179
1180#[inline]
1181#[expect(unsafe_code)]
1182pub(crate) fn get_attr_for_layout<'dom>(
1183    elem: LayoutDom<'dom, Element>,
1184    namespace: &Namespace,
1185    name: &LocalName,
1186) -> Option<&'dom AttrValue> {
1187    let storage = unsafe { elem.unsafe_get().attrs.borrow_for_layout() };
1188    storage
1189        .iter()
1190        .find(|e: &&AttributeEntry| {
1191            name == e.local_name_for_layout() && namespace == e.namespace_for_layout()
1192        })
1193        .map(|e: &AttributeEntry| e.value_for_layout())
1194}
1195
1196impl<'dom> LayoutDom<'dom, Element> {
1197    #[inline]
1198    pub(crate) fn is_root(&self) -> bool {
1199        self.upcast::<Node>()
1200            .parent_node_ref()
1201            .is_some_and(|parent| matches!(parent.type_id_for_layout(), NodeTypeId::Document(_)))
1202    }
1203
1204    /// Returns true if this element is the body child of an html element root element.
1205    pub(crate) fn is_body_element_of_html_element_root(&self) -> bool {
1206        if self.local_name() != &local_name!("body") {
1207            return false;
1208        }
1209        let Some(parent_node) = self.upcast::<Node>().parent_node_ref() else {
1210            return false;
1211        };
1212        let Some(parent_element) = parent_node.downcast::<Element>() else {
1213            return false;
1214        };
1215        parent_element.local_name() == &local_name!("html")
1216    }
1217
1218    /// Iterate over attribute local names for layout, handling mixed Raw and Dom entries.
1219    #[expect(unsafe_code)]
1220    #[inline]
1221    pub(crate) fn each_attr_name_for_layout<F>(self, mut callback: F)
1222    where
1223        F: FnMut(&LocalName),
1224    {
1225        let storage = unsafe { self.unsafe_get().attrs.borrow_for_layout() };
1226        for entry in storage.iter() {
1227            callback(entry.local_name_for_layout());
1228        }
1229    }
1230
1231    #[inline]
1232    pub(crate) fn has_class_or_part_for_layout(
1233        self,
1234        name: &AtomIdent,
1235        attr_name: &LocalName,
1236        case_sensitivity: CaseSensitivity,
1237    ) -> bool {
1238        get_attr_for_layout(self, &ns!(), attr_name).is_some_and(|attr| {
1239            attr.as_tokens()
1240                .iter()
1241                .any(|atom| case_sensitivity.eq_atom(atom, name))
1242        })
1243    }
1244
1245    #[inline]
1246    pub(crate) fn get_classes_for_layout(self) -> Option<&'dom [Atom]> {
1247        get_attr_for_layout(self, &ns!(), &local_name!("class")).map(|attr| attr.as_tokens())
1248    }
1249
1250    #[inline]
1251    pub(crate) fn get_parts_for_layout(self) -> Option<&'dom [Atom]> {
1252        get_attr_for_layout(self, &ns!(), &local_name!("part")).map(|attr| attr.as_tokens())
1253    }
1254
1255    #[inline]
1256    pub(crate) fn dimension_attr_value(self, name: LocalName) -> LengthOrPercentageOrAuto {
1257        self.get_attr_for_layout(&ns!(), &name)
1258            .map(AttrValue::as_dimension)
1259            .cloned()
1260            .unwrap_or(LengthOrPercentageOrAuto::Auto)
1261    }
1262
1263    #[inline]
1264    #[expect(unsafe_code)]
1265    pub(crate) fn style_data(self) -> Option<&'dom StyleData> {
1266        unsafe { self.unsafe_get().style_data.borrow_for_layout().as_deref() }
1267    }
1268
1269    #[inline]
1270    #[expect(unsafe_code)]
1271    pub(crate) unsafe fn initialize_style_data(self) {
1272        let data = unsafe { self.unsafe_get().style_data.borrow_mut_for_layout() };
1273        debug_assert!(data.is_none());
1274        *data = Some(Box::default());
1275    }
1276
1277    #[inline]
1278    #[expect(unsafe_code)]
1279    pub(crate) unsafe fn clear_style_data(self) {
1280        unsafe {
1281            self.unsafe_get().style_data.borrow_mut_for_layout().take();
1282        }
1283    }
1284
1285    #[inline]
1286    #[expect(unsafe_code)]
1287    pub(crate) fn presentational_hints(
1288        self,
1289    ) -> Option<&'dom ServoArc<Locked<PropertyDeclarationBlock>>> {
1290        unsafe { self.unsafe_get().attrs.borrow_for_layout() }.presentational_hints()
1291    }
1292
1293    #[inline]
1294    #[expect(unsafe_code)]
1295    pub(crate) fn ensure_presentational_hints(self) {
1296        let node = self.upcast::<Node>();
1297        if unsafe { node.get_flag(NodeFlags::HAS_RESOLVED_PRESENTATIONAL_HINTS) } {
1298            return;
1299        }
1300        self.unsafe_get()
1301            .attrs
1302            .set_presentational_hints(self.compute_presentational_hints());
1303        unsafe {
1304            node.set_flag(NodeFlags::HAS_RESOLVED_PRESENTATIONAL_HINTS, true);
1305        }
1306    }
1307
1308    #[inline]
1309    fn apply_property_for_length_percentage<Callback>(
1310        self,
1311        length_percentage: LengthOrPercentageOrAuto,
1312        callback: Callback,
1313    ) where
1314        Callback: FnOnce(specified::LengthPercentage),
1315    {
1316        match length_percentage {
1317            LengthOrPercentageOrAuto::Auto => {},
1318            LengthOrPercentageOrAuto::Percentage(percentage) => {
1319                let value = specified::LengthPercentage::Percentage(
1320                    specified::NoCalcPercentage::new(percentage),
1321                );
1322                callback(value)
1323            },
1324            LengthOrPercentageOrAuto::Length(length) => {
1325                let value = specified::LengthPercentage::Length(specified::NoCalcLength::from_px(
1326                    length.to_f32_px(),
1327                ));
1328                callback(value)
1329            },
1330        }
1331    }
1332
1333    fn compute_presentational_hints(&self) -> Option<ServoArc<Locked<PropertyDeclarationBlock>>> {
1334        // TODO: Move HTML presentational hints handling into
1335        // HTMLElement::synthesize_presentational_hints_for_legacy_attributes
1336        let document = self.upcast::<Node>().owner_doc_for_layout();
1337        let mut property_declaration_block = None;
1338        let mut push = |declaration| {
1339            property_declaration_block
1340                .get_or_insert_with(PropertyDeclarationBlock::default)
1341                .push(declaration, Importance::Normal);
1342        };
1343
1344        // TODO(xiaochengh): This is probably not enough. When the root element doesn't have a `lang`,
1345        // we should check the browser settings and system locale.
1346        if let Some(lang) = self.get_lang_attr_val_for_layout() {
1347            push(PropertyDeclaration::XLang(specified::XLang(Atom::from(
1348                lang.to_owned(),
1349            ))));
1350        }
1351
1352        let bgcolor = if let Some(this) = self.downcast::<HTMLBodyElement>() {
1353            this.get_background_color()
1354        } else if let Some(this) = self.downcast::<HTMLTableElement>() {
1355            this.get_background_color()
1356        } else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
1357            this.get_background_color()
1358        } else if let Some(this) = self.downcast::<HTMLTableRowElement>() {
1359            this.get_background_color()
1360        } else if let Some(this) = self.downcast::<HTMLTableSectionElement>() {
1361            this.get_background_color()
1362        } else {
1363            None
1364        };
1365
1366        if let Some(color) = bgcolor {
1367            push(PropertyDeclaration::BackgroundColor(
1368                specified::Color::from_absolute_color(color),
1369            ));
1370        }
1371
1372        if is_element_affected_by_legacy_background_presentational_hint(
1373            self.namespace(),
1374            self.local_name(),
1375        ) && let Some(url) = self
1376            .get_attr_for_layout(&ns!(), &local_name!("background"))
1377            .and_then(AttrValue::as_resolved_url)
1378            .cloned()
1379        {
1380            push(PropertyDeclaration::BackgroundImage(
1381                background_image::SpecifiedValue(vec![specified::Image::for_cascade(url)].into()),
1382            ));
1383        }
1384
1385        let color = if let Some(this) = self.downcast::<HTMLFontElement>() {
1386            this.get_color()
1387        } else if let Some(this) = self.downcast::<HTMLBodyElement>() {
1388            // https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20
1389            this.get_color()
1390        } else if let Some(this) = self.downcast::<HTMLHRElement>() {
1391            // https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5
1392            this.get_color()
1393        } else {
1394            None
1395        };
1396
1397        if let Some(color) = color {
1398            push(PropertyDeclaration::Color(
1399                longhands::color::SpecifiedValue(specified::Color::from_absolute_color(color)),
1400            ));
1401        }
1402
1403        let font_face = self
1404            .downcast::<HTMLFontElement>()
1405            .and_then(LayoutDom::get_face);
1406        if let Some(font_face) = font_face {
1407            push(PropertyDeclaration::FontFamily(
1408                font_family::SpecifiedValue::Values(computed::font::FontFamilyList {
1409                    list: ArcSlice::from_iter(
1410                        HTMLFontElement::parse_face_attribute(font_face).into_iter(),
1411                    ),
1412                }),
1413            ));
1414        }
1415
1416        let font_size = self
1417            .downcast::<HTMLFontElement>()
1418            .and_then(LayoutDom::get_size);
1419        if let Some(font_size) = font_size {
1420            push(PropertyDeclaration::FontSize(
1421                font_size::SpecifiedValue::from_html_size(font_size as u8),
1422            ));
1423        }
1424
1425        // Textual input, specifically text entry and domain specific input has
1426        // a default preferred size.
1427        //
1428        // <https://html.spec.whatwg.org/multipage/#the-input-element-as-a-text-entry-widget>
1429        // <https://html.spec.whatwg.org/multipage/#the-input-element-as-domain-specific-widgets>
1430        let size = self
1431            .downcast::<HTMLInputElement>()
1432            .and_then(|input_element| {
1433                // FIXME(pcwalton): More use of atoms, please!
1434                match self.get_attr_val_for_layout(&ns!(), &local_name!("type")) {
1435                    Some("hidden") | Some("range") | Some("color") | Some("checkbox") |
1436                    Some("radio") | Some("file") | Some("submit") | Some("image") |
1437                    Some("reset") | Some("button") => None,
1438                    // Others
1439                    _ => match input_element.size_for_layout() {
1440                        0 => None,
1441                        s => Some(s as i32),
1442                    },
1443                }
1444            });
1445
1446        if let Some(size) = size {
1447            let value = specified::NoCalcLength::from_servo_character_width(size);
1448            push(PropertyDeclaration::Width(
1449                specified::Size::LengthPercentage(NonNegative(
1450                    specified::LengthPercentage::Length(value),
1451                )),
1452            ));
1453        }
1454
1455        let width = if let Some(this) = self.downcast::<HTMLEmbedElement>() {
1456            this.width()
1457        } else if let Some(this) = self.downcast::<HTMLIFrameElement>() {
1458            this.width()
1459        } else if let Some(this) = self.downcast::<HTMLImageElement>() {
1460            this.width()
1461        } else if let Some(this) = self.downcast::<HTMLInputElement>() {
1462            this.width()
1463        } else if let Some(this) = self.downcast::<HTMLMarqueeElement>() {
1464            this.width()
1465        } else if let Some(this) = self.downcast::<HTMLObjectElement>() {
1466            this.width()
1467        } else if let Some(this) = self.downcast::<HTMLVideoElement>() {
1468            this.width()
1469        } else if let Some(this) = self.downcast::<HTMLTableElement>() {
1470            this.width()
1471        } else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
1472            this.width()
1473        } else if let Some(this) = self.downcast::<HTMLTableColElement>() {
1474            this.width()
1475        } else if let Some(this) = self.downcast::<HTMLHRElement>() {
1476            // https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width
1477            this.width()
1478        } else {
1479            LengthOrPercentageOrAuto::Auto
1480        };
1481
1482        self.apply_property_for_length_percentage(width, |value| {
1483            push(PropertyDeclaration::Width(
1484                specified::Size::LengthPercentage(NonNegative(value)),
1485            ));
1486        });
1487
1488        let height = if let Some(this) = self.downcast::<HTMLEmbedElement>() {
1489            this.height()
1490        } else if let Some(this) = self.downcast::<HTMLIFrameElement>() {
1491            this.height()
1492        } else if let Some(this) = self.downcast::<HTMLImageElement>() {
1493            this.height()
1494        } else if let Some(this) = self.downcast::<HTMLInputElement>() {
1495            this.height()
1496        } else if let Some(this) = self.downcast::<HTMLMarqueeElement>() {
1497            this.height()
1498        } else if let Some(this) = self.downcast::<HTMLObjectElement>() {
1499            this.height()
1500        } else if let Some(this) = self.downcast::<HTMLVideoElement>() {
1501            this.height()
1502        } else if let Some(this) = self.downcast::<HTMLTableElement>() {
1503            this.height()
1504        } else if let Some(this) = self.downcast::<HTMLTableCellElement>() {
1505            this.height()
1506        } else if let Some(this) = self.downcast::<HTMLTableRowElement>() {
1507            this.height()
1508        } else if let Some(this) = self.downcast::<HTMLTableSectionElement>() {
1509            this.height()
1510        } else {
1511            LengthOrPercentageOrAuto::Auto
1512        };
1513
1514        self.apply_property_for_length_percentage(height, |value| {
1515            push(PropertyDeclaration::Height(
1516                specified::Size::LengthPercentage(NonNegative(value)),
1517            ));
1518        });
1519
1520        let margin_right_left = if let Some(this) = self.downcast::<HTMLEmbedElement>() {
1521            this.margin_right_left()
1522        } else if let Some(this) = self.downcast::<HTMLImageElement>() {
1523            this.margin_right_left()
1524        } else if let Some(this) = self.downcast::<HTMLInputElement>() {
1525            this.margin_right_left()
1526        } else if let Some(this) = self.downcast::<HTMLMarqueeElement>() {
1527            this.margin_right_left()
1528        } else if let Some(this) = self.downcast::<HTMLObjectElement>() {
1529            this.margin_right_left()
1530        } else {
1531            LengthOrPercentageOrAuto::Auto
1532        };
1533
1534        self.apply_property_for_length_percentage(margin_right_left, |value| {
1535            let value = specified::Margin::LengthPercentage(value);
1536            push(PropertyDeclaration::MarginLeft(value.clone()));
1537            push(PropertyDeclaration::MarginRight(value));
1538        });
1539
1540        let margin_top_bottom = if let Some(this) = self.downcast::<HTMLEmbedElement>() {
1541            this.margin_top_bottom()
1542        } else if let Some(this) = self.downcast::<HTMLImageElement>() {
1543            this.margin_top_bottom()
1544        } else if let Some(this) = self.downcast::<HTMLInputElement>() {
1545            this.margin_top_bottom()
1546        } else if let Some(this) = self.downcast::<HTMLMarqueeElement>() {
1547            this.margin_top_bottom()
1548        } else if let Some(this) = self.downcast::<HTMLObjectElement>() {
1549            this.margin_top_bottom()
1550        } else {
1551            LengthOrPercentageOrAuto::Auto
1552        };
1553
1554        self.apply_property_for_length_percentage(margin_top_bottom, |value| {
1555            let value = specified::Margin::LengthPercentage(value);
1556            push(PropertyDeclaration::MarginTop(value.clone()));
1557            push(PropertyDeclaration::MarginBottom(value));
1558        });
1559
1560        if let Some(svg_element) = self.downcast::<SVGElement>() {
1561            svg_element.synthesize_presentational_hints(document, &mut push);
1562        }
1563
1564        if let Some(mathml_element) = self.downcast::<MathMLElement>() {
1565            mathml_element.synthesize_presentational_hints(document, &mut push);
1566        }
1567
1568        // Aspect ratio when providing both width and height.
1569        // https://html.spec.whatwg.org/multipage/#attributes-for-embedded-content-and-images
1570        if (self.is::<HTMLImageElement>() || self.is::<HTMLVideoElement>()) &&
1571            let LengthOrPercentageOrAuto::Length(width) = width &&
1572            let LengthOrPercentageOrAuto::Length(height) = height
1573        {
1574            let width_value = NonNegative(specified::Number::new(width.to_f32_px()));
1575            let height_value = NonNegative(specified::Number::new(height.to_f32_px()));
1576            let aspect_ratio = specified::position::AspectRatio {
1577                auto: true,
1578                ratio: PreferredRatio::Ratio(Ratio(width_value, height_value)),
1579            };
1580            push(PropertyDeclaration::AspectRatio(Box::new(aspect_ratio)));
1581        }
1582
1583        let cols = self
1584            .downcast::<HTMLTextAreaElement>()
1585            .map(LayoutDom::get_cols);
1586        if let Some(cols) = cols {
1587            let cols = cols as i32;
1588            if cols > 0 {
1589                // TODO(mttr) ServoCharacterWidth uses the size math for <input type="text">, but
1590                // the math for <textarea> is a little different since we need to take
1591                // scrollbar size into consideration (but we don't have a scrollbar yet!)
1592                //
1593                // https://html.spec.whatwg.org/multipage/#textarea-effective-width
1594                let value = specified::NoCalcLength::from_servo_character_width(cols);
1595                push(PropertyDeclaration::Width(
1596                    specified::Size::LengthPercentage(NonNegative(
1597                        specified::LengthPercentage::Length(value),
1598                    )),
1599                ));
1600            }
1601        }
1602
1603        if let Some(table) = self.downcast::<HTMLTableElement>() {
1604            if let Some(cellspacing) = table.get_cellspacing() {
1605                let width_value = specified::Length::from_px(cellspacing as f32);
1606                push(PropertyDeclaration::BorderSpacing(
1607                    border_spacing::SpecifiedValue::new(
1608                        width_value.clone().into(),
1609                        width_value.into(),
1610                    ),
1611                ));
1612            }
1613            if let Some(border) = table.get_border() {
1614                let width_value = specified::BorderSideWidth::from_px(border as f32);
1615                push(PropertyDeclaration::BorderTopWidth(width_value.clone()));
1616                push(PropertyDeclaration::BorderLeftWidth(width_value.clone()));
1617                push(PropertyDeclaration::BorderBottomWidth(width_value.clone()));
1618                push(PropertyDeclaration::BorderRightWidth(width_value));
1619            }
1620        }
1621
1622        if let Some(cellpadding) = self
1623            .downcast::<HTMLTableCellElement>()
1624            .and_then(|this| this.get_table())
1625            .and_then(|table| table.get_cellpadding())
1626        {
1627            let cellpadding = NonNegative(specified::LengthPercentage::Length(
1628                specified::NoCalcLength::from_px(cellpadding as f32),
1629            ));
1630            push(PropertyDeclaration::PaddingTop(cellpadding.clone()));
1631            push(PropertyDeclaration::PaddingLeft(cellpadding.clone()));
1632            push(PropertyDeclaration::PaddingBottom(cellpadding.clone()));
1633            push(PropertyDeclaration::PaddingRight(cellpadding));
1634        }
1635
1636        // https://html.spec.whatwg.org/multipage/#the-hr-element-2
1637        if let Some(size_info) = self
1638            .downcast::<HTMLHRElement>()
1639            .and_then(|hr_element| hr_element.get_size_info())
1640        {
1641            match size_info {
1642                SizePresentationalHint::SetHeightTo(height) => {
1643                    push(PropertyDeclaration::Height(height));
1644                },
1645                SizePresentationalHint::SetAllBorderWidthValuesTo(border_width) => {
1646                    push(PropertyDeclaration::BorderLeftWidth(border_width.clone()));
1647                    push(PropertyDeclaration::BorderRightWidth(border_width.clone()));
1648                    push(PropertyDeclaration::BorderTopWidth(border_width.clone()));
1649                    push(PropertyDeclaration::BorderBottomWidth(border_width));
1650                },
1651                SizePresentationalHint::SetBottomBorderWidthToZero => {
1652                    push(PropertyDeclaration::BorderBottomWidth(
1653                        specified::border::BorderSideWidth::from_px(0.),
1654                    ));
1655                },
1656            }
1657        }
1658
1659        let property_declaration_block = property_declaration_block?;
1660
1661        let shared_lock = &document.shared_style_locks().author;
1662        Some(ServoArc::new(shared_lock.wrap(property_declaration_block)))
1663    }
1664
1665    #[expect(unsafe_code)]
1666    pub(crate) fn synthesize_presentational_hints_for_legacy_attributes<'a, V>(self, hints: &mut V)
1667    where
1668        V: Push<ApplicableDeclarationBlock<'a>>,
1669    {
1670        debug_assert!(
1671            self.style_data().is_none() ||
1672                unsafe {
1673                    self.upcast::<Node>()
1674                        .get_flag(NodeFlags::HAS_RESOLVED_PRESENTATIONAL_HINTS)
1675                }
1676        );
1677        self.ensure_presentational_hints();
1678        if let Some(declarations) = self.presentational_hints() {
1679            // Safety: The declarations must outlive `'a`. That's the case for the presentational hints
1680            // above, which are owned by the element, and which can't change while we're matching.
1681            let declarations = unsafe { ServoArcBorrow::from_ref(&*(&**declarations as *const _)) };
1682            hints.push(ApplicableDeclarationBlock::from_declarations(
1683                StyleSourceBorrow::from_declarations(declarations),
1684                CascadeLevel::new(CascadeOrigin::PresHints),
1685                LayerOrder::root(),
1686            ));
1687        }
1688    }
1689
1690    pub(crate) fn get_span(self) -> Option<u32> {
1691        // Don't panic since `display` can cause this to be called on arbitrary elements.
1692        self.downcast::<HTMLTableColElement>()
1693            .and_then(|element| element.get_span())
1694    }
1695
1696    pub(crate) fn get_colspan(self) -> Option<u32> {
1697        // Don't panic since `display` can cause this to be called on arbitrary elements.
1698        self.downcast::<HTMLTableCellElement>()
1699            .and_then(|element| element.get_colspan())
1700    }
1701
1702    pub(crate) fn get_rowspan(self) -> Option<u32> {
1703        // Don't panic since `display` can cause this to be called on arbitrary elements.
1704        self.downcast::<HTMLTableCellElement>()
1705            .and_then(|element| element.get_rowspan())
1706    }
1707
1708    pub(crate) fn get_rows(self) -> Option<u32> {
1709        self.downcast::<HTMLTextAreaElement>()
1710            .map(|element| element.get_rows())
1711    }
1712
1713    #[inline]
1714    pub(crate) fn is_html_element(&self) -> bool {
1715        *self.namespace() == ns!(html)
1716    }
1717
1718    pub(crate) fn id_attribute(self) -> Option<AtomicRef<'dom, Atom>> {
1719        AtomicRef::filter_map(self.unsafe_get().id_attribute.borrow(), Option::as_ref)
1720    }
1721
1722    /// Like [`Self::id_attribute`], but without a borrow guard, for stylo's `TElement::id`.
1723    ///
1724    /// # Safety
1725    /// The id must not be mutated while the returned reference is alive.
1726    #[expect(unsafe_code)]
1727    pub(crate) unsafe fn id_attribute_unguarded(self) -> Option<&'dom Atom> {
1728        unsafe { (*self.unsafe_get().id_attribute.as_ptr()).as_ref() }
1729    }
1730
1731    #[expect(unsafe_code)]
1732    pub(crate) fn style_attribute(
1733        self,
1734    ) -> *const Option<ServoArc<Locked<PropertyDeclarationBlock>>> {
1735        unsafe { (self.unsafe_get()).style_attribute.borrow_for_layout() }
1736    }
1737
1738    pub(crate) fn local_name(self) -> &'dom LocalName {
1739        &(self.unsafe_get()).local_name
1740    }
1741
1742    pub(crate) fn namespace(self) -> &'dom Namespace {
1743        &(self.unsafe_get()).namespace
1744    }
1745
1746    /// <https://html.spec.whatwg.org/multipage/#language>
1747    pub(crate) fn get_lang_attr_val_for_layout(self) -> Option<&'dom str> {
1748        // > If the node is an element that has a lang attribute in the XML namespace set
1749        // >     Use the value of that attribute.
1750        if let Some(attr) = self.get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) {
1751            return Some(attr);
1752        }
1753        // > If the node is an HTML element or an element in the SVG namespace,
1754        // > and it has a lang in no namespace attribute set
1755        // >     Use the value of that attribute.
1756        if self.is_html_element() || self.namespace() == &ns!(svg) {
1757            return self.get_attr_val_for_layout(&ns!(), &local_name!("lang"));
1758        }
1759        None
1760    }
1761
1762    /// <https://html.spec.whatwg.org/multipage/#language>
1763    pub(crate) fn get_lang_for_layout(self) -> AtomString {
1764        // > To determine the language of a node,
1765        // > user agents must use the first appropriate step in the following list:
1766        let mut current_node = Some(self.upcast::<Node>());
1767        while let Some(node) = current_node {
1768            // > If the node's parent element is not null
1769            // >     Use the language of that parent element.
1770            // > If the node's parent is a shadow root
1771            // >     Use the language of that shadow root's host.
1772            current_node = node.composed_parent_node_ref();
1773            match node.downcast::<Element>() {
1774                Some(elem) => {
1775                    if let Some(attr) = elem.get_lang_attr_val_for_layout() {
1776                        return AtomString::from(attr);
1777                    }
1778                },
1779                None => continue,
1780            }
1781        }
1782        // > If there is a pragma-set default language set,
1783        // > then that is the language of the node.
1784        // > If there is no pragma-set default language set,
1785        // > then language information from a higher-level protocol (such as HTTP),
1786        // > if any, must be used as the final fallback language instead.
1787        // > In the absence of any such language information,
1788        // > and in cases where the higher-level protocol reports multiple languages,
1789        // > the language of the node is unknown,
1790        // > and the corresponding language tag is the empty string.
1791        //
1792        // We store the default_language when retrieving from HTTP
1793        // and then later overwrite if it we process a <meta> element
1794        // that sets content-language. Hence, we only need to call
1795        // default_language here to cover both cases.
1796        let document = self.upcast::<Node>().owner_doc_for_layout();
1797        if let Some(document_language) = document.default_language_for_layout().as_deref() {
1798            return AtomString::from(document_language);
1799        }
1800        AtomString::default()
1801    }
1802
1803    #[inline]
1804    pub(crate) fn get_state_for_layout(self) -> ElementState {
1805        (self.unsafe_get()).state.get()
1806    }
1807
1808    #[inline]
1809    pub(crate) fn insert_selector_flags(self, flags: ElementSelectorFlags) {
1810        debug_assert!(thread_state::get().is_layout());
1811        self.unsafe_get().insert_selector_flags(flags);
1812    }
1813
1814    #[inline]
1815    pub(crate) fn get_selector_flags(self) -> ElementSelectorFlags {
1816        self.unsafe_get().get_selector_flags()
1817    }
1818
1819    #[inline]
1820    #[expect(unsafe_code)]
1821    pub(crate) fn get_shadow_root_for_layout(self) -> Option<LayoutDom<'dom, ShadowRoot>> {
1822        unsafe {
1823            self.unsafe_get()
1824                .rare_data
1825                .borrow_for_layout()
1826                .as_ref()?
1827                .shadow_root
1828                .as_ref()
1829                .map(|sr| sr.to_layout())
1830        }
1831    }
1832
1833    #[inline]
1834    pub(crate) fn get_attr_for_layout(
1835        self,
1836        namespace: &Namespace,
1837        name: &LocalName,
1838    ) -> Option<&'dom AttrValue> {
1839        get_attr_for_layout(self, namespace, name)
1840    }
1841
1842    #[inline]
1843    pub(crate) fn get_attr_val_for_layout(
1844        self,
1845        namespace: &Namespace,
1846        name: &LocalName,
1847    ) -> Option<&'dom str> {
1848        get_attr_for_layout(self, namespace, name).map(|attr| &**attr)
1849    }
1850
1851    #[inline]
1852    #[expect(unsafe_code)]
1853    pub(crate) fn get_attr_vals_for_layout(
1854        self,
1855        name: &LocalName,
1856    ) -> impl Iterator<Item = &'dom AttrValue> {
1857        let storage = unsafe { self.unsafe_get().attrs.borrow_for_layout() };
1858        storage
1859            .iter()
1860            .filter(move |e: &&AttributeEntry| name == e.local_name_for_layout())
1861            .map(|e: &AttributeEntry| e.value_for_layout())
1862    }
1863
1864    #[expect(unsafe_code)]
1865    pub(crate) fn each_custom_state_for_layout(self, mut callback: impl FnMut(&AtomIdent)) {
1866        let rare_data = unsafe { self.unsafe_get().rare_data.borrow_for_layout() };
1867        let Some(rare_data) = rare_data.as_ref() else {
1868            return;
1869        };
1870        let Some(element_internals) = rare_data.element_internals.as_ref() else {
1871            return;
1872        };
1873
1874        let element_internals: LayoutDom<'_, _> = unsafe { element_internals.to_layout() };
1875        if let Some(states) = element_internals.unsafe_get().custom_states_for_layout() {
1876            for state in states.unsafe_get().set_for_layout().iter() {
1877                // FIXME: This creates new atoms whenever it is called, which is not optimal.
1878                callback(&AtomIdent::from(&*state.str()));
1879            }
1880        }
1881    }
1882}
1883
1884impl Element {
1885    pub(crate) fn is_html_element(&self) -> bool {
1886        self.namespace == ns!(html)
1887    }
1888
1889    pub(crate) fn is_svg_element(&self) -> bool {
1890        self.namespace == ns!(svg)
1891    }
1892
1893    pub(crate) fn html_element_in_html_document(&self) -> bool {
1894        self.is_html_element() && self.upcast::<Node>().is_in_html_doc()
1895    }
1896
1897    pub(crate) fn local_name(&self) -> &LocalName {
1898        &self.local_name
1899    }
1900
1901    pub(crate) fn parsed_name(&self, mut name: DOMString) -> LocalName {
1902        if self.html_element_in_html_document() {
1903            name.make_ascii_lowercase();
1904        }
1905        LocalName::from(name)
1906    }
1907
1908    pub(crate) fn namespace(&self) -> &Namespace {
1909        &self.namespace
1910    }
1911
1912    pub(crate) fn prefix(&self) -> Ref<'_, Option<Prefix>> {
1913        self.prefix.borrow()
1914    }
1915
1916    pub(crate) fn set_prefix(&self, prefix: Option<Prefix>) {
1917        *self.prefix.borrow_mut() = prefix;
1918    }
1919
1920    pub(crate) fn set_custom_element_registry(
1921        &self,
1922        registry: Option<&CustomElementRegistry>,
1923        no_gc: &NoGC,
1924    ) {
1925        self.ensure_rare_data(no_gc).custom_element_registry = registry.map(Dom::from_ref);
1926    }
1927
1928    pub(crate) fn custom_element_registry(&self) -> Option<DomRoot<CustomElementRegistry>> {
1929        self.rare_data()
1930            .as_ref()?
1931            .custom_element_registry
1932            .as_deref()
1933            .map(DomRoot::from_ref)
1934    }
1935
1936    pub(crate) fn attrs(&self) -> &AttributeStorage {
1937        &self.attrs
1938    }
1939
1940    pub(crate) fn dom_attrs(&self, cx: &mut JSContext) -> &AttributeStorage {
1941        // Materialize all entries to Dom<Attr> so callers can access full Attr nodes.
1942        let len = self.attrs.borrow().len();
1943        for i in 0..len {
1944            self.attrs.ensure_dom(cx, i, self);
1945        }
1946        &self.attrs
1947    }
1948
1949    /// Element branch of <https://dom.spec.whatwg.org/#locate-a-namespace>
1950    pub(crate) fn locate_namespace(&self, prefix: Option<DOMString>) -> Namespace {
1951        let namespace_prefix = prefix.as_ref().map(|s| Prefix::from(&*s.str()));
1952
1953        // Step 1. If prefix is "xml", then return the XML namespace.
1954        if namespace_prefix == Some(namespace_prefix!("xml")) {
1955            return ns!(xml);
1956        }
1957
1958        // Step 2. If prefix is "xmlns", then return the XMLNS namespace.
1959        if namespace_prefix == Some(namespace_prefix!("xmlns")) {
1960            return ns!(xmlns);
1961        }
1962
1963        let prefix = prefix.map(LocalName::from);
1964
1965        let inclusive_ancestor_elements = self
1966            .upcast::<Node>()
1967            .inclusive_ancestors(ShadowIncluding::No)
1968            .filter_map(DomRoot::downcast::<Self>);
1969
1970        // Step 5. If its parent element is null, then return null.
1971        // Step 6. Return the result of running locate a namespace on its parent element using prefix.
1972        for element in inclusive_ancestor_elements {
1973            // Step 3. If its namespace is non-null and its namespace prefix is prefix, then return namespace.
1974            if element.namespace() != &ns!() &&
1975                element.prefix().as_ref().map(|p| &**p) == prefix.as_deref()
1976            {
1977                return element.namespace().clone();
1978            }
1979
1980            // Step 4. If it has an attribute whose namespace is the XMLNS namespace, namespace prefix
1981            // is "xmlns", and local name is prefix, or if prefix is null and it has an attribute
1982            // whose namespace is the XMLNS namespace, namespace prefix is null, and local name is
1983            // "xmlns", then return its value if it is not the empty string, and null otherwise.
1984            let found_ns = element.attrs.borrow().iter().find_map(|attr| {
1985                if attr.namespace() != &ns!(xmlns) {
1986                    return None;
1987                }
1988                match (attr.prefix(), prefix.as_ref()) {
1989                    (Some(&namespace_prefix!("xmlns")), Some(prefix)) => {
1990                        if attr.local_name() == prefix {
1991                            Some(Namespace::from(&**attr.value()))
1992                        } else {
1993                            None
1994                        }
1995                    },
1996                    (None, None) => {
1997                        if attr.local_name() == &local_name!("xmlns") {
1998                            Some(Namespace::from(&**attr.value()))
1999                        } else {
2000                            None
2001                        }
2002                    },
2003                    _ => None,
2004                }
2005            });
2006
2007            if let Some(ns) = found_ns {
2008                return ns;
2009            }
2010        }
2011
2012        ns!()
2013    }
2014
2015    pub(crate) fn name_attribute(&self) -> Option<Atom> {
2016        self.rare_data().as_ref()?.name_attribute.clone()
2017    }
2018
2019    pub(crate) fn style_attribute(
2020        &self,
2021    ) -> &DomRefCell<Option<ServoArc<Locked<PropertyDeclarationBlock>>>> {
2022        &self.style_attribute
2023    }
2024
2025    #[cfg(feature = "devtools")]
2026    pub(crate) fn summarize(&self) -> Vec<devtools_traits::AttrInfo> {
2027        self.attrs
2028            .borrow()
2029            .iter()
2030            .map(|attr| attr.summarize())
2031            .collect()
2032    }
2033
2034    pub(crate) fn is_void(&self) -> bool {
2035        if self.namespace != ns!(html) {
2036            return false;
2037        }
2038        match self.local_name {
2039            /* List of void elements from
2040            https://html.spec.whatwg.org/multipage/#html-fragment-serialisation-algorithm */
2041            local_name!("area") |
2042            local_name!("base") |
2043            local_name!("basefont") |
2044            local_name!("bgsound") |
2045            local_name!("br") |
2046            local_name!("col") |
2047            local_name!("embed") |
2048            local_name!("frame") |
2049            local_name!("hr") |
2050            local_name!("img") |
2051            local_name!("input") |
2052            local_name!("keygen") |
2053            local_name!("link") |
2054            local_name!("meta") |
2055            local_name!("param") |
2056            local_name!("source") |
2057            local_name!("track") |
2058            local_name!("wbr") => true,
2059            _ => false,
2060        }
2061    }
2062
2063    pub(crate) fn root_element(&self) -> DomRoot<Element> {
2064        if self.node.is_in_a_document_tree() {
2065            self.upcast::<Node>()
2066                .owner_doc()
2067                .GetDocumentElement()
2068                .unwrap()
2069        } else {
2070            self.upcast::<Node>()
2071                .inclusive_ancestors(ShadowIncluding::No)
2072                .filter_map(DomRoot::downcast)
2073                .last()
2074                .expect("We know inclusive_ancestors will return `self` which is an element")
2075        }
2076    }
2077
2078    /// <https://dom.spec.whatwg.org/#locate-a-namespace-prefix>
2079    pub(crate) fn lookup_prefix(&self, namespace: Namespace) -> Option<DOMString> {
2080        for node in self
2081            .upcast::<Node>()
2082            .inclusive_ancestors(ShadowIncluding::No)
2083        {
2084            let element = node.downcast::<Element>()?;
2085            // Step 1.
2086            if *element.namespace() == namespace &&
2087                let Some(prefix) = element.GetPrefix()
2088            {
2089                return Some(prefix);
2090            }
2091
2092            // Step 2.
2093            for attr in element.attrs.borrow().iter() {
2094                if attr.prefix() == Some(&namespace_prefix!("xmlns")) &&
2095                    **attr.value() == *namespace
2096                {
2097                    return Some(TracedDOMString::from(attr.local_name().clone()).root());
2098                }
2099            }
2100        }
2101        None
2102    }
2103
2104    /// <https://dom.spec.whatwg.org/#document-element>
2105    pub(crate) fn is_document_element(&self) -> bool {
2106        if let Some(document_element) = self.owner_document().GetDocumentElement() {
2107            *document_element == *self
2108        } else {
2109            false
2110        }
2111    }
2112
2113    /// <https://html.spec.whatwg.org/multipage/#dom-document-activeelement>
2114    pub(crate) fn is_active_element(&self) -> bool {
2115        if let Some(active_element) = self.owner_document().GetActiveElement() {
2116            *active_element == *self
2117        } else {
2118            false
2119        }
2120    }
2121
2122    /// <https://html.spec.whatwg.org/multipage/#concept-element-disabled>
2123    pub(crate) fn is_actually_disabled(&self) -> bool {
2124        // This corresponds to the disabled state, so we can return that instead of recomputing if
2125        // an element is actually disabled on every call.
2126        self.state.get().contains(ElementState::DISABLED)
2127    }
2128
2129    pub(crate) fn invalidate_disabled_state(&self, cx: &mut JSContext) {
2130        if !self.enabled_state_applies() {
2131            return;
2132        }
2133
2134        let actually_disabled = self.compute_is_actually_disabled(cx);
2135        if actually_disabled == self.is_actually_disabled() {
2136            return;
2137        }
2138
2139        // https://html.spec.whatwg.org/multipage/#selector-disabled
2140        // > The :disabled pseudo-class must match any element that is actually disabled.
2141        self.set_state(cx.no_gc(), ElementState::DISABLED, actually_disabled);
2142
2143        // https://html.spec.whatwg.org/multipage/#selector-enabled
2144        // > The :enabled pseudo-class must match any button, input, select, textarea, optgroup,
2145        // > option, fieldset element, or form-associated custom element that is not actually
2146        // > disabled.
2147        self.set_state(cx.no_gc(), ElementState::ENABLED, !actually_disabled);
2148
2149        // https://html.spec.whatwg.org/multipage/#enabling-and-disabling-form-controls:-the-disabled-attribute
2150        // > If an element is disabled, it is barred from constraint validation.
2151        if let Some(validatable) = self.as_maybe_validatable() {
2152            validatable
2153                .validity_state(cx)
2154                .perform_validation_and_update(cx, ValidationFlags::all());
2155        } else if let Some(internals) = self.get_element_internals() {
2156            internals.validity_state(cx).update_pseudo_classes(cx);
2157        }
2158
2159        // https://html.spec.whatwg.org/multipage/#custom-element-reactions
2160        // > When the disabled state of a form-associated custom element is changed, its
2161        // > formDisabledCallback is called, given the new state as an argument.
2162        //
2163        // The linked spec refers to the form element disabled concept, but for form associated
2164        // custom elements this is the same as being actually disabled.
2165        if self
2166            .downcast::<HTMLElement>()
2167            .is_some_and(HTMLElement::is_form_associated_custom_element)
2168        {
2169            ScriptThread::enqueue_callback_reaction(
2170                cx,
2171                self,
2172                CallbackReaction::FormDisabled(actually_disabled),
2173                None,
2174            );
2175        }
2176
2177        if let Some(input) = self.downcast::<HTMLInputElement>() {
2178            input.disabled_state_changed(cx);
2179        } else if let Some(textarea) = self.downcast::<HTMLTextAreaElement>() {
2180            textarea.disabled_state_changed(cx.no_gc());
2181        }
2182
2183        if actually_disabled && (self.is::<HTMLInputElement>() || self.is::<HTMLSelectElement>()) {
2184            self.owner_document()
2185                .embedder_controls()
2186                .hide_embedder_control_for_element(self);
2187        }
2188    }
2189
2190    pub(crate) fn invalidate_descendants_disabled_state(&self, cx: &mut JSContext) {
2191        for descendant in self
2192            .upcast::<Node>()
2193            .traverse_preorder(ShadowIncluding::No)
2194            .skip(1)
2195            .filter_map(DomRoot::downcast::<Element>)
2196        {
2197            descendant.invalidate_disabled_state(cx);
2198        }
2199    }
2200
2201    /// <https://html.spec.whatwg.org/multipage/#concept-element-disabled>
2202    fn compute_is_actually_disabled(&self, cx: &mut JSContext) -> bool {
2203        // > An element is said to be actually disabled if it is one of the following:
2204        // > - a button element that is disabled
2205        // > - an input element that is disabled
2206        // > - a select element that is disabled
2207        // > - a textarea element that is disabled
2208        // > - a form-associated custom element that is disabled
2209        if let Some(html_element) = self.downcast::<HTMLElement>() &&
2210            html_element.is_disableable_form_control()
2211        {
2212            return html_element.is_form_element_disabled(cx.no_gc());
2213        }
2214
2215        // > - an optgroup element that has a disabled attribute or whose nearest ancestor select is disabled
2216        if let Some(opt_group) = self.downcast::<HTMLOptGroupElement>() {
2217            return self.has_attribute(&local_name!("disabled")) ||
2218                opt_group
2219                    .nearest_ancestor_select()
2220                    .is_some_and(|select_element| {
2221                        select_element
2222                            .upcast::<HTMLElement>()
2223                            .is_form_element_disabled(cx.no_gc())
2224                    });
2225        }
2226
2227        // > - an option element that is disabled or whose nearest ancestor select is disabled
2228        if let Some(option) = self.downcast::<HTMLOptionElement>() {
2229            return option.is_option_disabled(cx.no_gc()) ||
2230                option
2231                    .nearest_ancestor_select()
2232                    .is_some_and(|select_element| {
2233                        select_element
2234                            .upcast::<HTMLElement>()
2235                            .is_form_element_disabled(cx.no_gc())
2236                    });
2237        }
2238
2239        // > - a fieldset element that is a disabled fieldset
2240        if let Some(fieldset) = self.downcast::<HTMLFieldSetElement>() {
2241            return fieldset.is_fieldset_disabled(cx.no_gc());
2242        }
2243
2244        false
2245    }
2246
2247    /// <https://html.spec.whatwg.org/multipage/#selector-enabled>
2248    fn enabled_state_applies(&self) -> bool {
2249        // > ... any button, input, select, textarea, optgroup, option, fieldset element, or
2250        // > form-associated custom element
2251        matches!(
2252            self.upcast::<Node>().type_id(),
2253            NodeTypeId::Element(ElementTypeId::HTMLElement(
2254                HTMLElementTypeId::HTMLButtonElement |
2255                    HTMLElementTypeId::HTMLInputElement |
2256                    HTMLElementTypeId::HTMLSelectElement |
2257                    HTMLElementTypeId::HTMLTextAreaElement |
2258                    HTMLElementTypeId::HTMLOptGroupElement |
2259                    HTMLElementTypeId::HTMLOptionElement |
2260                    HTMLElementTypeId::HTMLFieldSetElement,
2261            ))
2262        ) || self
2263            .downcast::<HTMLElement>()
2264            .is_some_and(HTMLElement::is_form_associated_custom_element)
2265    }
2266
2267    pub(crate) fn push_new_attribute(
2268        &self,
2269        cx: &mut JSContext,
2270        local_name: LocalName,
2271        value: AttrValue,
2272        name: LocalName,
2273        namespace: Namespace,
2274        prefix: Option<Prefix>,
2275    ) {
2276        // Build ContentAttributeData on the stack. We keep the original on the
2277        // stack for the AttrRef (used by handle_attribute_changes / attribute_mutated),
2278        // and push a clone into the RefCell. This avoids holding a RefCell borrow
2279        // while attribute_mutated callbacks run (they may call get_attribute() etc.).
2280        let data = ContentAttributeData {
2281            identifier: AttrName::new(local_name, name, namespace, prefix),
2282            value,
2283        };
2284        let attr_ref = AttrRef::Raw(&data);
2285        self.will_mutate_attr(cx.no_gc(), attr_ref);
2286        // Step 1: Append to attribute list (push clone, keep original on stack).
2287        self.attrs.push_raw(ContentAttributeData {
2288            identifier: data.identifier.clone(),
2289            value: data.value.clone(),
2290        });
2291        // Step 4: Handle attribute changes using stack-local AttrRef.
2292        self.handle_attribute_changes(cx, attr_ref, None, Some(&*attr_ref.value()));
2293    }
2294
2295    /// <https://dom.spec.whatwg.org/#handle-attribute-changes>
2296    fn handle_attribute_changes(
2297        &self,
2298        cx: &mut JSContext,
2299        attr: AttrRef<'_>,
2300        old_value: Option<&AttrValue>,
2301        new_value: Option<&AttrValue>,
2302    ) {
2303        // Step 1. Queue a mutation record of "attributes" for element with attribute’s local name,
2304        // attribute’s namespace, oldValue, « », « », null, and null.
2305        let name = attr.local_name().clone();
2306        let namespace = attr.namespace().clone();
2307        let mutation = LazyCell::new(|| Mutation::Attribute {
2308            name: name.clone(),
2309            namespace: namespace.clone(),
2310            old_value,
2311        });
2312        MutationObserver::queue_a_mutation_record(cx, &self.node, mutation);
2313
2314        // Avoid double borrow
2315        let has_new_value = new_value.is_some();
2316
2317        // Step 2. If element is custom, then enqueue a custom element callback reaction with element,
2318        // callback name "attributeChangedCallback", and « attribute’s local name, oldValue, newValue, attribute’s namespace ».
2319        if self.is_custom() {
2320            let reaction = CallbackReaction::AttributeChanged(
2321                attr.local_name().clone(),
2322                old_value,
2323                new_value,
2324                attr.namespace().clone(),
2325            );
2326            ScriptThread::enqueue_callback_reaction(cx, self, reaction, None);
2327        }
2328
2329        // Step 3. Run the attribute change steps with element, attribute’s local name, oldValue, newValue, and attribute’s namespace.
2330        if is_relevant_attribute(attr.namespace(), attr.local_name()) {
2331            let attribute_mutation = if has_new_value {
2332                AttributeMutation::Set(old_value)
2333            } else {
2334                AttributeMutation::Removed
2335            };
2336            vtable_for(self.upcast()).attribute_mutated(cx, attr, attribute_mutation);
2337        }
2338    }
2339
2340    /// <https://dom.spec.whatwg.org/#concept-element-attributes-change>
2341    pub(crate) fn change_attribute(&self, cx: &mut JSContext, attr: &Attr, mut value: AttrValue) {
2342        // Step 1. Let oldValue be attribute’s value.
2343        //
2344        // Clone to avoid double borrow
2345        let old_value = &attr.value().clone();
2346        // Step 2. Set attribute’s value to value.
2347        self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2348        attr.swap_value(&mut value);
2349        // Step 3. Handle attribute changes for attribute with attribute’s element, oldValue, and value.
2350        //
2351        // Clone: attribute change steps can mutates this attribute again in beforetoggle handler.
2352        let new_value = attr.value().clone();
2353        self.handle_attribute_changes(cx, AttrRef::Dom(attr), Some(old_value), Some(&new_value));
2354    }
2355
2356    /// <https://dom.spec.whatwg.org/#concept-element-attributes-append>
2357    pub(crate) fn push_attribute(&self, cx: &mut JSContext, attr: &Attr) {
2358        // Step 2. Set attribute’s element to element.
2359        //
2360        // Handled by callers of this function and asserted here.
2361        assert!(attr.GetOwnerElement().as_deref() == Some(self));
2362        // Step 3. Set attribute’s node document to element’s node document.
2363        //
2364        // Handled by callers of this function and asserted here.
2365        assert!(attr.upcast::<Node>().owner_doc() == self.node.owner_doc());
2366        // Step 1. Append attribute to element’s attribute list.
2367        self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2368        self.attrs.push_dom(attr);
2369        // Step 4. Handle attribute changes for attribute with element, null, and attribute’s value.
2370        //
2371        // Put on a separate line to avoid double borrow
2372        self.handle_attribute_changes(cx, AttrRef::Dom(attr), None, Some(&*attr.value()));
2373    }
2374
2375    pub(crate) fn with_attribute<R, F>(
2376        &self,
2377        namespace: &Namespace,
2378        local_name: &LocalName,
2379        map_func: F,
2380    ) -> Option<R>
2381    where
2382        F: FnOnce(AttrRef<'_>) -> R,
2383    {
2384        self.attrs
2385            .borrow()
2386            .iter()
2387            .find(|attribute| {
2388                attribute.local_name() == local_name && attribute.namespace() == namespace
2389            })
2390            .map(map_func)
2391    }
2392
2393    pub(crate) fn attribute_str_ref<'a>(
2394        &'a self,
2395        namespace: &Namespace,
2396        local_name: &LocalName,
2397    ) -> Option<AttrStrRef<'a>> {
2398        AttrStrRef::maybe_new(self.attrs.borrow(), namespace, local_name)
2399    }
2400
2401    /// This is the inner logic for:
2402    /// <https://dom.spec.whatwg.org/#concept-element-attributes-get-by-namespace>
2403    ///
2404    /// In addition to taking a namespace argument, this version does not require the attribute
2405    /// to be lowercase ASCII, in accordance with the specification.
2406    pub(crate) fn get_attribute_with_namespace(
2407        &self,
2408        cx: &mut JSContext,
2409        namespace: &Namespace,
2410        local_name: &LocalName,
2411    ) -> Option<DomRoot<Attr>> {
2412        let idx = self
2413            .attrs
2414            .borrow()
2415            .iter()
2416            .position(|a| a.local_name() == local_name && a.namespace() == namespace)?;
2417        Some(self.attrs.ensure_dom(cx, idx, self))
2418    }
2419
2420    /// <https://dom.spec.whatwg.org/#concept-element-attributes-get-by-name>
2421    pub(crate) fn get_attribute_by_name(
2422        &self,
2423        cx: &mut JSContext,
2424        name: DOMString,
2425    ) -> Option<DomRoot<Attr>> {
2426        let name = &self.parsed_name(name);
2427        let idx = self.attrs.borrow().iter().position(|a| a.name() == name)?;
2428        let attr_dom = Some(self.attrs.ensure_dom(cx, idx, self));
2429        fn id_and_name_must_be_atoms(name: &LocalName, maybe_attr: &Option<DomRoot<Attr>>) -> bool {
2430            if *name == local_name!("id") || *name == local_name!("name") {
2431                match maybe_attr {
2432                    None => true,
2433                    Some(attr) => matches!(*attr.value(), AttrValue::Atom(_)),
2434                }
2435            } else {
2436                true
2437            }
2438        }
2439        debug_assert!(id_and_name_must_be_atoms(name, &attr_dom));
2440        attr_dom
2441    }
2442
2443    pub(crate) fn set_attribute_from_parser(
2444        &self,
2445        cx: &mut JSContext,
2446        qname: QualName,
2447        value: DOMString,
2448    ) {
2449        // Don't set if the attribute already exists, so we can handle add_attrs_if_missing
2450        if self
2451            .attrs
2452            .borrow()
2453            .iter()
2454            .any(|a| *a.local_name() == qname.local && *a.namespace() == qname.ns)
2455        {
2456            return;
2457        }
2458
2459        let name = match qname.prefix {
2460            None => qname.local.clone(),
2461            Some(ref prefix) => {
2462                let name = format!("{}:{}", &**prefix, &*qname.local);
2463                LocalName::from(name)
2464            },
2465        };
2466        let value = self.parse_attribute(&qname.ns, &qname.local, value);
2467        self.push_new_attribute(cx, qname.local, value, name, qname.ns, qname.prefix);
2468    }
2469
2470    pub(crate) fn set_attribute(&self, cx: &mut JSContext, name: &LocalName, value: AttrValue) {
2471        debug_assert_eq!(
2472            *name,
2473            name.to_ascii_lowercase(),
2474            "All attribute accesses should use a lowercase ASCII name"
2475        );
2476        debug_assert!(!name.contains(':'));
2477
2478        self.set_first_matching_attribute(
2479            cx,
2480            name.clone(),
2481            value,
2482            name.clone(),
2483            ns!(),
2484            None,
2485            |attr| attr.local_name() == name,
2486        );
2487    }
2488
2489    pub(crate) fn set_attribute_with_namespace(
2490        &self,
2491        cx: &mut JSContext,
2492        local_name: LocalName,
2493        value: AttrValue,
2494        name: LocalName,
2495        namespace: Namespace,
2496        prefix: Option<Prefix>,
2497    ) {
2498        self.set_first_matching_attribute(
2499            cx,
2500            local_name.clone(),
2501            value,
2502            name,
2503            namespace.clone(),
2504            prefix,
2505            |attr| *attr.local_name() == local_name && *attr.namespace() == namespace,
2506        );
2507    }
2508
2509    /// <https://dom.spec.whatwg.org/#concept-element-attributes-set-value>
2510    #[expect(clippy::too_many_arguments)]
2511    fn set_first_matching_attribute<F>(
2512        &self,
2513        cx: &mut JSContext,
2514        local_name: LocalName,
2515        value: AttrValue,
2516        name: LocalName,
2517        namespace: Namespace,
2518        prefix: Option<Prefix>,
2519        find: F,
2520    ) where
2521        F: Fn(AttrRef<'_>) -> bool,
2522    {
2523        // Step 1. Let attribute be the result of getting an attribute given namespace, localName, and element.
2524        // First check if a matching attribute exists (works for both Raw and Dom).
2525        let found_idx = self.attrs.borrow().iter().position(find);
2526        if let Some(idx) = found_idx {
2527            let attr = self.attrs.ensure_dom(cx, idx, self);
2528            // Step 3. Change attribute to value.
2529            self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(&attr));
2530            self.change_attribute(cx, &attr, value);
2531        } else {
2532            // Step 2. If attribute is null, create an attribute whose namespace is namespace,
2533            // namespace prefix is prefix, local name is localName, value is value,
2534            // and node document is element’s node document,
2535            // then append this attribute to element, and then return.
2536            self.push_new_attribute(cx, local_name, value, name, namespace, prefix);
2537        };
2538    }
2539
2540    pub(crate) fn parse_attribute(
2541        &self,
2542        namespace: &Namespace,
2543        local_name: &LocalName,
2544        value: DOMString,
2545    ) -> AttrValue {
2546        if is_relevant_attribute(namespace, local_name) {
2547            vtable_for(self.upcast()).parse_plain_attribute(local_name, value)
2548        } else {
2549            AttrValue::String(value.into())
2550        }
2551    }
2552
2553    pub(crate) fn remove_attribute(
2554        &self,
2555        cx: &mut JSContext,
2556        namespace: &Namespace,
2557        local_name: &LocalName,
2558    ) -> Option<DomRoot<Attr>> {
2559        self.remove_first_matching_attribute(cx, |attr| {
2560            attr.namespace() == namespace && attr.local_name() == local_name
2561        })
2562    }
2563
2564    pub(crate) fn remove_attribute_by_name(
2565        &self,
2566        cx: &mut JSContext,
2567        name: &LocalName,
2568    ) -> Option<DomRoot<Attr>> {
2569        self.remove_first_matching_attribute(cx, |attr| attr.name() == name)
2570    }
2571
2572    /// <https://dom.spec.whatwg.org/#concept-element-attributes-remove>
2573    fn remove_first_matching_attribute<F>(
2574        &self,
2575        cx: &mut JSContext,
2576        find: F,
2577    ) -> Option<DomRoot<Attr>>
2578    where
2579        F: Fn(AttrRef<'_>) -> bool,
2580    {
2581        let idx = self.attrs.borrow().iter().position(find);
2582        idx.map(|idx| {
2583            let attr = self.attrs.ensure_dom(cx, idx, self);
2584
2585            // Step 2. Remove attribute from element’s attribute list.
2586            self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(&attr));
2587            self.attrs.remove(idx);
2588            // Step 3. Set attribute’s element to null.
2589            attr.set_owner(cx, None);
2590            // Step 4. Handle attribute changes for attribute with element, attribute’s value, and null.
2591            self.handle_attribute_changes(cx, AttrRef::Dom(&attr), Some(&attr.value()), None);
2592
2593            attr
2594        })
2595    }
2596
2597    pub(crate) fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
2598        self.any_tokenlist_attribute(&local_name!("class"), |atom| {
2599            case_sensitivity.eq_atom(name, atom)
2600        })
2601    }
2602
2603    pub(crate) fn has_attribute(&self, local_name: &LocalName) -> bool {
2604        debug_assert_eq!(
2605            *local_name,
2606            local_name.to_ascii_lowercase(),
2607            "All attribute accesses should use a lowercase ASCII name"
2608        );
2609        debug_assert!(!local_name.contains(':'));
2610        self.attrs
2611            .borrow()
2612            .iter()
2613            .any(|attr| attr.local_name() == local_name && attr.namespace() == &ns!())
2614    }
2615
2616    pub(crate) fn will_mutate_attr(&self, no_gc: &NoGC, attr: AttrRef<'_>) {
2617        self.upcast::<Node>()
2618            .owner_doc_unrooted(no_gc)
2619            .element_attr_will_change(self, attr);
2620    }
2621
2622    /// <https://html.spec.whatwg.org/multipage/#the-style-attribute>
2623    fn update_style_attribute(
2624        &self,
2625        cx: &mut JSContext,
2626        attr: AttrRef<'_>,
2627        mutation: AttributeMutation,
2628    ) {
2629        let doc = self.upcast::<Node>().owner_doc();
2630        // Modifying the `style` attribute might change style.
2631        *self.style_attribute.borrow_mut() = match mutation {
2632            AttributeMutation::Set(_) => {
2633                let value = attr.as_attr().map_or_else(
2634                    || attr.value(),
2635                    |attribute| AttrValueRef::Borrowed(attribute.value()),
2636                );
2637
2638                Some(match &*value {
2639                    AttrValue::Declaration { block, .. } => block.clone(),
2640                    _ => {
2641                        let win = self.owner_window();
2642                        let source = &**attr.value();
2643                        let global = &self.owner_global();
2644                        // However, if the Should element's inline behavior be blocked by
2645                        // Content Security Policy? algorithm returns "Blocked" when executed
2646                        // upon the attribute's element, "style attribute", and the attribute's value,
2647                        // then the style rules defined in the attribute's value must not be applied to the element. [CSP]
2648                        if global.call_on_csp_list(|csp_list| {
2649                            csp_list.should_elements_inline_type_behavior_be_blocked(
2650                                cx,
2651                                global,
2652                                self,
2653                                InlineCheckType::StyleAttribute,
2654                                source,
2655                                doc.get_current_parser_line(),
2656                            )
2657                        }) {
2658                            return;
2659                        }
2660                        ServoArc::new(doc.style_shared_author_lock().wrap(parse_style_attribute(
2661                            source,
2662                            &UrlExtraData(doc.base_url().get_arc()),
2663                            Some(win.css_error_reporter()),
2664                            doc.quirks_mode(),
2665                            CssRuleType::Style,
2666                        )))
2667                    },
2668                })
2669            },
2670            AttributeMutation::Removed => None,
2671        };
2672    }
2673
2674    /// <https://dom.spec.whatwg.org/#concept-element-attributes-set>
2675    /// including steps of
2676    /// <https://dom.spec.whatwg.org/#concept-element-attributes-replace>
2677    fn set_attribute_node(
2678        &self,
2679        cx: &mut JSContext,
2680        attr: &Attr,
2681    ) -> Fallible<Option<DomRoot<Attr>>> {
2682        // Step 1. Let verifiedValue be the result of calling
2683        // get Trusted Types-compliant attribute value with attr’s local name,
2684        // attr’s namespace, element, and attr’s value. [TRUSTED-TYPES]
2685        let verified_value = TrustedTypePolicyFactory::get_trusted_types_compliant_attribute_value(
2686            cx,
2687            self.namespace(),
2688            self.local_name(),
2689            attr.local_name(),
2690            Some(attr.namespace()),
2691            TrustedTypeOrString::String(attr.Value()),
2692            &self.owner_global(),
2693        )?;
2694
2695        // Step 2. If attr’s element is neither null nor element,
2696        // throw an "InUseAttributeError" DOMException.
2697        if let Some(owner) = attr.GetOwnerElement() &&
2698            &*owner != self
2699        {
2700            return Err(Error::InUseAttribute(Some(
2701                "Attribute is already in use by another element".into(),
2702            )));
2703        }
2704
2705        let vtable = vtable_for(self.upcast());
2706
2707        // Step 5. Set attr’s value to verifiedValue.
2708        //
2709        // This ensures that the attribute is of the expected kind for this
2710        // specific element. This is inefficient and should probably be done
2711        // differently.
2712        attr.swap_value(
2713            &mut vtable.parse_plain_attribute(attr.local_name(), verified_value.clone()),
2714        );
2715
2716        // Step 3. Let oldAttr be the result of getting an attribute given attr’s namespace, attr’s local name, and element.
2717        let position = self.attrs.borrow().iter().position(|old_attr| {
2718            attr.namespace() == old_attr.namespace() && attr.local_name() == old_attr.local_name()
2719        });
2720
2721        let old_attr = if let Some(position) = position {
2722            let old_attr = self.attrs.ensure_dom(cx, position, self);
2723
2724            // Step 4. If oldAttr is attr, return attr.
2725            if &*old_attr == attr {
2726                return Ok(Some(DomRoot::from_ref(attr)));
2727            }
2728
2729            // Step 6. If oldAttr is non-null, then replace oldAttr with attr.
2730            //
2731            // Start of steps for https://dom.spec.whatwg.org/#concept-element-attributes-replace
2732
2733            // Step 1. Let element be oldAttribute’s element.
2734            //
2735            // Skipped, as that points to self.
2736
2737            // Step 2. Replace oldAttribute by newAttribute in element’s attribute list.
2738            self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2739            self.attrs
2740                .set(position, AttributeEntry::Dom(Dom::from_ref(attr)));
2741            // Step 3. Set newAttribute’s element to element.
2742            attr.set_owner(cx, Some(self));
2743            // Step 4. Set newAttribute’s node document to element’s node document.
2744            attr.upcast::<Node>().set_owner_doc(&self.node.owner_doc());
2745            // Step 5. Set oldAttribute’s element to null.
2746            old_attr.set_owner(cx, None);
2747            // Step 6. Handle attribute changes for oldAttribute with element, oldAttribute’s value, and newAttribute’s value.
2748            self.handle_attribute_changes(
2749                cx,
2750                AttrRef::Dom(attr),
2751                Some(&old_attr.value()),
2752                Some(&AttrValue::String(verified_value.into())),
2753            );
2754
2755            Some(old_attr)
2756        } else {
2757            // Step 7. Otherwise, append attr to element.
2758            attr.set_owner(cx, Some(self));
2759            attr.upcast::<Node>().set_owner_doc(&self.node.owner_doc());
2760            self.push_attribute(cx, attr);
2761
2762            None
2763        };
2764
2765        // Step 8. Return oldAttr.
2766        Ok(old_attr)
2767    }
2768
2769    /// <https://html.spec.whatwg.org/multipage/#nonce-attributes>
2770    pub(crate) fn update_nonce_internal_slot(&self, nonce: String, no_gc: &NoGC) {
2771        self.ensure_rare_data(no_gc).cryptographic_nonce = nonce;
2772    }
2773
2774    /// <https://html.spec.whatwg.org/multipage/#nonce-attributes>
2775    pub(crate) fn nonce_value(&self) -> String {
2776        match self.rare_data().as_ref() {
2777            None => String::new(),
2778            Some(rare_data) => rare_data.cryptographic_nonce.clone(),
2779        }
2780    }
2781
2782    /// <https://html.spec.whatwg.org/multipage/#nonce-attributes>
2783    pub(crate) fn update_nonce_post_connection(&self, cx: &mut JSContext) {
2784        // Whenever an element including HTMLOrSVGOrMathMLElement becomes browsing-context connected,
2785        // the user agent must execute the following steps on the element:
2786        if !self
2787            .upcast::<Node>()
2788            .is_connected_with_browsing_context(cx.no_gc())
2789        {
2790            return;
2791        }
2792        let global = self.owner_global();
2793        // Step 1: Let CSP list be element's shadow-including root's policy container's CSP list.
2794        // Step 2: If CSP list contains a header-delivered Content Security Policy,
2795        // and element has a nonce content attribute whose value is not the empty string, then:
2796        if global.call_on_csp_list(|csp_list| {
2797            csp_list.as_ref().is_none_or(|csp_list| {
2798                !csp_list.contains_a_header_delivered_content_security_policy() ||
2799                    self.get_string_attribute(&local_name!("nonce")).is_empty()
2800            })
2801        }) {
2802            return;
2803        }
2804
2805        // Step 2.1: Let nonce be element's [[CryptographicNonce]].
2806        let nonce = self.nonce_value();
2807        // Step 2.2: Set an attribute value for element using "nonce" and the empty string.
2808        self.set_string_attribute(cx, &local_name!("nonce"), DOMString::new());
2809        // Step 2.3: Set element's [[CryptographicNonce]] to nonce.
2810        self.update_nonce_internal_slot(nonce, cx.no_gc());
2811    }
2812
2813    /// <https://www.w3.org/TR/CSP/#is-element-nonceable>
2814    pub(crate) fn is_nonceable(&self) -> bool {
2815        // Step 1: If element does not have an attribute named "nonce", return "Not Nonceable".
2816        if !self.has_attribute(&local_name!("nonce")) {
2817            return false;
2818        }
2819        // Step 2: If element is a script element, then for each attribute of element’s attribute list:
2820        if self.is::<HTMLScriptElement>() {
2821            for attr in self.attrs().borrow().iter() {
2822                // Step 2.1: If attribute’s name contains an ASCII case-insensitive match
2823                // for "<link", "<script", or "<style", return "Not Nonceable".
2824
2825                // to_ascii_lowercase is already optimized for `LocalName`.
2826                let attr_name = attr.name().to_ascii_lowercase();
2827                if attr_name.contains("<link") ||
2828                    attr_name.contains("<script") ||
2829                    attr_name.contains("<style")
2830                {
2831                    return false;
2832                }
2833
2834                // Step 2.2: If attribute’s value contains an ASCII case-insensitive match
2835                // for "<link", "<script", or "<style", return "Not Nonceable".
2836                let attr_value = attr.value();
2837                let attr_value = string_as_ascii_lowercase(&attr_value);
2838                if attr_value.contains("<link") ||
2839                    attr_value.contains("<script") ||
2840                    attr_value.contains("<style")
2841                {
2842                    return false;
2843                }
2844            }
2845        }
2846        // Step 3: If element had a duplicate-attribute parse error during tokenization, return "Not Nonceable".
2847        if self
2848            .rare_data()
2849            .as_ref()
2850            .is_some_and(|d| d.had_duplicate_attributes)
2851        {
2852            return false;
2853        }
2854        // Step 4: Return "Nonceable".
2855        true
2856    }
2857
2858    /// <https://dom.spec.whatwg.org/#insert-adjacent>
2859    pub(crate) fn insert_adjacent(
2860        &self,
2861        cx: &mut JSContext,
2862        where_: AdjacentPosition,
2863        node: &Node,
2864    ) -> Fallible<Option<DomRoot<Node>>> {
2865        let self_node = self.upcast::<Node>();
2866        match where_ {
2867            AdjacentPosition::BeforeBegin => {
2868                if let Some(parent) = self_node.GetParentNode() {
2869                    Node::pre_insert(cx, node, &parent, Some(self_node)).map(Some)
2870                } else {
2871                    Ok(None)
2872                }
2873            },
2874            AdjacentPosition::AfterBegin => {
2875                Node::pre_insert(cx, node, self_node, self_node.GetFirstChild().as_deref())
2876                    .map(Some)
2877            },
2878            AdjacentPosition::BeforeEnd => Node::pre_insert(cx, node, self_node, None).map(Some),
2879            AdjacentPosition::AfterEnd => {
2880                if let Some(parent) = self_node.GetParentNode() {
2881                    Node::pre_insert(cx, node, &parent, self_node.GetNextSibling().as_deref())
2882                        .map(Some)
2883                } else {
2884                    Ok(None)
2885                }
2886            },
2887        }
2888    }
2889
2890    /// <https://drafts.csswg.org/cssom-view/#dom-element-scroll>
2891    pub(crate) fn scroll(&self, cx: &mut JSContext, x: f64, y: f64, behavior: ScrollBehavior) {
2892        // Step 1.2. Normalize non-finite values for left and top dictionary members of
2893        // options, if present.
2894        // Step 1.3. Normalize non-finite values for x and y.
2895        // We are delegating the remaining substeps of steps 1 and 2 to the callers.
2896        let x = if x.is_finite() { x } else { 0.0 } as f32;
2897        let y = if y.is_finite() { y } else { 0.0 } as f32;
2898
2899        let node = self.upcast::<Node>();
2900
2901        // Step 3. Let document be the element’s node document.
2902        let document = node.owner_doc();
2903
2904        // Step 4. If document is not the active document, return a promise resolved with
2905        // a non-interrupted scroll result and abort the remaining steps.
2906        // TODO: Implement the promise and smooth scroll behavior.
2907        if !document.is_fully_active() {
2908            return;
2909        }
2910
2911        // Step 5. Let window be the value of document’s defaultView attribute.
2912        let Some(window) = document.GetDefaultView() else {
2913            // Step 6. If window is null, return a promise resolved with a non-interrupted
2914            // scroll result and abort the remaining steps.
2915            // TODO: Implement the promise and smooth scroll behavior.
2916            return;
2917        };
2918
2919        // Step 7. If the element is the root element and document is in quirks mode,
2920        // return a promise resolved with a non-interrupted scroll result and abort the
2921        // remaining steps.
2922        // TODO: Implement the promise and smooth scroll behavior.
2923        if *self.root_element() == *self {
2924            if document.quirks_mode() == QuirksMode::Quirks {
2925                return;
2926            }
2927
2928            // Step 8. If the element is the root element, return the Promise returned by
2929            // scroll() on window after the method is invoked with scrollX on window as
2930            // first argument and y as second argument, and abort the remaining steps.
2931            // TODO: Implement the promise and smooth scroll behavior.
2932            window.scroll(cx, x, y, behavior);
2933            return;
2934        }
2935
2936        // Step 9. If the element is the body element, document is in quirks mode, and the
2937        // element is not potentially scrollable in either axis, return the Promise
2938        // returned by scroll() on window after the method is invoked with options as the
2939        // only argument, and abort the remaining steps.
2940        // TODO: Implement the promise and smooth scroll behavior.
2941        if document.GetBody().as_deref() == self.downcast::<HTMLElement>() &&
2942            document.quirks_mode() == QuirksMode::Quirks &&
2943            !self.is_potentially_scrollable_body(cx)
2944        {
2945            window.scroll(cx, x, y, behavior);
2946            return;
2947        }
2948
2949        // Step 10. If the element does not have any associated box, the element has no
2950        // associated scrolling box, or the element has no overflow, return a promise
2951        // resolved with a non-interrupted scroll result and abort the remaining steps.
2952        //
2953        // TODO: This needs to match the spec a bit more closely with regard to the
2954        // box and overflow checks.
2955        // TODO: Implement the promise and smooth scroll behavior.
2956        if !self.has_scrolling_box(cx) {
2957            return;
2958        }
2959
2960        // Step 11. Scroll the element to x,y, with the scroll behavior being the value of
2961        // the behavior dictionary member of options. Let scrollPromise be the Promise
2962        // returned from this step.
2963        // TODO: Implement the promise and smooth scroll behavior.
2964        window.scroll_an_element(cx, self, x, y, behavior);
2965
2966        // Step 12. Return scrollPromise.
2967        // TODO: Implement the promise and smooth scroll behavior.
2968    }
2969
2970    /// <https://html.spec.whatwg.org/multipage/#fragment-parsing-algorithm-steps>
2971    pub(crate) fn parse_fragment(
2972        &self,
2973        markup: DOMString,
2974        cx: &mut JSContext,
2975    ) -> Fallible<DomRoot<DocumentFragment>> {
2976        // Steps 1-2.
2977        // TODO(#11995): XML case.
2978        let new_children = ServoParser::parse_html_fragment(cx, self, markup, false);
2979        // Step 3.
2980        // See https://github.com/w3c/DOM-Parsing/issues/61.
2981        let context_document = {
2982            if let Some(template) = self.downcast::<HTMLTemplateElement>() {
2983                template.Content(cx).upcast::<Node>().owner_doc()
2984            } else {
2985                self.owner_document()
2986            }
2987        };
2988        let fragment = DocumentFragment::new(cx, &context_document);
2989        // Step 4.
2990        for child in new_children {
2991            fragment.upcast::<Node>().AppendChild(cx, &child).unwrap();
2992        }
2993        // Step 5.
2994        Ok(fragment)
2995    }
2996
2997    /// Step 4 of <https://html.spec.whatwg.org/multipage/#dom-element-insertadjacenthtml>
2998    /// and step 6. of <https://html.spec.whatwg.org/multipage/#dom-range-createcontextualfragment>
2999    pub(crate) fn fragment_parsing_context(
3000        cx: &mut JSContext,
3001        owner_doc: &Document,
3002        element: Option<&Self>,
3003    ) -> DomRoot<Self> {
3004        // If context is not an Element or all of the following are true:
3005        match element {
3006            Some(elem)
3007                // context's node document is an HTML document;
3008                // context's local name is "html"; and
3009                // context's namespace is the HTML namespace,
3010                if elem.local_name() != &local_name!("html") ||
3011                    !elem.html_element_in_html_document() =>
3012            {
3013                DomRoot::from_ref(elem)
3014            },
3015            // set context to the result of creating an element
3016            // given this's node document, "body", and the HTML namespace.
3017            _ => Element::create(
3018                cx,
3019                QualName::new(None, ns!(html), local_name!("body")),
3020                None,
3021                owner_doc,
3022                ElementCreator::ScriptCreated,
3023                CustomElementCreationMode::Asynchronous,
3024                None
3025            ),
3026        }
3027    }
3028
3029    /// <https://html.spec.whatwg.org/multipage/#home-subtree>
3030    pub(crate) fn is_in_same_home_subtree<T>(&self, other: &T) -> bool
3031    where
3032        T: DerivedFrom<Element> + DomObject,
3033    {
3034        let other = other.upcast::<Element>();
3035        self.root_element() == other.root_element()
3036    }
3037
3038    pub(crate) fn get_id(&self) -> Option<Atom> {
3039        self.id_attribute.borrow().clone()
3040    }
3041
3042    pub(crate) fn get_name(&self) -> Option<Atom> {
3043        self.rare_data().as_ref()?.name_attribute.clone()
3044    }
3045
3046    pub(crate) fn get_element_internals(&self) -> Option<DomRoot<ElementInternals>> {
3047        self.rare_data()
3048            .as_ref()?
3049            .element_internals
3050            .as_ref()
3051            .map(|sr| DomRoot::from_ref(&**sr))
3052    }
3053
3054    pub(crate) fn outer_html(&self, cx: &mut JSContext) -> Fallible<DOMString> {
3055        match self.GetOuterHTML(cx)? {
3056            TrustedHTMLOrNullIsEmptyString::NullIsEmptyString(str) => Ok(str),
3057            TrustedHTMLOrNullIsEmptyString::TrustedHTML(_) => unreachable!(),
3058        }
3059    }
3060
3061    pub(crate) fn compute_source_position(&self, line_number: u32) -> SourcePosition {
3062        SourcePosition {
3063            source_file: self.owner_global().get_url().to_string(),
3064            line_number: line_number + 2,
3065            column_number: 0,
3066        }
3067    }
3068
3069    pub(crate) fn explicitly_set_tab_index(&self) -> Option<i32> {
3070        if self.has_attribute(&local_name!("tabindex")) {
3071            Some(self.get_int_attribute(&local_name!("tabindex"), 0))
3072        } else {
3073            None
3074        }
3075    }
3076
3077    /// <https://html.spec.whatwg.org/multipage/#dom-tabindex>
3078    pub(crate) fn tab_index(&self) -> i32 {
3079        // > The tabIndex getter steps are:
3080        // > 1. Let attribute be this's tabindex attribute.
3081        // > 2. If attribute is not null:
3082        // >    1. Let parsedValue be the result of integer parsing attribute's value.
3083        // >    2. If parsedValue is not an error and is within the long range, then return parsedValue.
3084        if let Some(tab_index) = self.explicitly_set_tab_index() {
3085            return tab_index;
3086        }
3087
3088        // > 3. Return 0 if this is an a, area, button, frame, iframe, input, object, select, textarea,
3089        // > or SVG a element, or is a summary element that is a summary for its parent details;
3090        // > otherwise -1.
3091        //
3092        // Note: We do not currently support SVG `a` elements.
3093        if matches!(
3094            self.upcast::<Node>().type_id(),
3095            NodeTypeId::Element(ElementTypeId::HTMLElement(
3096                HTMLElementTypeId::HTMLAnchorElement |
3097                    HTMLElementTypeId::HTMLAreaElement |
3098                    HTMLElementTypeId::HTMLButtonElement |
3099                    HTMLElementTypeId::HTMLFrameElement |
3100                    HTMLElementTypeId::HTMLIFrameElement |
3101                    HTMLElementTypeId::HTMLInputElement |
3102                    HTMLElementTypeId::HTMLObjectElement |
3103                    HTMLElementTypeId::HTMLSelectElement |
3104                    HTMLElementTypeId::HTMLTextAreaElement
3105            ))
3106        ) {
3107            return 0;
3108        }
3109        if self
3110            .downcast::<HTMLElement>()
3111            .is_some_and(|html_element| html_element.is_a_summary_for_its_parent_details())
3112        {
3113            return 0;
3114        }
3115
3116        -1
3117    }
3118
3119    #[inline]
3120    fn insert_selector_flags(&self, flags: ElementSelectorFlags) {
3121        self.selector_flags
3122            .fetch_or(flags.bits(), Ordering::Relaxed);
3123    }
3124
3125    #[inline]
3126    fn get_selector_flags(&self) -> ElementSelectorFlags {
3127        ElementSelectorFlags::from_bits_retain(self.selector_flags.load(Ordering::Relaxed))
3128    }
3129
3130    /// Custom [`Element`]s and those with mutation observers sometimes need the old style
3131    /// attribute to persist after modification, because it is sent as an argument to
3132    /// script callbacks. Normally that's not the case, so this method tries to detect
3133    /// when it's required so it can be avoided for performance reasons.
3134    pub(crate) fn needs_preserved_style_attribute_after_change(&self) -> bool {
3135        // This is a global check for whether any mutation observers are installed on this
3136        // Document at all. If cloning of the property declaration block (look at the
3137        // caller of this method), starts showing up in profiles, this check may need to
3138        // be a bit smarter. For instance, maybe only returning true if any mutation
3139        // observer is installed on an inclusive ancestor and only if it has an observer
3140        // with the attribute filter set to include `style`.
3141        self.owner_window().get_exists_mut_observer() ||
3142            self.get_custom_element_definition()
3143                .is_some_and(|custom_element_definition| {
3144                    custom_element_definition.has_attribute_changed_callback()
3145                })
3146    }
3147
3148    pub(crate) fn register_current_id_and_name_attribute(&self, cx: &mut JSContext) {
3149        if let Some(shadow_root) = self.containing_shadow_root() {
3150            if let Some(ref id) = *self.id_attribute.borrow() {
3151                shadow_root.register_element_id(self, id);
3152            }
3153        } else {
3154            if let Some(ref id) = *self.id_attribute.borrow() {
3155                self.owner_document().register_element_id(cx, self, id);
3156            }
3157            if let Some(ref name) = self.name_attribute() {
3158                self.owner_document_unrooted(cx.no_gc())
3159                    .register_element_name(self, name);
3160            }
3161        }
3162    }
3163
3164    pub(crate) fn unregister_current_id_and_name_attribute(&self, cx: &mut JSContext) {
3165        if let Some(shadow_root) = self.containing_shadow_root() {
3166            // Only unregister the element id if the node was disconnected from it's
3167            // shadow root (as opposed to the whole shadow tree being disconnected as a
3168            // whole)
3169            if self.upcast::<Node>().is_in_a_shadow_tree() {
3170                return;
3171            }
3172            if let Some(ref id) = *self.id_attribute.borrow() {
3173                shadow_root.unregister_element_id(id);
3174            }
3175        } else {
3176            if let Some(ref id) = *self.id_attribute.borrow() {
3177                self.owner_document().unregister_element_id(cx, id);
3178            }
3179            if let Some(ref name) = self.name_attribute() {
3180                self.owner_document_unrooted(cx.no_gc())
3181                    .unregister_element_name(name);
3182            }
3183        }
3184    }
3185
3186    /// An element's qualified name is its local name if its namespace prefix is null;
3187    /// otherwise its namespace prefix, followed by ":", followed by its local name.
3188    /// <https://dom.spec.whatwg.org/#concept-element-qualified-name>
3189    pub(crate) fn qualified_name(&self) -> Cow<'_, str> {
3190        match &*self.prefix.borrow() {
3191            Some(prefix) => Cow::Owned(format!("{}:{}", prefix, &*self.local_name)),
3192            None => Cow::Borrowed(&*self.local_name),
3193        }
3194    }
3195}
3196
3197impl ElementMethods<crate::DomTypeHolder> for Element {
3198    /// <https://dom.spec.whatwg.org/#dom-element-namespaceuri>
3199    fn GetNamespaceURI(&self) -> Option<DOMString> {
3200        Node::namespace_to_string(self.namespace.clone())
3201    }
3202
3203    /// <https://dom.spec.whatwg.org/#dom-element-localname>
3204    fn LocalName(&self) -> DOMString {
3205        // FIXME(ajeffrey): Convert directly from LocalName to DOMString
3206        DOMString::from(&*self.local_name)
3207    }
3208
3209    /// <https://dom.spec.whatwg.org/#dom-element-prefix>
3210    fn GetPrefix(&self) -> Option<DOMString> {
3211        self.prefix
3212            .borrow()
3213            .as_ref()
3214            .map(|p| TracedDOMString::from(p.clone()).root())
3215    }
3216
3217    /// <https://dom.spec.whatwg.org/#dom-element-tagname>
3218    fn TagName(&self) -> DOMString {
3219        // The tagName getter steps are to return this's HTML-uppercased qualified name.
3220        //
3221        // An element's HTML-uppercased qualified name is the return value of these steps:
3222        let key = TagNameKey {
3223            prefix: self.prefix.borrow().clone(),
3224            local_name: self.local_name.clone(),
3225            html_element_in_html_document: self.html_element_in_html_document(),
3226        };
3227        let name = TAG_NAME_CACHE.with(|cache| {
3228            // Looking a name up makes it the most recently used one.
3229            if let Some(name) = cache.borrow_mut().get(&key).cloned() {
3230                return name;
3231            }
3232            // 1. Let qualifiedName be this's qualified name.
3233            let qualified_name = self.qualified_name();
3234            // 2. If this is in the HTML namespace and its node document is an HTML document,
3235            //    then return qualifiedName in ASCII uppercase.
3236            // 3. Return qualifiedName.
3237            let name = if key.html_element_in_html_document {
3238                LocalName::from(qualified_name.to_ascii_uppercase())
3239            } else {
3240                LocalName::from(&*qualified_name)
3241            };
3242            cache.borrow_mut().insert(key, name.clone());
3243            name
3244        });
3245        TracedDOMString::from(name).root()
3246    }
3247
3248    // https://dom.spec.whatwg.org/#dom-element-id
3249    // This always returns a string; if you'd rather see None
3250    // on a null id, call get_id
3251    fn Id(&self) -> DOMString {
3252        self.get_string_attribute(&local_name!("id"))
3253    }
3254
3255    /// <https://dom.spec.whatwg.org/#dom-element-id>
3256    fn SetId(&self, cx: &mut JSContext, id: DOMString) {
3257        self.set_atomic_attribute(cx, &local_name!("id"), id);
3258    }
3259
3260    /// <https://dom.spec.whatwg.org/#dom-element-classname>
3261    fn ClassName(&self) -> DOMString {
3262        self.get_string_attribute(&local_name!("class"))
3263    }
3264
3265    /// <https://dom.spec.whatwg.org/#dom-element-classname>
3266    fn SetClassName(&self, cx: &mut JSContext, class: DOMString) {
3267        self.set_tokenlist_attribute(cx, &local_name!("class"), class);
3268    }
3269
3270    /// <https://dom.spec.whatwg.org/#dom-element-classlist>
3271    fn ClassList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
3272        self.class_list
3273            .or_init(|| DOMTokenList::new(cx, self, &local_name!("class"), None))
3274    }
3275
3276    // https://dom.spec.whatwg.org/#dom-element-slot
3277    make_getter!(Slot, "slot");
3278
3279    // https://dom.spec.whatwg.org/#dom-element-slot
3280    make_setter!(SetSlot, "slot");
3281
3282    /// <https://dom.spec.whatwg.org/#dom-element-attributes>
3283    fn Attributes(&self, cx: &mut JSContext) -> DomRoot<NamedNodeMap> {
3284        self.attr_list
3285            .or_init(|| NamedNodeMap::new(cx, &self.owner_window(), self))
3286    }
3287
3288    /// <https://dom.spec.whatwg.org/#dom-element-hasattributes>
3289    fn HasAttributes(&self) -> bool {
3290        !self.attrs.borrow().is_empty()
3291    }
3292
3293    /// <https://dom.spec.whatwg.org/#dom-element-getattributenames>
3294    fn GetAttributeNames(&self) -> Vec<DOMString> {
3295        self.attrs
3296            .borrow()
3297            .iter()
3298            .map(|attr| TracedDOMString::from(attr.name().clone()).root())
3299            .collect()
3300    }
3301
3302    /// <https://dom.spec.whatwg.org/#dom-element-getattribute>
3303    fn GetAttribute(&self, cx: &mut JSContext, name: DOMString) -> Option<DOMString> {
3304        self.GetAttributeNode(cx, name).map(|s| s.Value())
3305    }
3306
3307    /// <https://dom.spec.whatwg.org/#dom-element-getattributens>
3308    fn GetAttributeNS(
3309        &self,
3310        cx: &mut JSContext,
3311        namespace: Option<DOMString>,
3312        local_name: DOMString,
3313    ) -> Option<DOMString> {
3314        self.GetAttributeNodeNS(cx, namespace, local_name)
3315            .map(|attr| attr.Value())
3316    }
3317
3318    /// <https://dom.spec.whatwg.org/#dom-element-getattributenode>
3319    fn GetAttributeNode(&self, cx: &mut JSContext, name: DOMString) -> Option<DomRoot<Attr>> {
3320        self.get_attribute_by_name(cx, name)
3321    }
3322
3323    /// <https://dom.spec.whatwg.org/#dom-element-getattributenodens>
3324    fn GetAttributeNodeNS(
3325        &self,
3326        cx: &mut JSContext,
3327        namespace: Option<DOMString>,
3328        local_name: DOMString,
3329    ) -> Option<DomRoot<Attr>> {
3330        let namespace = &namespace_from_domstring(namespace);
3331        self.get_attribute_with_namespace(cx, namespace, &LocalName::from(local_name))
3332    }
3333
3334    /// <https://dom.spec.whatwg.org/#dom-element-toggleattribute>
3335    fn ToggleAttribute(
3336        &self,
3337        cx: &mut JSContext,
3338        name: DOMString,
3339        force: Option<bool>,
3340    ) -> Fallible<bool> {
3341        // Step 1. If qualifiedName is not a valid attribute local name,
3342        //      then throw an "InvalidCharacterError" DOMException.
3343        if !is_valid_attribute_local_name(&name.str()) {
3344            return Err(Error::InvalidCharacter(Some(
3345                "Invalid attribute name".into(),
3346            )));
3347        }
3348
3349        // Step 3.
3350        let attribute = self.GetAttribute(cx, name.clone());
3351
3352        // Step 2.
3353        let name = self.parsed_name(name);
3354        match attribute {
3355            // Step 4
3356            None => match force {
3357                // Step 4.1.
3358                None | Some(true) => {
3359                    self.set_first_matching_attribute(
3360                        cx,
3361                        name.clone(),
3362                        AttrValue::String(String::new()),
3363                        name.clone(),
3364                        ns!(),
3365                        None,
3366                        |attr| *attr.name() == name,
3367                    );
3368                    Ok(true)
3369                },
3370                // Step 4.2.
3371                Some(false) => Ok(false),
3372            },
3373            Some(_index) => match force {
3374                // Step 5.
3375                None | Some(false) => {
3376                    self.remove_attribute_by_name(cx, &name);
3377                    Ok(false)
3378                },
3379                // Step 6.
3380                Some(true) => Ok(true),
3381            },
3382        }
3383    }
3384
3385    /// <https://dom.spec.whatwg.org/#dom-element-setattribute>
3386    fn SetAttribute(
3387        &self,
3388        cx: &mut JSContext,
3389        name: DOMString,
3390        value: TrustedTypeOrString,
3391    ) -> ErrorResult {
3392        // Step 1. If qualifiedName does not match the Name production in XML,
3393        // then throw an "InvalidCharacterError" DOMException.
3394        if !is_valid_attribute_local_name(&name.str()) {
3395            return Err(Error::InvalidCharacter(Some(
3396                "Invalid attribute name".into(),
3397            )));
3398        }
3399
3400        // Step 2. If this is in the HTML namespace and its node document is an HTML document,
3401        // then set qualifiedName to qualifiedName in ASCII lowercase.
3402        let name = self.parsed_name(name);
3403
3404        // Step 3. Let verifiedValue be the result of calling get
3405        // Trusted Types-compliant attribute value with qualifiedName, null,
3406        // this, and value. [TRUSTED-TYPES]
3407        let value = TrustedTypePolicyFactory::get_trusted_types_compliant_attribute_value(
3408            cx,
3409            self.namespace(),
3410            self.local_name(),
3411            &name,
3412            None,
3413            value,
3414            &self.owner_global(),
3415        )?;
3416
3417        // Step 4. Let attribute be the first attribute in this’s attribute list whose qualified name is qualifiedName, and null otherwise.
3418        // Step 5. If attribute is null, create an attribute whose local name is qualifiedName, value is verifiedValue, and node document
3419        // is this’s node document, then append this attribute to this, and then return.
3420        // Step 6. Change attribute to verifiedValue.
3421        let value = self.parse_attribute(&ns!(), &name, value);
3422        self.set_first_matching_attribute(
3423            cx,
3424            name.clone(),
3425            value,
3426            name.clone(),
3427            ns!(),
3428            None,
3429            |attr| *attr.name() == name,
3430        );
3431        Ok(())
3432    }
3433
3434    /// <https://dom.spec.whatwg.org/#dom-element-setattributens>
3435    fn SetAttributeNS(
3436        &self,
3437        cx: &mut JSContext,
3438        namespace: Option<DOMString>,
3439        qualified_name: DOMString,
3440        value: TrustedTypeOrString,
3441    ) -> ErrorResult {
3442        // Step 1. Let namespace, prefix, and localName be the result of passing namespace and qualifiedName to validate and extract.
3443        let (namespace, prefix, local_name) =
3444            domname::validate_and_extract(namespace, &qualified_name, domname::Context::Element)?;
3445        // Step 2. Let verifiedValue be the result of calling get
3446        // Trusted Types-compliant attribute value with localName, namespace, element, and value. [TRUSTED-TYPES]
3447        let value = TrustedTypePolicyFactory::get_trusted_types_compliant_attribute_value(
3448            cx,
3449            self.namespace(),
3450            self.local_name(),
3451            &local_name,
3452            Some(&namespace),
3453            value,
3454            &self.owner_global(),
3455        )?;
3456        // Step 3. Set an attribute value for this using localName, verifiedValue, and also prefix and namespace.
3457        let value = self.parse_attribute(&namespace, &local_name, value);
3458        self.set_attribute_with_namespace(
3459            cx,
3460            local_name,
3461            value,
3462            LocalName::from(qualified_name),
3463            namespace,
3464            prefix,
3465        );
3466        Ok(())
3467    }
3468
3469    /// <https://dom.spec.whatwg.org/#dom-element-setattributenode>
3470    fn SetAttributeNode(&self, cx: &mut JSContext, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
3471        self.set_attribute_node(cx, attr)
3472    }
3473
3474    /// <https://dom.spec.whatwg.org/#dom-element-setattributenodens>
3475    fn SetAttributeNodeNS(
3476        &self,
3477        cx: &mut JSContext,
3478        attr: &Attr,
3479    ) -> Fallible<Option<DomRoot<Attr>>> {
3480        self.set_attribute_node(cx, attr)
3481    }
3482
3483    /// <https://dom.spec.whatwg.org/#dom-element-removeattribute>
3484    fn RemoveAttribute(&self, cx: &mut JSContext, name: DOMString) {
3485        let name = self.parsed_name(name);
3486        self.remove_attribute_by_name(cx, &name);
3487    }
3488
3489    /// <https://dom.spec.whatwg.org/#dom-element-removeattributens>
3490    fn RemoveAttributeNS(
3491        &self,
3492        cx: &mut JSContext,
3493        namespace: Option<DOMString>,
3494        local_name: DOMString,
3495    ) {
3496        let namespace = namespace_from_domstring(namespace);
3497        let local_name = LocalName::from(local_name);
3498        self.remove_attribute(cx, &namespace, &local_name);
3499    }
3500
3501    /// <https://dom.spec.whatwg.org/#dom-element-removeattributenode>
3502    fn RemoveAttributeNode(&self, cx: &mut JSContext, attr: &Attr) -> Fallible<DomRoot<Attr>> {
3503        // The attr parameter passed here is already a Dom<Attr> that is somewhere present in the DOM,
3504        // hence already materialized. That means that `as_attr()` will never fail.
3505        self.remove_first_matching_attribute(cx, |a| a.as_attr().is_some_and(|a| a == attr))
3506            .ok_or(Error::NotFound(Some(
3507                "Attribute is not owned by this element".into(),
3508            )))
3509    }
3510
3511    /// <https://dom.spec.whatwg.org/#dom-element-hasattribute>
3512    fn HasAttribute(&self, cx: &mut JSContext, name: DOMString) -> bool {
3513        self.GetAttribute(cx, name).is_some()
3514    }
3515
3516    /// <https://dom.spec.whatwg.org/#dom-element-hasattributens>
3517    fn HasAttributeNS(
3518        &self,
3519        cx: &mut JSContext,
3520        namespace: Option<DOMString>,
3521        local_name: DOMString,
3522    ) -> bool {
3523        self.GetAttributeNS(cx, namespace, local_name).is_some()
3524    }
3525
3526    /// <https://dom.spec.whatwg.org/#dom-element-getelementsbytagname>
3527    fn GetElementsByTagName(
3528        &self,
3529        cx: &mut JSContext,
3530        localname: DOMString,
3531    ) -> DomRoot<HTMLCollection> {
3532        let window = self.owner_window();
3533        HTMLCollection::by_qualified_name(cx, &window, self.upcast(), LocalName::from(localname))
3534    }
3535
3536    /// <https://dom.spec.whatwg.org/#dom-element-getelementsbytagnamens>
3537    fn GetElementsByTagNameNS(
3538        &self,
3539        cx: &mut JSContext,
3540        maybe_ns: Option<DOMString>,
3541        localname: DOMString,
3542    ) -> DomRoot<HTMLCollection> {
3543        let window = self.owner_window();
3544        HTMLCollection::by_tag_name_ns(cx, &window, self.upcast(), localname, maybe_ns)
3545    }
3546
3547    /// <https://dom.spec.whatwg.org/#dom-element-getelementsbyclassname>
3548    fn GetElementsByClassName(
3549        &self,
3550        cx: &mut JSContext,
3551        classes: DOMString,
3552    ) -> DomRoot<HTMLCollection> {
3553        let window = self.owner_window();
3554        HTMLCollection::by_class_name(cx, &window, self.upcast(), classes)
3555    }
3556
3557    /// <https://drafts.csswg.org/cssom-view/#dom-element-getclientrects>
3558    fn GetClientRects(&self, cx: &mut JSContext) -> DomRoot<DOMRectList> {
3559        let win = self.owner_window();
3560        let raw_rects = self.upcast::<Node>().border_boxes(cx);
3561        let rects: Vec<DomRoot<DOMRect>> = raw_rects
3562            .into_iter()
3563            .map(|rect| {
3564                DOMRect::new(
3565                    cx,
3566                    win.upcast(),
3567                    rect.origin.x.to_f64_px(),
3568                    rect.origin.y.to_f64_px(),
3569                    rect.size.width.to_f64_px(),
3570                    rect.size.height.to_f64_px(),
3571                )
3572            })
3573            .collect();
3574        DOMRectList::new(cx, &win, rects)
3575    }
3576
3577    /// <https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect>
3578    fn GetBoundingClientRect(&self, cx: &mut JSContext) -> DomRoot<DOMRect> {
3579        let win = self.owner_window();
3580        let rect = self.upcast::<Node>().border_box(cx).unwrap_or_default();
3581        debug_assert!(rect.size.width.to_f64_px() >= 0.0 && rect.size.height.to_f64_px() >= 0.0);
3582        DOMRect::new(
3583            cx,
3584            win.upcast(),
3585            rect.origin.x.to_f64_px(),
3586            rect.origin.y.to_f64_px(),
3587            rect.size.width.to_f64_px(),
3588            rect.size.height.to_f64_px(),
3589        )
3590    }
3591
3592    /// <https://drafts.csswg.org/cssom-view/#dom-element-scroll>
3593    fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3594        // Step 1
3595        let left = options.left.unwrap_or(self.ScrollLeft(cx));
3596        let top = options.top.unwrap_or(self.ScrollTop(cx));
3597        self.scroll(cx, left, top, options.parent.behavior);
3598    }
3599
3600    /// <https://drafts.csswg.org/cssom-view/#dom-element-scroll>
3601    fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
3602        self.scroll(cx, x, y, ScrollBehavior::Auto);
3603    }
3604
3605    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollto>
3606    fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3607        self.Scroll(cx, options);
3608    }
3609
3610    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollto>
3611    fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
3612        self.Scroll_(cx, x, y);
3613    }
3614
3615    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollby>
3616    fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3617        // Step 2
3618        let delta_left = options.left.unwrap_or(0.0f64);
3619        let delta_top = options.top.unwrap_or(0.0f64);
3620        let left = self.ScrollLeft(cx);
3621        let top = self.ScrollTop(cx);
3622        self.scroll(
3623            cx,
3624            left + delta_left,
3625            top + delta_top,
3626            options.parent.behavior,
3627        );
3628    }
3629
3630    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollby>
3631    fn ScrollBy_(&self, cx: &mut JSContext, x: f64, y: f64) {
3632        let left = self.ScrollLeft(cx);
3633        let top = self.ScrollTop(cx);
3634        self.scroll(cx, left + x, top + y, ScrollBehavior::Auto);
3635    }
3636
3637    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrolltop>
3638    fn ScrollTop(&self, cx: &mut JSContext) -> f64 {
3639        let node = self.upcast::<Node>();
3640
3641        // Step 1. Let document be the element’s node document.
3642        let document = node.owner_doc();
3643
3644        // Step 2. If document is not the active document, return zero and terminate these
3645        // steps.
3646        if !document.is_fully_active() {
3647            return 0.0;
3648        }
3649
3650        // Step 3. Let window be the value of document’s defaultView attribute.
3651        let Some(window) = document.GetDefaultView() else {
3652            // Step 4. If window is null, return zero and terminate these steps.
3653            return 0.0;
3654        };
3655
3656        if self.is_document_element() {
3657            // Step 5. If the element is the root element and document is in quirks mode,
3658            // return zero and terminate these steps.
3659            if document.quirks_mode() == QuirksMode::Quirks {
3660                return 0.0;
3661            }
3662
3663            // Step 6. If the element is the root element return the value of scrollY on
3664            // window.
3665            return window.ScrollY(cx) as f64;
3666        }
3667
3668        // Step 7. If the element is the body element, document is in quirks mode, and the
3669        // element is not potentially scrollable in at least one axis, return the value of
3670        // scrollY on window.
3671        if document.GetBody().as_deref() == self.downcast::<HTMLElement>() &&
3672            document.quirks_mode() == QuirksMode::Quirks &&
3673            !self.is_potentially_scrollable_body(cx)
3674        {
3675            return window.ScrollY(cx) as f64;
3676        }
3677
3678        // Step 8. If the element does not have any associated box, return zero and
3679        // terminate these steps.
3680        if !self.has_css_layout_box_deprecated(cx) {
3681            return 0.0;
3682        }
3683
3684        // Step 9. Return the y-coordinate of the scrolling area at the alignment point
3685        // with the top of the padding edge of the element.
3686        let point = window.scroll_offset_query(cx, node);
3687        point.y as f64
3688    }
3689
3690    // https://drafts.csswg.org/cssom-view/#dom-element-scrolltop
3691    fn SetScrollTop(&self, cx: &mut JSContext, y_: f64) {
3692        let behavior = ScrollBehavior::Auto;
3693
3694        // Step 1. Let y be the given value.
3695        // Step 2. Normalize non-finite values for y.
3696        let y = if y_.is_finite() { y_ } else { 0.0 } as f32;
3697
3698        let node = self.upcast::<Node>();
3699
3700        // Step 3. Let document be the element’s node document.
3701        let document = node.owner_doc();
3702
3703        // Step 4. If document is not the active document, terminate these steps.
3704        if !document.is_fully_active() {
3705            return;
3706        }
3707
3708        // Step 5. Let window be the value of document’s defaultView attribute.
3709        let Some(window) = document.GetDefaultView() else {
3710            // Step 6. If window is null, terminate these steps.
3711            return;
3712        };
3713
3714        if self.is_document_element() {
3715            // Step 7. If the element is the root element and document is in quirks mode,
3716            // terminate these steps.
3717            if document.quirks_mode() == QuirksMode::Quirks {
3718                return;
3719            }
3720
3721            // Step 8. If the element is the root element invoke scroll() on window with
3722            // scrollX on window as first argument and y as second argument, and terminate
3723            // these steps.
3724            let window_scroll_x = window.ScrollX(cx) as f32;
3725            window.scroll(cx, window_scroll_x, y, behavior);
3726            return;
3727        }
3728
3729        // Step 9. If the element is the body element, document is in quirks mode, and the
3730        // element is not potentially scrollable in at least one axis, invoke scroll() on
3731        // window with scrollX as first argument and y as second argument, and terminate
3732        // these steps.
3733        if document.GetBody().as_deref() == self.downcast::<HTMLElement>() &&
3734            document.quirks_mode() == QuirksMode::Quirks &&
3735            !self.is_potentially_scrollable_body(cx)
3736        {
3737            let window_scroll_x = window.ScrollX(cx) as f32;
3738            window.scroll(cx, window_scroll_x, y, behavior);
3739            return;
3740        }
3741
3742        // Step 10. If the element does not have any associated box, the element has no
3743        // associated scrolling box, or the element has no overflow, terminate these
3744        // steps.
3745        if !self.has_scrolling_box(cx) {
3746            return;
3747        }
3748
3749        // Step 11. Scroll the element to scrollLeft,y, with the scroll behavior being
3750        // "auto".
3751        let element_scroll_left = self.ScrollLeft(cx) as f32;
3752        window.scroll_an_element(cx, self, element_scroll_left, y, behavior);
3753    }
3754
3755    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollleft>
3756    fn ScrollLeft(&self, cx: &mut JSContext) -> f64 {
3757        let node = self.upcast::<Node>();
3758
3759        // Step 1. Let document be the element’s node document.
3760        let document = node.owner_doc();
3761
3762        // Step 2. If document is not the active document, return zero and terminate these
3763        // steps.
3764        if !document.is_fully_active() {
3765            return 0.0;
3766        }
3767
3768        // Step 3. Let window be the value of document’s defaultView attribute.
3769        // Step 4. If window is null, return zero and terminate these steps.
3770        let Some(window) = document.GetDefaultView() else {
3771            return 0.0;
3772        };
3773
3774        if self.is_document_element() {
3775            // Step 5. If the element is the root element and document is in quirks mode,
3776            // return zero and terminate these steps.
3777            if document.quirks_mode() == QuirksMode::Quirks {
3778                return 0.0;
3779            }
3780
3781            // Step 6. If the element is the root element return the value of scrollX on window.
3782            return window.ScrollX(cx) as f64;
3783        }
3784
3785        // Step 7. If the element is the body element, document is in quirks mode, and the
3786        // element is not potentially scrollable in at least one axis, return the value of
3787        // scrollX on window.
3788        if document.GetBody().as_deref() == self.downcast::<HTMLElement>() &&
3789            document.quirks_mode() == QuirksMode::Quirks &&
3790            !self.is_potentially_scrollable_body(cx)
3791        {
3792            return window.ScrollX(cx) as f64;
3793        }
3794
3795        // Step 8. If the element does not have any associated box, return zero and
3796        // terminate these steps.
3797        if !self.has_css_layout_box_deprecated(cx) {
3798            return 0.0;
3799        }
3800
3801        // Step 9. Return the x-coordinate of the scrolling area at the alignment point
3802        // with the left of the padding edge of the element.
3803        let point = window.scroll_offset_query(cx, node);
3804        point.x as f64
3805    }
3806
3807    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollleft>
3808    fn SetScrollLeft(&self, cx: &mut JSContext, x: f64) {
3809        let behavior = ScrollBehavior::Auto;
3810
3811        // Step 1. Let x be the given value.
3812        // Step 2. Normalize non-finite values for x.
3813        let x = if x.is_finite() { x } else { 0.0 } as f32;
3814
3815        // Step 3. Let document be the element’s node document.
3816        let node = self.upcast::<Node>();
3817        let document = node.owner_doc();
3818
3819        // Step 4. If document is not the active document, terminate these steps.
3820        if !document.is_fully_active() {
3821            return;
3822        }
3823
3824        // Step 5. Let window be the value of document’s defaultView attribute.
3825        let Some(window) = document.GetDefaultView() else {
3826            // Step 6. If window is null, terminate these steps.
3827            return;
3828        };
3829
3830        if self.is_document_element() {
3831            // Step 7. If the element is the root element and document is in quirks mode,
3832            // terminate these steps.
3833            if document.quirks_mode() == QuirksMode::Quirks {
3834                return;
3835            }
3836
3837            // Step 8. If the element is the root element invoke scroll() on window with x
3838            // as first argument and scrollY on window as second argument, and terminate
3839            // these steps.
3840            let window_scroll_y = window.ScrollY(cx) as f32;
3841            window.scroll(cx, x, window_scroll_y, behavior);
3842            return;
3843        }
3844
3845        // Step 9. If the element is the body element, document is in quirks mode, and the
3846        // element is not potentially scrollable in at least one axis, invoke scroll() on
3847        // window with x as first argument and scrollY on window as second argument, and
3848        // terminate these steps.
3849        if document.GetBody().as_deref() == self.downcast::<HTMLElement>() &&
3850            document.quirks_mode() == QuirksMode::Quirks &&
3851            !self.is_potentially_scrollable_body(cx)
3852        {
3853            let window_scroll_y = window.ScrollY(cx) as f32;
3854            window.scroll(cx, x, window_scroll_y, behavior);
3855            return;
3856        }
3857
3858        // Step 10. If the element does not have any associated box, the element has no
3859        // associated scrolling box, or the element has no overflow, terminate these
3860        // steps.
3861        if !self.has_scrolling_box(cx) {
3862            return;
3863        }
3864
3865        // Step 11. Scroll the element to x,scrollTop, with the scroll behavior being
3866        // "auto".
3867        let element_scroll_top = self.ScrollTop(cx) as f32;
3868        window.scroll_an_element(cx, self, x, element_scroll_top, behavior);
3869    }
3870
3871    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollintoview>
3872    fn ScrollIntoView(&self, cx: &mut JSContext, arg: BooleanOrScrollIntoViewOptions) {
3873        let (behavior, block, inline, container) = match arg {
3874            // If arg is true:
3875            BooleanOrScrollIntoViewOptions::Boolean(true) => (
3876                ScrollBehavior::Auto,           // Step 1: Let behavior be "auto".
3877                ScrollLogicalPosition::Start,   // Step 2: Let block be "start".
3878                ScrollLogicalPosition::Nearest, // Step 3: Let inline be "nearest".
3879                None,                           // Step 4: Let container be null.
3880            ),
3881            // Step 5: If arg is a ScrollIntoViewOptions dictionary, set its properties
3882            // to the corresponding values in the dictionary.
3883            BooleanOrScrollIntoViewOptions::ScrollIntoViewOptions(options) => (
3884                options.parent.behavior,
3885                options.block,
3886                options.inline,
3887                // Step 5.4: If the container dictionary member of options is "nearest",
3888                // set container to the element.
3889                if options.container == ScrollIntoViewContainer::Nearest {
3890                    Some(self)
3891                } else {
3892                    None
3893                },
3894            ),
3895            // Step 6: Otherwise, if arg is false, then set block to "end".
3896            BooleanOrScrollIntoViewOptions::Boolean(false) => (
3897                ScrollBehavior::Auto,
3898                ScrollLogicalPosition::End,
3899                ScrollLogicalPosition::Nearest,
3900                None,
3901            ),
3902        };
3903
3904        // Step 7: If the element does not have any associated box, or is not
3905        //         available to user-agent features, then return.
3906        if !self.has_css_layout_box_deprecated(cx) {
3907            return;
3908        }
3909
3910        // Step 8: Scroll the element into view with behavior, block, inline, and container.
3911        self.scroll_into_view_with_options(
3912            cx,
3913            behavior,
3914            ScrollAxisState::new_always_scroll_position(block),
3915            ScrollAxisState::new_always_scroll_position(inline),
3916            container,
3917            None,
3918        );
3919
3920        // Step 9: Optionally perform some other action that brings the
3921        // element to the user’s attention.
3922    }
3923
3924    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth>
3925    fn ScrollWidth(&self, cx: &mut JSContext) -> i32 {
3926        self.upcast::<Node>().scroll_area(cx).size.width
3927    }
3928
3929    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollheight>
3930    fn ScrollHeight(&self, cx: &mut JSContext) -> i32 {
3931        self.upcast::<Node>().scroll_area(cx).size.height
3932    }
3933
3934    /// <https://drafts.csswg.org/cssom-view/#dom-element-clienttop>
3935    fn ClientTop(&self, cx: &mut JSContext) -> i32 {
3936        self.client_rect(cx).origin.y
3937    }
3938
3939    /// <https://drafts.csswg.org/cssom-view/#dom-element-clientleft>
3940    fn ClientLeft(&self, cx: &mut JSContext) -> i32 {
3941        self.client_rect(cx).origin.x
3942    }
3943
3944    /// <https://drafts.csswg.org/cssom-view/#dom-element-clientwidth>
3945    fn ClientWidth(&self, cx: &mut JSContext) -> i32 {
3946        self.client_rect(cx).size.width
3947    }
3948
3949    /// <https://drafts.csswg.org/cssom-view/#dom-element-clientheight>
3950    fn ClientHeight(&self, cx: &mut JSContext) -> i32 {
3951        self.client_rect(cx).size.height
3952    }
3953
3954    // https://drafts.csswg.org/cssom-view/#dom-element-currentcsszoom
3955    fn CurrentCSSZoom(&self, cx: &mut JSContext) -> Finite<f64> {
3956        let window = self.owner_window();
3957        Finite::wrap(window.current_css_zoom_query(cx, self.upcast::<Node>()) as f64)
3958    }
3959
3960    /// <https://html.spec.whatwg.org/multipage/#dom-element-sethtmlunsafe>
3961    fn SetHTMLUnsafe(
3962        &self,
3963        cx: &mut JSContext,
3964        html: TrustedHTMLOrString,
3965        options: &SetHTMLUnsafeOptions,
3966    ) -> ErrorResult {
3967        // Step 1. Let compliantHTML be the result of invoking the
3968        // Get Trusted Type compliant string algorithm with TrustedHTML,
3969        // this's relevant global object, html, "Element setHTMLUnsafe", and "script".
3970        let compliant_html = TrustedHTML::get_trusted_type_compliant_string(
3971            cx,
3972            &self.owner_global(),
3973            html,
3974            "Element setHTMLUnsafe",
3975        )?;
3976        // Step 2. Let target be this's template contents if this is a template element; otherwise this.
3977        let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
3978            DomRoot::upcast(template.Content(cx))
3979        } else {
3980            DomRoot::from_ref(self.upcast())
3981        };
3982
3983        // Step 3. Set and filter HTML given target, this, compliantHTML, options, and false.
3984        Sanitizer::set_and_filter_html(cx, &target, self, compliant_html, options, false)?;
3985
3986        Ok(())
3987    }
3988
3989    /// <https://wicg.github.io/sanitizer-api/#dom-element-sethtml>
3990    fn SetHTML(
3991        &self,
3992        cx: &mut JSContext,
3993        html: DOMString,
3994        options: &SetHTMLOptions,
3995    ) -> ErrorResult {
3996        // Step 1. Let target be this’s template contents if this is a template; otherwise this.
3997        let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
3998            DomRoot::upcast(template.Content(cx))
3999        } else {
4000            DomRoot::from_ref(self.upcast())
4001        };
4002
4003        // Step 2. Set and filter HTML given target, this, html, options, and true.
4004        Sanitizer::set_and_filter_html(cx, &target, self, html, options, true)
4005    }
4006
4007    /// <https://html.spec.whatwg.org/multipage/#dom-element-gethtml>
4008    fn GetHTML(&self, cx: &mut JSContext, options: &GetHTMLOptions) -> DOMString {
4009        let shadow_roots = options.shadowRoots.iter().map(Dom::as_rooted).collect();
4010        // > Element's getHTML(options) method steps are to return the result of HTML fragment serialization
4011        // > algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].
4012        self.upcast::<Node>().html_serialize(
4013            cx,
4014            TraversalScope::ChildrenOnly(None),
4015            options.serializableShadowRoots,
4016            shadow_roots,
4017        )
4018    }
4019
4020    /// <https://html.spec.whatwg.org/multipage/#dom-element-innerhtml>
4021    fn GetInnerHTML(&self, cx: &mut JSContext) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
4022        let qname = QualName::new(
4023            self.prefix().clone(),
4024            self.namespace().clone(),
4025            self.local_name().clone(),
4026        );
4027
4028        // FIXME: This should use the fragment serialization algorithm, which takes
4029        // care of distinguishing between html/xml documents
4030        let result = if self.owner_document().is_html_document() {
4031            self.upcast::<Node>()
4032                .html_serialize(cx, ChildrenOnly(Some(qname)), false, vec![])
4033        } else {
4034            self.upcast::<Node>()
4035                .xml_serialize(XmlChildrenOnly(Some(qname)))?
4036        };
4037
4038        Ok(TrustedHTMLOrNullIsEmptyString::NullIsEmptyString(result))
4039    }
4040
4041    /// <https://html.spec.whatwg.org/multipage/#dom-element-innerhtml>
4042    fn SetInnerHTML(
4043        &self,
4044        cx: &mut JSContext,
4045        value: TrustedHTMLOrNullIsEmptyString,
4046    ) -> ErrorResult {
4047        // Step 1: Let compliantString be the result of invoking the
4048        // Get Trusted Type compliant string algorithm with TrustedHTML,
4049        // this's relevant global object, the given value, "Element innerHTML", and "script".
4050        let value = TrustedHTML::get_trusted_type_compliant_string(
4051            cx,
4052            &self.owner_global(),
4053            value.convert(),
4054            "Element innerHTML",
4055        )?;
4056        // https://github.com/w3c/DOM-Parsing/issues/1
4057        let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
4058            // Step 4: If context is a template element, then set context to
4059            // the template element's template contents (a DocumentFragment).
4060            DomRoot::upcast(template.Content(cx))
4061        } else {
4062            // Step 2: Let context be this.
4063            DomRoot::from_ref(self.upcast())
4064        };
4065
4066        // Fast path for when the value is small, doesn't contain any markup and doesn't require
4067        // extra work to set innerHTML.
4068        if !self.node.has_weird_parser_insertion_mode() &&
4069            value.len_utf8_or_latin1() < 100 &&
4070            !value
4071                .as_bytes(cx.no_gc())
4072                .iter()
4073                .any(|c| matches!(*c, b'&' | b'\0' | b'<' | b'\r'))
4074        {
4075            return Node::SetTextContent(&target, cx, Some(value));
4076        }
4077
4078        // Step 3: Let fragment be the result of invoking the fragment parsing algorithm steps
4079        // with context and compliantString.
4080        let frag = self.parse_fragment(value, cx)?;
4081
4082        // Step 5: Replace all with fragment within context.
4083        Node::replace_all(cx, Some(frag.upcast()), &target);
4084        Ok(())
4085    }
4086
4087    /// <https://html.spec.whatwg.org/multipage/#dom-element-outerhtml>
4088    fn GetOuterHTML(&self, cx: &mut JSContext) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
4089        // FIXME: This should use the fragment serialization algorithm, which takes
4090        // care of distinguishing between html/xml documents
4091        let result = if self.owner_document().is_html_document() {
4092            self.upcast::<Node>()
4093                .html_serialize(cx, IncludeNode, false, vec![])
4094        } else {
4095            self.upcast::<Node>().xml_serialize(XmlIncludeNode)?
4096        };
4097
4098        Ok(TrustedHTMLOrNullIsEmptyString::NullIsEmptyString(result))
4099    }
4100
4101    /// <https://html.spec.whatwg.org/multipage/#dom-element-outerhtml>
4102    fn SetOuterHTML(
4103        &self,
4104        cx: &mut JSContext,
4105        value: TrustedHTMLOrNullIsEmptyString,
4106    ) -> ErrorResult {
4107        // Step 1: Let compliantString be the result of invoking the
4108        // Get Trusted Type compliant string algorithm with TrustedHTML,
4109        // this's relevant global object, the given value, "Element outerHTML", and "script".
4110        let value = TrustedHTML::get_trusted_type_compliant_string(
4111            cx,
4112            &self.owner_global(),
4113            value.convert(),
4114            "Element outerHTML",
4115        )?;
4116        let context_document = self.owner_document();
4117        let context_node = self.upcast::<Node>();
4118        // Step 2: Let parent be this's parent.
4119        let context_parent = match context_node.GetParentNode() {
4120            None => {
4121                // Step 3: If parent is null, return. There would be no way to
4122                // obtain a reference to the nodes created even if the remaining steps were run.
4123                return Ok(());
4124            },
4125            Some(parent) => parent,
4126        };
4127
4128        let parent = match context_parent.type_id() {
4129            // Step 4: If parent is a Document, throw a "NoModificationAllowedError" DOMException.
4130            NodeTypeId::Document(_) => {
4131                return Err(Error::NoModificationAllowed(Some(
4132                    "Parent is a Document".into(),
4133                )));
4134            },
4135
4136            // Step 5: If parent is a DocumentFragment, set parent to the result of
4137            // creating an element given this's node document, "body", and the HTML namespace.
4138            NodeTypeId::DocumentFragment(_) => {
4139                let body_elem = Element::create(
4140                    cx,
4141                    QualName::new(None, ns!(html), local_name!("body")),
4142                    None,
4143                    &context_document,
4144                    ElementCreator::ScriptCreated,
4145                    CustomElementCreationMode::Synchronous,
4146                    None,
4147                );
4148                DomRoot::upcast(body_elem)
4149            },
4150            _ => context_node.GetParentElement().unwrap(),
4151        };
4152
4153        // Step 6: Let fragment be the result of invoking the
4154        // fragment parsing algorithm steps given parent and compliantString.
4155        let frag = parent.parse_fragment(value, cx)?;
4156        // Step 7: Replace this with fragment within this's parent.
4157        context_parent.ReplaceChild(cx, frag.upcast(), context_node)?;
4158        Ok(())
4159    }
4160
4161    /// <https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling>
4162    fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
4163        self.upcast::<Node>()
4164            .preceding_siblings()
4165            .find_map(DomRoot::downcast)
4166    }
4167
4168    /// <https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling>
4169    fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
4170        self.upcast::<Node>()
4171            .following_siblings()
4172            .find_map(DomRoot::downcast)
4173    }
4174
4175    /// <https://dom.spec.whatwg.org/#dom-parentnode-children>
4176    fn Children(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
4177        let window = self.owner_window();
4178        HTMLCollection::children(cx, &window, self.upcast())
4179    }
4180
4181    /// <https://dom.spec.whatwg.org/#dom-parentnode-firstelementchild>
4182    fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
4183        self.upcast::<Node>().child_elements().next()
4184    }
4185
4186    /// <https://dom.spec.whatwg.org/#dom-parentnode-lastelementchild>
4187    fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
4188        self.upcast::<Node>()
4189            .rev_children()
4190            .find_map(DomRoot::downcast::<Element>)
4191    }
4192
4193    /// <https://dom.spec.whatwg.org/#dom-parentnode-childelementcount>
4194    fn ChildElementCount(&self) -> u32 {
4195        self.upcast::<Node>().child_elements().count() as u32
4196    }
4197
4198    /// <https://dom.spec.whatwg.org/#dom-parentnode-prepend>
4199    fn Prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4200        self.upcast::<Node>().prepend(cx, nodes)
4201    }
4202
4203    /// <https://dom.spec.whatwg.org/#dom-parentnode-append>
4204    fn Append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4205        self.upcast::<Node>().append(cx, nodes)
4206    }
4207
4208    /// <https://dom.spec.whatwg.org/#dom-parentnode-replacechildren>
4209    fn ReplaceChildren(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4210        self.upcast::<Node>().replace_children(cx, nodes)
4211    }
4212
4213    /// <https://dom.spec.whatwg.org/#dom-parentnode-movebefore>
4214    fn MoveBefore(&self, cx: &mut JSContext, node: &Node, child: Option<&Node>) -> ErrorResult {
4215        self.upcast::<Node>().move_before(cx, node, child)
4216    }
4217
4218    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselector>
4219    fn QuerySelector(
4220        &self,
4221        cx: &mut JSContext,
4222        selectors: DOMString,
4223    ) -> Fallible<Option<DomRoot<Element>>> {
4224        let root = self.upcast::<Node>();
4225        root.query_selector(cx.no_gc(), selectors)
4226    }
4227
4228    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall>
4229    fn QuerySelectorAll(
4230        &self,
4231        cx: &mut JSContext,
4232        selectors: DOMString,
4233    ) -> Fallible<DomRoot<NodeList>> {
4234        let root = self.upcast::<Node>();
4235        root.query_selector_all(cx, selectors)
4236    }
4237
4238    /// <https://dom.spec.whatwg.org/#dom-childnode-before>
4239    fn Before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4240        self.upcast::<Node>().before(cx, nodes)
4241    }
4242
4243    /// <https://dom.spec.whatwg.org/#dom-childnode-after>
4244    fn After(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4245        self.upcast::<Node>().after(cx, nodes)
4246    }
4247
4248    /// <https://dom.spec.whatwg.org/#dom-childnode-replacewith>
4249    fn ReplaceWith(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4250        self.upcast::<Node>().replace_with(cx, nodes)
4251    }
4252
4253    /// <https://dom.spec.whatwg.org/#dom-childnode-remove>
4254    fn Remove(&self, cx: &mut JSContext) {
4255        self.upcast::<Node>().remove_self(cx);
4256    }
4257
4258    /// <https://dom.spec.whatwg.org/#dom-element-matches>
4259    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
4260    fn Matches(&self, selectors: DOMString) -> Fallible<bool> {
4261        let document = self.owner_document();
4262        let url = document.url();
4263        let selectors = match SelectorParser::parse_author_origin_no_namespace(
4264            &selectors.str(),
4265            &UrlExtraData(url.get_arc()),
4266        ) {
4267            Err(_) => {
4268                return Err(Error::Syntax(
4269                    format!("'{selectors}' is not a valid selector").into(),
4270                ));
4271            },
4272            Ok(selectors) => selectors,
4273        };
4274
4275        // SAFETY: traced_self is unrooted, but we have a reference to "self" so it won't be freed.
4276        let traced_self = Dom::from_ref(self);
4277        let quirks_mode = document.quirks_mode();
4278        Ok(with_layout_state(|| {
4279            #[expect(unsafe_code)]
4280            let layout_element: LayoutDom<'_, _> = unsafe { traced_self.to_layout() };
4281            dom_apis::element_matches(
4282                &ServoDangerousStyleElement::from(layout_element.upcast()),
4283                &selectors,
4284                quirks_mode,
4285            )
4286        }))
4287    }
4288
4289    /// <https://dom.spec.whatwg.org/#dom-element-webkitmatchesselector>
4290    fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> {
4291        self.Matches(selectors)
4292    }
4293
4294    /// <https://dom.spec.whatwg.org/#dom-element-closest>
4295    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
4296    fn Closest(&self, selectors: DOMString) -> Fallible<Option<DomRoot<Element>>> {
4297        let document = self.owner_document();
4298        let url = document.url();
4299        let selectors = match SelectorParser::parse_author_origin_no_namespace(
4300            &selectors.str(),
4301            &UrlExtraData(url.get_arc()),
4302        ) {
4303            Err(_) => return Err(Error::Syntax(Some("Invalid selector".into()))),
4304            Ok(selectors) => selectors,
4305        };
4306
4307        // SAFETY: traced_self is unrooted, but we have a reference to "self" so it won't be freed.
4308        let traced_self = Dom::from_ref(self);
4309        let quirks_mode = document.quirks_mode();
4310        let closest_element = with_layout_state(|| {
4311            #[expect(unsafe_code)]
4312            let layout_element: LayoutDom<'_, _> = unsafe { traced_self.to_layout() };
4313            dom_apis::element_closest(
4314                ServoDangerousStyleElement::from(layout_element.upcast()),
4315                &selectors,
4316                quirks_mode,
4317            )
4318        });
4319        Ok(closest_element.map(ServoDangerousStyleElement::rooted))
4320    }
4321
4322    /// <https://dom.spec.whatwg.org/#dom-element-insertadjacentelement>
4323    fn InsertAdjacentElement(
4324        &self,
4325        cx: &mut JSContext,
4326        where_: DOMString,
4327        element: &Element,
4328    ) -> Fallible<Option<DomRoot<Element>>> {
4329        let where_ = where_.parse::<AdjacentPosition>()?;
4330        let inserted_node = self.insert_adjacent(cx, where_, element.upcast())?;
4331        Ok(inserted_node.map(|node| DomRoot::downcast(node).unwrap()))
4332    }
4333
4334    /// <https://dom.spec.whatwg.org/#dom-element-insertadjacenttext>
4335    fn InsertAdjacentText(
4336        &self,
4337        cx: &mut JSContext,
4338        where_: DOMString,
4339        data: DOMString,
4340    ) -> ErrorResult {
4341        // Step 1.
4342        let text = Text::new(cx, data, &self.owner_document());
4343
4344        // Step 2.
4345        let where_ = where_.parse::<AdjacentPosition>()?;
4346        self.insert_adjacent(cx, where_, text.upcast()).map(|_| ())
4347    }
4348
4349    /// <https://w3c.github.io/DOM-Parsing/#dom-element-insertadjacenthtml>
4350    fn InsertAdjacentHTML(
4351        &self,
4352        cx: &mut JSContext,
4353        position: DOMString,
4354        text: TrustedHTMLOrString,
4355    ) -> ErrorResult {
4356        // Step 1: Let compliantString be the result of invoking the
4357        // Get Trusted Type compliant string algorithm with TrustedHTML,
4358        // this's relevant global object, string, "Element insertAdjacentHTML", and "script".
4359        let text = TrustedHTML::get_trusted_type_compliant_string(
4360            cx,
4361            &self.owner_global(),
4362            text,
4363            "Element insertAdjacentHTML",
4364        )?;
4365        let position = position.parse::<AdjacentPosition>()?;
4366
4367        // Step 2: Let context be null.
4368        // Step 3: Use the first matching item from this list:
4369        let context = match position {
4370            // If position is an ASCII case-insensitive match for the string "beforebegin"
4371            // If position is an ASCII case-insensitive match for the string "afterend"
4372            AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
4373                match self.upcast::<Node>().GetParentNode() {
4374                    // Step 3.2: If context is null or a Document, throw a "NoModificationAllowedError" DOMException.
4375                    Some(ref node) if node.is::<Document>() => {
4376                        return Err(Error::NoModificationAllowed(Some(
4377                            "Parent is a Document".into(),
4378                        )));
4379                    },
4380                    None => {
4381                        return Err(Error::NoModificationAllowed(Some(
4382                            "Element has no parent".into(),
4383                        )));
4384                    },
4385                    // Step 3.1: Set context to this's parent.
4386                    Some(node) => node,
4387                }
4388            },
4389            // If position is an ASCII case-insensitive match for the string "afterbegin"
4390            // If position is an ASCII case-insensitive match for the string "beforeend"
4391            AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
4392                // Set context to this.
4393                DomRoot::from_ref(self.upcast::<Node>())
4394            },
4395        };
4396
4397        // Step 4.
4398        let context = Element::fragment_parsing_context(
4399            cx,
4400            &context.owner_doc(),
4401            context.downcast::<Element>(),
4402        );
4403
4404        // Step 5: Let fragment be the result of invoking the
4405        // fragment parsing algorithm steps with context and compliantString.
4406        let fragment = context.parse_fragment(text, cx)?;
4407
4408        // Step 6.
4409        self.insert_adjacent(cx, position, fragment.upcast())
4410            .map(|_| ())
4411    }
4412
4413    // check-tidy: no specs after this line
4414    fn EnterFormalActivationState(&self, cx: &JSContext) -> ErrorResult {
4415        match self.as_maybe_activatable() {
4416            Some(a) => {
4417                a.enter_formal_activation_state(cx.no_gc());
4418                Ok(())
4419            },
4420            None => Err(Error::NotSupported(Some(
4421                "Element is not activatable".into(),
4422            ))),
4423        }
4424    }
4425
4426    fn ExitFormalActivationState(&self, cx: &JSContext) -> ErrorResult {
4427        match self.as_maybe_activatable() {
4428            Some(a) => {
4429                a.exit_formal_activation_state(cx.no_gc());
4430                Ok(())
4431            },
4432            None => Err(Error::NotSupported(Some(
4433                "Element is not activatable".into(),
4434            ))),
4435        }
4436    }
4437
4438    /// <https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen>
4439    fn RequestFullscreen(
4440        &self,
4441        cx: &mut CurrentRealm,
4442        _options: &FullscreenOptions,
4443    ) -> RootedPromise {
4444        // Step 1. Let pendingDoc be this’s node document.
4445        let pending_doc = self.owner_document();
4446
4447        // Step 2. Let promise be a new promise.
4448        let promise = Promise::new_in_realm(cx);
4449
4450        // Step 3. If pendingDoc is not fully active, then reject promise with a TypeError
4451        // exception and return promise.
4452        if !pending_doc.is_fully_active() {
4453            promise.reject_error(cx, Error::Type(c"Document is not fully active".to_owned()));
4454            return promise;
4455        }
4456
4457        // Step 4. Let error be false.
4458        let mut error = false;
4459
4460        // Step 5. If any of the following conditions are false, then set error to true:
4461        // > - This’s namespace is the HTML namespace or this is an SVG svg or MathML math element.
4462        // > - This is not a dialog element.
4463        // > - The fullscreen element ready check for this returns true.
4464        // > - Fullscreen is supported.
4465        // > - This’s relevant global object has transient activation or the algorithm is triggered
4466        // > - by a user generated orientation change.
4467        //
4468        // This is the same as not all of the conditions being true.
4469        // FIXME: Triggered by a user generated orientation change.
4470        if !((*self.namespace() == ns!(html) ||
4471            (*self.namespace() == ns!(svg) && *self.local_name() == local_name!("svg")) ||
4472            (*self.namespace() == ns!(mathml) && *self.local_name() == local_name!("math"))) &&
4473            !self.is::<HTMLDialogElement>() &&
4474            self.fullscreen_element_ready_check() &&
4475            pending_doc.overlay_handler().fullscreen_is_supported() &&
4476            self.owner_window().has_transient_activation())
4477        {
4478            error = true;
4479        }
4480
4481        // Step 6. If error is false, then consume user activation given pendingDoc’s relevant
4482        // global object.
4483        if !error {
4484            pending_doc.window().consume_user_activation();
4485        }
4486
4487        // Step 7. Return promise, and run the remaining steps in parallel.
4488        let this = Trusted::new(self);
4489        let trusted_pending_doc = Trusted::new(&*pending_doc);
4490        let trusted_promise = TrustedPromise::from(&promise);
4491        self.owner_global()
4492            .task_manager()
4493            .dom_manipulation_task_source()
4494            .queue(task!(request_fullscreen_steps: move |cx| {
4495                let this = this.root();
4496                let pending_doc = trusted_pending_doc.root();
4497                let promise = trusted_promise.root(cx);
4498                let mut error = error;
4499
4500                // Step 8. If error is false, then resize pendingDoc’s node navigable’s top-level
4501                // traversable’s active document’s viewport’s dimensions, optionally taking into
4502                // account options["navigationUI"]:
4503                //
4504                // FIXME: Take options["navigationUI"] into account.
4505                if !error {
4506                    pending_doc.send_to_embedder(EmbedderMsg::NotifyFullscreenStateChanged(
4507                        pending_doc.webview_id(),
4508                        true,
4509                    ));
4510                }
4511
4512                // Step 9. If any of the following conditions are false, then set error to true:
4513                // > - This’s node document is pendingDoc.
4514                // > - The fullscreen element ready check for this returns true.
4515                if this.owner_document() != pending_doc || !this.fullscreen_element_ready_check() {
4516                    error = true;
4517                }
4518
4519                // Step 10. If error is true:
4520                if error {
4521                    // Step 10.1. Append (fullscreenerror, this) to pendingDoc’s list of pending
4522                    // fullscreen events.
4523                    pending_doc
4524                        .overlay_handler()
4525                        .append_to_list_of_pending_fullscreen_events(
4526                            cx.no_gc(),
4527                            atom!("fullscreenerror"),
4528                            &this,
4529                        );
4530
4531                    // Step 10.2. Reject promise with a TypeError exception and terminate these
4532                    // steps.
4533                    promise.reject_error(cx, Error::Type(c"Fullscreen request failed".to_owned()));
4534                    return;
4535                }
4536
4537                // Step 11. Let fullscreenElements be an ordered set initially consisting of this.
4538                let mut fullscreen_elements = vec![this.clone()];
4539
4540                // Step 12. While true:
4541                loop {
4542                    // Step 12.1. Let last be the last item of fullscreenElements.
4543                    let last = fullscreen_elements
4544                        .last()
4545                        .expect("fullscreenElements has an initial element");
4546
4547                    // Step 12.2. Let container be last’s node navigable’s container.
4548                    // Step 12.3. If container is null, then break.
4549                    // FIXME: Support cross-origin container
4550                    let Some(container) = last
4551                        .owner_document()
4552                        .window()
4553                        .window_proxy()
4554                        .frame_element()
4555                        .map(DomRoot::from_ref)
4556                    else {
4557                        break;
4558                    };
4559
4560                    // Step 12.4. Append container to fullscreenElements.
4561                    fullscreen_elements.push(container);
4562                }
4563
4564                // Step 13. For each element in fullscreenElements:
4565                for element in fullscreen_elements {
4566                    // Step 13.1. Let doc be element’s node document.
4567                    let doc = element.owner_document();
4568
4569                    // Step 13.2. If element is doc’s fullscreen element, continue.
4570                    if doc.overlay_handler().fullscreen_element().as_ref() == Some(&element) {
4571                        continue;
4572                    }
4573
4574                    // Step 13.3. If element is this and this is an iframe element, then set
4575                    // element’s iframe fullscreen flag.
4576                    if element == this &&
4577                        let Some(iframe) = element.downcast::<HTMLIFrameElement>()
4578                    {
4579                        iframe.set_iframe_fullscreen_flag(true);
4580                    }
4581
4582                    // Step 13.4. Fullscreen element within doc.
4583                    doc.overlay_handler().fullscreen_an_element(cx, &element);
4584
4585                    // Step 13.5. Append (fullscreenchange, element) to doc’s list of pending
4586                    // fullscreen events.
4587                    doc.overlay_handler()
4588                        .append_to_list_of_pending_fullscreen_events(
4589                            cx.no_gc(),
4590                            atom!("fullscreenchange"),
4591                            &element,
4592                        );
4593                }
4594
4595                // Step 14. Depending on the value of options["keyboardLock"]:
4596                // > "browser": Set this’s keyboard lock flag.
4597                // > "none": Unset this’s keyboard lock flag.
4598                //
4599                // FIXME: Set or unset keyboard lock flag.
4600
4601                // Step 15. Resolve promise with undefined.
4602                promise.resolve_native(cx, &());
4603            }));
4604
4605        promise
4606    }
4607
4608    // https://fullscreen.spec.whatwg.org/#handler-document-onfullscreenchange
4609    event_handler!(
4610        fullscreenchange,
4611        GetOnfullscreenchange,
4612        SetOnfullscreenchange
4613    );
4614
4615    // https://fullscreen.spec.whatwg.org/#handler-document-onfullscreenerror
4616    event_handler!(fullscreenerror, GetOnfullscreenerror, SetOnfullscreenerror);
4617
4618    /// <https://w3c.github.io/pointerevents/#dom-element-setpointercapture>
4619    fn SetPointerCapture(&self, pointer_id: i32) -> ErrorResult {
4620        let document = self.owner_document();
4621        let event_handler = document.event_handler();
4622
4623        // Step 1. If the pointerId provided as the method's argument does not match any of
4624        // the active pointers, then throw a DOMException with the name "NotFoundError".
4625        //
4626        // Note: "active pointers" is global across documents. We can only cheaply check
4627        // active pointers in this element's document. If the pointer is active in another
4628        // document (e.g., parent/child frame), step 5 below will silently terminate.
4629        // We intentionally do not throw here in that case to avoid being stricter than
4630        // the spec.
4631
4632        // Step 2. If the element is not connected, throw a "InvalidStateError" DOMException.
4633        if !self.upcast::<Node>().is_connected() {
4634            return Err(Error::InvalidState(Some(
4635                "Can't capture pointer on an unconnected element".into(),
4636            )));
4637        }
4638
4639        // Step 3. If this method is invoked while the document has a locked element
4640        // (pointerLockElement), throw an "InvalidStateError" DOMException.
4641        // TODO: Implement when pointer lock is supported.
4642
4643        // Step 4/5. If the pointer is not in the active buttons state or the element's
4644        // node document is not the active document of the pointer, then terminate these
4645        // steps. `is_active_pointer` on this document covers both conditions: it returns
4646        // true only when the pointer is in the active buttons state in *this* document,
4647        // which implies this document is the pointer's active document.
4648        if !event_handler.is_active_pointer(pointer_id) {
4649            return Ok(());
4650        }
4651
4652        // Step 6. For the specified pointerId, set the pending pointer capture target
4653        // override to the Element on which this method was invoked.
4654        event_handler.set_pending_pointer_capture(pointer_id, self);
4655
4656        Ok(())
4657    }
4658
4659    /// <https://w3c.github.io/pointerevents/#dom-element-releasepointercapture>
4660    fn ReleasePointerCapture(&self, pointer_id: i32) -> ErrorResult {
4661        let document = self.owner_document();
4662        let event_handler = document.event_handler();
4663
4664        // Step 1. If the pointerId provided as the method's argument does not match any of
4665        // the active pointers and these steps are not being invoked as a result of the
4666        // implicit release of pointer capture, then throw a DOMException with the name "NotFoundError".
4667        if !event_handler.is_active_pointer(pointer_id) {
4668            return Err(Error::NotFound(Some(
4669                "Can't release a pointer that is not active".into(),
4670            )));
4671        }
4672
4673        // Step 2. If hasPointerCapture is false for the Element with the specified pointerId,
4674        // then terminate these steps.
4675        if !event_handler.has_pointer_capture(pointer_id, self) {
4676            return Ok(());
4677        }
4678
4679        // Step 3. For the specified pointerId, clear the pending pointer capture target override.
4680        event_handler.clear_pending_pointer_capture(pointer_id);
4681
4682        Ok(())
4683    }
4684
4685    /// <https://w3c.github.io/pointerevents/#dom-element-haspointercapture>
4686    fn HasPointerCapture(&self, pointer_id: i32) -> bool {
4687        let document = self.owner_document();
4688        let event_handler = document.event_handler();
4689        event_handler.has_pointer_capture(pointer_id, self)
4690    }
4691
4692    /// <https://dom.spec.whatwg.org/#dom-element-attachshadow>
4693    fn AttachShadow(
4694        &self,
4695        cx: &mut JSContext,
4696        init: &ShadowRootInit,
4697    ) -> Fallible<DomRoot<ShadowRoot>> {
4698        // Step 1. Run attach a shadow root with this, init["mode"], init["clonable"], init["serializable"],
4699        // init["delegatesFocus"], and init["slotAssignment"].
4700        let shadow_root = self.attach_shadow(
4701            cx,
4702            IsUserAgentWidget::No,
4703            init.mode,
4704            init.clonable,
4705            init.serializable,
4706            init.delegatesFocus,
4707            init.slotAssignment,
4708        )?;
4709
4710        // Step 2. Return this’s shadow root.
4711        Ok(shadow_root)
4712    }
4713
4714    /// <https://dom.spec.whatwg.org/#dom-element-shadowroot>
4715    fn GetShadowRoot(&self) -> Option<DomRoot<ShadowRoot>> {
4716        // Step 1. Let shadow be this’s shadow root.
4717        let shadow_or_none = self.shadow_root();
4718
4719        // Step 2. If shadow is null or its mode is "closed", then return null.
4720        let shadow = shadow_or_none?;
4721        if shadow.Mode() == ShadowRootMode::Closed {
4722            return None;
4723        }
4724
4725        // Step 3. Return shadow.
4726        Some(shadow)
4727    }
4728
4729    /// <https://dom.spec.whatwg.org/#dom-element-customelementregistry>
4730    fn GetCustomElementRegistry(&self) -> Option<DomRoot<CustomElementRegistry>> {
4731        // The customElementRegistry getter steps are to return this’s custom element registry.
4732        self.custom_element_registry()
4733    }
4734
4735    /// <https://w3c.github.io/aria/#ref-for-dom-ariamixin-role-1>
4736    fn GetRole(&self) -> Option<DOMString> {
4737        self.get_nullable_string_attribute(&local_name!("role"))
4738    }
4739
4740    /// <https://w3c.github.io/aria/#ref-for-dom-ariamixin-role-1>
4741    fn SetRole(&self, cx: &mut JSContext, value: Option<DOMString>) {
4742        self.set_nullable_tokenlist_attribute(cx, &local_name!("role"), value);
4743    }
4744
4745    fn GetAriaAtomic(&self) -> Option<DOMString> {
4746        self.get_nullable_string_attribute(&local_name!("aria-atomic"))
4747    }
4748
4749    fn SetAriaAtomic(&self, cx: &mut JSContext, value: Option<DOMString>) {
4750        self.set_nullable_string_attribute(cx, &local_name!("aria-atomic"), value);
4751    }
4752
4753    fn GetAriaAutoComplete(&self) -> Option<DOMString> {
4754        self.get_nullable_string_attribute(&local_name!("aria-autocomplete"))
4755    }
4756
4757    fn SetAriaAutoComplete(&self, cx: &mut JSContext, value: Option<DOMString>) {
4758        self.set_nullable_string_attribute(cx, &local_name!("aria-autocomplete"), value);
4759    }
4760
4761    fn GetAriaBrailleLabel(&self) -> Option<DOMString> {
4762        self.get_nullable_string_attribute(&local_name!("aria-braillelabel"))
4763    }
4764
4765    fn SetAriaBrailleLabel(&self, cx: &mut JSContext, value: Option<DOMString>) {
4766        self.set_nullable_string_attribute(cx, &local_name!("aria-braillelabel"), value);
4767    }
4768
4769    fn GetAriaBrailleRoleDescription(&self) -> Option<DOMString> {
4770        self.get_nullable_string_attribute(&local_name!("aria-brailleroledescription"))
4771    }
4772
4773    fn SetAriaBrailleRoleDescription(&self, cx: &mut JSContext, value: Option<DOMString>) {
4774        self.set_nullable_string_attribute(cx, &local_name!("aria-brailleroledescription"), value);
4775    }
4776
4777    fn GetAriaBusy(&self) -> Option<DOMString> {
4778        self.get_nullable_string_attribute(&local_name!("aria-busy"))
4779    }
4780
4781    fn SetAriaBusy(&self, cx: &mut JSContext, value: Option<DOMString>) {
4782        self.set_nullable_string_attribute(cx, &local_name!("aria-busy"), value);
4783    }
4784
4785    fn GetAriaChecked(&self) -> Option<DOMString> {
4786        self.get_nullable_string_attribute(&local_name!("aria-checked"))
4787    }
4788
4789    fn SetAriaChecked(&self, cx: &mut JSContext, value: Option<DOMString>) {
4790        self.set_nullable_string_attribute(cx, &local_name!("aria-checked"), value);
4791    }
4792
4793    fn GetAriaColCount(&self) -> Option<DOMString> {
4794        self.get_nullable_string_attribute(&local_name!("aria-colcount"))
4795    }
4796
4797    fn SetAriaColCount(&self, cx: &mut JSContext, value: Option<DOMString>) {
4798        self.set_nullable_string_attribute(cx, &local_name!("aria-colcount"), value);
4799    }
4800
4801    fn GetAriaColIndex(&self) -> Option<DOMString> {
4802        self.get_nullable_string_attribute(&local_name!("aria-colindex"))
4803    }
4804
4805    fn SetAriaColIndex(&self, cx: &mut JSContext, value: Option<DOMString>) {
4806        self.set_nullable_string_attribute(cx, &local_name!("aria-colindex"), value);
4807    }
4808
4809    fn GetAriaColIndexText(&self) -> Option<DOMString> {
4810        self.get_nullable_string_attribute(&local_name!("aria-colindextext"))
4811    }
4812
4813    fn SetAriaColIndexText(&self, cx: &mut JSContext, value: Option<DOMString>) {
4814        self.set_nullable_string_attribute(cx, &local_name!("aria-colindextext"), value);
4815    }
4816
4817    fn GetAriaColSpan(&self) -> Option<DOMString> {
4818        self.get_nullable_string_attribute(&local_name!("aria-colspan"))
4819    }
4820
4821    fn SetAriaColSpan(&self, cx: &mut JSContext, value: Option<DOMString>) {
4822        self.set_nullable_string_attribute(cx, &local_name!("aria-colspan"), value);
4823    }
4824
4825    fn GetAriaCurrent(&self) -> Option<DOMString> {
4826        self.get_nullable_string_attribute(&local_name!("aria-current"))
4827    }
4828
4829    fn SetAriaCurrent(&self, cx: &mut JSContext, value: Option<DOMString>) {
4830        self.set_nullable_string_attribute(cx, &local_name!("aria-current"), value);
4831    }
4832
4833    fn GetAriaDescription(&self) -> Option<DOMString> {
4834        self.get_nullable_string_attribute(&local_name!("aria-description"))
4835    }
4836
4837    fn SetAriaDescription(&self, cx: &mut JSContext, value: Option<DOMString>) {
4838        self.set_nullable_string_attribute(cx, &local_name!("aria-description"), value);
4839    }
4840
4841    fn GetAriaDisabled(&self) -> Option<DOMString> {
4842        self.get_nullable_string_attribute(&local_name!("aria-disabled"))
4843    }
4844
4845    fn SetAriaDisabled(&self, cx: &mut JSContext, value: Option<DOMString>) {
4846        self.set_nullable_string_attribute(cx, &local_name!("aria-disabled"), value);
4847    }
4848
4849    fn GetAriaExpanded(&self) -> Option<DOMString> {
4850        self.get_nullable_string_attribute(&local_name!("aria-expanded"))
4851    }
4852
4853    fn SetAriaExpanded(&self, cx: &mut JSContext, value: Option<DOMString>) {
4854        self.set_nullable_string_attribute(cx, &local_name!("aria-expanded"), value);
4855    }
4856
4857    fn GetAriaHasPopup(&self) -> Option<DOMString> {
4858        self.get_nullable_string_attribute(&local_name!("aria-haspopup"))
4859    }
4860
4861    fn SetAriaHasPopup(&self, cx: &mut JSContext, value: Option<DOMString>) {
4862        self.set_nullable_string_attribute(cx, &local_name!("aria-haspopup"), value);
4863    }
4864
4865    fn GetAriaHidden(&self) -> Option<DOMString> {
4866        self.get_nullable_string_attribute(&local_name!("aria-hidden"))
4867    }
4868
4869    fn SetAriaHidden(&self, cx: &mut JSContext, value: Option<DOMString>) {
4870        self.set_nullable_string_attribute(cx, &local_name!("aria-hidden"), value);
4871    }
4872
4873    fn GetAriaInvalid(&self) -> Option<DOMString> {
4874        self.get_nullable_string_attribute(&local_name!("aria-invalid"))
4875    }
4876
4877    fn SetAriaInvalid(&self, cx: &mut JSContext, value: Option<DOMString>) {
4878        self.set_nullable_string_attribute(cx, &local_name!("aria-invalid"), value);
4879    }
4880
4881    fn GetAriaKeyShortcuts(&self) -> Option<DOMString> {
4882        self.get_nullable_string_attribute(&local_name!("aria-keyshortcuts"))
4883    }
4884
4885    fn SetAriaKeyShortcuts(&self, cx: &mut JSContext, value: Option<DOMString>) {
4886        self.set_nullable_string_attribute(cx, &local_name!("aria-keyshortcuts"), value);
4887    }
4888
4889    fn GetAriaLabel(&self) -> Option<DOMString> {
4890        self.get_nullable_string_attribute(&local_name!("aria-label"))
4891    }
4892
4893    fn SetAriaLabel(&self, cx: &mut JSContext, value: Option<DOMString>) {
4894        self.set_nullable_string_attribute(cx, &local_name!("aria-label"), value);
4895    }
4896
4897    fn GetAriaLevel(&self) -> Option<DOMString> {
4898        self.get_nullable_string_attribute(&local_name!("aria-level"))
4899    }
4900
4901    fn SetAriaLevel(&self, cx: &mut JSContext, value: Option<DOMString>) {
4902        self.set_nullable_string_attribute(cx, &local_name!("aria-level"), value);
4903    }
4904
4905    fn GetAriaLive(&self) -> Option<DOMString> {
4906        self.get_nullable_string_attribute(&local_name!("aria-live"))
4907    }
4908
4909    fn SetAriaLive(&self, cx: &mut JSContext, value: Option<DOMString>) {
4910        self.set_nullable_string_attribute(cx, &local_name!("aria-live"), value);
4911    }
4912
4913    fn GetAriaModal(&self) -> Option<DOMString> {
4914        self.get_nullable_string_attribute(&local_name!("aria-modal"))
4915    }
4916
4917    fn SetAriaModal(&self, cx: &mut JSContext, value: Option<DOMString>) {
4918        self.set_nullable_string_attribute(cx, &local_name!("aria-modal"), value);
4919    }
4920
4921    fn GetAriaMultiLine(&self) -> Option<DOMString> {
4922        self.get_nullable_string_attribute(&local_name!("aria-multiline"))
4923    }
4924
4925    fn SetAriaMultiLine(&self, cx: &mut JSContext, value: Option<DOMString>) {
4926        self.set_nullable_string_attribute(cx, &local_name!("aria-multiline"), value);
4927    }
4928
4929    fn GetAriaMultiSelectable(&self) -> Option<DOMString> {
4930        self.get_nullable_string_attribute(&local_name!("aria-multiselectable"))
4931    }
4932
4933    fn SetAriaMultiSelectable(&self, cx: &mut JSContext, value: Option<DOMString>) {
4934        self.set_nullable_string_attribute(cx, &local_name!("aria-multiselectable"), value);
4935    }
4936
4937    fn GetAriaOrientation(&self) -> Option<DOMString> {
4938        self.get_nullable_string_attribute(&local_name!("aria-orientation"))
4939    }
4940
4941    fn SetAriaOrientation(&self, cx: &mut JSContext, value: Option<DOMString>) {
4942        self.set_nullable_string_attribute(cx, &local_name!("aria-orientation"), value);
4943    }
4944
4945    fn GetAriaPlaceholder(&self) -> Option<DOMString> {
4946        self.get_nullable_string_attribute(&local_name!("aria-placeholder"))
4947    }
4948
4949    fn SetAriaPlaceholder(&self, cx: &mut JSContext, value: Option<DOMString>) {
4950        self.set_nullable_string_attribute(cx, &local_name!("aria-placeholder"), value);
4951    }
4952
4953    fn GetAriaPosInSet(&self) -> Option<DOMString> {
4954        self.get_nullable_string_attribute(&local_name!("aria-posinset"))
4955    }
4956
4957    fn SetAriaPosInSet(&self, cx: &mut JSContext, value: Option<DOMString>) {
4958        self.set_nullable_string_attribute(cx, &local_name!("aria-posinset"), value);
4959    }
4960
4961    fn GetAriaPressed(&self) -> Option<DOMString> {
4962        self.get_nullable_string_attribute(&local_name!("aria-pressed"))
4963    }
4964
4965    fn SetAriaPressed(&self, cx: &mut JSContext, value: Option<DOMString>) {
4966        self.set_nullable_string_attribute(cx, &local_name!("aria-pressed"), value);
4967    }
4968
4969    fn GetAriaReadOnly(&self) -> Option<DOMString> {
4970        self.get_nullable_string_attribute(&local_name!("aria-readonly"))
4971    }
4972
4973    fn SetAriaReadOnly(&self, cx: &mut JSContext, value: Option<DOMString>) {
4974        self.set_nullable_string_attribute(cx, &local_name!("aria-readonly"), value);
4975    }
4976
4977    fn GetAriaRelevant(&self) -> Option<DOMString> {
4978        self.get_nullable_string_attribute(&local_name!("aria-relevant"))
4979    }
4980
4981    fn SetAriaRelevant(&self, cx: &mut JSContext, value: Option<DOMString>) {
4982        self.set_nullable_string_attribute(cx, &local_name!("aria-relevant"), value);
4983    }
4984
4985    fn GetAriaRequired(&self) -> Option<DOMString> {
4986        self.get_nullable_string_attribute(&local_name!("aria-required"))
4987    }
4988
4989    fn SetAriaRequired(&self, cx: &mut JSContext, value: Option<DOMString>) {
4990        self.set_nullable_string_attribute(cx, &local_name!("aria-required"), value);
4991    }
4992
4993    fn GetAriaRoleDescription(&self) -> Option<DOMString> {
4994        self.get_nullable_string_attribute(&local_name!("aria-roledescription"))
4995    }
4996
4997    fn SetAriaRoleDescription(&self, cx: &mut JSContext, value: Option<DOMString>) {
4998        self.set_nullable_string_attribute(cx, &local_name!("aria-roledescription"), value);
4999    }
5000
5001    fn GetAriaRowCount(&self) -> Option<DOMString> {
5002        self.get_nullable_string_attribute(&local_name!("aria-rowcount"))
5003    }
5004
5005    fn SetAriaRowCount(&self, cx: &mut JSContext, value: Option<DOMString>) {
5006        self.set_nullable_string_attribute(cx, &local_name!("aria-rowcount"), value);
5007    }
5008
5009    fn GetAriaRowIndex(&self) -> Option<DOMString> {
5010        self.get_nullable_string_attribute(&local_name!("aria-rowindex"))
5011    }
5012
5013    fn SetAriaRowIndex(&self, cx: &mut JSContext, value: Option<DOMString>) {
5014        self.set_nullable_string_attribute(cx, &local_name!("aria-rowindex"), value);
5015    }
5016
5017    fn GetAriaRowIndexText(&self) -> Option<DOMString> {
5018        self.get_nullable_string_attribute(&local_name!("aria-rowindextext"))
5019    }
5020
5021    fn SetAriaRowIndexText(&self, cx: &mut JSContext, value: Option<DOMString>) {
5022        self.set_nullable_string_attribute(cx, &local_name!("aria-rowindextext"), value);
5023    }
5024
5025    fn GetAriaRowSpan(&self) -> Option<DOMString> {
5026        self.get_nullable_string_attribute(&local_name!("aria-rowspan"))
5027    }
5028
5029    fn SetAriaRowSpan(&self, cx: &mut JSContext, value: Option<DOMString>) {
5030        self.set_nullable_string_attribute(cx, &local_name!("aria-rowspan"), value);
5031    }
5032
5033    fn GetAriaSelected(&self) -> Option<DOMString> {
5034        self.get_nullable_string_attribute(&local_name!("aria-selected"))
5035    }
5036
5037    fn SetAriaSelected(&self, cx: &mut JSContext, value: Option<DOMString>) {
5038        self.set_nullable_string_attribute(cx, &local_name!("aria-selected"), value);
5039    }
5040
5041    fn GetAriaSetSize(&self) -> Option<DOMString> {
5042        self.get_nullable_string_attribute(&local_name!("aria-setsize"))
5043    }
5044
5045    fn SetAriaSetSize(&self, cx: &mut JSContext, value: Option<DOMString>) {
5046        self.set_nullable_string_attribute(cx, &local_name!("aria-setsize"), value);
5047    }
5048
5049    fn GetAriaSort(&self) -> Option<DOMString> {
5050        self.get_nullable_string_attribute(&local_name!("aria-sort"))
5051    }
5052
5053    fn SetAriaSort(&self, cx: &mut JSContext, value: Option<DOMString>) {
5054        self.set_nullable_string_attribute(cx, &local_name!("aria-sort"), value);
5055    }
5056
5057    fn GetAriaValueMax(&self) -> Option<DOMString> {
5058        self.get_nullable_string_attribute(&local_name!("aria-valuemax"))
5059    }
5060
5061    fn SetAriaValueMax(&self, cx: &mut JSContext, value: Option<DOMString>) {
5062        self.set_nullable_string_attribute(cx, &local_name!("aria-valuemax"), value);
5063    }
5064
5065    fn GetAriaValueMin(&self) -> Option<DOMString> {
5066        self.get_nullable_string_attribute(&local_name!("aria-valuemin"))
5067    }
5068
5069    fn SetAriaValueMin(&self, cx: &mut JSContext, value: Option<DOMString>) {
5070        self.set_nullable_string_attribute(cx, &local_name!("aria-valuemin"), value);
5071    }
5072
5073    fn GetAriaValueNow(&self) -> Option<DOMString> {
5074        self.get_nullable_string_attribute(&local_name!("aria-valuenow"))
5075    }
5076
5077    fn SetAriaValueNow(&self, cx: &mut JSContext, value: Option<DOMString>) {
5078        self.set_nullable_string_attribute(cx, &local_name!("aria-valuenow"), value);
5079    }
5080
5081    fn GetAriaValueText(&self) -> Option<DOMString> {
5082        self.get_nullable_string_attribute(&local_name!("aria-valuetext"))
5083    }
5084
5085    fn SetAriaValueText(&self, cx: &mut JSContext, value: Option<DOMString>) {
5086        self.set_nullable_string_attribute(cx, &local_name!("aria-valuetext"), value);
5087    }
5088
5089    /// <https://dom.spec.whatwg.org/#dom-slotable-assignedslot>
5090    fn GetAssignedSlot(&self, cx: &JSContext) -> Option<DomRoot<HTMLSlotElement>> {
5091        // > The assignedSlot getter steps are to return the result of
5092        // > find a slot given this and with the open flag set.
5093        rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(self.upcast::<Node>())));
5094        slottable.find_a_slot(cx.no_gc(), true)
5095    }
5096
5097    /// <https://drafts.csswg.org/css-shadow-parts/#dom-element-part>
5098    fn Part(&self, cx: &mut JSContext) -> DomRoot<DOMTokenList> {
5099        let Some(part) = self.rare_data().as_ref().and_then(|data| data.part.get()) else {
5100            let part = DOMTokenList::new(cx, self, &local_name!("part"), None);
5101            self.ensure_rare_data(cx.no_gc()).part.set(Some(&*part));
5102            return part;
5103        };
5104        part
5105    }
5106
5107    /// <https://drafts.csswg.org/web-animations-1/#dom-animatable-animate>
5108    fn Animate(
5109        &self,
5110        cx: &mut JSContext,
5111        keyframes: *mut JSObject,
5112        options: UnrestrictedDoubleOrKeyframeAnimationOptions,
5113    ) -> DomRoot<Animation> {
5114        let window = self.owner_window();
5115
5116        // Step 1. Let target be the object on which this method was called.
5117        let target = self;
5118
5119        // Step 3. If options is a KeyframeAnimationOptions object, let timeline be the timeline member of
5120        // options or, if timeline member of options is missing, the default document timeline of the node document
5121        // of the element on which this method was called.
5122        let timeline = match &options {
5123            UnrestrictedDoubleOrKeyframeAnimationOptions::KeyframeAnimationOptions(opts) => opts
5124                .timeline
5125                .as_ref()
5126                .and_then(|inner| inner.as_ref().map(Dom::as_rooted)),
5127            _ => None,
5128        };
5129        let timeline = timeline.unwrap_or_else(|| {
5130            let document = self.owner_document();
5131            DomRoot::upcast(document.Timeline())
5132        });
5133
5134        // Step 2. Construct a new KeyframeEffect object effect in the relevant Realm
5135        // of target by using the same procedure as the KeyframeEffect(target, keyframes, options)
5136        // constructor, passing target as the target argument, and the keyframes and options arguments
5137        //  as supplied.
5138        //
5139        // If the above procedure causes an exception to be thrown, propagate the exception and
5140        // abort this procedure.
5141        let parent_options = match options {
5142            UnrestrictedDoubleOrKeyframeAnimationOptions::UnrestrictedDouble(value) => {
5143                UnrestrictedDoubleOrKeyframeEffectOptions::UnrestrictedDouble(value)
5144            },
5145            UnrestrictedDoubleOrKeyframeAnimationOptions::KeyframeAnimationOptions(options) => {
5146                UnrestrictedDoubleOrKeyframeEffectOptions::KeyframeEffectOptions(
5147                    options.into_inner().parent,
5148                )
5149            },
5150        };
5151        let effect =
5152            KeyframeEffect::Constructor(cx, &window, None, Some(target), keyframes, parent_options);
5153
5154        // Step 4. Construct a new Animation object, animation, in the relevant Realm of target by using
5155        // the same procedure as the Animation() constructor, passing effect and timeline as arguments of
5156        // the same name.
5157        let animation = Animation::Constructor(
5158            cx,
5159            &window,
5160            None,
5161            Some(effect.upcast()),
5162            Some(Some(&timeline)),
5163        );
5164
5165        // TODO: Step 5. If options is a KeyframeAnimationOptions object, assign the value of the id member of options
5166        // to animation’s id attribute.
5167
5168        // TODO: Step 6. Run the procedure to play an animation for animation with the auto-rewind flag set to true.
5169
5170        // Step 7. Return animation.
5171        animation
5172    }
5173}
5174
5175impl VirtualMethods for Element {
5176    fn super_type(&self) -> Option<&dyn VirtualMethods> {
5177        Some(self.upcast::<Node>() as &dyn VirtualMethods)
5178    }
5179
5180    fn attribute_affects_presentational_hints(&self, attr: AttrRef<'_>) -> bool {
5181        // FIXME: This should be more fine-grained, not all elements care about these.
5182        if attr.local_name() == &local_name!("lang") {
5183            return true;
5184        }
5185
5186        self.super_type()
5187            .unwrap()
5188            .attribute_affects_presentational_hints(attr)
5189    }
5190
5191    fn attribute_mutated(
5192        &self,
5193        cx: &mut JSContext,
5194        attr: AttrRef<'_>,
5195        mutation: AttributeMutation,
5196    ) {
5197        self.super_type()
5198            .unwrap()
5199            .attribute_mutated(cx, attr, mutation);
5200        let node = self.upcast::<Node>();
5201        match *attr.local_name() {
5202            // https://html.spec.whatwg.org/multipage/#event-handler-attributes:event-handler-content-attributes-3
5203            // Event handler content attributes are defined on `Element` rather than `HTMLElement`
5204            // so that other element types (such as SVG elements) activate them as well.
5205            ref name if name.starts_with("on") && EventTarget::is_content_event_handler(name) => {
5206                let evtarget = self.upcast::<EventTarget>();
5207                let event_name = &name[2..];
5208                match mutation {
5209                    // https://html.spec.whatwg.org/multipage/#activate-an-event-handler
5210                    AttributeMutation::Set(_) => {
5211                        let source = &**attr.value();
5212                        let source_line = 1; // TODO(#9604) get current JS execution line
5213                        evtarget.set_event_handler_uncompiled(
5214                            cx,
5215                            self.owner_window_unrooted(cx.no_gc()).get_url(),
5216                            source_line,
5217                            event_name,
5218                            source,
5219                        );
5220                    },
5221                    // https://html.spec.whatwg.org/multipage/#deactivate-an-event-handler
5222                    AttributeMutation::Removed => {
5223                        evtarget
5224                            .set_event_handler_common::<EventHandlerNonNull>(cx, event_name, None);
5225                    },
5226                }
5227            },
5228            local_name!("style") => self.update_style_attribute(cx, attr, mutation),
5229            local_name!("id") => {
5230                // https://dom.spec.whatwg.org/#ref-for-concept-element-attributes-change-ext%E2%91%A2
5231                let id = mutation.new_value(attr).and_then(|value| {
5232                    let value = value.as_atom();
5233                    if value != &atom!("") {
5234                        // Step 2. Otherwise, if localName is id, namespace is null, then set element’s ID to value.
5235                        Some(value.clone())
5236                    } else {
5237                        // Step 1. If localName is id, namespace is null, and value is null or the empty string, then unset element’s ID.
5238                        None
5239                    }
5240                });
5241                *self.id_attribute.safe_borrow_mut(cx.no_gc()) = id;
5242
5243                let containing_shadow_root = self.containing_shadow_root();
5244                if node.is_in_a_document_tree() || node.is_in_a_shadow_tree() {
5245                    let value = attr.value().as_atom().clone();
5246                    let document = node.owner_document();
5247                    match mutation {
5248                        AttributeMutation::Set(old_value) => {
5249                            if let Some(old_value) = old_value {
5250                                let old_value = old_value.as_atom();
5251                                if let Some(ref shadow_root) = containing_shadow_root {
5252                                    shadow_root.unregister_element_id(old_value);
5253                                } else {
5254                                    document.unregister_element_id(cx, old_value);
5255                                }
5256                            }
5257                            if value != atom!("") {
5258                                if let Some(ref shadow_root) = containing_shadow_root {
5259                                    shadow_root.register_element_id(self, &value);
5260                                } else {
5261                                    document.register_element_id(cx, self, &value);
5262                                }
5263                            }
5264                        },
5265                        AttributeMutation::Removed => {
5266                            if value != atom!("") {
5267                                if let Some(ref shadow_root) = containing_shadow_root {
5268                                    shadow_root.unregister_element_id(&value);
5269                                } else {
5270                                    document.unregister_element_id(cx, &value);
5271                                }
5272                            }
5273                        },
5274                    }
5275                }
5276            },
5277            local_name!("name") => {
5278                // Keep the name in rare data for fast access
5279                self.ensure_rare_data(cx.no_gc()).name_attribute =
5280                    mutation.new_value(attr).and_then(|value| {
5281                        let value = value.as_atom();
5282                        if value != &atom!("") {
5283                            Some(value.clone())
5284                        } else {
5285                            None
5286                        }
5287                    });
5288                // Keep the document name_map up to date
5289                // (if we're not in shadow DOM)
5290                if node.is_connected() && node.containing_shadow_root().is_none() {
5291                    let value = attr.value().as_atom().clone();
5292                    let document = node.owner_document_unrooted(cx.no_gc());
5293                    match mutation {
5294                        AttributeMutation::Set(old_value) => {
5295                            if let Some(old_value) = old_value {
5296                                document.unregister_element_name(old_value.as_atom());
5297                            }
5298                            if value != atom!("") {
5299                                document.register_element_name(self, &value);
5300                            }
5301                        },
5302                        AttributeMutation::Removed => {
5303                            if value != atom!("") {
5304                                document.unregister_element_name(&value);
5305                            }
5306                        },
5307                    }
5308                }
5309            },
5310            local_name!("slot") => {
5311                // Update slottable data
5312                rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(self.upcast::<Node>())));
5313
5314                // Slottable name change steps from https://dom.spec.whatwg.org/#light-tree-slotables
5315                if let Some(assigned_slot) = slottable.assigned_slot() {
5316                    assigned_slot.assign_slottables(cx);
5317                }
5318                slottable.assign_a_slot(cx);
5319            },
5320            local_name!("role") => {
5321                self.upcast::<Node>()
5322                    .add_pending_accessibility_damage(cx.no_gc(), AccessibilityDamage::Node);
5323            },
5324            _ => {
5325                // FIXME(emilio): This is pretty dubious, and should be done in
5326                // the relevant super-classes.
5327                if attr.namespace() == &ns!() && attr.local_name() == &local_name!("src") {
5328                    node.dirty(cx.no_gc(), NodeDamage::Other);
5329                }
5330            },
5331        };
5332
5333        // TODO: This should really only take into account the actual attributes that are used
5334        // for the content attribute property.
5335        if self
5336            .upcast::<Node>()
5337            .get_flag(NodeFlags::USES_ATTR_IN_CONTENT_ATTRIBUTE)
5338        {
5339            node.dirty(cx.no_gc(), NodeDamage::ContentOrHeritage);
5340        }
5341
5342        // Make sure we rev the version even if we didn't dirty the node. If we
5343        // don't do this, various attribute-dependent htmlcollections (like those
5344        // generated by getElementsByClassName) might become stale.
5345        node.rev_version(cx.no_gc());
5346
5347        // Notify devtools that the DOM changed
5348        #[cfg(feature = "devtools")]
5349        {
5350            let window = self.owner_window_unrooted(cx.no_gc());
5351            if window.live_devtools_updates() {
5352                let global = window.upcast::<GlobalScope>();
5353                if let Some(sender) = global.devtools_chan() {
5354                    let pipeline_id = global.pipeline_id();
5355                    if ScriptThread::devtools_want_updates_for_node(pipeline_id, self.upcast()) {
5356                        let devtools_message =
5357                            devtools_traits::ScriptToDevtoolsControlMsg::DomMutation(
5358                                pipeline_id,
5359                                devtools_traits::DomMutation::AttributeModified {
5360                                    node: self.upcast::<Node>().unique_id(pipeline_id),
5361                                    attribute_name: attr.local_name().to_string(),
5362                                    new_value: mutation
5363                                        .new_value(attr)
5364                                        .map(|value| value.to_string()),
5365                                },
5366                            );
5367                        sender.send(devtools_message).unwrap();
5368                    }
5369                }
5370            }
5371        }
5372    }
5373
5374    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
5375        match *name {
5376            local_name!("id") => AttrValue::Atom(value.into()),
5377            local_name!("name") => AttrValue::Atom(value.into()),
5378            local_name!("class") | local_name!("part") | local_name!("role") => {
5379                AttrValue::from_serialized_tokenlist(value.into())
5380            },
5381            local_name!("exportparts") => AttrValue::from_shadow_parts(value.into()),
5382            local_name!("tabindex") => AttrValue::from_i32(value.into(), -1),
5383            _ => self
5384                .super_type()
5385                .unwrap()
5386                .parse_plain_attribute(name, value),
5387        }
5388    }
5389
5390    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
5391        if let Some(s) = self.super_type() {
5392            s.bind_to_tree(cx, context);
5393        }
5394
5395        if let Some(f) = self.as_maybe_form_control() {
5396            f.bind_form_control_to_tree(cx);
5397        }
5398
5399        if let Some(ref shadow_root) = self.shadow_root() {
5400            shadow_root.bind_to_tree(cx, context);
5401        }
5402
5403        if !context.is_in_tree() {
5404            return;
5405        }
5406
5407        self.register_current_id_and_name_attribute(cx);
5408    }
5409
5410    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
5411        self.super_type().unwrap().unbind_from_tree(cx, context);
5412
5413        // These are the node removal steps from:
5414        // <https://html.spec.whatwg.org/multipage/#dom-trees:concept-node-remove-ext>.
5415        // In practice, they only apply to elements. Putting the steps here avoids work
5416        // that doesn't need to happen when non-Element nodes are moved from the tree.
5417        //
5418        // 1. Let document be removedNode's node document.
5419        let document = self.owner_document_unrooted(cx.no_gc());
5420
5421        // 2. If document's focused area is removedNode, then set document's focused area to
5422        // document's viewport, and set document's relevant global object's navigation API's focus
5423        // changed during ongoing navigation to false.
5424        //
5425        // We are not calling the focusing steps on purpose here. There is a note about this in
5426        // the specification that reads:
5427        //
5428        // > This does not perform the unfocusing steps, focusing steps, or focus update steps, and
5429        // > thus no blur or change events are fired.
5430        let element_had_focus_within = self.focus_within_state();
5431        if document
5432            .focus_handler()
5433            .focused_area()
5434            .element()
5435            .is_some_and(|focused_element| focused_element == self)
5436        {
5437            document
5438                .focus_handler()
5439                .set_focused_area(cx.no_gc(), FocusableArea::Viewport);
5440        }
5441
5442        // 3. If removedNode is an element whose namespace is the HTML namespace, and this standard
5443        // defines HTML element removing steps for removedNode's local name, then run the
5444        // corresponding HTML element removing steps given removedNode, isSubtreeRoot, and
5445        // oldAncestor.
5446        //
5447        // Note: These steps live in each subclass, which has already called into this code.
5448
5449        // 4. If removedNode is a form-associated element with a non-null form owner and removedNode
5450        // and its form owner are no longer in the same tree, then reset the form owner of
5451        // removedNode.
5452        if let Some(form_control) = self.as_maybe_form_control() {
5453            // TODO: The valid state of ancestors might be wrong if the form control element
5454            // has a fieldset ancestor, for instance: `<form><fieldset><input>`,
5455            // if `<input>` is unbound, `<form><fieldset>` should trigger a call to `update_validity()`.
5456            form_control.unbind_form_control_from_tree(cx);
5457        }
5458
5459        self.dirty_presentational_hints();
5460
5461        if !context.tree_is_in_a_document_tree && !context.tree_is_in_a_shadow_tree {
5462            return;
5463        }
5464
5465        self.fullscreen_removing_steps(cx);
5466
5467        self.unregister_current_id_and_name_attribute(cx);
5468
5469        if element_had_focus_within &&
5470            let Some(parent_element) = context.parent.downcast::<Element>()
5471        {
5472            parent_element.set_focus_within_state_for_inclusive_ancestors(cx.no_gc(), None, false);
5473        }
5474    }
5475
5476    fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
5477        if let Some(super_type) = self.super_type() {
5478            super_type.moving_steps(cx, context);
5479        }
5480
5481        self.maybe_reset_focus_within_state(cx.no_gc(), context.old_ancestor.downcast::<Element>());
5482        if self.focus_state() {
5483            self.set_focus_within_state_for_inclusive_ancestors(cx.no_gc(), None, true);
5484        }
5485    }
5486
5487    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
5488        if let Some(s) = self.super_type() {
5489            s.children_changed(cx, mutation);
5490        }
5491
5492        let flags = self.get_selector_flags();
5493        if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR) {
5494            // All children of this node need to be restyled when any child changes.
5495            self.upcast::<Node>().dirty(cx.no_gc(), NodeDamage::Other);
5496        } else {
5497            if flags.intersects(ElementSelectorFlags::HAS_SLOW_SELECTOR_LATER_SIBLINGS) &&
5498                let Some(next_child) = mutation.next_child()
5499            {
5500                for child in next_child.inclusively_following_siblings_unrooted(cx.no_gc()) {
5501                    if child.is::<Element>() {
5502                        child.dirty(cx.no_gc(), NodeDamage::Other);
5503                    }
5504                }
5505            }
5506            if flags.intersects(ElementSelectorFlags::HAS_EDGE_CHILD_SELECTOR) &&
5507                let Some(child) = mutation.modified_edge_element(cx.no_gc())
5508            {
5509                child.dirty(cx.no_gc(), NodeDamage::Other);
5510            }
5511        }
5512    }
5513
5514    fn adopting_steps(&self, cx: &mut JSContext, old_doc: &Document) {
5515        self.super_type().unwrap().adopting_steps(cx, old_doc);
5516    }
5517
5518    fn post_connection_steps(&self, cx: &mut JSContext) {
5519        if let Some(s) = self.super_type() {
5520            s.post_connection_steps(cx);
5521        }
5522
5523        self.update_nonce_post_connection(cx);
5524    }
5525
5526    /// <https://html.spec.whatwg.org/multipage/#nonce-attributes%3Aconcept-node-clone-ext>
5527    fn cloning_steps(
5528        &self,
5529        cx: &mut JSContext,
5530        copy: &Node,
5531        maybe_doc: Option<&Document>,
5532        clone_children: CloneChildrenFlag,
5533    ) {
5534        if let Some(s) = self.super_type() {
5535            s.cloning_steps(cx, copy, maybe_doc, clone_children);
5536        }
5537        let elem = copy.downcast::<Element>().unwrap();
5538        if let Some(rare_data) = self.rare_data().as_ref() {
5539            elem.update_nonce_internal_slot(rare_data.cryptographic_nonce.clone(), cx.no_gc());
5540        }
5541    }
5542}
5543impl Element {
5544    pub(crate) fn client_rect(&self, cx: &mut JSContext) -> Rect<i32, CSSPixel> {
5545        let doc = self.node.owner_doc();
5546
5547        if let Some(rect) = self
5548            .rare_data()
5549            .as_ref()
5550            .and_then(|data| data.client_rect.as_ref())
5551            .and_then(|rect| rect.get().ok()) &&
5552            doc.restyle_reason(cx.no_gc()).is_empty()
5553        {
5554            return rect;
5555        }
5556
5557        let mut rect = self.upcast::<Node>().client_rect(cx);
5558        let in_quirks_mode = doc.quirks_mode() == QuirksMode::Quirks;
5559
5560        if (in_quirks_mode && doc.GetBody().as_deref() == self.downcast::<HTMLElement>()) ||
5561            (!in_quirks_mode && self.is_document_element())
5562        {
5563            rect.size = doc.window().viewport_details().size.round().to_i32();
5564        }
5565
5566        self.ensure_rare_data(cx.no_gc()).client_rect = Some(
5567            self.owner_window_unrooted(cx.no_gc())
5568                .cache_layout_value(rect),
5569        );
5570        rect
5571    }
5572
5573    pub(crate) fn as_maybe_activatable(&self) -> Option<&dyn Activatable> {
5574        let element = match self.upcast::<Node>().type_id() {
5575            NodeTypeId::Element(ElementTypeId::HTMLElement(
5576                HTMLElementTypeId::HTMLInputElement,
5577            )) => {
5578                let element = self.downcast::<HTMLInputElement>().unwrap();
5579                Some(element as &dyn Activatable)
5580            },
5581            NodeTypeId::Element(ElementTypeId::HTMLElement(
5582                HTMLElementTypeId::HTMLButtonElement,
5583            )) => {
5584                let element = self.downcast::<HTMLButtonElement>().unwrap();
5585                Some(element as &dyn Activatable)
5586            },
5587            NodeTypeId::Element(ElementTypeId::HTMLElement(
5588                HTMLElementTypeId::HTMLAnchorElement,
5589            )) => {
5590                let element = self.downcast::<HTMLAnchorElement>().unwrap();
5591                Some(element as &dyn Activatable)
5592            },
5593            NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLAreaElement)) => {
5594                let element = self.downcast::<HTMLAreaElement>().unwrap();
5595                Some(element as &dyn Activatable)
5596            },
5597            NodeTypeId::Element(ElementTypeId::HTMLElement(
5598                HTMLElementTypeId::HTMLLabelElement,
5599            )) => {
5600                let element = self.downcast::<HTMLLabelElement>().unwrap();
5601                Some(element as &dyn Activatable)
5602            },
5603            NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLElement)) => {
5604                let element = self.downcast::<HTMLElement>().unwrap();
5605                Some(element as &dyn Activatable)
5606            },
5607            _ => None,
5608        };
5609        element.filter(|elem| elem.is_instance_activatable())
5610    }
5611
5612    pub(crate) fn as_stylesheet_owner(&self) -> Option<&dyn StylesheetOwner> {
5613        if let Some(s) = self.downcast::<HTMLStyleElement>() {
5614            return Some(s as &dyn StylesheetOwner);
5615        }
5616
5617        if let Some(l) = self.downcast::<HTMLLinkElement>() {
5618            return Some(l as &dyn StylesheetOwner);
5619        }
5620
5621        None
5622    }
5623
5624    /// <https://html.spec.whatwg.org/multipage/#category-submit>
5625    pub(crate) fn as_maybe_validatable(&self) -> Option<&dyn Validatable> {
5626        match self.upcast::<Node>().type_id() {
5627            NodeTypeId::Element(ElementTypeId::HTMLElement(
5628                HTMLElementTypeId::HTMLInputElement,
5629            )) => {
5630                let element = self.downcast::<HTMLInputElement>().unwrap();
5631                Some(element as &dyn Validatable)
5632            },
5633            NodeTypeId::Element(ElementTypeId::HTMLElement(
5634                HTMLElementTypeId::HTMLButtonElement,
5635            )) => {
5636                let element = self.downcast::<HTMLButtonElement>().unwrap();
5637                Some(element as &dyn Validatable)
5638            },
5639            NodeTypeId::Element(ElementTypeId::HTMLElement(
5640                HTMLElementTypeId::HTMLObjectElement,
5641            )) => {
5642                let element = self.downcast::<HTMLObjectElement>().unwrap();
5643                Some(element as &dyn Validatable)
5644            },
5645            NodeTypeId::Element(ElementTypeId::HTMLElement(
5646                HTMLElementTypeId::HTMLSelectElement,
5647            )) => {
5648                let element = self.downcast::<HTMLSelectElement>().unwrap();
5649                Some(element as &dyn Validatable)
5650            },
5651            NodeTypeId::Element(ElementTypeId::HTMLElement(
5652                HTMLElementTypeId::HTMLTextAreaElement,
5653            )) => {
5654                let element = self.downcast::<HTMLTextAreaElement>().unwrap();
5655                Some(element as &dyn Validatable)
5656            },
5657            NodeTypeId::Element(ElementTypeId::HTMLElement(
5658                HTMLElementTypeId::HTMLFieldSetElement,
5659            )) => {
5660                let element = self.downcast::<HTMLFieldSetElement>().unwrap();
5661                Some(element as &dyn Validatable)
5662            },
5663            NodeTypeId::Element(ElementTypeId::HTMLElement(
5664                HTMLElementTypeId::HTMLOutputElement,
5665            )) => {
5666                let element = self.downcast::<HTMLOutputElement>().unwrap();
5667                Some(element as &dyn Validatable)
5668            },
5669            _ => None,
5670        }
5671    }
5672
5673    pub(crate) fn is_invalid(&self, cx: &mut JSContext, needs_update: bool) -> bool {
5674        if let Some(validatable) = self.as_maybe_validatable() {
5675            if needs_update {
5676                validatable
5677                    .validity_state(cx)
5678                    .perform_validation_and_update(cx, ValidationFlags::all());
5679            }
5680            return validatable.is_instance_validatable(cx.no_gc()) &&
5681                !validatable.satisfies_constraints();
5682        }
5683
5684        if let Some(internals) = self.get_element_internals() {
5685            return internals.is_invalid(cx.no_gc());
5686        }
5687        false
5688    }
5689
5690    pub(crate) fn is_instance_validatable(&self, no_gc: &NoGC) -> bool {
5691        if let Some(validatable) = self.as_maybe_validatable() {
5692            return validatable.is_instance_validatable(no_gc);
5693        }
5694        if let Some(internals) = self.get_element_internals() {
5695            return internals.is_instance_validatable(no_gc);
5696        }
5697        false
5698    }
5699
5700    pub(crate) fn init_state_for_internals(&self, no_gc: &NoGC) {
5701        self.set_state(no_gc, ElementState::ENABLED, true);
5702        self.set_state(no_gc, ElementState::VALID, true);
5703        self.set_state(no_gc, ElementState::INVALID, false);
5704    }
5705
5706    pub(crate) fn click_in_progress(&self) -> bool {
5707        self.upcast::<Node>().get_flag(NodeFlags::CLICK_IN_PROGRESS)
5708    }
5709
5710    pub(crate) fn set_click_in_progress(&self, click: bool) {
5711        self.upcast::<Node>()
5712            .set_flag(NodeFlags::CLICK_IN_PROGRESS, click)
5713    }
5714
5715    pub fn state(&self) -> ElementState {
5716        self.state.get()
5717    }
5718
5719    pub(crate) fn set_state(&self, no_gc: &NoGC, which: ElementState, value: bool) {
5720        let mut state = self.state.get();
5721        let previous_state = state;
5722        if value {
5723            state.insert(which);
5724        } else {
5725            state.remove(which);
5726        }
5727
5728        if previous_state == state {
5729            // Nothing to do
5730            return;
5731        }
5732
5733        // Add a pending restyle for this node which captures a snapshot of the state
5734        // before the change.
5735        {
5736            let document = self.owner_document_unrooted(no_gc);
5737            let mut entry = document.ensure_pending_restyle(self);
5738            if entry.snapshot.is_none() {
5739                entry.snapshot = Some(Snapshot::new());
5740            }
5741            let snapshot = entry.snapshot.as_mut().unwrap();
5742            if snapshot.state.is_none() {
5743                snapshot.state = Some(self.state());
5744            }
5745        }
5746
5747        self.state.set(state);
5748    }
5749
5750    /// <https://html.spec.whatwg.org/multipage/#concept-selector-active>
5751    pub(crate) fn set_active_state(&self, no_gc: &NoGC, value: bool) {
5752        self.set_state(no_gc, ElementState::ACTIVE, value);
5753
5754        if let Some(parent) = self.upcast::<Node>().GetParentElement() {
5755            parent.set_active_state(no_gc, value);
5756        }
5757    }
5758
5759    pub(crate) fn focus_state(&self) -> bool {
5760        self.state.get().contains(ElementState::FOCUS)
5761    }
5762
5763    pub(crate) fn set_focus_state(&self, no_gc: &NoGC, value: bool) {
5764        self.set_state(no_gc, ElementState::FOCUS, value);
5765    }
5766
5767    pub(crate) fn set_focusring_state(&self, no_gc: &NoGC, value: bool) {
5768        self.set_state(no_gc, ElementState::FOCUSRING, value);
5769    }
5770
5771    pub(crate) fn focus_within_state(&self) -> bool {
5772        self.state.get().contains(ElementState::FOCUS_WITHIN)
5773    }
5774
5775    pub(crate) fn set_focus_within_state(&self, no_gc: &NoGC, value: bool) {
5776        self.set_state(no_gc, ElementState::FOCUS_WITHIN, value);
5777    }
5778
5779    pub(crate) fn set_hover_state(&self, no_gc: &NoGC, value: bool) {
5780        self.set_state(no_gc, ElementState::HOVER, value);
5781    }
5782
5783    pub(crate) fn read_write_state(&self) -> bool {
5784        self.state.get().contains(ElementState::READWRITE)
5785    }
5786
5787    pub(crate) fn set_read_write_state(&self, no_gc: &NoGC, value: bool) {
5788        self.set_state(no_gc, ElementState::READWRITE, value)
5789    }
5790
5791    pub(crate) fn set_open_state(&self, no_gc: &NoGC, value: bool) {
5792        self.set_state(no_gc, ElementState::OPEN, value);
5793    }
5794
5795    pub(crate) fn set_placeholder_shown_state(&self, no_gc: &NoGC, value: bool) {
5796        self.set_state(no_gc, ElementState::PLACEHOLDER_SHOWN, value);
5797    }
5798
5799    pub(crate) fn set_modal_state(&self, no_gc: &NoGC, value: bool) {
5800        self.set_state(no_gc, ElementState::MODAL, value);
5801        self.owner_document_unrooted(no_gc)
5802            .overlay_handler()
5803            .update_topmost_modal(no_gc);
5804    }
5805
5806    pub(crate) fn set_target_state(&self, no_gc: &NoGC, value: bool) {
5807        self.set_state(no_gc, ElementState::URLTARGET, value)
5808    }
5809
5810    /// <https://fullscreen.spec.whatwg.org/#removing-steps>
5811    pub(crate) fn fullscreen_removing_steps(&self, cx: &mut JSContext) {
5812        // Step 1. Let document be removedNode’s node document.
5813        let document = self.owner_document();
5814
5815        // Step 2. Let nodes be removedNode’s shadow-including inclusive descendants that have
5816        // their fullscreen flag set, in shadow-including tree order.
5817        let nodes: Vec<DomRoot<Element>> = self
5818            .upcast::<Node>()
5819            .traverse_preorder(ShadowIncluding::Yes)
5820            .filter_map(DomRoot::downcast::<Element>)
5821            .filter(|element| element.fullscreen_flag())
5822            .collect();
5823
5824        // Step 3. For each node in nodes:
5825        for node in nodes {
5826            // Step 3.1. If node is document’s fullscreen element, exit fullscreen document.
5827            if document.overlay_handler().fullscreen_element().as_deref() == Some(&*node) {
5828                let _ = document.overlay_handler().exit_fullscreen(cx);
5829            }
5830            // Step 3.2. Otherwise, unfullscreen node.
5831            else {
5832                document
5833                    .overlay_handler()
5834                    .unfullscreen_an_element(cx.no_gc(), &node);
5835            }
5836
5837            // Step 3.3. If document’s top layer contains node, remove from the top layer
5838            // immediately given node.
5839            if document.overlay_handler().top_layer_contains(&node) {
5840                document
5841                    .overlay_handler()
5842                    .remove_an_element_from_the_top_layer_immediately(&node, cx.no_gc());
5843            }
5844        }
5845    }
5846
5847    /// <https://html.spec.whatwg.org/multipage/#topmost-popover-ancestor>
5848    ///
5849    /// `self` is the spec's newPopoverOrTopLayerElement.
5850    pub(crate) fn topmost_popover_ancestor(
5851        &self,
5852        no_gc: &NoGC,
5853        source: Option<&HTMLElement>,
5854        is_popover: bool,
5855    ) -> Option<DomRoot<HTMLElement>> {
5856        // Step 1. If isPopover is true:
5857        if is_popover {
5858            // Step 1.1. Assert: newPopoverOrTopLayerElement is an HTML element.
5859            // Step 1.2. Assert: newPopoverOrTopLayerElement's popover attribute is not in the
5860            // No Popover State or the Manual state.
5861            debug_assert!(!matches!(
5862                self.downcast::<HTMLElement>()
5863                    .expect("newPopoverOrTopLayerElement is expected to be an HTML element")
5864                    .popover_state(),
5865                PopoverState::NoPopover | PopoverState::Manual
5866            ));
5867
5868            // Step 1.3. Assert: newPopoverOrTopLayerElement's popover visibility state is not in
5869            // the popover showing state.
5870            debug_assert!(!self.popover_visibility_state_showing());
5871        }
5872        // Step 2. Otherwise:
5873        else {
5874            // Step 2.1. Assert: source is null.
5875            debug_assert!(source.is_none());
5876        }
5877
5878        // Step 3. Let document be newPopoverOrTopLayerElement's node document.
5879        let document = self.owner_document();
5880        let overlay_handler = document.overlay_handler();
5881
5882        // Step 4. Let combinedPopovers be document's showing auto popover list, extended with
5883        // document's showing hint popover list.
5884        let mut combined_popovers =
5885            overlay_handler.showing_popover_list_unrooted(no_gc, PopoverState::Auto);
5886        combined_popovers
5887            .extend(overlay_handler.showing_popover_list_unrooted(no_gc, PopoverState::Hint));
5888
5889        // Step 5. Let popoverAncestorIndex be the index of the last item in combinedPopovers of
5890        // which newPopoverOrTopLayerElement is a flat tree descendant, or -1 if there is none.
5891        //
5892        // We use None instead of -1. Since None < Some(_), `max` below matches the spec's
5893        // maximum with -1.
5894        let last_flat_tree_ancestor_index = |node: &Node| {
5895            combined_popovers.iter().rposition(|popover| {
5896                node.inclusive_ancestors_in_flat_tree_unrooted(no_gc)
5897                    .any(|ancestor| **ancestor == *popover.upcast::<Node>())
5898            })
5899        };
5900        let popover_ancestor_index = last_flat_tree_ancestor_index(self.upcast());
5901
5902        // Step 6. Let sourceAncestorIndex be -1.
5903        // Step 7. If source is not null, then set sourceAncestorIndex to the index of the last
5904        // item in combinedPopovers of which source is a flat tree descendant, or -1 if there is
5905        // none.
5906        let source_ancestor_index =
5907            source.and_then(|source| last_flat_tree_ancestor_index(source.upcast()));
5908
5909        // Step 8. Let ancestorIndex be the maximum of popoverAncestorIndex and
5910        // sourceAncestorIndex.
5911        // Step 9. If ancestorIndex is -1, then return null.
5912        let ancestor_index = popover_ancestor_index.max(source_ancestor_index)?;
5913
5914        // Step 10. Return combinedPopovers[ancestorIndex].
5915        //
5916        // We discard combinedPopovers, so this is the fastest operation.
5917        Some(combined_popovers.swap_remove(ancestor_index).as_rooted())
5918    }
5919
5920    /// <https://html.spec.whatwg.org/multipage/#popover-visibility-state>
5921    pub(crate) fn popover_visibility_state_showing(&self) -> bool {
5922        self.state.get().contains(ElementState::POPOVER_OPEN)
5923    }
5924
5925    /// <https://html.spec.whatwg.org/multipage/#popover-visibility-state>
5926    pub(crate) fn set_popover_visibility_state_showing(&self, no_gc: &NoGC, value: bool) {
5927        self.set_state(no_gc, ElementState::POPOVER_OPEN, value);
5928    }
5929
5930    /// <https://fullscreen.spec.whatwg.org/#fullscreen-flag>
5931    pub(crate) fn fullscreen_flag(&self) -> bool {
5932        self.state().contains(ElementState::FULLSCREEN)
5933    }
5934
5935    /// <https://fullscreen.spec.whatwg.org/#fullscreen-flag>
5936    pub(crate) fn set_fullscreen_state(&self, no_gc: &NoGC, value: bool) {
5937        self.set_state(no_gc, ElementState::FULLSCREEN, value)
5938    }
5939
5940    /// <https://dom.spec.whatwg.org/#connected>
5941    pub(crate) fn is_connected(&self) -> bool {
5942        self.upcast::<Node>().is_connected()
5943    }
5944
5945    /// <https://html.spec.whatwg.org/multipage/#cannot-navigate>
5946    pub(crate) fn cannot_navigate(&self) -> bool {
5947        // > An element element cannot navigate if any of the following are true:
5948        // >  - element's node document is not fully active; or
5949        // >  - element is not an a element and is not connected.
5950        let document = self.owner_document();
5951        !document.is_fully_active() || (!self.is::<HTMLAnchorElement>() && !self.is_connected())
5952    }
5953
5954    pub(crate) fn get_computed_role(&self, cx: &mut JSContext) -> Option<DOMString> {
5955        let accesskit_node = self
5956            .owner_window()
5957            .accesskit_node_query(cx, self.upcast::<Node>().to_trusted_node_address())?;
5958        let aria_role = ACCESSKIT_ROLE_TO_ARIA_ROLE.get(&accesskit_node.role())?;
5959        Some(TracedDOMString::from(aria_role.clone()).root())
5960    }
5961}
5962
5963impl Element {
5964    /// Whether this [`Element`] is disabled by an [`HTMLFieldSetElement`] ancestor:
5965    ///
5966    /// 1. It is the descendant of a disabled fieldset.
5967    /// 2. It is not the descendant of of that fieldset's first [`HTMLLegendElement`] child.
5968    pub(crate) fn is_disabled_by_ancestor_fieldset(&self, no_gc: &NoGC) -> bool {
5969        let node = self.upcast::<Node>();
5970        let mut previous_ancestor = UnrootedDom::from_ref(node, no_gc);
5971        for ancestor in previous_ancestor.ancestors_unrooted(no_gc) {
5972            let child = std::mem::replace(&mut previous_ancestor, ancestor.clone());
5973            let Some(ancestor_element) = ancestor.downcast::<HTMLFieldSetElement>() else {
5974                continue;
5975            };
5976            if !ancestor_element
5977                .upcast::<Element>()
5978                .has_attribute(&local_name!("disabled"))
5979            {
5980                continue;
5981            }
5982            if !ancestor.is_parent_of(node) &&
5983                ancestor
5984                    .children_unrooted(no_gc)
5985                    .find(|node| node.is::<HTMLLegendElement>())
5986                    .is_some_and(|fieldset| fieldset == child)
5987            {
5988                continue;
5989            }
5990
5991            return true;
5992        }
5993
5994        false
5995    }
5996
5997    pub(crate) fn update_read_write_state_from_readonly_attribute(&self, no_gc: &NoGC) {
5998        let has_readonly_attribute = self.has_attribute(&local_name!("readonly"));
5999        self.set_read_write_state(no_gc, has_readonly_attribute);
6000    }
6001}
6002
6003#[derive(Clone, Copy)]
6004pub(crate) enum AttributeMutation<'a> {
6005    /// The attribute is set, keep track of old value.
6006    /// <https://dom.spec.whatwg.org/#attribute-is-set>
6007    Set(Option<&'a AttrValue>),
6008
6009    /// The attribute is removed.
6010    /// <https://dom.spec.whatwg.org/#attribute-is-removed>
6011    Removed,
6012}
6013
6014impl AttributeMutation<'_> {
6015    pub(crate) fn is_removal(&self) -> bool {
6016        match *self {
6017            AttributeMutation::Removed => true,
6018            AttributeMutation::Set(_) => false,
6019        }
6020    }
6021
6022    pub(crate) fn new_value<'b>(&self, attr: AttrRef<'b>) -> Option<AttrValueRef<'b>> {
6023        match *self {
6024            AttributeMutation::Set(_) => Some(attr.value()),
6025            AttributeMutation::Removed => None,
6026        }
6027    }
6028
6029    pub(crate) fn old_value(&self, attr: AttrRef<'_>) -> Option<String> {
6030        match *self {
6031            AttributeMutation::Set(old) => old.map(|value| value.to_string()),
6032            AttributeMutation::Removed => Some(attr.value().to_string()),
6033        }
6034    }
6035}
6036
6037/// The inputs that fully determine an element's HTML-uppercased qualified name.
6038///
6039/// See [`TAG_NAME_CACHE`].
6040#[derive(Eq, Hash, PartialEq)]
6041struct TagNameKey {
6042    prefix: Option<Prefix>,
6043    local_name: LocalName,
6044    html_element_in_html_document: bool,
6045}
6046
6047/// The maximum number of names in [`TAG_NAME_CACHE`].
6048const TAG_NAME_CACHE_CAPACITY: usize = 128;
6049
6050thread_local! {
6051    /// Memoized HTML-uppercased qualified names, shared by every element on the
6052    /// thread. When it's full, the least recently used name is evicted.
6053    ///
6054    /// An element's `tagName` is a pure function of its prefix, its local name,
6055    /// and whether it is an HTML element in an HTML document, so there is no
6056    /// reason to cache it per element.
6057    static TAG_NAME_CACHE: RefCell<LruCache<TagNameKey, LocalName, FxBuildHasher>> =
6058        RefCell::new(LruCache::with_hasher(TAG_NAME_CACHE_CAPACITY, FxBuildHasher));
6059}
6060
6061/// <https://html.spec.whatwg.org/multipage/#cors-settings-attribute>
6062pub(crate) fn reflect_cross_origin_attribute(element: &Element) -> Option<DOMString> {
6063    element
6064        .get_attribute_string_ref(&local_name!("crossorigin"))
6065        .map(|value| {
6066            DOMString::from_static(
6067                ["anonymous", "use-credentials"]
6068                    .into_iter()
6069                    .find(|keyword| value.eq_ignore_ascii_case(keyword))
6070                    .unwrap_or("anonymous"),
6071            )
6072        })
6073}
6074
6075pub(crate) fn set_cross_origin_attribute(
6076    cx: &mut JSContext,
6077    element: &Element,
6078    value: Option<DOMString>,
6079) {
6080    match value {
6081        Some(val) => element.set_string_attribute(cx, &local_name!("crossorigin"), val),
6082        None => {
6083            element.remove_attribute(cx, &ns!(), &local_name!("crossorigin"));
6084        },
6085    }
6086}
6087
6088/// <https://html.spec.whatwg.org/multipage/#referrer-policy-attribute>
6089pub(crate) fn reflect_referrer_policy_attribute(element: &Element) -> DOMString {
6090    element
6091        .get_attribute_string_ref(&local_name!("referrerpolicy"))
6092        .map(|value| {
6093            DOMString::from(
6094                [
6095                    "no-referrer",
6096                    "no-referrer-when-downgrade",
6097                    "same-origin",
6098                    "origin",
6099                    "strict-origin",
6100                    "origin-when-cross-origin",
6101                    "strict-origin-when-cross-origin",
6102                    "unsafe-url",
6103                ]
6104                .into_iter()
6105                .find(|keyword| value.eq_ignore_ascii_case(keyword))
6106                .unwrap_or(""),
6107            )
6108        })
6109        .unwrap_or_default()
6110}
6111
6112pub(crate) fn referrer_policy_for_element(element: &Element) -> ReferrerPolicy {
6113    element
6114        .get_attribute_string_ref(&local_name!("referrerpolicy"))
6115        .map(|value| {
6116            let value = value.as_attr_ref().value();
6117            ReferrerPolicy::from(value.as_ref())
6118        })
6119        .unwrap_or(element.owner_document().get_referrer_policy())
6120}
6121
6122pub(crate) fn cors_setting_for_element(element: &Element) -> Option<CorsSettings> {
6123    element
6124        .get_attribute_string_ref(&local_name!("crossorigin"))
6125        .map(|value| {
6126            let value = value.as_attr_ref().value();
6127            CorsSettings::from_enumerated_attribute(&value)
6128        })
6129}
6130
6131/// <https://html.spec.whatwg.org/multipage/#cors-settings-attribute-credentials-mode>
6132pub(crate) fn cors_settings_attribute_credential_mode(element: &Element) -> CredentialsMode {
6133    element
6134        .get_attribute_string_ref(&local_name!("crossorigin"))
6135        .map(|value| {
6136            if value.eq_ignore_ascii_case("use-credentials") {
6137                CredentialsMode::Include
6138            } else {
6139                // The attribute's invalid value default and empty value default are both the Anonymous state.
6140                CredentialsMode::CredentialsSameOrigin
6141            }
6142        })
6143        // The attribute's missing value default is the No CORS state, which defaults to "same-origin"
6144        .unwrap_or(CredentialsMode::CredentialsSameOrigin)
6145}
6146
6147pub(crate) fn is_element_affected_by_legacy_background_presentational_hint(
6148    namespace: &Namespace,
6149    local_name: &LocalName,
6150) -> bool {
6151    *namespace == ns!(html) &&
6152        matches!(
6153            *local_name,
6154            local_name!("body") |
6155                local_name!("table") |
6156                local_name!("thead") |
6157                local_name!("tbody") |
6158                local_name!("tfoot") |
6159                local_name!("tr") |
6160                local_name!("td") |
6161                local_name!("th")
6162        )
6163}
6164
6165impl script_bindings::callback::OwnerWindow<crate::DomTypeHolder> for Element {
6166    fn owner_window(&self) -> Option<DomRoot<Window>> {
6167        Some(NodeTraits::owner_window(self))
6168    }
6169}