1#![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#[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 selector_flags: AtomicUsize,
232 rare_data: DomRefCell<Option<Box<ElementRareData>>>,
233
234 #[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
297impl 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 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 pub(crate) fn get_is(&self) -> Option<LocalName> {
437 self.rare_data().as_ref()?.is_value.clone()
438 }
439
440 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 pub(crate) fn set_custom_element_state(&self, state: CustomElementState, no_gc: &NoGC) {
456 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 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 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 pub(crate) fn has_css_layout_box(&self) -> bool {
557 self.upcast::<Node>().is_being_rendered(None)
561 }
562
563 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 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 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 if !self.has_css_layout_box_deprecated(cx) {
592 return false;
593 }
594
595 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 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 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 pub(crate) fn establishes_scroll_container(&self, cx: &mut JSContext) -> bool {
634 self.upcast::<Node>()
636 .effective_overflow(cx)
637 .is_some_and(|overflow| overflow.establishes_scroll_container())
638 }
639
640 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 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 #[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 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 if !is_valid_shadow_host_name(self.local_name()) {
710 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 if is_valid_custom_element_name(self.local_name()) || self.get_is().is_some() {
723 let definition = self.get_custom_element_definition();
727 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 if let Some(current_shadow_root) = self.shadow_root() {
741 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 for child in current_shadow_root.upcast::<Node>().children() {
754 child.remove_self(cx);
755 }
756
757 current_shadow_root.set_declarative(false);
759
760 return Ok(current_shadow_root);
762 }
763
764 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 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 shadow_root.set_delegates_focus(delegates_focus);
796
797 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 shadow_root.set_declarative(false);
808
809 shadow_root.set_serializable(serializable);
811
812 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 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 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 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| ®istrations[index]))
898 } else {
899 None
900 }
901 }
902
903 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 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 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 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 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 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 if position != scrolling_box.scroll_position(cx) {
978 scrolling_box.scroll_to(cx, position, behavior);
989 }
990
991 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 pub(crate) fn handle_scroll_event(&self) {
1046 let document = self.owner_document();
1048
1049 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 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 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 pub(crate) fn fullscreen_element_ready_check(&self) -> bool {
1133 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#[inline]
1148pub(crate) fn is_valid_shadow_host_name(name: &LocalName) -> bool {
1149 if is_valid_custom_element_name(name) {
1152 return true;
1153 }
1154
1155 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 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 #[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 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 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 this.get_color()
1390 } else if let Some(this) = self.downcast::<HTMLHRElement>() {
1391 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 let size = self
1431 .downcast::<HTMLInputElement>()
1432 .and_then(|input_element| {
1433 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 _ => 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 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 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 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 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 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 self.downcast::<HTMLTableColElement>()
1693 .and_then(|element| element.get_span())
1694 }
1695
1696 pub(crate) fn get_colspan(self) -> Option<u32> {
1697 self.downcast::<HTMLTableCellElement>()
1699 .and_then(|element| element.get_colspan())
1700 }
1701
1702 pub(crate) fn get_rowspan(self) -> Option<u32> {
1703 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 #[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 pub(crate) fn get_lang_attr_val_for_layout(self) -> Option<&'dom str> {
1748 if let Some(attr) = self.get_attr_val_for_layout(&ns!(xml), &local_name!("lang")) {
1751 return Some(attr);
1752 }
1753 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 pub(crate) fn get_lang_for_layout(self) -> AtomString {
1764 let mut current_node = Some(self.upcast::<Node>());
1767 while let Some(node) = current_node {
1768 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 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 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 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 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 if namespace_prefix == Some(namespace_prefix!("xml")) {
1955 return ns!(xml);
1956 }
1957
1958 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 for element in inclusive_ancestor_elements {
1973 if element.namespace() != &ns!() &&
1975 element.prefix().as_ref().map(|p| &**p) == prefix.as_deref()
1976 {
1977 return element.namespace().clone();
1978 }
1979
1980 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 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 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 if *element.namespace() == namespace &&
2087 let Some(prefix) = element.GetPrefix()
2088 {
2089 return Some(prefix);
2090 }
2091
2092 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 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 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 pub(crate) fn is_actually_disabled(&self) -> bool {
2124 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 self.set_state(cx.no_gc(), ElementState::DISABLED, actually_disabled);
2142
2143 self.set_state(cx.no_gc(), ElementState::ENABLED, !actually_disabled);
2148
2149 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 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 fn compute_is_actually_disabled(&self, cx: &mut JSContext) -> bool {
2203 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 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 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 if let Some(fieldset) = self.downcast::<HTMLFieldSetElement>() {
2241 return fieldset.is_fieldset_disabled(cx.no_gc());
2242 }
2243
2244 false
2245 }
2246
2247 fn enabled_state_applies(&self) -> bool {
2249 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 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 self.attrs.push_raw(ContentAttributeData {
2288 identifier: data.identifier.clone(),
2289 value: data.value.clone(),
2290 });
2291 self.handle_attribute_changes(cx, attr_ref, None, Some(&*attr_ref.value()));
2293 }
2294
2295 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 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 let has_new_value = new_value.is_some();
2316
2317 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 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 pub(crate) fn change_attribute(&self, cx: &mut JSContext, attr: &Attr, mut value: AttrValue) {
2342 let old_value = &attr.value().clone();
2346 self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2348 attr.swap_value(&mut value);
2349 let new_value = attr.value().clone();
2353 self.handle_attribute_changes(cx, AttrRef::Dom(attr), Some(old_value), Some(&new_value));
2354 }
2355
2356 pub(crate) fn push_attribute(&self, cx: &mut JSContext, attr: &Attr) {
2358 assert!(attr.GetOwnerElement().as_deref() == Some(self));
2362 assert!(attr.upcast::<Node>().owner_doc() == self.node.owner_doc());
2366 self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2368 self.attrs.push_dom(attr);
2369 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 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 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 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 #[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 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 self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(&attr));
2530 self.change_attribute(cx, &attr, value);
2531 } else {
2532 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 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 self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(&attr));
2587 self.attrs.remove(idx);
2588 attr.set_owner(cx, None);
2590 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 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 *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 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 fn set_attribute_node(
2678 &self,
2679 cx: &mut JSContext,
2680 attr: &Attr,
2681 ) -> Fallible<Option<DomRoot<Attr>>> {
2682 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 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 attr.swap_value(
2713 &mut vtable.parse_plain_attribute(attr.local_name(), verified_value.clone()),
2714 );
2715
2716 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 if &*old_attr == attr {
2726 return Ok(Some(DomRoot::from_ref(attr)));
2727 }
2728
2729 self.will_mutate_attr(cx.no_gc(), AttrRef::Dom(attr));
2739 self.attrs
2740 .set(position, AttributeEntry::Dom(Dom::from_ref(attr)));
2741 attr.set_owner(cx, Some(self));
2743 attr.upcast::<Node>().set_owner_doc(&self.node.owner_doc());
2745 old_attr.set_owner(cx, None);
2747 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 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 Ok(old_attr)
2767 }
2768
2769 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 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 pub(crate) fn update_nonce_post_connection(&self, cx: &mut JSContext) {
2784 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 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 let nonce = self.nonce_value();
2807 self.set_string_attribute(cx, &local_name!("nonce"), DOMString::new());
2809 self.update_nonce_internal_slot(nonce, cx.no_gc());
2811 }
2812
2813 pub(crate) fn is_nonceable(&self) -> bool {
2815 if !self.has_attribute(&local_name!("nonce")) {
2817 return false;
2818 }
2819 if self.is::<HTMLScriptElement>() {
2821 for attr in self.attrs().borrow().iter() {
2822 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 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 if self
2848 .rare_data()
2849 .as_ref()
2850 .is_some_and(|d| d.had_duplicate_attributes)
2851 {
2852 return false;
2853 }
2854 true
2856 }
2857
2858 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 pub(crate) fn scroll(&self, cx: &mut JSContext, x: f64, y: f64, behavior: ScrollBehavior) {
2892 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 let document = node.owner_doc();
2903
2904 if !document.is_fully_active() {
2908 return;
2909 }
2910
2911 let Some(window) = document.GetDefaultView() else {
2913 return;
2917 };
2918
2919 if *self.root_element() == *self {
2924 if document.quirks_mode() == QuirksMode::Quirks {
2925 return;
2926 }
2927
2928 window.scroll(cx, x, y, behavior);
2933 return;
2934 }
2935
2936 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 if !self.has_scrolling_box(cx) {
2957 return;
2958 }
2959
2960 window.scroll_an_element(cx, self, x, y, behavior);
2965
2966 }
2969
2970 pub(crate) fn parse_fragment(
2972 &self,
2973 markup: DOMString,
2974 cx: &mut JSContext,
2975 ) -> Fallible<DomRoot<DocumentFragment>> {
2976 let new_children = ServoParser::parse_html_fragment(cx, self, markup, false);
2979 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 for child in new_children {
2991 fragment.upcast::<Node>().AppendChild(cx, &child).unwrap();
2992 }
2993 Ok(fragment)
2995 }
2996
2997 pub(crate) fn fragment_parsing_context(
3000 cx: &mut JSContext,
3001 owner_doc: &Document,
3002 element: Option<&Self>,
3003 ) -> DomRoot<Self> {
3004 match element {
3006 Some(elem)
3007 if elem.local_name() != &local_name!("html") ||
3011 !elem.html_element_in_html_document() =>
3012 {
3013 DomRoot::from_ref(elem)
3014 },
3015 _ => 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 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 pub(crate) fn tab_index(&self) -> i32 {
3079 if let Some(tab_index) = self.explicitly_set_tab_index() {
3085 return tab_index;
3086 }
3087
3088 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 pub(crate) fn needs_preserved_style_attribute_after_change(&self) -> bool {
3135 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 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 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 fn GetNamespaceURI(&self) -> Option<DOMString> {
3200 Node::namespace_to_string(self.namespace.clone())
3201 }
3202
3203 fn LocalName(&self) -> DOMString {
3205 DOMString::from(&*self.local_name)
3207 }
3208
3209 fn GetPrefix(&self) -> Option<DOMString> {
3211 self.prefix
3212 .borrow()
3213 .as_ref()
3214 .map(|p| TracedDOMString::from(p.clone()).root())
3215 }
3216
3217 fn TagName(&self) -> DOMString {
3219 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 if let Some(name) = cache.borrow_mut().get(&key).cloned() {
3230 return name;
3231 }
3232 let qualified_name = self.qualified_name();
3234 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 fn Id(&self) -> DOMString {
3252 self.get_string_attribute(&local_name!("id"))
3253 }
3254
3255 fn SetId(&self, cx: &mut JSContext, id: DOMString) {
3257 self.set_atomic_attribute(cx, &local_name!("id"), id);
3258 }
3259
3260 fn ClassName(&self) -> DOMString {
3262 self.get_string_attribute(&local_name!("class"))
3263 }
3264
3265 fn SetClassName(&self, cx: &mut JSContext, class: DOMString) {
3267 self.set_tokenlist_attribute(cx, &local_name!("class"), class);
3268 }
3269
3270 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 make_getter!(Slot, "slot");
3278
3279 make_setter!(SetSlot, "slot");
3281
3282 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 fn HasAttributes(&self) -> bool {
3290 !self.attrs.borrow().is_empty()
3291 }
3292
3293 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 fn GetAttribute(&self, cx: &mut JSContext, name: DOMString) -> Option<DOMString> {
3304 self.GetAttributeNode(cx, name).map(|s| s.Value())
3305 }
3306
3307 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 fn GetAttributeNode(&self, cx: &mut JSContext, name: DOMString) -> Option<DomRoot<Attr>> {
3320 self.get_attribute_by_name(cx, name)
3321 }
3322
3323 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 fn ToggleAttribute(
3336 &self,
3337 cx: &mut JSContext,
3338 name: DOMString,
3339 force: Option<bool>,
3340 ) -> Fallible<bool> {
3341 if !is_valid_attribute_local_name(&name.str()) {
3344 return Err(Error::InvalidCharacter(Some(
3345 "Invalid attribute name".into(),
3346 )));
3347 }
3348
3349 let attribute = self.GetAttribute(cx, name.clone());
3351
3352 let name = self.parsed_name(name);
3354 match attribute {
3355 None => match force {
3357 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 Some(false) => Ok(false),
3372 },
3373 Some(_index) => match force {
3374 None | Some(false) => {
3376 self.remove_attribute_by_name(cx, &name);
3377 Ok(false)
3378 },
3379 Some(true) => Ok(true),
3381 },
3382 }
3383 }
3384
3385 fn SetAttribute(
3387 &self,
3388 cx: &mut JSContext,
3389 name: DOMString,
3390 value: TrustedTypeOrString,
3391 ) -> ErrorResult {
3392 if !is_valid_attribute_local_name(&name.str()) {
3395 return Err(Error::InvalidCharacter(Some(
3396 "Invalid attribute name".into(),
3397 )));
3398 }
3399
3400 let name = self.parsed_name(name);
3403
3404 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 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 fn SetAttributeNS(
3436 &self,
3437 cx: &mut JSContext,
3438 namespace: Option<DOMString>,
3439 qualified_name: DOMString,
3440 value: TrustedTypeOrString,
3441 ) -> ErrorResult {
3442 let (namespace, prefix, local_name) =
3444 domname::validate_and_extract(namespace, &qualified_name, domname::Context::Element)?;
3445 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 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 fn SetAttributeNode(&self, cx: &mut JSContext, attr: &Attr) -> Fallible<Option<DomRoot<Attr>>> {
3471 self.set_attribute_node(cx, attr)
3472 }
3473
3474 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 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 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 fn RemoveAttributeNode(&self, cx: &mut JSContext, attr: &Attr) -> Fallible<DomRoot<Attr>> {
3503 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 fn HasAttribute(&self, cx: &mut JSContext, name: DOMString) -> bool {
3513 self.GetAttribute(cx, name).is_some()
3514 }
3515
3516 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 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 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 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 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 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 fn Scroll(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3594 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 fn Scroll_(&self, cx: &mut JSContext, x: f64, y: f64) {
3602 self.scroll(cx, x, y, ScrollBehavior::Auto);
3603 }
3604
3605 fn ScrollTo(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3607 self.Scroll(cx, options);
3608 }
3609
3610 fn ScrollTo_(&self, cx: &mut JSContext, x: f64, y: f64) {
3612 self.Scroll_(cx, x, y);
3613 }
3614
3615 fn ScrollBy(&self, cx: &mut JSContext, options: &ScrollToOptions) {
3617 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 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 fn ScrollTop(&self, cx: &mut JSContext) -> f64 {
3639 let node = self.upcast::<Node>();
3640
3641 let document = node.owner_doc();
3643
3644 if !document.is_fully_active() {
3647 return 0.0;
3648 }
3649
3650 let Some(window) = document.GetDefaultView() else {
3652 return 0.0;
3654 };
3655
3656 if self.is_document_element() {
3657 if document.quirks_mode() == QuirksMode::Quirks {
3660 return 0.0;
3661 }
3662
3663 return window.ScrollY(cx) as f64;
3666 }
3667
3668 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 if !self.has_css_layout_box_deprecated(cx) {
3681 return 0.0;
3682 }
3683
3684 let point = window.scroll_offset_query(cx, node);
3687 point.y as f64
3688 }
3689
3690 fn SetScrollTop(&self, cx: &mut JSContext, y_: f64) {
3692 let behavior = ScrollBehavior::Auto;
3693
3694 let y = if y_.is_finite() { y_ } else { 0.0 } as f32;
3697
3698 let node = self.upcast::<Node>();
3699
3700 let document = node.owner_doc();
3702
3703 if !document.is_fully_active() {
3705 return;
3706 }
3707
3708 let Some(window) = document.GetDefaultView() else {
3710 return;
3712 };
3713
3714 if self.is_document_element() {
3715 if document.quirks_mode() == QuirksMode::Quirks {
3718 return;
3719 }
3720
3721 let window_scroll_x = window.ScrollX(cx) as f32;
3725 window.scroll(cx, window_scroll_x, y, behavior);
3726 return;
3727 }
3728
3729 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 if !self.has_scrolling_box(cx) {
3746 return;
3747 }
3748
3749 let element_scroll_left = self.ScrollLeft(cx) as f32;
3752 window.scroll_an_element(cx, self, element_scroll_left, y, behavior);
3753 }
3754
3755 fn ScrollLeft(&self, cx: &mut JSContext) -> f64 {
3757 let node = self.upcast::<Node>();
3758
3759 let document = node.owner_doc();
3761
3762 if !document.is_fully_active() {
3765 return 0.0;
3766 }
3767
3768 let Some(window) = document.GetDefaultView() else {
3771 return 0.0;
3772 };
3773
3774 if self.is_document_element() {
3775 if document.quirks_mode() == QuirksMode::Quirks {
3778 return 0.0;
3779 }
3780
3781 return window.ScrollX(cx) as f64;
3783 }
3784
3785 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 if !self.has_css_layout_box_deprecated(cx) {
3798 return 0.0;
3799 }
3800
3801 let point = window.scroll_offset_query(cx, node);
3804 point.x as f64
3805 }
3806
3807 fn SetScrollLeft(&self, cx: &mut JSContext, x: f64) {
3809 let behavior = ScrollBehavior::Auto;
3810
3811 let x = if x.is_finite() { x } else { 0.0 } as f32;
3814
3815 let node = self.upcast::<Node>();
3817 let document = node.owner_doc();
3818
3819 if !document.is_fully_active() {
3821 return;
3822 }
3823
3824 let Some(window) = document.GetDefaultView() else {
3826 return;
3828 };
3829
3830 if self.is_document_element() {
3831 if document.quirks_mode() == QuirksMode::Quirks {
3834 return;
3835 }
3836
3837 let window_scroll_y = window.ScrollY(cx) as f32;
3841 window.scroll(cx, x, window_scroll_y, behavior);
3842 return;
3843 }
3844
3845 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 if !self.has_scrolling_box(cx) {
3862 return;
3863 }
3864
3865 let element_scroll_top = self.ScrollTop(cx) as f32;
3868 window.scroll_an_element(cx, self, x, element_scroll_top, behavior);
3869 }
3870
3871 fn ScrollIntoView(&self, cx: &mut JSContext, arg: BooleanOrScrollIntoViewOptions) {
3873 let (behavior, block, inline, container) = match arg {
3874 BooleanOrScrollIntoViewOptions::Boolean(true) => (
3876 ScrollBehavior::Auto, ScrollLogicalPosition::Start, ScrollLogicalPosition::Nearest, None, ),
3881 BooleanOrScrollIntoViewOptions::ScrollIntoViewOptions(options) => (
3884 options.parent.behavior,
3885 options.block,
3886 options.inline,
3887 if options.container == ScrollIntoViewContainer::Nearest {
3890 Some(self)
3891 } else {
3892 None
3893 },
3894 ),
3895 BooleanOrScrollIntoViewOptions::Boolean(false) => (
3897 ScrollBehavior::Auto,
3898 ScrollLogicalPosition::End,
3899 ScrollLogicalPosition::Nearest,
3900 None,
3901 ),
3902 };
3903
3904 if !self.has_css_layout_box_deprecated(cx) {
3907 return;
3908 }
3909
3910 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 }
3923
3924 fn ScrollWidth(&self, cx: &mut JSContext) -> i32 {
3926 self.upcast::<Node>().scroll_area(cx).size.width
3927 }
3928
3929 fn ScrollHeight(&self, cx: &mut JSContext) -> i32 {
3931 self.upcast::<Node>().scroll_area(cx).size.height
3932 }
3933
3934 fn ClientTop(&self, cx: &mut JSContext) -> i32 {
3936 self.client_rect(cx).origin.y
3937 }
3938
3939 fn ClientLeft(&self, cx: &mut JSContext) -> i32 {
3941 self.client_rect(cx).origin.x
3942 }
3943
3944 fn ClientWidth(&self, cx: &mut JSContext) -> i32 {
3946 self.client_rect(cx).size.width
3947 }
3948
3949 fn ClientHeight(&self, cx: &mut JSContext) -> i32 {
3951 self.client_rect(cx).size.height
3952 }
3953
3954 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 fn SetHTMLUnsafe(
3962 &self,
3963 cx: &mut JSContext,
3964 html: TrustedHTMLOrString,
3965 options: &SetHTMLUnsafeOptions,
3966 ) -> ErrorResult {
3967 let compliant_html = TrustedHTML::get_trusted_type_compliant_string(
3971 cx,
3972 &self.owner_global(),
3973 html,
3974 "Element setHTMLUnsafe",
3975 )?;
3976 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 Sanitizer::set_and_filter_html(cx, &target, self, compliant_html, options, false)?;
3985
3986 Ok(())
3987 }
3988
3989 fn SetHTML(
3991 &self,
3992 cx: &mut JSContext,
3993 html: DOMString,
3994 options: &SetHTMLOptions,
3995 ) -> ErrorResult {
3996 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 Sanitizer::set_and_filter_html(cx, &target, self, html, options, true)
4005 }
4006
4007 fn GetHTML(&self, cx: &mut JSContext, options: &GetHTMLOptions) -> DOMString {
4009 let shadow_roots = options.shadowRoots.iter().map(Dom::as_rooted).collect();
4010 self.upcast::<Node>().html_serialize(
4013 cx,
4014 TraversalScope::ChildrenOnly(None),
4015 options.serializableShadowRoots,
4016 shadow_roots,
4017 )
4018 }
4019
4020 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 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 fn SetInnerHTML(
4043 &self,
4044 cx: &mut JSContext,
4045 value: TrustedHTMLOrNullIsEmptyString,
4046 ) -> ErrorResult {
4047 let value = TrustedHTML::get_trusted_type_compliant_string(
4051 cx,
4052 &self.owner_global(),
4053 value.convert(),
4054 "Element innerHTML",
4055 )?;
4056 let target = if let Some(template) = self.downcast::<HTMLTemplateElement>() {
4058 DomRoot::upcast(template.Content(cx))
4061 } else {
4062 DomRoot::from_ref(self.upcast())
4064 };
4065
4066 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 let frag = self.parse_fragment(value, cx)?;
4081
4082 Node::replace_all(cx, Some(frag.upcast()), &target);
4084 Ok(())
4085 }
4086
4087 fn GetOuterHTML(&self, cx: &mut JSContext) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
4089 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 fn SetOuterHTML(
4103 &self,
4104 cx: &mut JSContext,
4105 value: TrustedHTMLOrNullIsEmptyString,
4106 ) -> ErrorResult {
4107 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 let context_parent = match context_node.GetParentNode() {
4120 None => {
4121 return Ok(());
4124 },
4125 Some(parent) => parent,
4126 };
4127
4128 let parent = match context_parent.type_id() {
4129 NodeTypeId::Document(_) => {
4131 return Err(Error::NoModificationAllowed(Some(
4132 "Parent is a Document".into(),
4133 )));
4134 },
4135
4136 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 let frag = parent.parse_fragment(value, cx)?;
4156 context_parent.ReplaceChild(cx, frag.upcast(), context_node)?;
4158 Ok(())
4159 }
4160
4161 fn GetPreviousElementSibling(&self) -> Option<DomRoot<Element>> {
4163 self.upcast::<Node>()
4164 .preceding_siblings()
4165 .find_map(DomRoot::downcast)
4166 }
4167
4168 fn GetNextElementSibling(&self) -> Option<DomRoot<Element>> {
4170 self.upcast::<Node>()
4171 .following_siblings()
4172 .find_map(DomRoot::downcast)
4173 }
4174
4175 fn Children(&self, cx: &mut JSContext) -> DomRoot<HTMLCollection> {
4177 let window = self.owner_window();
4178 HTMLCollection::children(cx, &window, self.upcast())
4179 }
4180
4181 fn GetFirstElementChild(&self) -> Option<DomRoot<Element>> {
4183 self.upcast::<Node>().child_elements().next()
4184 }
4185
4186 fn GetLastElementChild(&self) -> Option<DomRoot<Element>> {
4188 self.upcast::<Node>()
4189 .rev_children()
4190 .find_map(DomRoot::downcast::<Element>)
4191 }
4192
4193 fn ChildElementCount(&self) -> u32 {
4195 self.upcast::<Node>().child_elements().count() as u32
4196 }
4197
4198 fn Prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4200 self.upcast::<Node>().prepend(cx, nodes)
4201 }
4202
4203 fn Append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4205 self.upcast::<Node>().append(cx, nodes)
4206 }
4207
4208 fn ReplaceChildren(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4210 self.upcast::<Node>().replace_children(cx, nodes)
4211 }
4212
4213 fn MoveBefore(&self, cx: &mut JSContext, node: &Node, child: Option<&Node>) -> ErrorResult {
4215 self.upcast::<Node>().move_before(cx, node, child)
4216 }
4217
4218 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 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 fn Before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4240 self.upcast::<Node>().before(cx, nodes)
4241 }
4242
4243 fn After(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4245 self.upcast::<Node>().after(cx, nodes)
4246 }
4247
4248 fn ReplaceWith(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
4250 self.upcast::<Node>().replace_with(cx, nodes)
4251 }
4252
4253 fn Remove(&self, cx: &mut JSContext) {
4255 self.upcast::<Node>().remove_self(cx);
4256 }
4257
4258 #[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 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 fn WebkitMatchesSelector(&self, selectors: DOMString) -> Fallible<bool> {
4291 self.Matches(selectors)
4292 }
4293
4294 #[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 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 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 fn InsertAdjacentText(
4336 &self,
4337 cx: &mut JSContext,
4338 where_: DOMString,
4339 data: DOMString,
4340 ) -> ErrorResult {
4341 let text = Text::new(cx, data, &self.owner_document());
4343
4344 let where_ = where_.parse::<AdjacentPosition>()?;
4346 self.insert_adjacent(cx, where_, text.upcast()).map(|_| ())
4347 }
4348
4349 fn InsertAdjacentHTML(
4351 &self,
4352 cx: &mut JSContext,
4353 position: DOMString,
4354 text: TrustedHTMLOrString,
4355 ) -> ErrorResult {
4356 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 let context = match position {
4370 AdjacentPosition::BeforeBegin | AdjacentPosition::AfterEnd => {
4373 match self.upcast::<Node>().GetParentNode() {
4374 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 Some(node) => node,
4387 }
4388 },
4389 AdjacentPosition::AfterBegin | AdjacentPosition::BeforeEnd => {
4392 DomRoot::from_ref(self.upcast::<Node>())
4394 },
4395 };
4396
4397 let context = Element::fragment_parsing_context(
4399 cx,
4400 &context.owner_doc(),
4401 context.downcast::<Element>(),
4402 );
4403
4404 let fragment = context.parse_fragment(text, cx)?;
4407
4408 self.insert_adjacent(cx, position, fragment.upcast())
4410 .map(|_| ())
4411 }
4412
4413 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 fn RequestFullscreen(
4440 &self,
4441 cx: &mut CurrentRealm,
4442 _options: &FullscreenOptions,
4443 ) -> RootedPromise {
4444 let pending_doc = self.owner_document();
4446
4447 let promise = Promise::new_in_realm(cx);
4449
4450 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 let mut error = false;
4459
4460 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 if !error {
4484 pending_doc.window().consume_user_activation();
4485 }
4486
4487 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 if !error {
4506 pending_doc.send_to_embedder(EmbedderMsg::NotifyFullscreenStateChanged(
4507 pending_doc.webview_id(),
4508 true,
4509 ));
4510 }
4511
4512 if this.owner_document() != pending_doc || !this.fullscreen_element_ready_check() {
4516 error = true;
4517 }
4518
4519 if error {
4521 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 promise.reject_error(cx, Error::Type(c"Fullscreen request failed".to_owned()));
4534 return;
4535 }
4536
4537 let mut fullscreen_elements = vec![this.clone()];
4539
4540 loop {
4542 let last = fullscreen_elements
4544 .last()
4545 .expect("fullscreenElements has an initial element");
4546
4547 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 fullscreen_elements.push(container);
4562 }
4563
4564 for element in fullscreen_elements {
4566 let doc = element.owner_document();
4568
4569 if doc.overlay_handler().fullscreen_element().as_ref() == Some(&element) {
4571 continue;
4572 }
4573
4574 if element == this &&
4577 let Some(iframe) = element.downcast::<HTMLIFrameElement>()
4578 {
4579 iframe.set_iframe_fullscreen_flag(true);
4580 }
4581
4582 doc.overlay_handler().fullscreen_an_element(cx, &element);
4584
4585 doc.overlay_handler()
4588 .append_to_list_of_pending_fullscreen_events(
4589 cx.no_gc(),
4590 atom!("fullscreenchange"),
4591 &element,
4592 );
4593 }
4594
4595 promise.resolve_native(cx, &());
4603 }));
4604
4605 promise
4606 }
4607
4608 event_handler!(
4610 fullscreenchange,
4611 GetOnfullscreenchange,
4612 SetOnfullscreenchange
4613 );
4614
4615 event_handler!(fullscreenerror, GetOnfullscreenerror, SetOnfullscreenerror);
4617
4618 fn SetPointerCapture(&self, pointer_id: i32) -> ErrorResult {
4620 let document = self.owner_document();
4621 let event_handler = document.event_handler();
4622
4623 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 if !event_handler.is_active_pointer(pointer_id) {
4649 return Ok(());
4650 }
4651
4652 event_handler.set_pending_pointer_capture(pointer_id, self);
4655
4656 Ok(())
4657 }
4658
4659 fn ReleasePointerCapture(&self, pointer_id: i32) -> ErrorResult {
4661 let document = self.owner_document();
4662 let event_handler = document.event_handler();
4663
4664 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 if !event_handler.has_pointer_capture(pointer_id, self) {
4676 return Ok(());
4677 }
4678
4679 event_handler.clear_pending_pointer_capture(pointer_id);
4681
4682 Ok(())
4683 }
4684
4685 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 fn AttachShadow(
4694 &self,
4695 cx: &mut JSContext,
4696 init: &ShadowRootInit,
4697 ) -> Fallible<DomRoot<ShadowRoot>> {
4698 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 Ok(shadow_root)
4712 }
4713
4714 fn GetShadowRoot(&self) -> Option<DomRoot<ShadowRoot>> {
4716 let shadow_or_none = self.shadow_root();
4718
4719 let shadow = shadow_or_none?;
4721 if shadow.Mode() == ShadowRootMode::Closed {
4722 return None;
4723 }
4724
4725 Some(shadow)
4727 }
4728
4729 fn GetCustomElementRegistry(&self) -> Option<DomRoot<CustomElementRegistry>> {
4731 self.custom_element_registry()
4733 }
4734
4735 fn GetRole(&self) -> Option<DOMString> {
4737 self.get_nullable_string_attribute(&local_name!("role"))
4738 }
4739
4740 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 fn GetAssignedSlot(&self, cx: &JSContext) -> Option<DomRoot<HTMLSlotElement>> {
5091 rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(self.upcast::<Node>())));
5094 slottable.find_a_slot(cx.no_gc(), true)
5095 }
5096
5097 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 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 let target = self;
5118
5119 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 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 let animation = Animation::Constructor(
5158 cx,
5159 &window,
5160 None,
5161 Some(effect.upcast()),
5162 Some(Some(&timeline)),
5163 );
5164
5165 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 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 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 AttributeMutation::Set(_) => {
5211 let source = &**attr.value();
5212 let source_line = 1; 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 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 let id = mutation.new_value(attr).and_then(|value| {
5232 let value = value.as_atom();
5233 if value != &atom!("") {
5234 Some(value.clone())
5236 } else {
5237 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 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 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 rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(self.upcast::<Node>())));
5313
5314 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 if attr.namespace() == &ns!() && attr.local_name() == &local_name!("src") {
5328 node.dirty(cx.no_gc(), NodeDamage::Other);
5329 }
5330 },
5331 };
5332
5333 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 node.rev_version(cx.no_gc());
5346
5347 #[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 let document = self.owner_document_unrooted(cx.no_gc());
5420
5421 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 if let Some(form_control) = self.as_maybe_form_control() {
5453 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 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 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 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 return;
5731 }
5732
5733 {
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 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 pub(crate) fn fullscreen_removing_steps(&self, cx: &mut JSContext) {
5812 let document = self.owner_document();
5814
5815 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 for node in nodes {
5826 if document.overlay_handler().fullscreen_element().as_deref() == Some(&*node) {
5828 let _ = document.overlay_handler().exit_fullscreen(cx);
5829 }
5830 else {
5832 document
5833 .overlay_handler()
5834 .unfullscreen_an_element(cx.no_gc(), &node);
5835 }
5836
5837 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 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 if is_popover {
5858 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 debug_assert!(!self.popover_visibility_state_showing());
5871 }
5872 else {
5874 debug_assert!(source.is_none());
5876 }
5877
5878 let document = self.owner_document();
5880 let overlay_handler = document.overlay_handler();
5881
5882 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 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 let source_ancestor_index =
5907 source.and_then(|source| last_flat_tree_ancestor_index(source.upcast()));
5908
5909 let ancestor_index = popover_ancestor_index.max(source_ancestor_index)?;
5913
5914 Some(combined_popovers.swap_remove(ancestor_index).as_rooted())
5918 }
5919
5920 pub(crate) fn popover_visibility_state_showing(&self) -> bool {
5922 self.state.get().contains(ElementState::POPOVER_OPEN)
5923 }
5924
5925 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 pub(crate) fn fullscreen_flag(&self) -> bool {
5932 self.state().contains(ElementState::FULLSCREEN)
5933 }
5934
5935 pub(crate) fn set_fullscreen_state(&self, no_gc: &NoGC, value: bool) {
5937 self.set_state(no_gc, ElementState::FULLSCREEN, value)
5938 }
5939
5940 pub(crate) fn is_connected(&self) -> bool {
5942 self.upcast::<Node>().is_connected()
5943 }
5944
5945 pub(crate) fn cannot_navigate(&self) -> bool {
5947 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 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 Set(Option<&'a AttrValue>),
6008
6009 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#[derive(Eq, Hash, PartialEq)]
6041struct TagNameKey {
6042 prefix: Option<Prefix>,
6043 local_name: LocalName,
6044 html_element_in_html_document: bool,
6045}
6046
6047const TAG_NAME_CACHE_CAPACITY: usize = 128;
6049
6050thread_local! {
6051 static TAG_NAME_CACHE: RefCell<LruCache<TagNameKey, LocalName, FxBuildHasher>> =
6058 RefCell::new(LruCache::with_hasher(TAG_NAME_CACHE_CAPACITY, FxBuildHasher));
6059}
6060
6061pub(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
6088pub(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
6131pub(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 CredentialsMode::CredentialsSameOrigin
6141 }
6142 })
6143 .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}