/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Element nodes. #![cfg_attr(crown, allow(crown::jscontext_first_arg))] use std::borrow::Cow; use std::cell::{Cell, LazyCell}; use std::default::Default; use std::rc::Rc; use std::str::FromStr; use std::sync::atomic::{AtomicUsize, Ordering}; use std::{fmt, mem}; use app_units::Au; use cssparser::match_ignore_ascii_case; use devtools_traits::{AttrInfo, DomMutation, ScriptToDevtoolsControlMsg}; use dom_struct::dom_struct; use euclid::Rect; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode}; use html5ever::{LocalName, Namespace, Prefix, QualName, local_name, namespace_prefix, ns}; use js::context::{JSContext, NoGC}; use js::jsapi::{Heap, JSObject}; use js::jsval::JSVal; use js::realm::CurrentRealm; use js::rust::HandleObject; use layout_api::{ AccessibilityDamage, LayoutDamage, QueryMsg, ScrollContainerQueryFlags, StyleData, with_layout_state, }; use net_traits::ReferrerPolicy; use net_traits::request::{CorsSettings, CredentialsMode}; use script_bindings::callback::RootedCallback; use script_bindings::cell::{DomRefCell, Ref, RefMut}; use script_bindings::codegen::GenericBindings::AnimationBinding::AnimationMethods; use script_bindings::codegen::GenericBindings::KeyframeEffectBinding::KeyframeEffectMethods; use script_bindings::dom::UnrootedDom; use script_bindings::reflector::DomObject; use selectors::attr::CaseSensitivity; use selectors::matching::ElementSelectorFlags; use selectors::sink::Push; use servo_arc::Arc as ServoArc; use style::applicable_declarations::ApplicableDeclarationBlock; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; use style::context::QuirksMode; use style::invalidation::element::restyle_hints::RestyleHint; use style::properties::longhands::{ self, background_image, border_spacing, color, font_family, font_size, }; use style::properties::{ ComputedValues, Importance, PropertyDeclaration, PropertyDeclarationBlock, parse_style_attribute, }; use style::rule_tree::{CascadeLevel, CascadeOrigin}; use style::selector_parser::{RestyleDamage, SelectorParser, Snapshot}; use style::shared_lock::Locked; use style::stylesheets::layer_rule::LayerOrder; use style::stylesheets::{CssRuleType, UrlExtraData}; use style::values::computed::{Overflow, UserSelect}; use style::values::generics::NonNegative; use style::values::generics::position::PreferredRatio; use style::values::generics::ratio::Ratio; use style::values::{AtomIdent, AtomString, CSSFloat, computed, specified}; use style::{ArcSlice, CaseSensitivityExt, dom_apis, thread_state}; use style_traits::CSSPixel; use stylo_atoms::Atom; use stylo_dom::ElementState; use xml5ever::serialize::TraversalScope::{ ChildrenOnly as XmlChildrenOnly, IncludeNode as XmlIncludeNode, }; use crate::conversions::Convert; use crate::css::stylesheet_loader::StylesheetOwner; use crate::dom::RootedPromise; use crate::dom::activation::Activatable; use crate::dom::animation::Animation; use crate::dom::animations::keyframeeffect::KeyframeEffect; use crate::dom::attr::{Attr, is_relevant_attribute}; use crate::dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use crate::dom::bindings::codegen::Bindings::ElementBinding::{ ElementMethods, GetHTMLOptions, ScrollIntoViewContainer, ScrollLogicalPosition, ShadowRootInit, }; use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function; use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods; use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use crate::dom::bindings::codegen::Bindings::SanitizerBinding::{ SetHTMLOptions, SetHTMLUnsafeOptions, }; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{ ShadowRootMethods, ShadowRootMode, SlotAssignmentMode, }; use crate::dom::bindings::codegen::Bindings::WindowBinding::{ ScrollBehavior, ScrollToOptions, WindowMethods, }; use crate::dom::bindings::codegen::UnionTypes::{ BooleanOrScrollIntoViewOptions, NodeOrString, TrustedHTMLOrNullIsEmptyString, TrustedHTMLOrString, TrustedHTMLOrTrustedScriptOrTrustedScriptURLOrString as TrustedTypeOrString, UnrestrictedDoubleOrKeyframeAnimationOptions, UnrestrictedDoubleOrKeyframeEffectOptions, }; use crate::dom::bindings::conversions::DerivedFrom; use crate::dom::bindings::domname::{ self, is_valid_attribute_local_name, namespace_from_domstring, }; use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use crate::dom::bindings::num::Finite; use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, ToLayout}; use crate::dom::bindings::str::DOMString; use crate::dom::csp::{CspReporting, InlineCheckType, SourcePosition}; use crate::dom::customelementregistry::{ CallbackReaction, CustomElementDefinition, CustomElementReaction, CustomElementRegistry, CustomElementState, is_valid_custom_element_name, }; use crate::dom::document::Document; use crate::dom::documentfragment::DocumentFragment; use crate::dom::domrect::DOMRect; use crate::dom::domrectlist::DOMRectList; use crate::dom::domtokenlist::DOMTokenList; use crate::dom::element::attributes::storage::{ AttrName, AttrRef, AttrValueRef, AttributeEntry, AttributeStorage, ContentAttributeData, }; use crate::dom::element::create::create_element; use crate::dom::eventtarget::EventTarget; use crate::dom::globalscope::GlobalScope; use crate::dom::html::form_controls::htmlinputelement::HTMLInputElement; use crate::dom::html::htmlanchorelement::HTMLAnchorElement; use crate::dom::html::htmlareaelement::HTMLAreaElement; use crate::dom::html::htmlbodyelement::HTMLBodyElement; use crate::dom::html::htmlbuttonelement::HTMLButtonElement; use crate::dom::html::htmlcollection::HTMLCollection; use crate::dom::html::htmlelement::HTMLElement; use crate::dom::html::htmlfieldsetelement::HTMLFieldSetElement; use crate::dom::html::htmlfontelement::HTMLFontElement; use crate::dom::html::htmlformelement::FormControlElementHelpers; use crate::dom::html::htmlhrelement::{HTMLHRElement, SizePresentationalHint}; use crate::dom::html::htmliframeelement::HTMLIFrameElement; use crate::dom::html::htmlimageelement::HTMLImageElement; use crate::dom::html::htmllabelelement::HTMLLabelElement; use crate::dom::html::htmllegendelement::HTMLLegendElement; use crate::dom::html::htmllinkelement::HTMLLinkElement; use crate::dom::html::htmlobjectelement::HTMLObjectElement; use crate::dom::html::htmloptgroupelement::HTMLOptGroupElement; use crate::dom::html::htmloutputelement::HTMLOutputElement; use crate::dom::html::htmlscriptelement::HTMLScriptElement; use crate::dom::html::htmlselectelement::HTMLSelectElement; use crate::dom::html::htmlslotelement::{HTMLSlotElement, Slottable}; use crate::dom::html::htmlstyleelement::HTMLStyleElement; use crate::dom::html::htmltablecellelement::HTMLTableCellElement; use crate::dom::html::htmltablecolelement::HTMLTableColElement; use crate::dom::html::htmltableelement::HTMLTableElement; use crate::dom::html::htmltablerowelement::HTMLTableRowElement; use crate::dom::html::htmltablesectionelement::HTMLTableSectionElement; use crate::dom::html::htmltemplateelement::HTMLTemplateElement; use crate::dom::html::htmltextareaelement::HTMLTextAreaElement; use crate::dom::html::htmlvideoelement::HTMLVideoElement; use crate::dom::html::internals::elementinternals::ElementInternals; use crate::dom::intersectionobserver::{IntersectionObserver, IntersectionObserverRegistration}; use crate::dom::iterators::ShadowIncluding; use crate::dom::mutationobserver::{Mutation, MutationObserver}; use crate::dom::namednodemap::NamedNodeMap; use crate::dom::node::virtualmethods::{VirtualMethods, vtable_for}; use crate::dom::node::{ BindContext, ChildrenMutation, CloneChildrenFlag, IsShadowTree, Node, NodeDamage, NodeFlags, NodeTraits, UnbindContext, }; use crate::dom::nodelist::NodeList; use crate::dom::range::Range; use crate::dom::raredata::ElementRareData; use crate::dom::sanitizer::Sanitizer; use crate::dom::servoparser::ServoParser; use crate::dom::shadowroot::{IsUserAgentWidget, ShadowRoot}; use crate::dom::svg::svgelement::SVGElement; use crate::dom::text::Text; use crate::dom::trustedtypes::trustedhtml::TrustedHTML; use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory; use crate::dom::validation::Validatable; use crate::dom::validitystate::ValidationFlags; use crate::dom::window::Window; use crate::dom::window::scrolling_box::{ScrollAxisState, ScrollingBox}; use crate::event_loop::script_thread::ScriptThread; use crate::layout_dom::ServoDangerousStyleElement; use crate::realms::enter_auto_realm; // TODO: Update focus state when the top-level browsing context gains or loses system focus, // and when the element enters or leaves a browsing context container. // https://html.spec.whatwg.org/multipage/#selector-focus /// #[dom_struct] pub struct Element { node: Node, #[no_trace] local_name: LocalName, tag_name: TagName, #[no_trace] namespace: Namespace, #[no_trace] prefix: DomRefCell>, attrs: AttributeStorage, #[no_trace] id_attribute: DomRefCell>, /// #[no_trace] is: DomRefCell>, #[conditional_malloc_size_of] #[no_trace] style_attribute: DomRefCell>>>, attr_list: MutNullableDom, class_list: MutNullableDom, #[no_trace] state: Cell, /// These flags are set by the style system to indicate the that certain /// operations may require restyling this element or its descendants. selector_flags: AtomicUsize, rare_data: DomRefCell>>, /// Style data for this node. This is accessed and mutated by style /// passes and is used to lay out this node and populate layout data. #[no_trace] style_data: DomRefCell>>, } impl fmt::Debug for Element { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<{}", self.local_name)?; if let Some(ref id) = *self.id_attribute.borrow() { write!(f, " id={}", id)?; } write!(f, ">") } } #[derive(MallocSizeOf, PartialEq)] pub(crate) enum ElementCreator { ParserCreated(u64), ScriptCreated, } pub(crate) enum CustomElementCreationMode { Synchronous, Asynchronous, } impl ElementCreator { pub(crate) fn is_parser_created(&self) -> bool { match *self { ElementCreator::ParserCreated(_) => true, ElementCreator::ScriptCreated => false, } } pub(crate) fn return_line_number(&self) -> u64 { match *self { ElementCreator::ParserCreated(l) => l, ElementCreator::ScriptCreated => 1, } } } pub(crate) enum AdjacentPosition { BeforeBegin, AfterEnd, AfterBegin, BeforeEnd, } impl FromStr for AdjacentPosition { type Err = Error; fn from_str(position: &str) -> Result { match_ignore_ascii_case! { position, "beforebegin" => Ok(AdjacentPosition::BeforeBegin), "afterbegin" => Ok(AdjacentPosition::AfterBegin), "beforeend" => Ok(AdjacentPosition::BeforeEnd), "afterend" => Ok(AdjacentPosition::AfterEnd), _ => Err(Error::Syntax(None)) } } } // // Element methods // impl Element { pub(crate) fn create( cx: &mut JSContext, name: QualName, is: Option, document: &Document, creator: ElementCreator, mode: CustomElementCreationMode, proto: Option, ) -> DomRoot { create_element(cx, name, is, document, creator, mode, proto) } pub(crate) fn new_inherited( local_name: LocalName, namespace: Namespace, prefix: Option, document: &Document, ) -> Element { Element::new_inherited_with_state( ElementState::empty(), local_name, namespace, prefix, document, ) } pub(crate) fn new_inherited_with_state( state: ElementState, local_name: LocalName, namespace: Namespace, prefix: Option, document: &Document, ) -> Element { Element { node: Node::new_inherited(document), local_name, tag_name: TagName::new(), namespace, prefix: DomRefCell::new(prefix), attrs: Default::default(), id_attribute: DomRefCell::new(None), is: DomRefCell::new(None), style_attribute: DomRefCell::new(None), attr_list: Default::default(), class_list: Default::default(), state: Cell::new(state), selector_flags: Default::default(), rare_data: Default::default(), style_data: Default::default(), } } pub(crate) fn set_had_duplicate_attributes(&self, no_gc: &NoGC) { self.ensure_rare_data(no_gc).had_duplicate_attributes = true; } pub(crate) fn new( cx: &mut JSContext, local_name: LocalName, namespace: Namespace, prefix: Option, document: &Document, proto: Option, ) -> DomRoot { Node::reflect_node_with_proto( cx, Box::new(Element::new_inherited( local_name, namespace, prefix, document, )), document, proto, ) } fn rare_data(&self) -> Ref<'_, Option>> { self.rare_data.borrow() } fn rare_data_mut(&self) -> RefMut<'_, Option>> { self.rare_data.borrow_mut() } pub(crate) fn ensure_rare_data<'a: 'b, 'b>( &'a self, no_gc: &'b NoGC, ) -> RefMut<'b, Box> { let mut rare_data = self.rare_data.safe_borrow_mut(no_gc); if rare_data.is_none() { *rare_data = Some(Default::default()); } RefMut::map(rare_data, |rare_data| rare_data.as_mut().unwrap()) } pub(crate) fn clean_up_style_data(&self) { self.style_data.borrow_mut().take(); } pub(crate) fn restyle(&self, no_gc: &NoGC, damage: NodeDamage) { let doc = self.node.owner_doc(); let mut restyle = doc.ensure_pending_restyle(self); // FIXME(bholley): I think we should probably only do this for // NodeStyleDamaged, but I'm preserving existing behavior. restyle.hint.insert(RestyleHint::RESTYLE_SELF); match damage { NodeDamage::Style => {}, NodeDamage::ContentOrHeritage => { doc.note_dirty_element(no_gc, self); restyle .damage .insert(RestyleDamage::from(LayoutDamage::DescendantHasBoxDamage)); }, NodeDamage::Other => { doc.note_dirty_element(no_gc, self); restyle.damage.insert(RestyleDamage::reconstruct()); }, } } pub(crate) fn has_dirty_descendants(&self) -> bool { self.upcast::() .get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS) } pub(crate) fn note_dirty_descendants(&self, no_gc: &NoGC) { self.upcast::() .owner_doc_unrooted(no_gc) .note_dirty_element(no_gc, self); } pub(crate) fn set_is(&self, is: LocalName) { *self.is.borrow_mut() = Some(is); } /// pub(crate) fn get_is(&self) -> Option { self.is.borrow().clone() } /// This is a performance optimization. `Element::create` can simply call /// `element.set_custom_element_state(CustomElementState::Uncustomized)` to initialize /// uncustomized, built-in elements with the right state, which currently just means that the /// `DEFINED` state should be `true` for styling. However `set_custom_element_state` has a high /// performance cost and it is unnecessary if the element is being created as an uncustomized /// built-in element. /// /// See for more details. pub(crate) fn set_initial_custom_element_state_to_uncustomized(&self) { let mut state = self.state.get(); state.insert(ElementState::DEFINED); self.state.set(state); } /// pub(crate) fn set_custom_element_state(&self, state: CustomElementState, no_gc: &NoGC) { // no need to inflate rare data for uncustomized if state != CustomElementState::Uncustomized { self.ensure_rare_data(no_gc).custom_element_state = state; } let in_defined_state = matches!( state, CustomElementState::Uncustomized | CustomElementState::Custom ); self.set_state(ElementState::DEFINED, in_defined_state) } pub(crate) fn get_custom_element_state(&self) -> CustomElementState { if let Some(rare_data) = self.rare_data().as_ref() { return rare_data.custom_element_state; } CustomElementState::Uncustomized } /// pub(crate) fn is_custom(&self) -> bool { self.get_custom_element_state() == CustomElementState::Custom } pub(crate) fn set_custom_element_definition( &self, definition: Rc, no_gc: &NoGC, ) { self.ensure_rare_data(no_gc).custom_element_definition = Some(definition); } pub(crate) fn get_custom_element_definition(&self) -> Option> { self.rare_data().as_ref()?.custom_element_definition.clone() } pub(crate) fn clear_custom_element_definition(&self, no_gc: &NoGC) { self.ensure_rare_data(no_gc).custom_element_definition = None; } #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub(crate) fn push_callback_reaction( &self, function: RootedCallback, args: Box<[Heap]>, no_gc: &NoGC, ) { self.ensure_rare_data(no_gc) .custom_element_reaction_queue .push(CustomElementReaction::Callback(function.to_traced(), args)); } pub(crate) fn push_upgrade_reaction( &self, definition: Rc, no_gc: &NoGC, ) { self.ensure_rare_data(no_gc) .custom_element_reaction_queue .push(CustomElementReaction::Upgrade(definition)); } pub(crate) fn clear_reaction_queue(&self) { if let Some(ref mut rare_data) = *self.rare_data_mut() { rare_data.custom_element_reaction_queue.clear(); } } pub(crate) fn invoke_reactions(&self, cx: &mut JSContext) { loop { rooted_vec!(let mut reactions); match *self.rare_data_mut() { Some(ref mut data) => { mem::swap(&mut *reactions, &mut data.custom_element_reaction_queue) }, None => break, }; if reactions.is_empty() { break; } for reaction in reactions.iter() { reaction.invoke(cx, self); } reactions.clear(); } } // https://drafts.csswg.org/cssom-view/#css-layout-box pub(crate) fn has_css_layout_box(&self) -> bool { self.style() .is_some_and(|s| !s.get_box().clone_display().is_none()) } /// pub(crate) fn is_potentially_scrollable_body(&self) -> bool { self.is_potentially_scrollable_body_shared_logic(false) } /// pub(crate) fn is_potentially_scrollable_body_for_scrolling_element(&self) -> bool { self.is_potentially_scrollable_body_shared_logic(true) } /// fn is_potentially_scrollable_body_shared_logic( &self, treat_overflow_clip_on_parent_as_hidden: bool, ) -> bool { let node = self.upcast::(); debug_assert!( node.owner_doc().GetBody().as_deref() == self.downcast::(), "Called is_potentially_scrollable_body on element that is not the " ); // "An element body (which will be the body element) is potentially // scrollable if all of the following conditions are true: // - body has an associated box." if !self.has_css_layout_box() { return false; } // " - body’s parent element’s computed value of the overflow-x or // overflow-y properties is neither visible nor clip." if let Some(parent) = node.GetParentElement() && let Some(style) = parent.style() { let mut overflow_x = style.get_box().clone_overflow_x(); let mut overflow_y = style.get_box().clone_overflow_y(); // This fulfills the 'treat parent element overflow:clip as overflow:hidden' stipulation // from the document.scrollingElement specification. if treat_overflow_clip_on_parent_as_hidden { if overflow_x == Overflow::Clip { overflow_x = Overflow::Hidden; } if overflow_y == Overflow::Clip { overflow_y = Overflow::Hidden; } } if !overflow_x.is_scrollable() && !overflow_y.is_scrollable() { return false; } }; // " - body’s computed value of the overflow-x or overflow-y properties // is neither visible nor clip." if let Some(style) = self.style() && !style.get_box().clone_overflow_x().is_scrollable() && !style.get_box().clone_overflow_y().is_scrollable() { return false; }; true } /// Whether this element is styled such that it establishes a scroll container. /// pub(crate) fn establishes_scroll_container(&self) -> bool { // The CSS computed value has made sure that either both axes are scrollable or none are scrollable. self.upcast::() .effective_overflow() .is_some_and(|overflow| overflow.establishes_scroll_container()) } /// Like [`Self::establishes_scroll_container`], but without forcing a reflow. pub(crate) fn establishes_scroll_container_without_reflow(&self) -> bool { self.upcast::() .effective_overflow_without_reflow() .is_some_and(|overflow| overflow.establishes_scroll_container()) } pub(crate) fn has_overflow(&self, no_gc: &NoGC) -> bool { self.ScrollHeight() > self.ClientHeight(no_gc) || self.ScrollWidth() > self.ClientWidth(no_gc) } /// Whether or not this element has a scrolling box according to /// . /// /// This is true if: /// 1. The element has a layout box. /// 2. The style specifies that overflow should be scrollable (`auto`, `hidden` or `scroll`). /// 3. The fragment actually has content that overflows the box. fn has_scrolling_box(&self, no_gc: &NoGC) -> bool { self.has_css_layout_box() && self.establishes_scroll_container() && self.has_overflow(no_gc) } pub(crate) fn shadow_root(&self) -> Option> { self.rare_data() .as_ref()? .shadow_root .as_ref() .map(|sr| DomRoot::from_ref(&**sr)) } pub(crate) fn shadow_root_unrooted<'a>( &self, no_gc: &'a NoGC, ) -> Option> { self.rare_data() .as_ref()? .shadow_root .as_ref() .map(|shadow_root| shadow_root.as_unrooted(no_gc)) } pub(crate) fn is_shadow_host(&self) -> bool { self.shadow_root().is_some() } /// #[expect(clippy::too_many_arguments)] pub(crate) fn attach_shadow( &self, cx: &mut JSContext, is_ua_widget: IsUserAgentWidget, mode: ShadowRootMode, clonable: bool, serializable: bool, delegates_focus: bool, slot_assignment_mode: SlotAssignmentMode, ) -> Fallible> { // Step 1. If element’s namespace is not the HTML namespace, // then throw a "NotSupportedError" DOMException. if self.namespace != ns!(html) { return Err(Error::NotSupported(Some( "Cannot attach shadow roots to elements with non-HTML namespaces".to_owned(), ))); } // Step 2. If element’s local name is not a valid shadow host name, // then throw a "NotSupportedError" DOMException. if !is_valid_shadow_host_name(self.local_name()) { // UA shadow roots may be attached to anything if is_ua_widget != IsUserAgentWidget::Yes { let error_message = format!( "Cannot attach shadow roots to <{}> elements", *self.local_name() ); return Err(Error::NotSupported(Some(error_message))); } } // Step 3. If element’s local name is a valid custom element name, // or element’s is value is non-null if is_valid_custom_element_name(self.local_name()) || self.get_is().is_some() { // Step 3.1. Let definition be the result of looking up a custom element definition // given element’s node document, its namespace, its local name, and its is value. let definition = self.get_custom_element_definition(); // Step 3.2. If definition is not null and definition’s disable shadow // is true, then throw a "NotSupportedError" DOMException. if definition.is_some_and(|definition| definition.disable_shadow) { let error_message = format!( "The custom element constructor of <{}> disabled attachment of shadow roots", self.local_name() ); return Err(Error::NotSupported(Some(error_message))); } } // Step 4. If element is a shadow host: // Step 4.1. Let currentShadowRoot be element’s shadow root. if let Some(current_shadow_root) = self.shadow_root() { // Step 4.2. If currentShadowRoot’s declarative is false // or currentShadowRoot’s mode is not mode // then throw a "NotSupportedError" DOMException. if !current_shadow_root.is_declarative() || current_shadow_root.shadow_root_mode() != mode { return Err(Error::NotSupported(Some( "Cannot attach a second shadow root to the same element".into(), ))); } // Step 4.3.1. Remove all of currentShadowRoot’s children, in tree order. for child in current_shadow_root.upcast::().children() { child.remove_self(cx); } // Step 4.3.2. Set currentShadowRoot’s declarative to false. current_shadow_root.set_declarative(false); // Step 4.3.3. Return return Ok(current_shadow_root); } // Step 5. Let shadow be a new shadow root whose node document // is element’s node document, host is element, and mode is mode // // Step 8. Set shadow’s slot assignment to slotAssignment // // Step 10. Set shadow’s clonable to clonable let document = self.node.owner_doc(); let shadow_root = ShadowRoot::new( cx, self, &document, mode, slot_assignment_mode, clonable, is_ua_widget, ); // This is not in the specification, but this is where we ensure that the // non-shadow-tree children of `self` no longer have layout boxes as they are no // longer in the flat tree. let node = self.upcast::(); if node.is_connected() { document.remove_style_and_layout_data_from_subtree(cx.no_gc(), node); } if let Some(selection) = self.owner_document().selection() && node.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) { selection.set_visible_selection_dirty(); } // Step 6. Set shadow's delegates focus to delegatesFocus shadow_root.set_delegates_focus(delegates_focus); // Step 7. If element’s custom element state is "precustomized" or "custom", // then set shadow’s available to element internals to true. if matches!( self.get_custom_element_state(), CustomElementState::Precustomized | CustomElementState::Custom ) { shadow_root.set_available_to_element_internals(true); } // Step 9. Set shadow's declarative to false shadow_root.set_declarative(false); // Step 11. Set shadow's serializable to serializable shadow_root.set_serializable(serializable); // Step 12. Set element’s shadow root to shadow self.ensure_rare_data(cx.no_gc()).shadow_root = Some(Dom::from_ref(&*shadow_root)); shadow_root .upcast::() .set_containing_shadow_root(Some(&shadow_root)); let bind_context = BindContext::new(self.upcast(), IsShadowTree::Yes); shadow_root.bind_to_tree(cx, &bind_context); node.dirty(cx.no_gc(), NodeDamage::Other); Ok(shadow_root) } /// Attach a UA widget shadow root with its default parameters. /// Additionally mark ShadowRoot to use styling configuration for a UA widget. /// /// The general trait of these elements is that it would hide the implementation. /// Thus, we would make it inaccessible (i.e., closed mode, not cloneable, and /// not serializable). /// /// With UA shadow root element being assumed as one element, any focus should /// be delegated to its host. /// // TODO: Ideally, all of the UA shadow root should use UA widget styling, but // some of the UA widget implemented prior to the implementation of Gecko's // UA widget matching might need some tweaking. // FIXME: We are yet to implement more complex focusing with that is necessary // for delegate focus, and we are using workarounds for that right now. pub(crate) fn attach_ua_shadow_root( &self, cx: &mut JSContext, use_ua_widget_styling: bool, ) -> DomRoot { let root = self .attach_shadow( cx, IsUserAgentWidget::Yes, ShadowRootMode::Closed, false, false, false, SlotAssignmentMode::Manual, ) .expect("Attaching UA shadow root failed"); root.upcast::() .set_in_ua_widget(use_ua_widget_styling); root } /// pub(crate) fn is_translate_enabled(&self) -> bool { let name = &local_name!("translate"); if self.has_attribute(name) { let attribute = self.get_string_attribute(name); match_ignore_ascii_case! { &*attribute.str(), "yes" | "" => return true, "no" => return false, _ => {}, } } if let Some(parent) = self.upcast::().GetParentNode() && let Some(elem) = parent.downcast::() { return elem.is_translate_enabled(); } true } /// pub(crate) fn directionality(&self) -> String { self.downcast::() .and_then(|html_element| html_element.directionality()) .unwrap_or_else(|| { let node = self.upcast::(); node.parent_directionality() }) } pub(crate) fn is_root(&self) -> bool { match self.node.GetParentNode() { None => false, Some(node) => node.is::(), } } /// Return all IntersectionObserverRegistration for this element. /// Lazily initialize the raredata if it does not exist. pub(crate) fn registered_intersection_observers_mut<'a: 'b, 'b>( &'a self, no_gc: &'b NoGC, ) -> RefMut<'b, Vec> { RefMut::map(self.ensure_rare_data(no_gc), |rare_data| { &mut rare_data.registered_intersection_observers }) } pub(crate) fn registered_intersection_observers( &self, ) -> Option>> { let rare_data: Ref<'_, _> = self.rare_data.borrow(); if rare_data.is_none() { return None; } Some(Ref::map(rare_data, |rare_data| { &rare_data .as_ref() .unwrap() .registered_intersection_observers })) } pub(crate) fn get_intersection_observer_registration( &self, observer: &IntersectionObserver, ) -> Option> { if let Some(registrations) = self.registered_intersection_observers() { registrations .iter() .position(|reg_obs| reg_obs.observer == observer) .map(|index| Ref::map(registrations, |registrations| ®istrations[index])) } else { None } } /// Add a new IntersectionObserverRegistration with initial value to the element. pub(crate) fn add_initial_intersection_observer_registration( &self, observer: &IntersectionObserver, no_gc: &NoGC, ) { self.ensure_rare_data(no_gc) .registered_intersection_observers .push(IntersectionObserverRegistration::new_initial(observer)); } /// Removes a certain IntersectionObserver. pub(crate) fn remove_intersection_observer( &self, observer: &IntersectionObserver, no_gc: &NoGC, ) { self.ensure_rare_data(no_gc) .registered_intersection_observers .retain(|reg_obs| *reg_obs.observer != *observer) } /// Get the [`ScrollingBox`] that contains this element, if one does. `position: /// fixed` elements do not have a containing [`ScrollingBox`]. pub(crate) fn scrolling_box(&self, flags: ScrollContainerQueryFlags) -> Option { self.owner_window() .scrolling_box_query(Some(self.upcast()), flags) } /// pub(crate) fn scroll_into_view_with_options( &self, cx: &mut JSContext, behavior: ScrollBehavior, block: ScrollAxisState, inline: ScrollAxisState, container: Option<&Element>, inner_target_rect: Option>, ) { let get_target_rect = || match inner_target_rect { None => self.upcast::().border_box().unwrap_or_default(), Some(inner_target_rect) => inner_target_rect.translate( self.upcast::() .content_box() .unwrap_or_default() .origin .to_vector(), ), }; // Step 1: For each ancestor element or viewport that establishes a scrolling box `scrolling // box`, in order of innermost to outermost scrolling box, run these substeps: let mut parent_scrolling_box = self.scrolling_box(ScrollContainerQueryFlags::empty()); while let Some(scrolling_box) = parent_scrolling_box { parent_scrolling_box = scrolling_box.parent(); // Step 1.1: If the Document associated with `target` is not same origin with the // Document associated with the element or viewport associated with `scrolling box`, // terminate these steps. // // TODO: Handle this. We currently do not chain up to parent Documents. // Step 1.2 Let `position` be the scroll position resulting from running the steps to // determine the scroll-into-view position of `target` with `behavior` as the scroll // behavior, `block` as the block flow position, `inline` as the inline base direction // position and `scrolling box` as the scrolling box. let position = scrolling_box.determine_scroll_into_view_position( cx.no_gc(), block, inline, get_target_rect(), ); // Step 1.3: If `position` is not the same as `scrolling box`’s current scroll position, or // `scrolling box` has an ongoing smooth scroll, // // TODO: Handle smooth scrolling. if position != scrolling_box.scroll_position() { // ↪ If `scrolling box` is associated with an element // Perform a scroll of the element’s scrolling box to `position`, // with the `element` as the associated element and `behavior` as the // scroll behavior. // ↪ If `scrolling box` is associated with a viewport // Step 1: Let `document` be the viewport’s associated Document. // Step 2: Let `root element` be document’s root element, if there is one, or // null otherwise. // Step 3: Perform a scroll of the viewport to `position`, with `root element` // as the associated element and `behavior` as the scroll behavior. scrolling_box.scroll_to(cx, position, behavior); } // Step 1.4: If `container` is not null and either `scrolling box` is a shadow-including // inclusive ancestor of `container` or is a viewport whose document is a shadow-including // inclusive ancestor of `container`, abort the rest of these steps. if container.is_some_and(|container| { let container_node = container.upcast::(); scrolling_box .node() .is_shadow_including_inclusive_ancestor_of(container_node) }) { return; } } let window_proxy = self.owner_window().window_proxy(); let Some(frame_element) = window_proxy.frame_element() else { return; }; let inner_target_rect = Some(get_target_rect()); let mut realm = enter_auto_realm(cx, frame_element); let cx = &mut realm; frame_element.scroll_into_view_with_options( cx, behavior, block, inline, None, inner_target_rect, ) } pub(crate) fn ensure_contenteditable_selection_range( &self, cx: &mut JSContext, document: &Document, ) -> DomRoot { let Some(selection_range) = self .rare_data() .as_ref() .and_then(|data| data.contenteditable_selection_range.get()) else { let range = Range::new_with_doc(cx, document, None); self.ensure_rare_data(cx.no_gc()) .contenteditable_selection_range .set(Some(&*range)); return range; }; selection_range } /// /// /// > Whenever an element gets scrolled (whether in response to user interaction or /// > by an API), the user agent must run these steps: pub(crate) fn handle_scroll_event(&self) { // Step 1: Let doc be the element’s node document. let document = self.owner_document(); // Step 2: If the element is a snap container, run the steps to update // scrollsnapchanging targets for the element with the element’s eventual // snap target in the block axis as newBlockTarget and the element’s eventual // snap target in the inline axis as newInlineTarget. // // TODO(#7673): Implement scroll snapping // Steps 3 and 4 are shared with other scroll targets. document.finish_handle_scroll_event(self.upcast()); } pub(crate) fn style(&self) -> Option> { self.owner_window().layout_reflow(QueryMsg::StyleQuery); self.style_data .borrow() .as_ref() .map(|data| data.element_data.borrow().styles.primary().clone()) } pub(crate) fn is_styled(&self) -> bool { self.style_data.borrow().is_some() } pub(crate) fn is_display_none(&self) -> bool { self.style_data.borrow().as_ref().is_none_or(|data| { data.element_data .borrow() .styles .primary() .get_box() .display .is_none() }) } /// Returns the computed value of the [`user-select`] property. Returns `None` if the /// element is unstyled. /// /// [`user-select`]: pub(crate) fn computed_user_select(&self) -> Option { Some( self.style_data .borrow() .as_ref()? .element_data .borrow() .styles .primary() .get_ui() .user_select, ) } pub(crate) fn check_style_on_self_or_eager_pseudos( &self, check_styles_fn: impl Fn(&ComputedValues) -> bool, ) -> bool { let style_data = self.style_data.borrow(); let Some(data) = style_data.as_ref().map(|data| data.element_data.borrow()) else { return false; }; if check_styles_fn(data.styles.primary()) { return true; } let mut pseudo_styles = data.styles.pseudos.as_array().iter(); pseudo_styles.any(|style| style.as_deref().is_some_and(&check_styles_fn)) } } /// #[inline] pub(crate) fn is_valid_shadow_host_name(name: &LocalName) -> bool { // > A valid shadow host name is: // > - a valid custom element name if is_valid_custom_element_name(name) { return true; } // > - "article", "aside", "blockquote", "body", "div", "footer", "h1", "h2", "h3", // > "h4", "h5", "h6", "header", "main", "nav", "p", "section", or "span" matches!( name, &local_name!("article") | &local_name!("aside") | &local_name!("blockquote") | &local_name!("body") | &local_name!("div") | &local_name!("footer") | &local_name!("h1") | &local_name!("h2") | &local_name!("h3") | &local_name!("h4") | &local_name!("h5") | &local_name!("h6") | &local_name!("header") | &local_name!("main") | &local_name!("nav") | &local_name!("p") | &local_name!("section") | &local_name!("span") ) } #[inline] #[expect(unsafe_code)] pub(crate) fn get_attr_for_layout<'dom>( elem: LayoutDom<'dom, Element>, namespace: &Namespace, name: &LocalName, ) -> Option<&'dom AttrValue> { let storage = unsafe { elem.unsafe_get().attrs.borrow_for_layout() }; storage .iter() .find(|e: &&AttributeEntry| { name == e.local_name_for_layout() && namespace == e.namespace_for_layout() }) .map(|e: &AttributeEntry| e.value_for_layout()) } impl<'dom> LayoutDom<'dom, Element> { #[inline] pub(crate) fn is_root(&self) -> bool { self.upcast::() .parent_node_ref() .is_some_and(|parent| matches!(parent.type_id_for_layout(), NodeTypeId::Document(_))) } /// Returns true if this element is the body child of an html element root element. pub(crate) fn is_body_element_of_html_element_root(&self) -> bool { if self.local_name() != &local_name!("body") { return false; } let Some(parent_node) = self.upcast::().parent_node_ref() else { return false; }; let Some(parent_element) = parent_node.downcast::() else { return false; }; parent_element.local_name() == &local_name!("html") } /// Iterate over attribute local names for layout, handling mixed Raw and Dom entries. #[expect(unsafe_code)] #[inline] pub(crate) fn each_attr_name_for_layout(self, mut callback: F) where F: FnMut(&LocalName), { let storage = unsafe { self.unsafe_get().attrs.borrow_for_layout() }; for entry in storage.iter() { callback(entry.local_name_for_layout()); } } #[inline] pub(crate) fn has_class_or_part_for_layout( self, name: &AtomIdent, attr_name: &LocalName, case_sensitivity: CaseSensitivity, ) -> bool { get_attr_for_layout(self, &ns!(), attr_name).is_some_and(|attr| { attr.as_tokens() .iter() .any(|atom| case_sensitivity.eq_atom(atom, name)) }) } #[inline] pub(crate) fn get_classes_for_layout(self) -> Option<&'dom [Atom]> { get_attr_for_layout(self, &ns!(), &local_name!("class")).map(|attr| attr.as_tokens()) } pub(crate) fn get_parts_for_layout(self) -> Option<&'dom [Atom]> { get_attr_for_layout(self, &ns!(), &local_name!("part")).map(|attr| attr.as_tokens()) } #[inline] #[expect(unsafe_code)] pub(crate) fn style_data(self) -> Option<&'dom StyleData> { unsafe { self.unsafe_get().style_data.borrow_for_layout().as_deref() } } #[inline] #[expect(unsafe_code)] pub(crate) unsafe fn initialize_style_data(self) { let data = unsafe { self.unsafe_get().style_data.borrow_mut_for_layout() }; debug_assert!(data.is_none()); *data = Some(Box::default()); } #[inline] #[expect(unsafe_code)] pub(crate) unsafe fn clear_style_data(self) { unsafe { self.unsafe_get().style_data.borrow_mut_for_layout().take(); } } pub(crate) fn synthesize_presentational_hints_for_legacy_attributes(self, hints: &mut V) where V: Push, { // TODO: Move HTML presentational hints handling into // HTMLElement::synthesize_presentational_hints_for_legacy_attributes let document = self.upcast::().owner_doc_for_layout(); let mut property_declaration_block = None; let mut push = |declaration| { property_declaration_block .get_or_insert_with(PropertyDeclarationBlock::default) .push(declaration, Importance::Normal); }; // TODO(xiaochengh): This is probably not enough. When the root element doesn't have a `lang`, // we should check the browser settings and system locale. if let Some(lang) = self.get_lang_attr_val_for_layout() { push(PropertyDeclaration::XLang(specified::XLang(Atom::from( lang.to_owned(), )))); } let bgcolor = if let Some(this) = self.downcast::() { this.get_background_color() } else if let Some(this) = self.downcast::() { this.get_background_color() } else if let Some(this) = self.downcast::() { this.get_background_color() } else if let Some(this) = self.downcast::() { this.get_background_color() } else if let Some(this) = self.downcast::() { this.get_background_color() } else { None }; if let Some(color) = bgcolor { push(PropertyDeclaration::BackgroundColor( specified::Color::from_absolute_color(color), )); } if is_element_affected_by_legacy_background_presentational_hint( self.namespace(), self.local_name(), ) && let Some(url) = self .get_attr_for_layout(&ns!(), &local_name!("background")) .and_then(AttrValue::as_resolved_url) .cloned() { push(PropertyDeclaration::BackgroundImage( background_image::SpecifiedValue(vec![specified::Image::for_cascade(url)].into()), )); } let color = if let Some(this) = self.downcast::() { this.get_color() } else if let Some(this) = self.downcast::() { // https://html.spec.whatwg.org/multipage/#the-page:the-body-element-20 this.get_color() } else if let Some(this) = self.downcast::() { // https://html.spec.whatwg.org/multipage/#the-hr-element-2:presentational-hints-5 this.get_color() } else { None }; if let Some(color) = color { push(PropertyDeclaration::Color( longhands::color::SpecifiedValue(specified::Color::from_absolute_color(color)), )); } let font_face = self .downcast::() .and_then(LayoutDom::get_face); if let Some(font_face) = font_face { push(PropertyDeclaration::FontFamily( font_family::SpecifiedValue::Values(computed::font::FontFamilyList { list: ArcSlice::from_iter( HTMLFontElement::parse_face_attribute(font_face).into_iter(), ), }), )); } let font_size = self .downcast::() .and_then(LayoutDom::get_size); if let Some(font_size) = font_size { push(PropertyDeclaration::FontSize( font_size::SpecifiedValue::from_html_size(font_size as u8), )); } // Textual input, specifically text entry and domain specific input has // a default preferred size. // // // let size = self .downcast::() .and_then(|input_element| { // FIXME(pcwalton): More use of atoms, please! match self.get_attr_val_for_layout(&ns!(), &local_name!("type")) { Some("hidden") | Some("range") | Some("color") | Some("checkbox") | Some("radio") | Some("file") | Some("submit") | Some("image") | Some("reset") | Some("button") => None, // Others _ => match input_element.size_for_layout() { 0 => None, s => Some(s as i32), }, } }); if let Some(size) = size { let value = specified::NoCalcLength::from_servo_character_width(size); push(PropertyDeclaration::Width( specified::Size::LengthPercentage(NonNegative( specified::LengthPercentage::Length(value), )), )); } let width = if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { this.get_width() } else if let Some(this) = self.downcast::() { // https://html.spec.whatwg.org/multipage/#the-hr-element-2:attr-hr-width this.get_width() } else { LengthOrPercentageOrAuto::Auto }; // FIXME(emilio): Use from_computed value here and below. match width { LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Percentage(percentage) => { let width_value = specified::Size::LengthPercentage(NonNegative( specified::LengthPercentage::Percentage(specified::NoCalcPercentage::new( percentage, )), )); push(PropertyDeclaration::Width(width_value)); }, LengthOrPercentageOrAuto::Length(length) => { let width_value = specified::Size::LengthPercentage(NonNegative( specified::LengthPercentage::Length(specified::NoCalcLength::from_px( length.to_f32_px(), )), )); push(PropertyDeclaration::Width(width_value)); }, } let height = if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else if let Some(this) = self.downcast::() { this.get_height() } else { LengthOrPercentageOrAuto::Auto }; match height { LengthOrPercentageOrAuto::Auto => {}, LengthOrPercentageOrAuto::Percentage(percentage) => { let height_value = specified::Size::LengthPercentage(NonNegative( specified::LengthPercentage::Percentage(specified::NoCalcPercentage::new( percentage, )), )); push(PropertyDeclaration::Height(height_value)); }, LengthOrPercentageOrAuto::Length(length) => { let height_value = specified::Size::LengthPercentage(NonNegative( specified::LengthPercentage::Length(specified::NoCalcLength::from_px( length.to_f32_px(), )), )); push(PropertyDeclaration::Height(height_value)); }, } if let Some(svg_element) = self.downcast::() { svg_element.synthesize_presentational_hints(document, &mut push); } // Aspect ratio when providing both width and height. // https://html.spec.whatwg.org/multipage/#attributes-for-embedded-content-and-images if (self.is::() || self.is::()) && let LengthOrPercentageOrAuto::Length(width) = width && let LengthOrPercentageOrAuto::Length(height) = height { let width_value = NonNegative(specified::Number::new(width.to_f32_px())); let height_value = NonNegative(specified::Number::new(height.to_f32_px())); let aspect_ratio = specified::position::AspectRatio { auto: true, ratio: PreferredRatio::Ratio(Ratio(width_value, height_value)), }; push(PropertyDeclaration::AspectRatio(Box::new(aspect_ratio))); } let cols = self .downcast::() .map(LayoutDom::get_cols); if let Some(cols) = cols { let cols = cols as i32; if cols > 0 { // TODO(mttr) ServoCharacterWidth uses the size math for , but // the math for