Skip to main content

script/dom/node/
node.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! The core DOM types. Defines the basic DOM hierarchy as well as all the HTML elements.
6
7use std::cell::{Cell, LazyCell};
8use std::cmp::Ordering;
9use std::default::Default;
10use std::f64::consts::PI;
11use std::ops::Deref;
12use std::rc::Rc;
13use std::slice::from_ref;
14use std::{cmp, fmt, iter};
15
16use app_units::Au;
17use bitflags::bitflags;
18use dom_struct::dom_struct;
19use embedder_traits::{MouseButton, UntrustedNodeAddress};
20use euclid::default::Size2D;
21use euclid::{Point2D, Rect};
22use html5ever::serialize::HtmlSerializer;
23use html5ever::{Namespace, Prefix, QualName, ns, serialize as html_serialize};
24use js::context::{JSContext, NoGC};
25use js::jsapi::JSObject;
26use js::rust::HandleObject;
27use keyboard_types::Modifiers;
28use layout_api::{
29    AccessibilityDamage, AxesOverflow, BoxAreaType, CSSPixelRectVec, GenericLayoutData,
30    NodeRenderingType, PhysicalSides, QueryMsg, TrustedNodeAddress, with_layout_state,
31};
32use libc::{self, uintptr_t};
33use script_bindings::cell::{DomRefCell, Ref, RefMut};
34use script_bindings::codegen::GenericBindings::DocumentTypeBinding::DocumentTypeMethods;
35use script_bindings::codegen::GenericBindings::ElementBinding::ElementMethods;
36use script_bindings::codegen::GenericBindings::EventBinding::EventMethods;
37use script_bindings::codegen::GenericBindings::HTMLButtonElementBinding::HTMLButtonElementMethods;
38use script_bindings::codegen::GenericBindings::ProcessingInstructionBinding::ProcessingInstructionMethods;
39use script_bindings::codegen::InheritTypes::{DocumentFragmentTypeId, TextTypeId};
40use script_bindings::domstring::TracedDOMString;
41use script_bindings::reflector::{
42    DomObject, DomObjectWrap, WeakReferenceableDomObjectWrap, reflect_dom_object_with_proto,
43    reflect_weak_referenceable_dom_object_with_proto,
44};
45use script_bindings::trace::{RootedTraceableBox, TraceableSmallVec};
46use script_traits::{DocumentActivity, MouseButtons};
47use servo_base::id::PipelineId;
48use smallvec::SmallVec;
49use style::Atom;
50use style::context::QuirksMode;
51use style::dom::OpaqueNode;
52use style::dom_apis::{QueryAll, QueryFirst};
53use style::selector_parser::PseudoElement;
54use style::values::computed::{Inert, Interactivity};
55use style_traits::CSSPixel;
56use uuid::Uuid;
57use xml5ever::{local_name, serialize as xml_serialize};
58
59use crate::dom::ChildrenMutation;
60use crate::dom::attr::Attr;
61use crate::dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
62use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
63use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
64use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods;
65use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods;
66use crate::dom::bindings::codegen::Bindings::NodeBinding::{
67    GetRootNodeOptions, NodeConstants, NodeMethods,
68};
69use crate::dom::bindings::codegen::Bindings::NodeListBinding::NodeListMethods;
70use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
71use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
72    ShadowRootMode, SlotAssignmentMode,
73};
74use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
75use crate::dom::bindings::codegen::UnionTypes::NodeOrString;
76use crate::dom::bindings::conversions::{self, DerivedFrom};
77use crate::dom::bindings::domname::namespace_from_domstring;
78use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
79use crate::dom::bindings::inheritance::{
80    Castable, CharacterDataTypeId, EventTargetTypeId, NodeTypeId,
81};
82use crate::dom::bindings::root::{
83    Dom, DomRoot, DomSlice, LayoutDom, MutNullableDom, ToLayout, UnrootedDom,
84};
85use crate::dom::bindings::str::{DOMString, USVString};
86use crate::dom::characterdata::CharacterData;
87use crate::dom::comparator::{DomPositionContainment, compare_dom_positions};
88use crate::dom::context::{BindContext, IsShadowTree, MoveContext, UnbindContext};
89use crate::dom::css::cssstylesheet::CSSStyleSheet;
90use crate::dom::css::stylesheetlist::StyleSheetListOwner;
91use crate::dom::customelementregistry::{
92    CallbackReaction, CustomElementRegistry, try_upgrade_element,
93};
94use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument};
95use crate::dom::documentfragment::DocumentFragment;
96use crate::dom::documenttype::DocumentType;
97use crate::dom::element::{CustomElementCreationMode, Element, ElementCreator};
98use crate::dom::event::{Event, EventBubbles, EventCancelable, EventFlags};
99use crate::dom::eventtarget::EventTarget;
100use crate::dom::globalscope::GlobalScope;
101use crate::dom::html::htmlbuttonelement::{ButtonType, CommandState, HTMLButtonElement};
102use crate::dom::html::htmlcollection::HTMLCollection;
103use crate::dom::html::htmlelement::HTMLElement;
104use crate::dom::html::htmlformelement::FormControl;
105use crate::dom::html::htmllinkelement::HTMLLinkElement;
106use crate::dom::html::htmlslotelement::{HTMLSlotElement, Slottable};
107use crate::dom::html::htmlstyleelement::HTMLStyleElement;
108use crate::dom::htmlelement::PopoverState;
109use crate::dom::iterators::{
110    ShadowIncluding, UnrootedAncestorIterator, UnrootedFollowingFlatTreeNodesTraversal,
111    UnrootedFollowingNodeIterator, UnrootedPrecedingNodeIterator,
112};
113use crate::dom::mutationobserver::{Mutation, MutationObserver, RegisteredObserver};
114use crate::dom::node::iterators::{
115    FollowingNodeIterator, PrecedingNodeIterator, SimpleNodeIterator, TreeIterator,
116    UnrootedSimpleNodeIterator, UnrootedTreeIterator,
117};
118use crate::dom::node::nodelist::NodeList;
119use crate::dom::node::virtualmethods::{VirtualMethods, vtable_for};
120use crate::dom::pointerevent::{PointerEvent, PointerId};
121use crate::dom::raredata::NodeRareData;
122use crate::dom::servoparser::html::HtmlSerialize;
123use crate::dom::servoparser::serialize_html_fragment;
124use crate::dom::shadowroot::shadowroot::{IsUserAgentWidget, ShadowRoot};
125use crate::dom::text::Text;
126use crate::dom::traversal::LightDomNoGcTraversal;
127use crate::dom::types::{CDATASection, KeyboardEvent, ProcessingInstruction};
128use crate::dom::window::Window;
129use crate::event_loop::document_loader::DocumentLoader;
130use crate::event_loop::script_thread::ScriptThread;
131use crate::layout_dom::{ServoDangerousStyleElement, ServoDangerousStyleNode};
132
133/// An HTML node.
134#[dom_struct]
135pub struct Node {
136    /// The JavaScript reflector for this node.
137    eventtarget: EventTarget,
138
139    /// The parent of this node.
140    parent_node: MutNullableDom<Node>,
141
142    /// The first child of this node.
143    first_child: MutNullableDom<Node>,
144
145    /// The last child of this node.
146    last_child: MutNullableDom<Node>,
147
148    /// The next sibling of this node.
149    next_sibling: MutNullableDom<Node>,
150
151    /// The previous sibling of this node.
152    prev_sibling: MutNullableDom<Node>,
153
154    /// The document that this node belongs to.
155    owner_doc: MutNullableDom<Document>,
156
157    /// Rare node data.
158    rare_data: DomRefCell<Option<Box<NodeRareData>>>,
159
160    /// The live count of children of this node.
161    children_count: Cell<u32>,
162
163    /// A bitfield of flags for node items.
164    flags: Cell<NodeFlags>,
165
166    /// The maximum version of any inclusive descendant of this node.
167    inclusive_descendants_version: Cell<u64>,
168
169    /// Layout data for this node. This is populated during layout and can
170    /// be used for incremental relayout and script queries.
171    #[no_trace]
172    layout_data: DomRefCell<Option<Box<GenericLayoutData>>>,
173}
174
175impl fmt::Debug for Node {
176    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177        if let Some(element) = self.downcast::<Element>() {
178            element.fmt(f)
179        } else if let Some(character_data) = self.downcast::<CharacterData>() {
180            write!(f, "[Text({})]", *character_data.data())
181        } else {
182            write!(f, "[Node({:?})]", self.type_id())
183        }
184    }
185}
186
187/// Flags for node items
188#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
189pub(crate) struct NodeFlags(u16);
190
191bitflags! {
192    impl NodeFlags: u16 {
193        /// Specifies whether this node is in a document.
194        ///
195        /// <https://dom.spec.whatwg.org/#in-a-document-tree>
196        const IS_IN_A_DOCUMENT_TREE = 1 << 0;
197
198        /// Specifies whether this node needs style recalc on next reflow.
199        const HAS_DIRTY_DESCENDANTS = 1 << 1;
200
201        /// Specifies whether or not there is an authentic click in progress on
202        /// this element.
203        const CLICK_IN_PROGRESS = 1 << 2;
204
205        /// Whether this node has ever taken part in a CSS animation/transition or has been an
206        /// animating image. This flag is never cleared once it is set.
207        const HAS_EVER_ANIMATED = 1 << 3;
208
209        // There is one free bit here.
210
211        /// Whether the style declarations mapped from attributes (presentational hints)
212        /// have been resolved already and are up-to-date.
213        const HAS_RESOLVED_PRESENTATIONAL_HINTS = 1 << 5;
214
215        /// Specifies whether the parser has set an associated form owner for
216        /// this element. Only applicable for form-associatable elements.
217        const PARSER_ASSOCIATED_FORM_OWNER = 1 << 6;
218
219        /// Whether this element has a snapshot stored due to a style or
220        /// attribute change.
221        ///
222        /// See the `style::restyle_hints` module.
223        const HAS_SNAPSHOT = 1 << 7;
224
225        /// Whether this element has already handled the stored snapshot.
226        const HANDLED_SNAPSHOT = 1 << 8;
227
228        /// Whether this node participates in a shadow tree.
229        const IS_IN_SHADOW_TREE = 1 << 9;
230
231        /// Specifies whether this node's shadow-including root is a document.
232        ///
233        /// <https://dom.spec.whatwg.org/#connected>
234        const IS_CONNECTED = 1 << 10;
235
236        /// Whether this node has a weird parser insertion mode. i.e whether setting innerHTML
237        /// needs extra work or not
238        const HAS_WEIRD_PARSER_INSERTION_MODE = 1 << 11;
239
240        /// Whether this node resides in UA shadow DOM. Element within UA Shadow DOM
241        /// will have a different style computation behavior
242        const IS_IN_UA_WIDGET = 1 << 12;
243
244        /// Whether this node has a pseudo-element style which uses `attr()` in the `content` attribute.
245        const USES_ATTR_IN_CONTENT_ATTRIBUTE = 1 << 13;
246
247        /// Whether any part of this node or its flat tree descendants overlaps with
248        /// the [Document selection](https://w3c.github.io/selection-api/#dfn-selection).
249        ///
250        /// By definition, if a node has this flag set then all its flat tree ancestors
251        /// have it set too. Conversely, if a node has this flag unset then all its flat
252        /// tree descendants have it unset too.
253        const OVERLAPS_DOCUMENT_SELECTION = 1 << 14;
254
255        /// For nodes with the `OVERLAPS_DOCUMENT_SELECTION`, whether the used value of
256        /// [`user-select`](https://drafts.csswg.org/css-ui-4/#propdef-user-select) is `none`.
257        const SELECTION_INHIBITED = 1 << 15;
258    }
259}
260
261/// suppress observers flag
262/// <https://dom.spec.whatwg.org/#insert-suppressobservers>
263/// <https://dom.spec.whatwg.org/#remove-suppressobservers>
264#[derive(Clone, Copy, MallocSizeOf)]
265pub(crate) enum SuppressObserver {
266    Suppressed,
267    Unsuppressed,
268}
269
270pub(crate) enum ForceSlottableNodeReconciliation {
271    Force,
272    Skip,
273}
274
275impl Node {
276    // Getters for internal values
277    pub(super) fn parent_node(&self) -> &MutNullableDom<Node> {
278        &self.parent_node
279    }
280
281    pub(super) fn first_child(&self) -> &MutNullableDom<Node> {
282        &self.first_child
283    }
284
285    pub(super) fn last_child(&self) -> &MutNullableDom<Node> {
286        &self.last_child
287    }
288
289    pub(super) fn next_sibling(&self) -> &MutNullableDom<Node> {
290        &self.next_sibling
291    }
292
293    pub(super) fn prev_sibling(&self) -> &MutNullableDom<Node> {
294        &self.prev_sibling
295    }
296
297    pub(super) fn get_owner_doc(&self) -> &MutNullableDom<Document> {
298        &self.owner_doc
299    }
300
301    pub(super) fn get_rare_data(&self) -> &DomRefCell<Option<Box<NodeRareData>>> {
302        &self.rare_data
303    }
304
305    pub(super) fn flags(&self) -> &Cell<NodeFlags> {
306        &self.flags
307    }
308
309    pub(crate) fn layout_data(&self) -> &DomRefCell<Option<Box<GenericLayoutData>>> {
310        &self.layout_data
311    }
312
313    /// Adds a new child to the end of this node's list of children.
314    ///
315    /// Fails unless `new_child` is disconnected from the tree.
316    fn add_child(
317        &self,
318        cx: &mut JSContext,
319        operation: MoveOrInsert,
320        new_child: &Node,
321        before: Option<&Node>,
322    ) {
323        assert!(new_child.parent_node.get().is_none());
324        assert!(new_child.prev_sibling.get().is_none());
325        assert!(new_child.next_sibling.get().is_none());
326
327        self.add_pending_accessibility_damage(cx.no_gc(), AccessibilityDamage::Children);
328
329        match before {
330            Some(before) => {
331                assert!(before.parent_node.get().as_deref() == Some(self));
332                let prev_sibling = before.GetPreviousSibling();
333                match prev_sibling {
334                    None => {
335                        assert!(self.first_child.get().as_deref() == Some(before));
336                        self.first_child.set(Some(new_child));
337                    },
338                    Some(ref prev_sibling) => {
339                        prev_sibling.next_sibling.set(Some(new_child));
340                        new_child.prev_sibling.set(Some(prev_sibling));
341                    },
342                }
343                before.prev_sibling.set(Some(new_child));
344                new_child.next_sibling.set(Some(before));
345            },
346            None => {
347                let last_child = self.GetLastChild();
348                match last_child {
349                    None => self.first_child.set(Some(new_child)),
350                    Some(ref last_child) => {
351                        assert!(last_child.next_sibling.get().is_none());
352                        last_child.next_sibling.set(Some(new_child));
353                        new_child.prev_sibling.set(Some(last_child));
354                    },
355                }
356
357                self.last_child.set(Some(new_child));
358            },
359        }
360
361        new_child.parent_node.set(Some(self));
362        self.children_count.set(self.children_count.get() + 1);
363
364        let parent_is_in_a_document_tree = self.is_in_a_document_tree();
365        let parent_in_shadow_tree = self.is_in_a_shadow_tree();
366        let parent_is_connected = self.is_connected();
367        let parent_is_in_ua_widget = self.is_in_ua_widget();
368        let context = LazyCell::new(|| BindContext::new(self, IsShadowTree::No));
369
370        for node in new_child.traverse_preorder(ShadowIncluding::No) {
371            if parent_in_shadow_tree {
372                if let Some(shadow_root) = self.containing_shadow_root() {
373                    node.set_containing_shadow_root(Some(&*shadow_root));
374                }
375                debug_assert!(node.containing_shadow_root().is_some());
376            }
377            node.set_flag(
378                NodeFlags::IS_IN_A_DOCUMENT_TREE,
379                parent_is_in_a_document_tree,
380            );
381            node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, parent_in_shadow_tree);
382            node.set_flag(NodeFlags::IS_CONNECTED, parent_is_connected);
383            node.set_flag(NodeFlags::IS_IN_UA_WIDGET, parent_is_in_ua_widget);
384
385            // Out-of-document elements never have the descendants flag set.
386            debug_assert!(!node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS));
387
388            match operation {
389                MoveOrInsert::Move => {
390                    if let Some(element) = node.downcast::<Element>() {
391                        if parent_is_in_a_document_tree || parent_in_shadow_tree {
392                            element.register_current_id_and_name_attribute(cx);
393                        }
394
395                        // Shadow-including descendants of this node's shadow root were marked as
396                        // disconnected in the first phase of the move, so they have to be marked as
397                        // connected as it finishes. This mirrors what happens in
398                        // `ShadowRoot::bind_to_tree`, but only handling the IS_CONNECTED flag.
399                        if parent_is_connected && let Some(shadow_root) = element.shadow_root() {
400                            for node in shadow_root
401                                .upcast::<Node>()
402                                .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::Yes)
403                            {
404                                node.set_flag(NodeFlags::IS_CONNECTED, true);
405                                // This node should never have been marked as dirty, because it
406                                // wasn't flagged as connected.
407                                debug_assert!(!node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS));
408                            }
409                        }
410                    }
411                },
412                MoveOrInsert::Insert => vtable_for(&node).bind_to_tree(cx, &context),
413            }
414        }
415    }
416
417    /// Clean up flags and runs steps 11-14 of remove a node.
418    /// <https://dom.spec.whatwg.org/#concept-node-remove>
419    pub(crate) fn complete_remove_subtree(
420        cx: &mut JSContext,
421        root: &Node,
422        context: &UnbindContext,
423    ) {
424        // Flags that reset when a node is disconnected
425        const RESET_FLAGS: NodeFlags = NodeFlags::IS_IN_A_DOCUMENT_TREE
426            .union(NodeFlags::IS_CONNECTED)
427            .union(NodeFlags::HAS_DIRTY_DESCENDANTS)
428            .union(NodeFlags::HAS_SNAPSHOT)
429            .union(NodeFlags::HANDLED_SNAPSHOT)
430            .union(NodeFlags::OVERLAPS_DOCUMENT_SELECTION)
431            .union(NodeFlags::SELECTION_INHIBITED);
432
433        for node in root.traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::No) {
434            node.set_flag(RESET_FLAGS | NodeFlags::IS_IN_SHADOW_TREE, false);
435
436            // If the element has a shadow root attached to it then we traverse that as well,
437            // but without touching the IS_IN_SHADOW_TREE flags of the children
438            if let Some(shadow_root) = node.downcast::<Element>().and_then(Element::shadow_root) {
439                for node in shadow_root
440                    .upcast::<Node>()
441                    .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::Yes)
442                {
443                    node.set_flag(RESET_FLAGS, false);
444                }
445            }
446        }
447
448        // Step 12.
449        let is_parent_connected = context.parent.is_connected();
450        let custom_element_reaction_stack = ScriptThread::custom_element_reaction_stack();
451
452        // Since both the initial traversal in light dom and the inner traversal
453        // in shadow DOM share the same code, we define a closure to prevent omissions.
454        let cleanup_node = |cx: &mut JSContext, node: &Node| {
455            let document = node.owner_document_unrooted(cx.no_gc());
456            document.cancel_animations_for_node(node);
457            document.clean_up_style_and_layout_data_for_node(node);
458
459            // Step 11 & 14.1. Run the removing steps.
460            // This needs to be in its own loop, because unbind_from_tree may
461            // rely on the state of IS_IN_DOC of the context node's descendants,
462            // e.g. when removing a <form>.
463            vtable_for(node).unbind_from_tree(cx, context);
464
465            // Step 12 & 14.2. Enqueue disconnected custom element reactions.
466            if is_parent_connected && let Some(element) = node.as_custom_element() {
467                custom_element_reaction_stack.enqueue_callback_reaction(
468                    cx,
469                    &element,
470                    CallbackReaction::Disconnected,
471                    None,
472                );
473            }
474        };
475
476        for node in root.traverse_preorder(ShadowIncluding::No) {
477            cleanup_node(cx, &node);
478
479            // Make sure that we don't accidentally initialize the rare data for this node
480            // by setting it to None
481            if node.containing_shadow_root().is_some() {
482                // Reset the containing shadowRoot after we unbind the node, since some elements
483                // require the containing shadowRoot for cleanup logic (e.g. <style>).
484                node.set_containing_shadow_root(None);
485            }
486
487            // If the element has a shadow root attached to it then we traverse that as well,
488            // but without resetting the contained shadow root
489            if let Some(shadow_root) = node.downcast::<Element>().and_then(Element::shadow_root) {
490                for node in shadow_root
491                    .upcast::<Node>()
492                    .traverse_preorder(ShadowIncluding::Yes)
493                {
494                    cleanup_node(cx, &node);
495                }
496            }
497        }
498
499        // Make sure the node and its subtree aren't GCed until the accessibility tree has had a
500        // chance to remove them.
501        let no_gc = cx.no_gc();
502        let document = root.owner_document_unrooted(no_gc);
503        if document.accessibility_active() {
504            document
505                .accessibility_data_mut()
506                .root_removed_node(no_gc, root);
507        }
508    }
509
510    pub(crate) fn complete_move_subtree(cx: &mut JSContext, root: &Node) {
511        // Flags that reset when a node is moved
512        const RESET_FLAGS: NodeFlags = NodeFlags::IS_IN_A_DOCUMENT_TREE
513            .union(NodeFlags::IS_CONNECTED)
514            .union(NodeFlags::HAS_DIRTY_DESCENDANTS)
515            .union(NodeFlags::HAS_SNAPSHOT)
516            .union(NodeFlags::HANDLED_SNAPSHOT)
517            .union(NodeFlags::OVERLAPS_DOCUMENT_SELECTION)
518            .union(NodeFlags::SELECTION_INHIBITED);
519
520        let document = root.owner_document();
521        for node in root.traverse_preorder(ShadowIncluding::No) {
522            let node_was_in_tree = node.is_in_a_document_tree() || node.is_in_a_shadow_tree();
523
524            node.set_flag(RESET_FLAGS | NodeFlags::IS_IN_SHADOW_TREE, false);
525            document.clean_up_style_and_layout_data_for_node(&node);
526
527            // Unregister the `id` and `name` attributes for this node. Note that they
528            // will be re-registered when added to the tree again.
529            if node_was_in_tree && let Some(element) = node.downcast::<Element>() {
530                element.unregister_current_id_and_name_attribute(cx);
531            }
532
533            // Make sure that we don't accidentally initialize the rare data for this node
534            // by setting it to None
535            if node.containing_shadow_root().is_some() {
536                // Reset the containing shadowRoot after we unbind the node, since some elements
537                // require the containing shadowRoot for cleanup logic (e.g. <style>).
538                node.set_containing_shadow_root(None);
539            }
540
541            // If the element has a shadow root attached to it then we traverse that as well,
542            // but without touching the IS_IN_SHADOW_TREE flags of the children,
543            // and without resetting the contained shadow root
544            if let Some(shadow_root) = node.downcast::<Element>().and_then(Element::shadow_root) {
545                for node in shadow_root
546                    .upcast::<Node>()
547                    .traverse_preorder(ShadowIncluding::Yes)
548                {
549                    // Moving can never change the shadow-including root of a node, so IS_CONNECTED
550                    // will maintain the value that it had before the move.
551                    node.set_flag(RESET_FLAGS, false);
552                    document.clean_up_style_and_layout_data_for_node(&node);
553                }
554            }
555        }
556    }
557
558    /// Removes the given child from this node's list of children.
559    ///
560    /// Fails unless `child` is a child of this node.
561    fn remove_child(&self, cx: &mut JSContext, child: &Node) {
562        assert!(child.parent_node.get().as_deref() == Some(self));
563
564        if let Some(element) = self.downcast::<Element>() {
565            element.note_dirty_descendants(cx.no_gc());
566        }
567        self.add_pending_accessibility_damage(cx.no_gc(), AccessibilityDamage::Children);
568
569        let prev_sibling = child.GetPreviousSibling();
570        match prev_sibling {
571            None => {
572                self.first_child.set(child.next_sibling.get().as_deref());
573            },
574            Some(ref prev_sibling) => {
575                prev_sibling
576                    .next_sibling
577                    .set(child.next_sibling.get().as_deref());
578            },
579        }
580        let next_sibling = child.GetNextSibling();
581        match next_sibling {
582            None => {
583                self.last_child.set(child.prev_sibling.get().as_deref());
584            },
585            Some(ref next_sibling) => {
586                next_sibling
587                    .prev_sibling
588                    .set(child.prev_sibling.get().as_deref());
589            },
590        }
591
592        let context = UnbindContext::new(self, next_sibling.as_deref());
593
594        child.prev_sibling.set(None);
595        child.next_sibling.set(None);
596        child.parent_node.set(None);
597        self.children_count.set(self.children_count.get() - 1);
598
599        Self::complete_remove_subtree(cx, child, &context);
600    }
601
602    fn move_child(&self, cx: &mut JSContext, child: &Node) {
603        assert!(child.parent_node.get().as_deref() == Some(self));
604        self.dirty(cx.no_gc(), NodeDamage::ContentOrHeritage);
605        if let Some(element) = self.downcast::<Element>() {
606            element.note_dirty_descendants(cx.no_gc());
607        }
608
609        self.add_pending_accessibility_damage(cx.no_gc(), AccessibilityDamage::Children);
610
611        child.prev_sibling.set(None);
612        child.next_sibling.set(None);
613        child.parent_node.set(None);
614        self.children_count.set(self.children_count.get() - 1);
615        Self::complete_move_subtree(cx, child)
616    }
617
618    pub(crate) fn to_opaque(&self) -> OpaqueNode {
619        OpaqueNode(self.reflector().get_jsobject().get() as usize)
620    }
621
622    pub(crate) fn as_custom_element(&self) -> Option<DomRoot<Element>> {
623        self.downcast::<Element>().and_then(|element| {
624            if element.is_custom() {
625                assert!(element.get_custom_element_definition().is_some());
626                Some(DomRoot::from_ref(element))
627            } else {
628                None
629            }
630        })
631    }
632
633    /// <https://html.spec.whatwg.org/multipage/#fire-a-synthetic-pointer-event>
634    pub(crate) fn fire_synthetic_pointer_event_not_trusted(
635        &self,
636        cx: &mut JSContext,
637        event_type: Atom,
638    ) {
639        // Spec says the choice of which global to create the pointer event
640        // on is not well-defined,
641        // and refers to heycam/webidl#135
642        let window = self.owner_window();
643
644        // <https://w3c.github.io/pointerevents/#the-click-auxclick-and-contextmenu-events>
645        let pointer_event = PointerEvent::new(
646            cx,
647            &window, // ambiguous in spec
648            event_type,
649            EventBubbles::Bubbles,              // Step 3: bubbles
650            EventCancelable::Cancelable,        // Step 3: cancelable
651            Some(&window),                      // Step 7: view
652            0,                                  // detail uninitialized
653            Point2D::zero(),                    // coordinates uninitialized
654            Point2D::zero(),                    // coordinates uninitialized
655            Point2D::zero(),                    // coordinates uninitialized
656            Modifiers::empty(),                 // empty modifiers
657            MouseButton::Primary,               // button, primary mouse button
658            MouseButtons::empty(),              // buttons
659            None,                               // related_target
660            None,                               // point_in_target
661            PointerId::NonPointerDevice as i32, // pointer_id
662            1,                                  // width
663            1,                                  // height
664            0.5,                                // pressure
665            0.0,                                // tangential_pressure
666            0,                                  // tilt_x
667            0,                                  // tilt_y
668            0,                                  // twist
669            PI / 2.0,                           // altitude_angle
670            0.0,                                // azimuth_angle
671            DOMString::new(),                   // pointer_type
672            false,                              // is_primary
673            &[],                                // coalesced_events
674            &[],                                // predicted_events
675        );
676
677        // Step 4. Set event's composed flag.
678        pointer_event.upcast::<Event>().set_composed(true);
679
680        // Step 5. If the not trusted flag is set, initialize event's isTrusted attribute to false.
681        pointer_event.upcast::<Event>().set_trusted(false);
682
683        // Step 6,8. TODO keyboard modifiers
684
685        pointer_event
686            .upcast::<Event>()
687            .dispatch(cx, self.upcast::<EventTarget>(), false);
688    }
689
690    pub(crate) fn parent_directionality(&self) -> String {
691        let mut current = self.GetParentNode();
692
693        loop {
694            match current {
695                Some(node) => {
696                    if let Some(directionality) = node
697                        .downcast::<HTMLElement>()
698                        .and_then(|html_element| html_element.directionality())
699                    {
700                        return directionality;
701                    } else {
702                        current = node.GetParentNode();
703                    }
704                },
705                None => return "ltr".to_owned(),
706            }
707        }
708    }
709
710    /// Implements the combination of:
711    ///  - <https://html.spec.whatwg.org/multipage/#being-rendered>
712    ///  - <https://html.spec.whatwg.org/multipage/#delegating-its-rendering-to-its-children>
713    pub(crate) fn is_being_rendered_or_delegates_rendering(
714        &self,
715        pseudo_element: Option<PseudoElement>,
716    ) -> bool {
717        matches!(
718            self.owner_window()
719                .layout()
720                .node_rendering_type(self.to_trusted_node_address(), pseudo_element),
721            NodeRenderingType::Rendered | NodeRenderingType::DelegatesRendering
722        )
723    }
724
725    /// <https://html.spec.whatwg.org/multipage/#being-rendered>
726    pub(crate) fn is_being_rendered(&self, pseudo_element: Option<PseudoElement>) -> bool {
727        matches!(
728            self.owner_window()
729                .layout()
730                .node_rendering_type(self.to_trusted_node_address(), pseudo_element),
731            NodeRenderingType::Rendered
732        )
733    }
734
735    pub(crate) fn add_pending_accessibility_damage(
736        &self,
737        no_gc: &NoGC,
738        damage: AccessibilityDamage,
739    ) {
740        let document = self.owner_document_unrooted(no_gc);
741        if document.accessibility_active() {
742            document
743                .accessibility_data_mut()
744                .add_pending_accessibility_damage_for_node(self, damage);
745        }
746    }
747
748    /// Set selection information on the given node if it is an element that responds to selection.
749    /// Returns `true` if a new display list is necessary after this update.
750    pub(crate) fn set_element_selection(&self, selected: bool) -> bool {
751        debug_assert!(
752            self.downcast::<CharacterData>().is_none(),
753            "Should never be called on CharacterData"
754        );
755        self.layout_data()
756            .borrow()
757            .as_ref()
758            .is_some_and(|layout_data| layout_data.set_element_selection(selected))
759    }
760}
761
762impl Node {
763    fn ensure_rare_data(&self) -> RefMut<'_, Box<NodeRareData>> {
764        let mut rare_data = self.rare_data.borrow_mut();
765        if rare_data.is_none() {
766            *rare_data = Some(Default::default());
767        }
768        RefMut::map(rare_data, |rare_data| rare_data.as_mut().unwrap())
769    }
770
771    /// Returns true if this node is before `other` in the same connected DOM
772    /// tree.
773    pub(crate) fn is_before(&self, no_gc: &NoGC, other: &Node) -> bool {
774        let cmp = other.CompareDocumentPosition(no_gc, self);
775        if cmp & NodeConstants::DOCUMENT_POSITION_DISCONNECTED != 0 {
776            return false;
777        }
778
779        cmp & NodeConstants::DOCUMENT_POSITION_PRECEDING != 0
780    }
781
782    /// Return all registered mutation observers for this node. Lazily initialize the
783    /// raredata if it does not exist.
784    pub(crate) fn registered_mutation_observers_mut(&self) -> RefMut<'_, Vec<RegisteredObserver>> {
785        RefMut::map(self.ensure_rare_data(), |rare_data| {
786            &mut rare_data.mutation_observers
787        })
788    }
789
790    pub(crate) fn registered_mutation_observers(&self) -> Option<Ref<'_, Vec<RegisteredObserver>>> {
791        let rare_data = self.rare_data.borrow();
792        if rare_data.is_none() {
793            return None;
794        }
795        Some(Ref::map(rare_data, |rare_data| {
796            &rare_data.as_ref().unwrap().mutation_observers
797        }))
798    }
799
800    /// Add a new mutation observer for a given node.
801    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
802    pub(crate) fn add_mutation_observer(&self, observer: RegisteredObserver) {
803        self.ensure_rare_data().mutation_observers.push(observer);
804    }
805
806    /// Removes the mutation observer for a given node.
807    pub(crate) fn remove_mutation_observer(&self, observer: &MutationObserver) {
808        let mut rare_data = self.rare_data.borrow_mut();
809        let Some(rare_data) = rare_data.as_mut() else {
810            return;
811        };
812        rare_data
813            .mutation_observers
814            .retain(|registered_observer| &*registered_observer.observer != observer)
815    }
816
817    /// Returns a string that describes this node.
818    pub(crate) fn debug_str(&self) -> String {
819        format!("{:?}", self.type_id())
820    }
821
822    /// <https://dom.spec.whatwg.org/#in-a-document-tree>
823    pub(crate) fn is_in_a_document_tree(&self) -> bool {
824        self.flags.get().contains(NodeFlags::IS_IN_A_DOCUMENT_TREE)
825    }
826
827    /// Return true iff node's root is a shadow-root.
828    pub(crate) fn is_in_a_shadow_tree(&self) -> bool {
829        self.flags.get().contains(NodeFlags::IS_IN_SHADOW_TREE)
830    }
831
832    pub(crate) fn has_weird_parser_insertion_mode(&self) -> bool {
833        self.flags
834            .get()
835            .contains(NodeFlags::HAS_WEIRD_PARSER_INSERTION_MODE)
836    }
837
838    pub(crate) fn set_weird_parser_insertion_mode(&self) {
839        self.set_flag(NodeFlags::HAS_WEIRD_PARSER_INSERTION_MODE, true)
840    }
841
842    /// <https://dom.spec.whatwg.org/#connected>
843    pub(crate) fn is_connected(&self) -> bool {
844        self.flags.get().contains(NodeFlags::IS_CONNECTED)
845    }
846
847    /// Returns true if this [`Node`] is in the flat tree and false otherwise.
848    ///
849    /// **Performance**: This check isn't cheap. It must walk up the entire ancestor
850    /// chain.
851    pub(crate) fn is_in_flat_tree(&self, no_gc: &NoGC) -> bool {
852        if !self.is_connected() {
853            return false;
854        }
855
856        let mut node = UnrootedDom::from_ref(self, no_gc);
857        loop {
858            match node.parent_in_flat_tree(no_gc) {
859                FlatTreeParent::Parent(parent) => node = parent,
860                FlatTreeParent::NotInFlatTree => return false,
861                FlatTreeParent::RootNode => return true,
862            }
863        }
864    }
865
866    pub(crate) fn mark_in_ua_widget(&self) {
867        self.set_flag(NodeFlags::IS_IN_UA_WIDGET, true)
868    }
869
870    pub(crate) fn is_in_ua_widget(&self) -> bool {
871        self.flags.get().contains(NodeFlags::IS_IN_UA_WIDGET)
872    }
873
874    /// Returns the type ID of this node.
875    pub(crate) fn type_id(&self) -> NodeTypeId {
876        match *self.eventtarget.type_id() {
877            EventTargetTypeId::Node(type_id) => type_id,
878            _ => unreachable!(),
879        }
880    }
881
882    /// <https://dom.spec.whatwg.org/#concept-node-length>
883    pub(crate) fn len(&self) -> u32 {
884        match self.type_id() {
885            NodeTypeId::DocumentType => 0,
886            NodeTypeId::CharacterData(_) => self.downcast::<CharacterData>().unwrap().Length(),
887            _ => self.children_count(),
888        }
889    }
890
891    pub(crate) fn is_empty(&self) -> bool {
892        // A node is considered empty if its length is 0.
893        self.len() == 0
894    }
895
896    /// <https://dom.spec.whatwg.org/#concept-tree-index>
897    pub(crate) fn index(&self) -> u32 {
898        self.preceding_siblings().count() as u32
899    }
900
901    /// Returns true if this node has a parent.
902    pub(crate) fn has_parent(&self) -> bool {
903        self.parent_node.get().is_some()
904    }
905
906    pub(crate) fn children_count(&self) -> u32 {
907        self.children_count.get()
908    }
909
910    #[inline]
911    pub(crate) fn is_doctype(&self) -> bool {
912        self.type_id() == NodeTypeId::DocumentType
913    }
914
915    pub(crate) fn get_flag(&self, flag: NodeFlags) -> bool {
916        self.flags.get().contains(flag)
917    }
918
919    pub(crate) fn set_flag(&self, flag: NodeFlags, value: bool) {
920        let mut flags = self.flags.get();
921
922        if value {
923            flags.insert(flag);
924        } else {
925            flags.remove(flag);
926        }
927
928        self.flags.set(flags);
929    }
930
931    pub(crate) fn rev_version(&self, no_gc: &NoGC) {
932        // The new version counter is 1 plus the max of the node's current version counter,
933        // its descendants version, and the document's version. Normally, this will just be
934        // the document's version, but we do have to deal with the case where the node has moved
935        // document, so may have a higher version count than its owning document.
936        let document = UnrootedDom::upcast::<Node>(self.owner_doc_unrooted(no_gc));
937        let version = cmp::max(
938            self.inclusive_descendants_version(),
939            document.inclusive_descendants_version(),
940        ) + 1;
941
942        for node in self.inclusive_ancestors_unrooted(no_gc, ShadowIncluding::No) {
943            node.inclusive_descendants_version.set(version);
944        }
945        document.inclusive_descendants_version.set(version);
946    }
947
948    pub(crate) fn clear_layout_data(&self) {
949        self.layout_data.take();
950    }
951
952    pub(crate) fn dirty(&self, no_gc: &NoGC, damage: NodeDamage) {
953        self.rev_version(no_gc);
954        if !self.is_connected() {
955            return;
956        }
957
958        match self.type_id() {
959            NodeTypeId::CharacterData(CharacterDataTypeId::Text(..)) => {
960                // This drops the cached `TextRun` that is stored here, ultimately meaning that
961                // shaped text will no longer be reused for this text node.
962                *self.layout_data.borrow_mut() = None;
963
964                // For content changes in text nodes, we should accurately use
965                // [`NodeDamage::ContentOrHeritage`] to mark the parent node, thereby
966                // reducing the scope of incremental box tree construction.
967                if let Some(parent) = self.parent_node.get() {
968                    parent.dirty(no_gc, NodeDamage::ContentOrHeritage);
969                }
970
971                if damage == NodeDamage::Other {
972                    self.add_pending_accessibility_damage(no_gc, AccessibilityDamage::Node);
973                }
974            },
975            NodeTypeId::Element(_) => self.downcast::<Element>().unwrap().restyle(no_gc, damage),
976            NodeTypeId::DocumentFragment(DocumentFragmentTypeId::ShadowRoot) => self
977                .downcast::<ShadowRoot>()
978                .unwrap()
979                .Host()
980                .upcast::<Element>()
981                .restyle(no_gc, damage),
982            _ => {},
983        };
984    }
985
986    /// The maximum version number of this node's descendants, including itself
987    pub(crate) fn inclusive_descendants_version(&self) -> u64 {
988        self.inclusive_descendants_version.get()
989    }
990
991    /// Iterates over this node and all its descendants, in preorder.
992    pub(crate) fn traverse_preorder(&self, shadow_including: ShadowIncluding) -> TreeIterator {
993        TreeIterator::new(self, shadow_including)
994    }
995
996    /// Iterates over this node and all its descendants, in preorder.
997    /// We take &NoGC to prevent GC which allows us to avoid rooting.
998    pub(crate) fn traverse_preorder_unrooted<'b>(
999        &self,
1000        no_gc: &'b NoGC,
1001        shadow_including: ShadowIncluding,
1002    ) -> UnrootedTreeIterator<'b> {
1003        UnrootedTreeIterator::new(self, shadow_including, no_gc)
1004    }
1005
1006    pub(crate) fn inclusively_following_siblings(
1007        &self,
1008    ) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1009        SimpleNodeIterator::new(Some(DomRoot::from_ref(self)), |n| n.GetNextSibling())
1010    }
1011
1012    pub(crate) fn inclusively_following_siblings_unrooted<'b>(
1013        &self,
1014        no_gc: &'b NoGC,
1015    ) -> impl Iterator<Item = UnrootedDom<'b, Node>> + use<'b> {
1016        UnrootedSimpleNodeIterator::new(
1017            Some(UnrootedDom::from_ref(self, no_gc)),
1018            |n, no_gc| n.get_next_sibling_unrooted(no_gc),
1019            no_gc,
1020        )
1021    }
1022
1023    pub(crate) fn inclusively_preceding_siblings_unrooted<'b>(
1024        &self,
1025        no_gc: &'b NoGC,
1026    ) -> impl Iterator<Item = UnrootedDom<'b, Node>> + use<'b> {
1027        UnrootedSimpleNodeIterator::new(
1028            Some(UnrootedDom::from_ref(self, no_gc)),
1029            |n, no_gc| n.get_previous_sibling_unrooted(no_gc),
1030            no_gc,
1031        )
1032    }
1033
1034    pub(crate) fn common_ancestor(
1035        &self,
1036        other: &Node,
1037        shadow_including: ShadowIncluding,
1038    ) -> Option<DomRoot<Node>> {
1039        self.inclusive_ancestors(shadow_including).find(|ancestor| {
1040            other
1041                .inclusive_ancestors(shadow_including)
1042                .any(|node| node == *ancestor)
1043        })
1044    }
1045
1046    pub(crate) fn common_ancestor_in_flat_tree(
1047        &self,
1048        no_gc: &NoGC,
1049        other: &Node,
1050    ) -> Option<DomRoot<Node>> {
1051        self.inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1052            .find(|ancestor| {
1053                other
1054                    .inclusive_ancestors_in_flat_tree_unrooted(no_gc)
1055                    .any(|node| node == *ancestor)
1056            })
1057            .map(|node| node.as_rooted())
1058    }
1059
1060    pub(crate) fn following_flat_tree_nodes_unrooted<'no_gc>(
1061        &self,
1062        no_gc: &'no_gc NoGC,
1063    ) -> UnrootedFollowingFlatTreeNodesTraversal<'no_gc> {
1064        UnrootedFollowingFlatTreeNodesTraversal::new(self, no_gc)
1065    }
1066
1067    /// <https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor>
1068    pub(crate) fn is_inclusive_ancestor_of(&self, child: &Node) -> bool {
1069        // > An inclusive ancestor is an object or one of its ancestors.
1070        self == child || self.is_ancestor_of(child)
1071    }
1072
1073    /// <https://dom.spec.whatwg.org/#concept-tree-ancestor>
1074    pub(crate) fn is_ancestor_of(&self, possible_descendant: &Node) -> bool {
1075        // > An object A is called an ancestor of an object B if and only if B is a descendant of A.
1076        let mut current = &possible_descendant.parent_node;
1077        let mut done = false;
1078
1079        while let Some(node) = current.if_is_some(|node| {
1080            done = node == self;
1081            &node.parent_node
1082        }) {
1083            if done {
1084                break;
1085            }
1086            current = node
1087        }
1088        done
1089    }
1090
1091    /// <https://dom.spec.whatwg.org/#concept-tree-host-including-inclusive-ancestor>
1092    fn is_host_including_inclusive_ancestor(&self, child: &Node) -> bool {
1093        // An object A is a host-including inclusive ancestor of an object B, if either A is an inclusive ancestor of B,
1094        // or if B’s root has a non-null host and A is a host-including inclusive ancestor of B’s root’s host.
1095        self.is_inclusive_ancestor_of(child) ||
1096            child
1097                .GetRootNode(&GetRootNodeOptions::empty())
1098                .downcast::<DocumentFragment>()
1099                .and_then(|fragment| fragment.host())
1100                .is_some_and(|host| self.is_host_including_inclusive_ancestor(host.upcast()))
1101    }
1102
1103    /// <https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor>
1104    pub(crate) fn is_shadow_including_inclusive_ancestor_of(&self, node: &Node) -> bool {
1105        node.inclusive_ancestors(ShadowIncluding::Yes)
1106            .any(|ancestor| &*ancestor == self)
1107    }
1108
1109    pub(crate) fn following_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1110        SimpleNodeIterator::new(self.GetNextSibling(), |n| n.GetNextSibling())
1111    }
1112
1113    pub(crate) fn preceding_siblings(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1114        SimpleNodeIterator::new(self.GetPreviousSibling(), |n| n.GetPreviousSibling())
1115    }
1116
1117    pub(crate) fn following_nodes(
1118        &self,
1119        root: &Node,
1120        shadow_including: ShadowIncluding,
1121    ) -> FollowingNodeIterator {
1122        FollowingNodeIterator::new(
1123            Some(DomRoot::from_ref(self)),
1124            DomRoot::from_ref(root),
1125            shadow_including,
1126        )
1127    }
1128
1129    pub(crate) fn following_nodes_unrooted<'b>(
1130        &self,
1131        no_gc: &'b NoGC,
1132        root: &Node,
1133        shadow_including: ShadowIncluding,
1134    ) -> UnrootedFollowingNodeIterator<'b> {
1135        UnrootedFollowingNodeIterator::new(
1136            Some(UnrootedDom::from_ref(self, no_gc)),
1137            UnrootedDom::from_ref(root, no_gc),
1138            shadow_including,
1139            no_gc,
1140        )
1141    }
1142
1143    pub(crate) fn preceding_nodes(&self, root: &Node) -> PrecedingNodeIterator {
1144        PrecedingNodeIterator::new(Some(DomRoot::from_ref(self)), DomRoot::from_ref(root))
1145    }
1146
1147    pub(crate) fn preceding_nodes_unrooted<'b>(
1148        &self,
1149        no_gc: &'b NoGC,
1150        root: &Node,
1151    ) -> UnrootedPrecedingNodeIterator<'b> {
1152        UnrootedPrecedingNodeIterator::new(
1153            Some(UnrootedDom::from_ref(self, no_gc)),
1154            UnrootedDom::from_ref(root, no_gc),
1155            no_gc,
1156        )
1157    }
1158
1159    /// Return an iterator that moves from `self` down the tree, choosing the last child
1160    /// at each step of the way.
1161    pub(crate) fn descending_last_children(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1162        SimpleNodeIterator::new(self.GetLastChild(), |n| n.GetLastChild())
1163    }
1164
1165    pub(crate) fn descending_last_children_unrooted<'b>(
1166        &self,
1167        no_gc: &'b NoGC,
1168    ) -> impl Iterator<Item = UnrootedDom<'b, Node>> {
1169        UnrootedSimpleNodeIterator::new(
1170            self.get_last_child_unrooted(no_gc),
1171            |n, no_gc| n.get_last_child_unrooted(no_gc),
1172            no_gc,
1173        )
1174    }
1175
1176    pub(crate) fn is_parent_of(&self, child: &Node) -> bool {
1177        child
1178            .parent_node
1179            .get()
1180            .is_some_and(|parent| &*parent == self)
1181    }
1182
1183    pub(crate) fn to_trusted_node_address(&self) -> TrustedNodeAddress {
1184        TrustedNodeAddress(self as *const Node as *const libc::c_void)
1185    }
1186
1187    /// Return the node that establishes a containing block for this node.
1188    pub(crate) fn containing_block_node_without_reflow(&self) -> Option<DomRoot<Node>> {
1189        self.owner_window()
1190            .containing_block_node_query_without_reflow(self)
1191    }
1192
1193    pub(crate) fn padding(&self) -> Option<PhysicalSides<Au>> {
1194        self.owner_window().padding_query_without_reflow(self)
1195    }
1196
1197    pub(crate) fn content_box(&self, cx: &mut JSContext) -> Option<Rect<Au, CSSPixel>> {
1198        self.owner_window()
1199            .box_area_query(cx, self, BoxAreaType::Content, false)
1200    }
1201
1202    pub(crate) fn border_box(&self, cx: &mut JSContext) -> Option<Rect<Au, CSSPixel>> {
1203        self.owner_window()
1204            .box_area_query(cx, self, BoxAreaType::Border, false)
1205    }
1206
1207    pub(crate) fn border_box_without_reflow(&self) -> Option<Rect<Au, CSSPixel>> {
1208        self.owner_window()
1209            .box_area_query_without_reflow(self, BoxAreaType::Border, false)
1210    }
1211
1212    pub(crate) fn padding_box(&self, cx: &mut JSContext) -> Option<Rect<Au, CSSPixel>> {
1213        self.owner_window()
1214            .box_area_query(cx, self, BoxAreaType::Padding, false)
1215    }
1216
1217    pub(crate) fn padding_box_without_reflow(&self) -> Option<Rect<Au, CSSPixel>> {
1218        self.owner_window()
1219            .box_area_query_without_reflow(self, BoxAreaType::Padding, false)
1220    }
1221
1222    pub(crate) fn border_boxes(&self, cx: &mut JSContext) -> CSSPixelRectVec {
1223        self.owner_window()
1224            .box_areas_query(cx, self, BoxAreaType::Border)
1225    }
1226
1227    pub(crate) fn client_rect(&self, cx: &mut JSContext) -> Rect<i32, CSSPixel> {
1228        self.owner_window().client_rect_query(cx, self)
1229    }
1230
1231    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollwidth>
1232    /// <https://drafts.csswg.org/cssom-view/#dom-element-scrollheight>
1233    pub(crate) fn scroll_area(&self, cx: &mut JSContext) -> Rect<i32, CSSPixel> {
1234        // "1. Let document be the element’s node document.""
1235        let document = self.owner_doc();
1236
1237        // "2. If document is not the active document, return zero and terminate these steps.""
1238        if !document.is_active() {
1239            return Rect::zero();
1240        }
1241
1242        // "3. Let viewport width/height be the width of the viewport excluding the width/height of the
1243        // scroll bar, if any, or zero if there is no viewport."
1244        let window = document.window();
1245        let viewport = Size2D::new(window.InnerWidth(), window.InnerHeight()).cast_unit();
1246
1247        let in_quirks_mode = document.quirks_mode() == QuirksMode::Quirks;
1248        let is_root = self.downcast::<Element>().is_some_and(|e| e.is_root());
1249        let is_body_element = self
1250            .downcast::<HTMLElement>()
1251            .is_some_and(|e| e.is_body_element());
1252
1253        // "4. If the element is the root element and document is not in quirks mode
1254        // return max(viewport scrolling area width/height, viewport width/height)."
1255        // "5. If the element is the body element, document is in quirks mode and the
1256        // element is not potentially scrollable, return max(viewport scrolling area
1257        // width, viewport width)."
1258        if (is_root && !in_quirks_mode) || (is_body_element && in_quirks_mode) {
1259            let viewport_scrolling_area = window.scrolling_area_query(cx, None);
1260            return Rect::new(
1261                viewport_scrolling_area.origin,
1262                viewport_scrolling_area.size.max(viewport),
1263            );
1264        }
1265
1266        // "6. If the element does not have any associated box return zero and terminate
1267        // these steps."
1268        // "7. Return the width of the element’s scrolling area."
1269        window.scrolling_area_query(cx, Some(self))
1270    }
1271
1272    pub(crate) fn effective_overflow(&self, cx: &mut JSContext) -> Option<AxesOverflow> {
1273        self.owner_window().query_effective_overflow(cx, self)
1274    }
1275
1276    pub(crate) fn effective_overflow_without_reflow(&self) -> Option<AxesOverflow> {
1277        self.owner_window()
1278            .query_effective_overflow_without_reflow(self)
1279    }
1280
1281    /// <https://dom.spec.whatwg.org/#dom-childnode-before>
1282    pub(crate) fn before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1283        // Step 1.
1284        let parent = &self.parent_node;
1285
1286        // Step 2.
1287        let parent = match parent.get() {
1288            None => return Ok(()),
1289            Some(parent) => parent,
1290        };
1291
1292        // Step 3.
1293        let viable_previous_sibling = first_node_not_in(self.preceding_siblings(), &nodes);
1294
1295        // Step 4.
1296        let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1297
1298        // Step 5.
1299        let viable_previous_sibling = match viable_previous_sibling {
1300            Some(ref viable_previous_sibling) => viable_previous_sibling.next_sibling.get(),
1301            None => parent.first_child.get(),
1302        };
1303
1304        // Step 6.
1305        Node::pre_insert(cx, &node, &parent, viable_previous_sibling.as_deref())?;
1306
1307        Ok(())
1308    }
1309
1310    /// <https://dom.spec.whatwg.org/#dom-childnode-after>
1311    pub(crate) fn after(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1312        // Step 1.
1313        let parent = &self.parent_node;
1314
1315        // Step 2.
1316        let parent = match parent.get() {
1317            None => return Ok(()),
1318            Some(parent) => parent,
1319        };
1320
1321        // Step 3.
1322        let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
1323
1324        // Step 4.
1325        let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1326
1327        // Step 5.
1328        Node::pre_insert(cx, &node, &parent, viable_next_sibling.as_deref())?;
1329
1330        Ok(())
1331    }
1332
1333    /// <https://dom.spec.whatwg.org/#dom-childnode-replacewith>
1334    pub(crate) fn replace_with(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1335        // Step 1. Let parent be this’s parent.
1336        let Some(parent) = self.GetParentNode() else {
1337            // Step 2. If parent is null, then return.
1338            return Ok(());
1339        };
1340
1341        // Step 3. Let viableNextSibling be this’s first following sibling not in nodes; otherwise null.
1342        let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
1343
1344        // Step 4. Let node be the result of converting nodes into a node, given nodes and this’s node document.
1345        let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1346
1347        if self.parent_node == Some(&*parent) {
1348            // Step 5. If this’s parent is parent, replace this with node within parent.
1349            parent.ReplaceChild(cx, &node, self)?;
1350        } else {
1351            // Step 6. Otherwise, pre-insert node into parent before viableNextSibling.
1352            Node::pre_insert(cx, &node, &parent, viable_next_sibling.as_deref())?;
1353        }
1354        Ok(())
1355    }
1356
1357    /// <https://dom.spec.whatwg.org/#dom-parentnode-prepend>
1358    pub(crate) fn prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1359        // Step 1.
1360        let doc = self.owner_doc();
1361        let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1362        // Step 2.
1363        let first_child = self.first_child.get();
1364        Node::pre_insert(cx, &node, self, first_child.as_deref()).map(|_| ())
1365    }
1366
1367    /// <https://dom.spec.whatwg.org/#dom-parentnode-append>
1368    pub(crate) fn append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1369        // Step 1.
1370        let doc = self.owner_doc();
1371        let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1372        // Step 2.
1373        self.AppendChild(cx, &node).map(|_| ())
1374    }
1375
1376    /// <https://dom.spec.whatwg.org/#dom-parentnode-replacechildren>
1377    pub(crate) fn replace_children(
1378        &self,
1379        cx: &mut JSContext,
1380        nodes: Vec<NodeOrString>,
1381    ) -> ErrorResult {
1382        // Step 1. Let node be the result of converting nodes into a node given nodes and this’s
1383        // node document.
1384        let doc = self.owner_doc();
1385        let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1386
1387        // Step 2. Ensure pre-insert validity of node into this before null.
1388        Node::ensure_pre_insertion_validity(cx.no_gc(), &node, self, None, &[])?;
1389
1390        // Step 3. Replace all with node within this.
1391        Node::replace_all(cx, Some(&node), self);
1392        Ok(())
1393    }
1394
1395    /// <https://dom.spec.whatwg.org/#dom-parentnode-movebefore>
1396    pub(crate) fn move_before(
1397        &self,
1398        cx: &mut JSContext,
1399        node: &Node,
1400        child: Option<&Node>,
1401    ) -> ErrorResult {
1402        // Step 1. Let referenceChild be child.
1403        // Step 2. If referenceChild is node, then set referenceChild to node’s next sibling.
1404        let reference_child_root;
1405        let reference_child = match child {
1406            Some(child) if child == node => {
1407                reference_child_root = node.GetNextSibling();
1408                reference_child_root.as_deref()
1409            },
1410            _ => child,
1411        };
1412
1413        // Step 3. Move node into this before referenceChild.
1414        Node::move_fn(cx, node, self, reference_child)
1415    }
1416
1417    /// <https://dom.spec.whatwg.org/#move>
1418    fn move_fn(
1419        cx: &mut JSContext,
1420        node: &Node,
1421        new_parent: &Node,
1422        child: Option<&Node>,
1423    ) -> ErrorResult {
1424        // Step 1. If newParent’s shadow-including root is not the same as node’s shadow-including
1425        // root, then throw a "HierarchyRequestError" DOMException.
1426        // This has the side effect of ensuring that a move is only performed if newParent’s
1427        // connected is node’s connected.
1428        let mut options = GetRootNodeOptions::empty();
1429        options.composed = true;
1430        if new_parent.GetRootNode(&options) != node.GetRootNode(&options) {
1431            return Err(Error::HierarchyRequest(Some(
1432                "The `newParent` node's shadow root is not the same as the `node`'s shadow root"
1433                    .into(),
1434            )));
1435        }
1436
1437        // Step 2. If node is a host-including inclusive ancestor of newParent, then throw a
1438        // "HierarchyRequestError" DOMException.
1439        if node.is_host_including_inclusive_ancestor(new_parent) {
1440            return Err(Error::HierarchyRequest(Some(
1441                "`node` node cannot be the inclusive ancestor of the `newParent` node".into(),
1442            )));
1443        }
1444
1445        // Step 3. If child is non-null and its parent is not newParent, then throw a
1446        // "NotFoundError" DOMException.
1447        if let Some(child) = child &&
1448            !new_parent.is_parent_of(child)
1449        {
1450            return Err(Error::NotFound(Some(
1451                "`child` node's parent node is not `newParent`".into(),
1452            )));
1453        }
1454
1455        // Step 4. If node is not an Element or a CharacterData node, then throw a
1456        // "HierarchyRequestError" DOMException.
1457        // Step 5. If node is a Text node and newParent is a document, then throw a
1458        // "HierarchyRequestError" DOMException.
1459        match node.type_id() {
1460            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => {
1461                if new_parent.is::<Document>() {
1462                    return Err(Error::HierarchyRequest(Some(
1463                        "`node` cannot be a text node when `newParent` is a document".into(),
1464                    )));
1465                }
1466            },
1467            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) |
1468            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) |
1469            NodeTypeId::Element(_) => (),
1470            NodeTypeId::DocumentFragment(_) |
1471            NodeTypeId::DocumentType |
1472            NodeTypeId::Document(_) |
1473            NodeTypeId::Attr => {
1474                return Err(Error::HierarchyRequest(Some(
1475                    "To move `node` into a `newParent`, it must be an Element".into(),
1476                )));
1477            },
1478        }
1479
1480        // Step 6. If newParent is a document, node is an Element node, and either newParent has an
1481        // element child, child is a doctype, or child is non-null and a doctype is following child
1482        // then throw a "HierarchyRequestError" DOMException.
1483        if new_parent.is::<Document>() && node.is::<Element>() {
1484            // either newParent has an element child
1485            if new_parent.child_elements().next().is_some() {
1486                return Err(Error::HierarchyRequest(Some(
1487                    "`newParent` document cannot have an element child".into(),
1488                )));
1489            }
1490
1491            // child is a doctype
1492            // or child is non-null and a doctype is following child
1493            if child.is_some_and(|child| {
1494                child
1495                    .inclusively_following_siblings_unrooted(cx.no_gc())
1496                    .any(|child| child.is_doctype())
1497            }) {
1498                return Err(Error::HierarchyRequest(Some(
1499                    "`child` node has a document node following it".into(),
1500                )));
1501            }
1502        }
1503
1504        // Step 7. Let oldParent be node’s parent.
1505        // Step 8. Assert: oldParent is non-null.
1506        let old_parent = node
1507            .parent_node
1508            .get()
1509            .expect("old_parent should always be initialized");
1510
1511        // Step 9. Run the live range pre-remove steps, given node.
1512        let document = node.owner_doc_unrooted(cx.no_gc());
1513        let mut cached_index = None;
1514        let mut lazy_index = || *cached_index.get_or_insert_with(|| node.index());
1515        if let Some(selection) = document.selection() {
1516            selection.pre_remove_steps(node, &old_parent, &mut lazy_index);
1517        }
1518        document.live_range_pre_remove_steps(cx.no_gc(), node, &old_parent, &mut lazy_index);
1519
1520        // TODO Step 10. For each NodeIterator object iterator whose root’s node document is node’s
1521        // node document: run the NodeIterator pre-remove steps given node and iterator.
1522
1523        // Step 11. Let oldPreviousSibling be node’s previous sibling.
1524        let old_previous_sibling = node.prev_sibling.get();
1525
1526        // Step 12. Let oldNextSibling be node’s next sibling.
1527        let old_next_sibling = node.next_sibling.get();
1528
1529        let prev_sibling = node.GetPreviousSibling();
1530        match prev_sibling {
1531            None => {
1532                old_parent
1533                    .first_child
1534                    .set(node.next_sibling.get().as_deref());
1535            },
1536            Some(ref prev_sibling) => {
1537                prev_sibling
1538                    .next_sibling
1539                    .set(node.next_sibling.get().as_deref());
1540            },
1541        }
1542        let next_sibling = node.GetNextSibling();
1543        match next_sibling {
1544            None => {
1545                old_parent
1546                    .last_child
1547                    .set(node.prev_sibling.get().as_deref());
1548            },
1549            Some(ref next_sibling) => {
1550                next_sibling
1551                    .prev_sibling
1552                    .set(node.prev_sibling.get().as_deref());
1553            },
1554        }
1555
1556        // Step 13. Remove node from oldParent’s children.
1557        old_parent.move_child(cx, node);
1558
1559        // Step 14. If node is assigned, then run assign slottables for node’s assigned slot.
1560        if let Some(slot) = node.assigned_slot() {
1561            slot.assign_slottables(cx);
1562        }
1563
1564        // Step 15. If oldParent’s root is a shadow root, and oldParent is a slot whose assigned
1565        // nodes is empty, then run signal a slot change for oldParent.
1566        if old_parent.is_in_a_shadow_tree() &&
1567            let Some(slot_element) = old_parent.downcast::<HTMLSlotElement>() &&
1568            !slot_element.has_assigned_nodes()
1569        {
1570            slot_element.signal_a_slot_change(cx);
1571        }
1572
1573        // Step 16. If node has an inclusive descendant that is a slot:
1574        let has_slot_descendant = node
1575            .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::No)
1576            .any(|element| element.is::<HTMLSlotElement>());
1577        if has_slot_descendant {
1578            // Step 16.1. Run assign slottables for a tree with oldParent’s root.
1579            old_parent
1580                .GetRootNode(&GetRootNodeOptions::empty())
1581                .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1582
1583            // Step 16.2. Run assign slottables for a tree with node.
1584            node.assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1585        }
1586
1587        // Step 17. Add transient registered observers given node and oldParent.
1588        // TODO: Implement this.
1589
1590        // Step 18. If child is non-null:
1591        if let Some(child) = child {
1592            // Steps 18.1-18.2: The live range move steps.
1593            let document = new_parent.owner_doc_unrooted(cx.no_gc());
1594            if let Some(selection) = document.selection() {
1595                selection.insert_steps(new_parent, child, 1);
1596            }
1597            document.live_range_insert_steps(cx.no_gc(), new_parent, child, 1);
1598        }
1599
1600        // Step 19. Let newPreviousSibling be child’s previous sibling if child is non-null, and
1601        // newParent’s last child otherwise.
1602        let new_previous_sibling = child.map_or_else(
1603            || new_parent.last_child.get(),
1604            |child| child.prev_sibling.get(),
1605        );
1606
1607        // Step 20. If child is null, then append node to newParent’s children.
1608        // Step 21. Otherwise, insert node into newParent’s children before child’s index.
1609        new_parent.add_child(cx, MoveOrInsert::Move, node, child);
1610
1611        // Step 22. If newParent is a shadow host whose shadow root’s slot assignment is "named" and
1612        // node is a slottable, then assign a slot for node.
1613        if let Some(shadow_root) = new_parent
1614            .downcast::<Element>()
1615            .and_then(Element::shadow_root) &&
1616            shadow_root.SlotAssignment() == SlotAssignmentMode::Named &&
1617            (node.is::<Element>() || node.is::<Text>())
1618        {
1619            rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(node)));
1620            slottable.assign_a_slot(cx);
1621        }
1622
1623        // Step 23. If newParent’s root is a shadow root, and newParent is a slot whose assigned
1624        // nodes is empty, then run signal a slot change for newParent.
1625        if new_parent.is_in_a_shadow_tree() &&
1626            let Some(slot_element) = new_parent.downcast::<HTMLSlotElement>() &&
1627            !slot_element.has_assigned_nodes()
1628        {
1629            slot_element.signal_a_slot_change(cx);
1630        }
1631
1632        // Step 24. Run assign slottables for a tree with node’s root.
1633        node.GetRootNode(&GetRootNodeOptions::empty())
1634            .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1635
1636        // Step 25. For each shadow-including inclusive descendant inclusiveDescendant of node, in
1637        // shadow-including tree order:
1638        for descendant in node.traverse_preorder(ShadowIncluding::Yes) {
1639            // Step 25.1. Let isSubtreeRoot be true if inclusiveDescendant is node; otherwise false.
1640            let is_subtree_root = descendant.deref() == node;
1641            // Step 25.2. Run the moving steps with inclusiveDescendant, isSubtreeRoot, and oldParent.
1642            vtable_for(&descendant)
1643                .moving_steps(cx, &MoveContext::new(&old_parent, is_subtree_root));
1644
1645            // Step 25.3. If inclusiveDescendant is custom and newParent is connected,
1646            if let Some(descendant) = descendant.downcast::<Element>() &&
1647                descendant.is_custom() &&
1648                new_parent.is_connected()
1649            {
1650                // then enqueue a custom element callback reaction with
1651                // inclusiveDescendant, callback name "connectedMoveCallback", and « ».
1652                let custom_element_reaction_stack = ScriptThread::custom_element_reaction_stack();
1653                custom_element_reaction_stack.enqueue_callback_reaction(
1654                    cx,
1655                    descendant,
1656                    CallbackReaction::ConnectedMove,
1657                    None,
1658                );
1659            }
1660        }
1661
1662        // Step 26. Queue a tree mutation record for oldParent with « », « node »,
1663        // oldPreviousSibling, and oldNextSibling.
1664        let moved = [node];
1665        let mutation = LazyCell::new(|| Mutation::ChildList {
1666            added: None,
1667            removed: Some(&moved),
1668            prev: old_previous_sibling.as_deref(),
1669            next: old_next_sibling.as_deref(),
1670        });
1671        MutationObserver::queue_a_mutation_record(cx, &old_parent, mutation);
1672
1673        // Step 27. Queue a tree mutation record for newParent with « node », « »,
1674        // newPreviousSibling, and child.
1675        let mutation = LazyCell::new(|| Mutation::ChildList {
1676            added: Some(&moved),
1677            removed: None,
1678            prev: new_previous_sibling.as_deref(),
1679            next: child,
1680        });
1681        MutationObserver::queue_a_mutation_record(cx, new_parent, mutation);
1682
1683        Ok(())
1684    }
1685
1686    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselector>
1687    #[allow(unsafe_code)]
1688    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
1689    pub(crate) fn query_selector(
1690        &self,
1691        no_gc: &NoGC,
1692        selectors: DOMString,
1693    ) -> Fallible<Option<DomRoot<Element>>> {
1694        // > The querySelector(selectors) method steps are to return the first result of running scope-match
1695        // > a selectors string selectors against this, if the result is not an empty list; otherwise null.
1696        let document_url = self.owner_document().url().get_arc();
1697
1698        // If there are any duplicate ids, their targets may need to be updated in the id map before
1699        // layout runs, so that the map can gather their elements in DOM order.
1700        self.owner_document()
1701            .id_map()
1702            .resolve_all(no_gc, self.owner_doc().upcast());
1703
1704        // SAFETY: traced_node is unrooted, but we have a reference to "self" so it won't be freed.
1705        let traced_node = Dom::from_ref(self);
1706
1707        let first_matching_element = with_layout_state(|| {
1708            let layout_node: LayoutDom<'_, _> = unsafe { traced_node.to_layout() };
1709            ServoDangerousStyleNode::from(layout_node)
1710                .scope_match_a_selectors_string::<QueryFirst>(document_url, &selectors.str())
1711        })?;
1712
1713        Ok(first_matching_element.map(ServoDangerousStyleElement::rooted))
1714    }
1715
1716    /// <https://dom.spec.whatwg.org/#dom-parentnode-queryselectorall>
1717    #[allow(unsafe_code)]
1718    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
1719    pub(crate) fn query_selector_all(
1720        &self,
1721        cx: &mut JSContext,
1722        selectors: DOMString,
1723    ) -> Fallible<DomRoot<NodeList>> {
1724        // > The querySelectorAll(selectors) method steps are to return the static result of running scope-match
1725        // > a selectors string selectors against this.
1726        let document_url = self.owner_document().url().get_arc();
1727
1728        // If there are any duplicate ids, their targets may need to be updated in the id map before
1729        // layout runs, so that the map can gather their elements in DOM order.
1730        self.owner_document()
1731            .id_map()
1732            .resolve_all(cx.no_gc(), self.owner_doc().upcast());
1733
1734        let unrooted_node = UnrootedDom::from_ref(self, cx.no_gc());
1735        let matching_elements = with_layout_state(|| {
1736            let layout_node: LayoutDom<'_, _> = unsafe { unrooted_node.to_layout() };
1737            ServoDangerousStyleNode::from(layout_node)
1738                .scope_match_a_selectors_string::<QueryAll>(document_url, &selectors.str())
1739        })?;
1740        let iter = matching_elements
1741            .into_iter()
1742            .map(ServoDangerousStyleElement::rooted)
1743            .map(DomRoot::upcast::<Node>);
1744
1745        // NodeList::new_simple_list immediately collects the iterator, so we're not leaking LayoutDom
1746        // elements here.
1747        Ok(NodeList::new_simple_list(cx, &self.owner_window(), iter))
1748    }
1749
1750    pub(crate) fn ancestors(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1751        SimpleNodeIterator::new(self.GetParentNode(), |n| n.GetParentNode())
1752    }
1753
1754    pub(crate) fn ancestors_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedAncestorIterator<'a> {
1755        UnrootedSimpleNodeIterator::new(
1756            self.get_parent_node_unrooted(no_gc),
1757            |node, no_gc| node.get_parent_node_unrooted(no_gc),
1758            no_gc,
1759        )
1760    }
1761
1762    /// <https://dom.spec.whatwg.org/#concept-shadow-including-inclusive-ancestor>
1763    pub(crate) fn inclusive_ancestors(
1764        &self,
1765        shadow_including: ShadowIncluding,
1766    ) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1767        SimpleNodeIterator::new(Some(DomRoot::from_ref(self)), move |n| {
1768            if shadow_including == ShadowIncluding::Yes &&
1769                let Some(shadow_root) = n.downcast::<ShadowRoot>()
1770            {
1771                return Some(DomRoot::from_ref(shadow_root.Host().upcast::<Node>()));
1772            }
1773            n.GetParentNode()
1774        })
1775    }
1776
1777    pub(crate) fn inclusive_ancestors_unrooted<'a>(
1778        &self,
1779        no_gc: &'a NoGC,
1780        shadow_including: ShadowIncluding,
1781    ) -> impl Iterator<Item = UnrootedDom<'a, Node>> + use<'a> {
1782        UnrootedSimpleNodeIterator::new(
1783            Some(UnrootedDom::from_ref(self, no_gc)),
1784            move |node, no_gc| {
1785                if shadow_including == ShadowIncluding::Yes &&
1786                    let Some(shadow_root) = node.downcast::<ShadowRoot>()
1787                {
1788                    return Some(UnrootedDom::upcast(shadow_root.host_unrooted(no_gc)));
1789                }
1790                node.get_parent_node_unrooted(no_gc)
1791            },
1792            no_gc,
1793        )
1794    }
1795
1796    pub(crate) fn ancestors_in_flat_tree_unrooted<'a>(
1797        &self,
1798        no_gc: &'a NoGC,
1799    ) -> UnrootedAncestorIterator<'a> {
1800        UnrootedSimpleNodeIterator::new(
1801            self.parent_in_flat_tree(no_gc).into_parent(),
1802            |node, no_gc| node.parent_in_flat_tree(no_gc).into_parent(),
1803            no_gc,
1804        )
1805    }
1806
1807    pub(crate) fn inclusive_ancestors_in_flat_tree_unrooted<'a>(
1808        &self,
1809        no_gc: &'a NoGC,
1810    ) -> UnrootedAncestorIterator<'a> {
1811        UnrootedSimpleNodeIterator::new(
1812            Some(UnrootedDom::from_ref(self, no_gc)),
1813            |node, no_gc| node.parent_in_flat_tree(no_gc).into_parent(),
1814            no_gc,
1815        )
1816    }
1817
1818    /// Use this if you have a Node already as this skips the cast. Otherwise you can use the [`NodeTraits::owner_document`].
1819    pub(crate) fn owner_doc(&self) -> DomRoot<Document> {
1820        self.owner_doc.get().unwrap()
1821    }
1822
1823    /// See [`owner_doc`]
1824    pub(crate) fn owner_doc_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Document> {
1825        self.owner_doc.get_unrooted(no_gc).unwrap()
1826    }
1827
1828    pub(crate) fn set_owner_doc(&self, document: &Document) {
1829        self.owner_doc.set(Some(document));
1830    }
1831
1832    pub(crate) fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>> {
1833        self.rare_data
1834            .borrow()
1835            .as_ref()?
1836            .containing_shadow_root
1837            .as_ref()
1838            .map(|shadow_root| DomRoot::from_ref(&**shadow_root))
1839    }
1840
1841    pub(crate) fn containing_shadow_root_unrooted<'a>(
1842        &self,
1843        no_gc: &'a NoGC,
1844    ) -> Option<UnrootedDom<'a, ShadowRoot>> {
1845        self.rare_data
1846            .borrow()
1847            .as_ref()?
1848            .containing_shadow_root
1849            .as_ref()
1850            .map(|shadow_root| shadow_root.as_unrooted(no_gc))
1851    }
1852
1853    pub(crate) fn set_containing_shadow_root(&self, shadow_root: Option<&ShadowRoot>) {
1854        self.ensure_rare_data().containing_shadow_root = shadow_root.map(Dom::from_ref);
1855    }
1856
1857    pub(crate) fn is_in_html_doc(&self) -> bool {
1858        self.owner_doc().is_html_document()
1859    }
1860
1861    pub(crate) fn is_connected_with_browsing_context(&self, no_gc: &NoGC) -> bool {
1862        self.is_connected() &&
1863            self.owner_document_unrooted(no_gc)
1864                .browsing_context()
1865                .is_some()
1866    }
1867
1868    pub(crate) fn children(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1869        SimpleNodeIterator::new(self.GetFirstChild(), |n| n.GetNextSibling())
1870    }
1871
1872    pub(crate) fn children_unrooted<'a>(
1873        &self,
1874        no_gc: &'a NoGC,
1875    ) -> impl Iterator<Item = UnrootedDom<'a, Node>> + use<'a> {
1876        UnrootedSimpleNodeIterator::new(
1877            self.get_first_child_unrooted(no_gc),
1878            |n, no_gc| n.get_next_sibling_unrooted(no_gc),
1879            no_gc,
1880        )
1881    }
1882
1883    pub(crate) fn rev_children(&self) -> impl Iterator<Item = DomRoot<Node>> + use<> {
1884        SimpleNodeIterator::new(self.GetLastChild(), |n| n.GetPreviousSibling())
1885    }
1886
1887    /// Returns the children that are Elements
1888    pub(crate) fn child_elements(&self) -> impl Iterator<Item = DomRoot<Element>> + use<> {
1889        self.children()
1890            .filter_map(DomRoot::downcast as fn(_) -> _)
1891            .peekable()
1892    }
1893
1894    pub(crate) fn child_elements_unrooted<'a>(
1895        &self,
1896        no_gc: &'a NoGC,
1897    ) -> impl Iterator<Item = UnrootedDom<'a, Element>> + use<'a> {
1898        self.children_unrooted(no_gc)
1899            .filter_map(UnrootedDom::downcast)
1900            .peekable()
1901    }
1902
1903    pub(crate) fn remove_self(&self, cx: &mut JSContext) {
1904        if let Some(ref parent) = self.GetParentNode() {
1905            Node::remove(cx, self, parent, SuppressObserver::Unsuppressed);
1906        }
1907    }
1908
1909    /// Returns the node's `unique_id` if it has been computed before and `None` otherwise.
1910    #[cfg(feature = "devtools")]
1911    pub(crate) fn unique_id_if_already_present(&self) -> Option<String> {
1912        Ref::filter_map(self.rare_data.borrow(), |rare_data| {
1913            rare_data
1914                .as_ref()
1915                .and_then(|rare_data| rare_data.unique_id.as_ref())
1916        })
1917        .ok()
1918        .map(|unique_id| unique_id.simple().to_string())
1919    }
1920
1921    pub(crate) fn unique_id(&self, pipeline: PipelineId) -> String {
1922        let mut rare_data = self.ensure_rare_data();
1923
1924        if rare_data.unique_id.is_none() {
1925            let node_id = Uuid::new_v4();
1926            ScriptThread::save_node_id(pipeline, node_id.simple().to_string());
1927            rare_data.unique_id = Some(node_id);
1928        }
1929        rare_data.unique_id.as_ref().unwrap().simple().to_string()
1930    }
1931
1932    #[cfg(feature = "devtools")]
1933    pub(crate) fn summarize(&self, cx: &mut JSContext) -> devtools_traits::NodeInfo {
1934        use crate::conversions::Convert;
1935        use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods;
1936        let USVString(base_uri) = self.BaseURI();
1937        let node_type = self.NodeType();
1938        let pipeline = self.owner_window().pipeline_id();
1939
1940        let maybe_shadow_root = self.downcast::<ShadowRoot>();
1941        let shadow_root_mode = maybe_shadow_root
1942            .map(ShadowRoot::Mode)
1943            .map(ShadowRootMode::convert);
1944        let host = maybe_shadow_root
1945            .map(ShadowRoot::Host)
1946            .map(|host| host.upcast::<Node>().unique_id(pipeline));
1947        let is_shadow_host = self.downcast::<Element>().is_some_and(|potential_host| {
1948            let Some(root) = potential_host.shadow_root() else {
1949                return false;
1950            };
1951            !root.is_user_agent_widget() ||
1952                servo_config::pref!(inspector_show_servo_internal_shadow_roots)
1953        });
1954
1955        let num_children = if is_shadow_host {
1956            // Shadow roots count as children
1957            self.ChildNodes(cx).Length(cx.no_gc()) as usize + 1
1958        } else {
1959            self.ChildNodes(cx).Length(cx.no_gc()) as usize
1960        };
1961
1962        let window = self.owner_window();
1963        let element = self.downcast::<Element>();
1964        let display = element
1965            .map(|elem| window.GetComputedStyle(cx, elem, None))
1966            .map(|style| style.Display().into());
1967
1968        // It is not entirely clear when this should be set to false.
1969        // Firefox considers nodes with "display: contents" to be displayed.
1970        // The doctype node is displayed despite being `display: none`.
1971        //
1972        // TODO: Should this be false if the node is in a `display: none` subtree?
1973        let is_displayed =
1974            element.is_none_or(|element| !element.is_display_none()) || self.is::<DocumentType>();
1975        let attrs = element.map(Element::summarize).unwrap_or_default();
1976
1977        devtools_traits::NodeInfo {
1978            unique_id: self.unique_id(pipeline),
1979            host,
1980            base_uri,
1981            parent: self
1982                .GetParentNode()
1983                .map_or(String::new(), |node| node.unique_id(pipeline)),
1984            node_type,
1985            is_top_level_document: node_type == NodeConstants::DOCUMENT_NODE,
1986            node_name: String::from(self.NodeName()),
1987            node_value: self.GetNodeValue().map(|v| v.into()),
1988            num_children,
1989            attrs,
1990            is_shadow_host,
1991            shadow_root_mode,
1992            display,
1993            is_displayed,
1994            doctype_name: self
1995                .downcast::<DocumentType>()
1996                .map(DocumentType::name)
1997                .cloned()
1998                .map(String::from),
1999            doctype_public_identifier: self
2000                .downcast::<DocumentType>()
2001                .map(DocumentType::public_id)
2002                .cloned()
2003                .map(String::from),
2004            doctype_system_identifier: self
2005                .downcast::<DocumentType>()
2006                .map(DocumentType::system_id)
2007                .cloned()
2008                .map(String::from),
2009            has_event_listeners: self.upcast::<EventTarget>().has_handlers(),
2010        }
2011    }
2012
2013    /// Used by `HTMLTableSectionElement::InsertRow` and `HTMLTableRowElement::InsertCell`
2014    pub(crate) fn insert_cell_or_row<F, G, I>(
2015        &self,
2016        cx: &mut JSContext,
2017        index: i32,
2018        get_items: F,
2019        new_child: G,
2020    ) -> Fallible<DomRoot<HTMLElement>>
2021    where
2022        F: Fn(&mut JSContext) -> DomRoot<HTMLCollection>,
2023        G: Fn(&mut JSContext) -> DomRoot<I>,
2024        I: DerivedFrom<Node> + DerivedFrom<HTMLElement> + DomObject,
2025    {
2026        if index < -1 {
2027            return Err(Error::IndexSize(Some("Index is out of bounds".into())));
2028        }
2029
2030        let tr = new_child(cx);
2031
2032        {
2033            let tr_node = tr.upcast::<Node>();
2034            if index == -1 {
2035                self.InsertBefore(cx, tr_node, None)?;
2036            } else {
2037                let items = get_items(cx);
2038                let node = match items
2039                    .elements_iter(cx.no_gc())
2040                    .map(UnrootedDom::upcast::<Node>)
2041                    .map(Some)
2042                    .chain(iter::once(None))
2043                    .nth(index as usize)
2044                {
2045                    None => return Err(Error::IndexSize(Some("Index is out of bounds".into()))),
2046                    Some(node) => node,
2047                };
2048                self.InsertBefore(cx, tr_node, node.map(|node| node.as_rooted()).as_deref())?;
2049            }
2050        }
2051
2052        Ok(DomRoot::upcast::<HTMLElement>(tr))
2053    }
2054
2055    /// Used by `HTMLTableSectionElement::DeleteRow` and `HTMLTableRowElement::DeleteCell`
2056    pub(crate) fn delete_cell_or_row<F, G>(
2057        &self,
2058        cx: &mut JSContext,
2059        index: i32,
2060        get_items: F,
2061        is_delete_type: G,
2062    ) -> ErrorResult
2063    where
2064        F: Fn(&mut JSContext) -> DomRoot<HTMLCollection>,
2065        G: Fn(&Element) -> bool,
2066    {
2067        let element = match index {
2068            index if index < -1 => {
2069                return Err(Error::IndexSize(Some("Index is out of bounds".into())));
2070            },
2071            -1 => {
2072                let last_child = self.upcast::<Node>().GetLastChild();
2073                match last_child.and_then(|node| {
2074                    node.inclusively_preceding_siblings_unrooted(cx.no_gc())
2075                        .filter_map(UnrootedDom::downcast::<Element>)
2076                        .find(|elem| is_delete_type(elem))
2077                        .map(|elem| elem.as_rooted())
2078                }) {
2079                    Some(element) => element,
2080                    None => return Ok(()),
2081                }
2082            },
2083            index => match get_items(cx).Item(cx, index as u32) {
2084                Some(element) => element,
2085                None => return Err(Error::IndexSize(Some("Index is out of bounds".into()))),
2086            },
2087        };
2088
2089        element.upcast::<Node>().remove_self(cx);
2090        Ok(())
2091    }
2092
2093    pub(crate) fn get_cssom_stylesheet(
2094        &self,
2095        cx: &mut JSContext,
2096    ) -> Option<DomRoot<CSSStyleSheet>> {
2097        if let Some(node) = self.downcast::<HTMLStyleElement>() {
2098            node.get_cssom_stylesheet(cx)
2099        } else if let Some(node) = self.downcast::<HTMLLinkElement>() {
2100            node.get_cssom_stylesheet(cx)
2101        } else {
2102            None
2103        }
2104    }
2105
2106    /// <https://html.spec.whatwg.org/multipage/#language>
2107    pub(crate) fn get_lang(&self) -> Option<String> {
2108        // > To determine the language of a node,
2109        // > user agents must use the first appropriate step in the following list:
2110
2111        // > If the node's parent is a shadow root
2112        // >     Use the language of that shadow root's host.
2113        // > If the node's parent element is not null
2114        // >     Use the language of that parent element.
2115        self.inclusive_ancestors(ShadowIncluding::Yes)
2116            .find_map(|node| {
2117                node.downcast::<Element>().and_then(|element| {
2118                    // > If the node is an element that has a lang attribute in the XML namespace set
2119                    // >     Use the value of that attribute.
2120                    element
2121                        .get_attribute_string_value_with_namespace(&ns!(xml), &local_name!("lang"))
2122                        // > If the node is an HTML element or an element in the SVG namespace,
2123                        // > and it has a lang in no namespace attribute set
2124                        // >     Use the value of that attribute.
2125                        .or_else(|| {
2126                            if element.namespace() == &ns!() || element.namespace() == &ns!(svg) {
2127                                element.get_attribute_string_value(&local_name!("lang"))
2128                            } else {
2129                                None
2130                            }
2131                        })
2132                })
2133            })
2134            // > If there is a pragma-set default language set,
2135            // > then that is the language of the node.
2136            // > If there is no pragma-set default language set,
2137            // > then language information from a higher-level protocol (such as HTTP),
2138            // > if any, must be used as the final fallback language instead.
2139            // > In the absence of any such language information,
2140            // > and in cases where the higher-level protocol reports multiple languages,
2141            // > the language of the node is unknown,
2142            // > and the corresponding language tag is the empty string.
2143            //
2144            // We store the default_language when retrieving from HTTP
2145            // and then later overwrite if it we process a <meta> element
2146            // that sets content-language. Hence, we only need to call
2147            // default_language here to cover both cases.
2148            .or_else(|| self.owner_document().default_language())
2149    }
2150
2151    /// <https://dom.spec.whatwg.org/#assign-slotables-for-a-tree>
2152    pub(crate) fn assign_slottables_for_a_tree(
2153        &self,
2154        cx: &JSContext,
2155        force: ForceSlottableNodeReconciliation,
2156    ) {
2157        // NOTE: This method traverses all descendants of the node and is potentially very
2158        // expensive. If the node is neither a shadowroot nor a slot then assigning slottables
2159        // for it won't have any effect, so we take a fast path out.
2160        // In the case of node removal, we need to force re-assignment of slottables
2161        // even if the node is not a shadow root or slot, this allows us to clear assigned
2162        // slots from any slottables that were assigned to slots in the removed subtree.
2163        let is_shadow_root_with_slots = self
2164            .downcast::<ShadowRoot>()
2165            .is_some_and(|shadow_root| shadow_root.has_slot_descendants());
2166        if !is_shadow_root_with_slots &&
2167            !self.is::<HTMLSlotElement>() &&
2168            matches!(force, ForceSlottableNodeReconciliation::Skip)
2169        {
2170            return;
2171        }
2172
2173        // > To assign slottables for a tree, given a node root, run assign slottables for each slot
2174        // > slot in root’s inclusive descendants, in tree order.
2175        for node in self.traverse_preorder_unrooted(cx, ShadowIncluding::No) {
2176            if let Some(slot) = node.downcast::<HTMLSlotElement>() {
2177                slot.assign_slottables(cx);
2178            }
2179        }
2180    }
2181
2182    pub(crate) fn assigned_slot(&self) -> Option<DomRoot<HTMLSlotElement>> {
2183        let assigned_slot = self
2184            .rare_data
2185            .borrow()
2186            .as_ref()?
2187            .slottable_data
2188            .assigned_slot
2189            .as_ref()?
2190            .as_rooted();
2191        Some(assigned_slot)
2192    }
2193
2194    pub(crate) fn assigned_slot_unrooted<'a>(
2195        &self,
2196        no_gc: &'a NoGC,
2197    ) -> Option<UnrootedDom<'a, HTMLSlotElement>> {
2198        let rare_data = self.rare_data.borrow();
2199        let assigned_slot = rare_data.as_ref()?.slottable_data.assigned_slot.as_ref()?;
2200        Some(UnrootedDom::from_ref(assigned_slot, no_gc))
2201    }
2202
2203    pub(crate) fn set_assigned_slot(&self, assigned_slot: Option<&HTMLSlotElement>) {
2204        self.ensure_rare_data().slottable_data.assigned_slot = assigned_slot.map(Dom::from_ref);
2205    }
2206
2207    pub(crate) fn manual_slot_assignment(&self) -> Option<DomRoot<HTMLSlotElement>> {
2208        let manually_assigned_slot = self
2209            .rare_data
2210            .borrow()
2211            .as_ref()?
2212            .slottable_data
2213            .manual_slot_assignment
2214            .as_ref()?
2215            .as_rooted();
2216        Some(manually_assigned_slot)
2217    }
2218
2219    pub(crate) fn set_manual_slot_assignment(
2220        &self,
2221        manually_assigned_slot: Option<&HTMLSlotElement>,
2222    ) {
2223        self.ensure_rare_data()
2224            .slottable_data
2225            .manual_slot_assignment = manually_assigned_slot.map(Dom::from_ref);
2226    }
2227
2228    /// Gets the parent of this node from the perspective of layout and style.
2229    ///
2230    /// If the node and its parent have a flat tree relationship, this returns:
2231    ///  - The node's assigned slot.
2232    ///  - The parent node's shadow host if it's a shadow root.
2233    ///  - Or the node's parent.
2234    ///
2235    /// The parent might not have a flat tree relationship with the node if
2236    ///  - It's a light tree child of a shadow host.
2237    ///  - It's fallback content for an assigned slot.
2238    pub(crate) fn parent_in_flat_tree<'b>(&self, no_gc: &'b NoGC) -> FlatTreeParent<'b> {
2239        if let Some(assigned_slot) = self.assigned_slot_unrooted(no_gc) {
2240            return FlatTreeParent::Parent(UnrootedDom::upcast::<Node>(assigned_slot));
2241        }
2242
2243        let Some(parent) = self.get_parent_node_unrooted(no_gc) else {
2244            return FlatTreeParent::RootNode;
2245        };
2246
2247        if let Some(shadow_root) = parent.downcast::<ShadowRoot>() {
2248            return FlatTreeParent::Parent(UnrootedDom::upcast(shadow_root.host_unrooted(no_gc)));
2249        }
2250
2251        if parent
2252            .downcast::<Element>()
2253            .is_some_and(|element| element.is_shadow_host())
2254        {
2255            return FlatTreeParent::NotInFlatTree;
2256        }
2257
2258        if parent
2259            .downcast::<HTMLSlotElement>()
2260            .is_some_and(|slot| slot.has_assigned_nodes())
2261        {
2262            return FlatTreeParent::NotInFlatTree;
2263        }
2264
2265        FlatTreeParent::Parent(parent)
2266    }
2267
2268    /// We are marking this as an implemented pseudo element.
2269    pub(crate) fn set_implemented_pseudo_element(&self, pseudo_element: PseudoElement) {
2270        // Implemented pseudo element should exist only in the UA shadow DOM.
2271        debug_assert!(self.is_in_ua_widget());
2272        debug_assert!(pseudo_element.is_element_backed());
2273        self.ensure_rare_data().implemented_pseudo_element = Some(pseudo_element);
2274    }
2275
2276    pub(crate) fn implemented_pseudo_element(&self) -> Option<PseudoElement> {
2277        self.rare_data
2278            .borrow()
2279            .as_ref()
2280            .and_then(|rare_data| rare_data.implemented_pseudo_element)
2281    }
2282
2283    /// <https://w3c.github.io/editing/docs/execCommand/#editing-host-of>
2284    pub(crate) fn editing_host_of(&self) -> Option<DomRoot<Node>> {
2285        // > The editing host of node is null if node is neither editable nor an editing host;
2286        // > node itself, if node is an editing host;
2287        // > or the nearest ancestor of node that is an editing host, if node is editable.
2288        for ancestor in self.inclusive_ancestors(ShadowIncluding::No) {
2289            if ancestor.is_editing_host() {
2290                return Some(ancestor);
2291            }
2292            if ancestor
2293                .downcast::<HTMLElement>()
2294                .is_some_and(|el| el.ContentEditable().str() == "false")
2295            {
2296                return None;
2297            }
2298        }
2299        None
2300    }
2301
2302    pub(crate) fn is_editable_or_editing_host(&self) -> bool {
2303        self.editing_host_of().is_some()
2304    }
2305
2306    /// <https://html.spec.whatwg.org/multipage/#editing-host>
2307    pub(crate) fn is_editing_host(&self) -> bool {
2308        self.downcast::<HTMLElement>()
2309            .is_some_and(HTMLElement::is_editing_host)
2310    }
2311
2312    /// <https://w3c.github.io/editing/docs/execCommand/#editable>
2313    pub(crate) fn is_editable(&self, cx: &mut JSContext) -> bool {
2314        // https://html.spec.whatwg.org/multipage/#inert
2315        // When a node is inert: If it is editable, the node behaves as if it were non-editable.
2316        if self.is_inert(cx) {
2317            return false;
2318        }
2319
2320        // > Something is editable if it is a node; it is not an editing host;
2321        if self.is_editing_host() {
2322            return false;
2323        }
2324        // > it does not have a contenteditable attribute set to the false state;
2325        let html_element = self.downcast::<HTMLElement>();
2326        if html_element.is_some_and(|el| el.ContentEditable().str() == "false") {
2327            return false;
2328        }
2329        // > its parent is an editing host or editable;
2330        let Some(parent) = self.GetParentNode() else {
2331            return false;
2332        };
2333        if !parent.is_editable_or_editing_host() {
2334            return false;
2335        }
2336        // > and either it is an HTML element, or it is an svg or math element, or it is not an Element and its parent is an HTML element.
2337        html_element.is_some() || (!self.is::<Element>() && parent.is::<HTMLElement>())
2338    }
2339
2340    /// Like [`Self::is_inert`], but does not trigger a reflow.
2341    pub(crate) fn is_inert_without_reflow(&self) -> bool {
2342        self.downcast::<Element>()
2343            .and_then(Element::style_without_reflow)
2344            .is_some_and(|style| {
2345                *style.get__moz_inert() == Inert::Inert ||
2346                    *style.get_interactivity() == Interactivity::Inert
2347            })
2348    }
2349
2350    /// <https://html.spec.whatwg.org/multipage/#inert>
2351    /// A node (in particular elements and text nodes) can be inert.
2352    ///
2353    /// Inertness is propagated using the internal `-moz-inert` property.
2354    pub(crate) fn is_inert(&self, cx: &mut JSContext) -> bool {
2355        self.owner_window().layout_reflow(cx, QueryMsg::StyleQuery);
2356        self.is_inert_without_reflow()
2357    }
2358
2359    /// <https://html.spec.whatwg.org/multipage/#nearest-inclusive-open-popover>
2360    pub(crate) fn nearest_inclusive_open_popover(
2361        &self,
2362        cx: &mut JSContext,
2363    ) -> Option<DomRoot<HTMLElement>> {
2364        // Step 1. Let currentNode be node.
2365        // Step 2. While currentNode is not null:
2366        // Step 2.2. Set currentNode to currentNode's parent in the flat tree.
2367        // Step 3. Return null.
2368        self.inclusive_ancestors_in_flat_tree_unrooted(cx.no_gc())
2369            .find_map(|current_node| {
2370                // Step 2.1. If currentNode's opened in popover mode is "auto" or "hint", and currentNode's popover visibility state is showing, then return currentNode.
2371                current_node
2372                    .downcast::<HTMLElement>()
2373                    .filter(|html_element| {
2374                        (matches!(
2375                            html_element.opened_in_popover_mode(),
2376                            Some(PopoverState::Auto | PopoverState::Hint)
2377                        ) && html_element
2378                            .upcast::<Element>()
2379                            .popover_visibility_state_showing())
2380                    })
2381                    .map(DomRoot::from_ref)
2382            })
2383    }
2384
2385    /// <https://html.spec.whatwg.org/multipage/#topmost-clicked-popover>
2386    pub(crate) fn topmost_clicked_popover(
2387        &self,
2388        cx: &mut JSContext,
2389    ) -> Option<DomRoot<HTMLElement>> {
2390        // Step 1. Let clickedPopover be the result of running nearest inclusive open popover given node.
2391        let clicked_popover = self.nearest_inclusive_open_popover(cx);
2392
2393        // Step 2. Let targetPopover be the result of running nearest inclusive target popover given node.
2394        let target_popover = self.nearest_inclusive_target_popover(cx);
2395
2396        // The spec does not handle the case where one of the popovers is null, so in that case we
2397        // return the other one or none.
2398        let Some(clicked_popover) = clicked_popover else {
2399            return target_popover;
2400        };
2401        let Some(target_popover) = target_popover else {
2402            return Some(clicked_popover);
2403        };
2404
2405        // Step 3. If the result of getting the popover stack position given clickedPopover is
2406        // greater than the result of getting the popover stack position given targetPopover, then
2407        // return clickedPopover.
2408        if clicked_popover.popover_stack_position(cx) > target_popover.popover_stack_position(cx) {
2409            return Some(clicked_popover);
2410        }
2411
2412        // Step 4. Return targetPopover.
2413        Some(target_popover)
2414    }
2415
2416    /// <https://html.spec.whatwg.org/multipage/#nearest-inclusive-target-popover>
2417    pub(crate) fn nearest_inclusive_target_popover(
2418        &self,
2419        cx: &mut JSContext,
2420    ) -> Option<DomRoot<HTMLElement>> {
2421        // Step 1. Let currentNode be node.
2422        // Step 2. While currentNode is not null:
2423        // Step 2.3. Set currentNode to currentNode's parent in the flat tree.
2424        let ancestors: Vec<DomRoot<Node>> = self
2425            .inclusive_ancestors_in_flat_tree_unrooted(cx.no_gc())
2426            .map(|node| DomRoot::from_ref(&**node))
2427            .collect();
2428        ancestors.into_iter().find_map(|current_node| {
2429            // Step 2.1. Let targetPopover be currentNode's target popover.
2430            // Step 2.2. If targetPopover is not null and targetPopover's popover attribute is in
2431            // the Auto state or the Hint state, and targetPopover's popover visibility state is
2432            // showing, then return targetPopover.
2433            current_node.target_popover(cx).filter(|target_popover| {
2434                matches!(
2435                    target_popover.opened_in_popover_mode(),
2436                    Some(PopoverState::Auto | PopoverState::Hint)
2437                ) && target_popover
2438                    .upcast::<Element>()
2439                    .popover_visibility_state_showing()
2440            })
2441        })
2442    }
2443
2444    /// <https://html.spec.whatwg.org/multipage/#target-popover>
2445    fn target_popover(&self, cx: &mut JSContext) -> Option<DomRoot<HTMLElement>> {
2446        // Step 1. If node is not a button element, then return node's popover target element.
2447        let Some(button) = self.downcast::<HTMLButtonElement>() else {
2448            return self
2449                .downcast::<HTMLElement>()
2450                .and_then(|element| element.popover_target_element(cx));
2451        };
2452
2453        // Step 2. If node is disabled, then return null.
2454        if button
2455            .upcast::<HTMLElement>()
2456            .is_form_element_disabled(cx.no_gc())
2457        {
2458            return None;
2459        }
2460
2461        // Step 3. Let target be the result of running node's get the commandfor-associated element.
2462        let target = button.GetCommandForElement(cx);
2463
2464        // Step 4. If target is null, then return node's popover target element.
2465        let Some(target) = target else {
2466            return button.upcast::<HTMLElement>().popover_target_element(cx);
2467        };
2468
2469        // Step 5. If node has a form owner:
2470        if button.form_owner().is_some() {
2471            // Step 5.1. If element is a submit button, then return null.
2472            if button.is_submit_button() {
2473                return None;
2474            }
2475
2476            // Step 5.2. If element's type attribute is in the Reset Button state, then return null.
2477            // Step 5.3. If element's type attribute is in the Auto state, then return null.
2478            if matches!(button.button_type(), ButtonType::Reset | ButtonType::Auto) {
2479                return None;
2480            }
2481        }
2482
2483        // Step 6. Let command be node's command attribute.
2484        let command = button.command_state();
2485
2486        // Step 7. If command is not in the Toggle Popover, Hide Popover, or Show Popover states, then return null.
2487        if !matches!(
2488            command,
2489            CommandState::TogglePopover | CommandState::HidePopover | CommandState::ShowPopover
2490        ) {
2491            return None;
2492        }
2493
2494        // Step 8. If target's popover attribute is in the No Popover state, then return null.
2495        let target = DomRoot::downcast::<HTMLElement>(target)?;
2496        if target.popover_state() == PopoverState::NoPopover {
2497            return None;
2498        }
2499
2500        // Step 9. Return target.
2501        Some(target)
2502    }
2503}
2504
2505/// Iterate through `nodes` until we find a `Node` that is not in `not_in`
2506fn first_node_not_in<I>(mut nodes: I, not_in: &[NodeOrString]) -> Option<DomRoot<Node>>
2507where
2508    I: Iterator<Item = DomRoot<Node>>,
2509{
2510    nodes.find(|node| {
2511        not_in.iter().all(|n| match *n {
2512            NodeOrString::Node(ref n) => n != node,
2513            _ => true,
2514        })
2515    })
2516}
2517
2518/// If the given untrusted node address represents a valid DOM node in the given runtime,
2519/// returns it.
2520#[expect(unsafe_code)]
2521pub(crate) unsafe fn from_untrusted_node_address(candidate: UntrustedNodeAddress) -> DomRoot<Node> {
2522    let node = unsafe { Node::from_untrusted_node_address(candidate) };
2523    DomRoot::from_ref(node)
2524}
2525
2526/// Specifies whether children must be recursively cloned or not.
2527#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
2528pub(crate) enum CloneChildrenFlag {
2529    CloneChildren,
2530    DoNotCloneChildren,
2531}
2532
2533impl From<bool> for CloneChildrenFlag {
2534    fn from(boolean: bool) -> Self {
2535        if boolean {
2536            CloneChildrenFlag::CloneChildren
2537        } else {
2538            CloneChildrenFlag::DoNotCloneChildren
2539        }
2540    }
2541}
2542
2543pub(super) fn as_uintptr<T>(t: &T) -> uintptr_t {
2544    t as *const T as uintptr_t
2545}
2546
2547impl Node {
2548    pub(crate) fn reflect_node<N>(
2549        cx: &mut JSContext,
2550        node: Box<N>,
2551        document: &Document,
2552    ) -> DomRoot<N>
2553    where
2554        N: DerivedFrom<Node> + DomObject + DomObjectWrap<crate::DomTypeHolder>,
2555    {
2556        Self::reflect_node_with_proto(cx, node, document, None)
2557    }
2558
2559    pub(crate) fn reflect_node_with_proto<N>(
2560        cx: &mut JSContext,
2561        node: Box<N>,
2562        document: &Document,
2563        proto: Option<HandleObject>,
2564    ) -> DomRoot<N>
2565    where
2566        N: DerivedFrom<Node> + DomObject + DomObjectWrap<crate::DomTypeHolder>,
2567    {
2568        let window = document.window();
2569        reflect_dom_object_with_proto(cx, node, window, proto)
2570    }
2571
2572    pub(crate) fn reflect_weak_referenceable_node_with_proto<N>(
2573        cx: &mut JSContext,
2574        node: Rc<N>,
2575        document: &Document,
2576        proto: Option<HandleObject>,
2577    ) -> DomRoot<N>
2578    where
2579        N: DerivedFrom<Node> + DomObject + WeakReferenceableDomObjectWrap<crate::DomTypeHolder>,
2580    {
2581        let window = document.window();
2582        reflect_weak_referenceable_dom_object_with_proto(cx, node, window, proto)
2583    }
2584
2585    pub(crate) fn new_inherited(doc: &Document) -> Node {
2586        Node::new_(NodeFlags::empty(), Some(doc))
2587    }
2588
2589    pub(crate) fn new_document_node() -> Node {
2590        Node::new_(
2591            NodeFlags::IS_IN_A_DOCUMENT_TREE | NodeFlags::IS_CONNECTED,
2592            None,
2593        )
2594    }
2595
2596    fn new_(flags: NodeFlags, doc: Option<&Document>) -> Node {
2597        Node {
2598            eventtarget: EventTarget::new_inherited(),
2599            parent_node: Default::default(),
2600            first_child: Default::default(),
2601            last_child: Default::default(),
2602            next_sibling: Default::default(),
2603            prev_sibling: Default::default(),
2604            owner_doc: MutNullableDom::new(doc),
2605            rare_data: Default::default(),
2606            children_count: Cell::new(0u32),
2607            flags: Cell::new(flags),
2608            inclusive_descendants_version: Cell::new(0),
2609            layout_data: Default::default(),
2610        }
2611    }
2612
2613    /// <https://dom.spec.whatwg.org/#concept-node-adopt>
2614    pub(crate) fn adopt(cx: &mut JSContext, node: &Node, document: &Document) {
2615        document.add_script_and_layout_blocker();
2616
2617        // Step 1. Let oldDocument be node’s node document.
2618        let old_doc = node.owner_doc();
2619        old_doc.add_script_and_layout_blocker();
2620
2621        // Step 2. If node’s parent is non-null, then remove node.
2622        node.remove_self(cx);
2623
2624        // Step 3. If document is not oldDocument, then for each inclusiveDescendant
2625        // of node’s shadow-including inclusive descendants, in shadow-including
2626        // tree order:
2627        if &*old_doc != document {
2628            for descendant in node.traverse_preorder(ShadowIncluding::Yes) {
2629                // Step 3.1. Set inclusiveDescendant’s node document to document.
2630                descendant.set_owner_doc(document);
2631
2632                // Step 3.2. If inclusiveDescendant is a shadow root and if any of the following
2633                // are true:
2634                //   - inclusiveDescendant’s custom element registry is null and
2635                //     inclusiveDescendant’s keep custom element registry null is false; or
2636                //   - inclusiveDescendant’s custom element registry is a global
2637                //     custom element registry,
2638                // then set inclusiveDescendant’s custom element registry to document’s
2639                // effective global custom element registry.
2640                //
2641                // Note: `keep custom element registry null` is not yet implemented in servo.
2642                if let Some(shadow_root) = descendant.downcast::<ShadowRoot>() {
2643                    if shadow_root
2644                        .custom_element_registry()
2645                        .is_none_or(|registry| {
2646                            CustomElementRegistry::is_a_global_element_registry(Some(&*registry))
2647                        })
2648                    {
2649                        shadow_root.set_custom_element_registry(
2650                            document
2651                                .effective_global_custom_element_registry()
2652                                .as_deref(),
2653                        );
2654                    }
2655                }
2656                // Step 3.3. Otherwise, if inclusiveDescendant is an element:
2657                else if let Some(element) = descendant.downcast::<Element>() {
2658                    // Step 3.3.1. Set the node document of each attribute in inclusiveDescendant’s
2659                    // attribute list to document.
2660                    for attribute in element.attrs().borrow().iter() {
2661                        if let Some(attr) = attribute.as_attr() {
2662                            attr.upcast::<Node>().set_owner_doc(document);
2663                        }
2664                    }
2665
2666                    // Step 3.3.2. If inclusiveDescendant’s custom element
2667                    // registry is null or inclusiveDescendant’s custom element
2668                    // registry’s is scoped is false, then set inclusiveDescendant’s
2669                    // custom element registry to document’s effective global
2670                    // custom element registry.
2671                    if element
2672                        .custom_element_registry()
2673                        .is_none_or(|registry| !registry.is_scoped())
2674                    {
2675                        element.set_custom_element_registry(
2676                            document
2677                                .effective_global_custom_element_registry()
2678                                .as_deref(),
2679                            cx.no_gc(),
2680                        );
2681                    }
2682
2683                    // Step 3.3.3. If inclusiveDescendant is custom, then enqueue a custom element
2684                    // callback reaction with inclusiveDescendant, callback name
2685                    // “adoptedCallback”, and « oldDocument, document ».
2686                    if element.is_custom() {
2687                        ScriptThread::custom_element_reaction_stack().enqueue_callback_reaction(
2688                            cx,
2689                            element,
2690                            CallbackReaction::Adopted(old_doc.clone(), DomRoot::from_ref(document)),
2691                            None,
2692                        );
2693                    }
2694                }
2695
2696                // Step 3.4. Run the adopting steps with inclusiveDescendant and oldDocument.
2697                vtable_for(&descendant).adopting_steps(cx, &old_doc);
2698            }
2699
2700            // It's possible that in the process of adopting this node a Range has moved from the
2701            // old document to the new one. We must iterate a vector here because
2702            // `maybe_udpate_document` modifies the list of Ranges we'd like to iterate.
2703            for range in old_doc.live_ranges().as_vec() {
2704                range.maybe_update_document();
2705            }
2706        }
2707
2708        old_doc.remove_script_and_layout_blocker(cx);
2709        document.remove_script_and_layout_blocker(cx);
2710    }
2711
2712    /// <https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity>
2713    pub(crate) fn ensure_pre_insertion_validity(
2714        no_gc: &NoGC,
2715        node: &Node,
2716        parent: &Node,
2717        child: Option<&Node>,
2718        children_to_exclude: &[&Node],
2719    ) -> ErrorResult {
2720        let excluded = |node: &Node| children_to_exclude.contains(&node);
2721
2722        // Step 1. If parent is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException.
2723        match parent.type_id() {
2724            NodeTypeId::Document(_) | NodeTypeId::DocumentFragment(_) | NodeTypeId::Element(..) => {
2725            },
2726            _ => {
2727                return Err(Error::HierarchyRequest(Some(
2728                    "Parent is not a Document, DocumentFragment, or Element node".to_owned(),
2729                )));
2730            },
2731        }
2732
2733        // Step 2. If node is a host-including inclusive ancestor of parent, then throw a "HierarchyRequestError" DOMException.
2734        if node.is_host_including_inclusive_ancestor(parent) {
2735            return Err(Error::HierarchyRequest(Some(
2736                "Node is a host-including inclusive ancestor of parent".to_owned(),
2737            )));
2738        }
2739
2740        // Step 3. If child is non-null and its parent is not parent, then throw a "NotFoundError" DOMException.
2741        if let Some(child) = child &&
2742            !parent.is_parent_of(child)
2743        {
2744            return Err(Error::NotFound(Some(
2745                "Child is non-null and its parent is not parent".to_owned(),
2746            )));
2747        }
2748
2749        match node.type_id() {
2750            // Step 5. If either node is a Text node and parent is a document,
2751            // or node is a doctype and parent is not a document,
2752            // then throw a "HierarchyRequestError" DOMException.
2753            NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) => {
2754                if parent.is::<Document>() {
2755                    return Err(Error::HierarchyRequest(Some(
2756                        "Node is a Text node and parent is a document".to_owned(),
2757                    )));
2758                }
2759            },
2760            NodeTypeId::DocumentType => {
2761                if !parent.is::<Document>() {
2762                    return Err(Error::HierarchyRequest(Some(
2763                        "Node is a doctype and parent is not a document".to_owned(),
2764                    )));
2765                }
2766            },
2767            NodeTypeId::DocumentFragment(_) |
2768            NodeTypeId::Element(_) |
2769            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) |
2770            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => (),
2771            // Step 4. If node is not a DocumentFragment, DocumentType, Element,
2772            // or CharacterData node, then throw a "HierarchyRequestError" DOMException.
2773            NodeTypeId::Document(_) | NodeTypeId::Attr => {
2774                return Err(Error::HierarchyRequest(Some(
2775                    "Node is not a DocumentFragment, DocumentType, Element, or CharacterData node"
2776                        .to_owned(),
2777                )));
2778            },
2779        }
2780
2781        // Step 6. If parent is a document, and any of the statements below, switched on the interface node implements,
2782        // are true, then throw a "HierarchyRequestError" DOMException.
2783        if parent.is::<Document>() {
2784            match node.type_id() {
2785                NodeTypeId::DocumentFragment(_) => {
2786                    // Step 6."DocumentFragment". If node has more than one element child or has a Text node child.
2787                    if node.children_unrooted(no_gc).any(|c| c.is::<Text>()) {
2788                        return Err(Error::HierarchyRequest(Some(
2789                            "Parent is a document and node has a Text node child".into(),
2790                        )));
2791                    }
2792                    match node.child_elements_unrooted(no_gc).count() {
2793                        0 => (),
2794                        // Step 6."DocumentFragment". Otherwise, if node has one element child and either parent has an element child
2795                        // that childrenToExclude does not contain, child is non-null and a doctype is following child, or child is a
2796                        // doctype that childrenToExclude does not contain.
2797                        1 => {
2798                            if parent
2799                                .child_elements_unrooted(no_gc)
2800                                .any(|c| !excluded(c.upcast()))
2801                            {
2802                                return Err(Error::HierarchyRequest(Some(
2803                                    "Node has one element child and parent has an element child"
2804                                        .into(),
2805                                )));
2806                            }
2807                            if let Some(child) = child &&
2808                                child
2809                                    .inclusively_following_siblings_unrooted(no_gc)
2810                                    .any(|sibling| sibling.is_doctype() && !excluded(&sibling))
2811                            {
2812                                return Err(Error::HierarchyRequest(Some(
2813                                    "Node has one element child and child is a doctype".into(),
2814                                )));
2815                            }
2816                        },
2817                        _ => {
2818                            return Err(Error::HierarchyRequest(Some(
2819                                "Node cannot have more than one child element".into(),
2820                            )));
2821                        },
2822                    }
2823                },
2824                NodeTypeId::Element(_) => {
2825                    // Step 6."Element". parent has an element child that childrenToExclude does not contain, child is non-null
2826                    // and a doctype is following child, or child is a doctype that childrenToExclude does not contain.
2827                    if parent
2828                        .child_elements_unrooted(no_gc)
2829                        .any(|c| !excluded(c.upcast()))
2830                    {
2831                        return Err(Error::HierarchyRequest(Some(
2832                            "Parent has an element child".to_owned(),
2833                        )));
2834                    }
2835                    if let Some(child) = child &&
2836                        child
2837                            .inclusively_following_siblings_unrooted(no_gc)
2838                            .any(|following| following.is_doctype() && !excluded(&following))
2839                    {
2840                        return Err(Error::HierarchyRequest(Some(
2841                                "Child is a doctype, or child is non-null and a doctype is following child".to_owned(),
2842                            )));
2843                    }
2844                },
2845                NodeTypeId::DocumentType => {
2846                    // Step 6."DocumentType". parent has a doctype child that childrenToExclude does not contain, child is
2847                    // non-null and an element is preceding child, or child is null and parent has an element child that
2848                    // childrenToExclude does not contain.
2849                    if parent
2850                        .children_unrooted(no_gc)
2851                        .any(|c| c.is_doctype() && !excluded(&c))
2852                    {
2853                        return Err(Error::HierarchyRequest(Some(
2854                            "Parent cannot have a doctype child".into(),
2855                        )));
2856                    }
2857                    match child {
2858                        Some(child) => {
2859                            if parent
2860                                .children_unrooted(no_gc)
2861                                .take_while(|c| **c != child)
2862                                .any(|c| c.is::<Element>())
2863                            {
2864                                return Err(Error::HierarchyRequest(Some(
2865                                    "Child is non-null and an element is preceding child".into(),
2866                                )));
2867                            }
2868                        },
2869                        None => {
2870                            if parent
2871                                .child_elements_unrooted(no_gc)
2872                                .any(|c| !excluded(c.upcast()))
2873                            {
2874                                return Err(Error::HierarchyRequest(Some(
2875                                    "Child is null and parent has an element child".into(),
2876                                )));
2877                            }
2878                        },
2879                    }
2880                },
2881                NodeTypeId::CharacterData(_) => (),
2882                // Because Document and Attr should already throw `HierarchyRequest`
2883                // error, both of them are unreachable here.
2884                NodeTypeId::Document(_) | NodeTypeId::Attr => unreachable!(),
2885            }
2886        }
2887        Ok(())
2888    }
2889
2890    /// <https://dom.spec.whatwg.org/#concept-node-pre-insert>
2891    pub(crate) fn pre_insert(
2892        cx: &mut JSContext,
2893        node: &Node,
2894        parent: &Node,
2895        child: Option<&Node>,
2896    ) -> Fallible<DomRoot<Node>> {
2897        // Step 1. Ensure pre-insert validity of node into parent before child.
2898        Node::ensure_pre_insertion_validity(cx.no_gc(), node, parent, child, &[])?;
2899
2900        // Step 2. Let referenceChild be child.
2901        let reference_child_root;
2902        let reference_child = match child {
2903            // Step 3. If referenceChild is node, then set referenceChild to node’s next sibling.
2904            Some(child) if child == node => {
2905                reference_child_root = node.GetNextSibling();
2906                reference_child_root.as_deref()
2907            },
2908            _ => child,
2909        };
2910
2911        // Step 4. Insert node into parent before referenceChild.
2912        Node::insert(
2913            cx,
2914            node,
2915            parent,
2916            reference_child,
2917            SuppressObserver::Unsuppressed,
2918        );
2919
2920        // Step 5. Return node.
2921        Ok(DomRoot::from_ref(node))
2922    }
2923
2924    /// <https://dom.spec.whatwg.org/#concept-node-insert>
2925    pub(crate) fn insert(
2926        cx: &mut JSContext,
2927        node: &Node,
2928        parent: &Node,
2929        child: Option<&Node>,
2930        suppress_observers: SuppressObserver,
2931    ) {
2932        debug_assert!(child.is_none_or(|child| Some(parent) == child.GetParentNode().as_deref()));
2933
2934        // Step 1. Let nodes be node’s children, if node is a DocumentFragment node; otherwise « node ».
2935        rooted_vec!(let mut new_nodes);
2936        let new_nodes = if let NodeTypeId::DocumentFragment(_) = node.type_id() {
2937            new_nodes.extend(
2938                node.children_unrooted(cx.no_gc())
2939                    .map(|node| Dom::from_ref(&**node)),
2940            );
2941            new_nodes.as_ref_slice()
2942        } else {
2943            from_ref(&node)
2944        };
2945
2946        // Step 2. Let count be nodes’s size.
2947        let count = new_nodes.len();
2948
2949        // Step 3. If count is 0, then return.
2950        if count == 0 {
2951            return;
2952        }
2953
2954        // Script and layout blockers must be added after any early return.
2955        // `node.owner_doc()` may change during the algorithm.
2956        let parent_document = parent.owner_document();
2957        let from_document = node.owner_document();
2958        parent_document.add_script_and_layout_blocker();
2959        from_document.add_script_and_layout_blocker();
2960
2961        // Step 4. If node is a DocumentFragment node:
2962        if let NodeTypeId::DocumentFragment(_) = node.type_id() {
2963            // Step 4.1. Remove its children with the suppress observers flag set.
2964            for kid in new_nodes {
2965                Node::remove(cx, kid, node, SuppressObserver::Suppressed);
2966            }
2967            vtable_for(node).children_changed(cx, &ChildrenMutation::ReplaceAll);
2968
2969            // Step 4.2. Queue a tree mutation record for node with « », nodes, null, and null.
2970            let mutation = LazyCell::new(|| Mutation::ChildList {
2971                added: None,
2972                removed: Some(new_nodes),
2973                prev: None,
2974                next: None,
2975            });
2976            MutationObserver::queue_a_mutation_record(cx, node, mutation);
2977        }
2978
2979        // Step 5. If child is non-null:
2980        if let Some(child) = child {
2981            // Step 5.1. The live range insert steps.
2982            let count = count.try_into().unwrap();
2983            if let Some(selection) = parent_document.selection() {
2984                selection.insert_steps(parent, child, count);
2985            }
2986            parent_document.live_range_insert_steps(cx.no_gc(), parent, child, count);
2987        }
2988
2989        // Step 6. Let previousSibling be child’s previous sibling or parent’s last child if child is null.
2990        let previous_sibling = match suppress_observers {
2991            SuppressObserver::Unsuppressed => match child {
2992                Some(child) => child.GetPreviousSibling(),
2993                None => parent.GetLastChild(),
2994            },
2995            SuppressObserver::Suppressed => None,
2996        };
2997
2998        // Step 10. Let staticNodeList be a list of nodes, initially « ».
2999        //
3000        // This is incredibly hot code, so in an effort to avoiding rooting every single
3001        // node in the `static_node_list`, this code only roots the entire list itself.
3002        let mut static_node_list: Option<RootedTraceableBox<TraceableSmallVec<[Dom<Node>; 4]>>> =
3003            None;
3004
3005        let parent_shadow_root = parent.downcast::<Element>().and_then(Element::shadow_root);
3006        let parent_in_shadow_tree = parent.is_in_a_shadow_tree();
3007        let parent_as_slot = parent.downcast::<HTMLSlotElement>();
3008
3009        // Step 7. For each node in nodes, in tree order:
3010        for kid in new_nodes {
3011            // Step 7.1. Adopt node into parent’s node document.
3012            Node::adopt(cx, kid, &parent_document);
3013
3014            // Step 7.2. If child is null, then append node to parent’s children.
3015            // Step 7.3. Otherwise, insert node into parent’s children before child’s index.
3016            parent.add_child(cx, MoveOrInsert::Insert, kid, child);
3017
3018            // Step 7.4 If parent is a shadow host whose shadow root’s slot assignment is "named"
3019            // and node is a slottable, then assign a slot for node.
3020            if let Some(ref shadow_root) = parent_shadow_root &&
3021                shadow_root.SlotAssignment() == SlotAssignmentMode::Named &&
3022                (kid.is::<Element>() || kid.is::<Text>())
3023            {
3024                rooted!(&in(cx) let slottable = Slottable(Dom::from_ref(kid)));
3025                slottable.assign_a_slot(cx);
3026            }
3027
3028            // Step 7.5 If parent’s root is a shadow root, and parent is a slot whose assigned nodes
3029            // is the empty list, then run signal a slot change for parent.
3030            if parent_in_shadow_tree &&
3031                let Some(slot_element) = parent_as_slot &&
3032                !slot_element.has_assigned_nodes()
3033            {
3034                slot_element.signal_a_slot_change(cx);
3035            }
3036
3037            // Step 7.6 Run assign slottables for a tree with node’s root.
3038            kid.GetRootNode(&GetRootNodeOptions::empty())
3039                .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
3040
3041            // Step 7.7. For each shadow-including inclusive descendant inclusiveDescendant of node,
3042            // in shadow-including tree order:
3043            for descendant in kid.traverse_preorder(ShadowIncluding::Yes) {
3044                // Step 7.7.1. Run the insertion steps with inclusiveDescendant.
3045                // This is done in `parent.add_child()`.
3046
3047                // From <https://github.com/whatwg/dom/issues/833>:
3048                // try_upgrade_element fires even for disconnected elements.
3049                if let Some(element) = descendant.downcast::<Element>() &&
3050                    !element.is_custom()
3051                {
3052                    try_upgrade_element(cx, element);
3053                }
3054
3055                // Step 7.7.2. If inclusiveDescendant is not connected, then continue.
3056                if !descendant.is_connected() {
3057                    continue;
3058                }
3059
3060                // Step 7.7.3. If inclusiveDescendant is an element
3061                if let Some(element) = descendant.downcast::<Element>() {
3062                    // and inclusiveDescendant’s custom element registry is non-null:
3063                    if let Some(registry) = element.custom_element_registry() {
3064                        // Step 7.7.3.1. If inclusiveDescendant’s custom element
3065                        // registry’s is scoped is true, then append
3066                        // inclusiveDescendant’s node document to inclusiveDescendant’s
3067                        // custom element registry’s scoped document set.
3068                        if registry.is_scoped() {
3069                            registry
3070                                .add_scoped_document(&element.owner_document_unrooted(cx.no_gc()));
3071                        }
3072                    }
3073                    // TODO: As per the spec, following steps should only be
3074                    // executed for non-null custom element registry. But, it
3075                    // causes some WPT tests to fail. Needs Investigation.
3076                    //
3077                    // Step 7.7.3.2. If inclusiveDescendant is custom, then enqueue
3078                    // a custom element callback reaction with inclusiveDescendant,
3079                    // callback name "connectedCallback", and « ».
3080                    if element.is_custom() {
3081                        ScriptThread::custom_element_reaction_stack().enqueue_callback_reaction(
3082                            cx,
3083                            element,
3084                            CallbackReaction::Connected,
3085                            None,
3086                        );
3087                    }
3088                    // Step 7.7.3.3. Otherwise, try to upgrade inclusiveDescendant.
3089                    else {
3090                        try_upgrade_element(cx, element);
3091                    }
3092                }
3093                // Step 7.7.4. Otherwise, if inclusiveDescendant is a shadow
3094                // root, inclusiveDescendant’s custom element registry is
3095                // non-null, and inclusiveDescendant’s custom element registry’s
3096                // is scoped is true, then append inclusiveDescendant’s node
3097                // document to inclusiveDescendant’s custom element registry’s
3098                // scoped document set.
3099                else if let Some(shadow_root) =
3100                    DomRoot::downcast::<ShadowRoot>(descendant.clone()) &&
3101                    let Some(custom_element_registry) = shadow_root.custom_element_registry() &&
3102                    custom_element_registry.is_scoped()
3103                {
3104                    custom_element_registry.add_scoped_document(shadow_root.owner_doc());
3105                }
3106
3107                // Step 11.1 For each shadow-including inclusive descendant inclusiveDescendant of node,
3108                //           in shadow-including tree order, append inclusiveDescendant to staticNodeList.
3109                static_node_list
3110                    .get_or_insert_default()
3111                    .push(descendant.as_traced());
3112            }
3113        }
3114
3115        Self::maybe_dirty_visible_selection_for_newly_inserted_nodes(cx.no_gc(), parent, new_nodes);
3116
3117        if let SuppressObserver::Unsuppressed = suppress_observers {
3118            // Step 9. Run the children changed steps for parent.
3119            // TODO(xiaochengh): If we follow the spec and move it out of the if block, some WPT fail. Investigate.
3120            vtable_for(parent).children_changed(
3121                cx,
3122                &ChildrenMutation::insert(previous_sibling.as_deref(), child),
3123            );
3124
3125            // Step 8. If suppress observers flag is unset, then queue a tree mutation record for parent
3126            // with nodes, « », previousSibling, and child.
3127            let mutation = LazyCell::new(|| Mutation::ChildList {
3128                added: Some(new_nodes),
3129                removed: None,
3130                prev: previous_sibling.as_deref(),
3131                next: child,
3132            });
3133            MutationObserver::queue_a_mutation_record(cx, parent, mutation);
3134        }
3135
3136        // We use a delayed task for this step to work around an awkward interaction between
3137        // script/layout blockers, Node::replace_all, and the children_changed vtable method.
3138        // Any node with a post connection step that triggers layout (such as iframes) needs
3139        // to be marked as dirty before doing so. This is handled by Node's children_changed
3140        // callback, but when Node::insert is called as part of Node::replace_all then the
3141        // callback is suppressed until we return to Node::replace_all. To ensure the sequence:
3142        // 1) children_changed in Node::replace_all,
3143        // 2) post_connection_steps from Node::insert,
3144        // we use a delayed task that will run as soon as Node::insert removes its
3145        // script/layout blocker.
3146        if let Some(static_node_list) = static_node_list {
3147            parent_document.add_delayed_task(
3148                task!(PostConnectionSteps: |cx, static_node_list: RootedTraceableBox<TraceableSmallVec<[Dom<Node>; 4]>>| {
3149                    // Step 12. For each node of staticNodeList, if node is connected, then run the
3150                    //          post-connection steps with node.
3151                    //
3152                    // Note: We only add the nodes to the static_node_list which are connected.
3153                    for node in static_node_list.iter() {
3154                        vtable_for(node).post_connection_steps(cx);
3155                    }
3156                }),
3157            );
3158        }
3159
3160        parent_document.remove_script_and_layout_blocker(cx);
3161        from_document.remove_script_and_layout_blocker(cx);
3162    }
3163
3164    /// If insertion of any of the given nodes happened within an existing visible
3165    /// selection, mark the [`Document`]'s visible selection as dirty.
3166    pub(crate) fn maybe_dirty_visible_selection_for_newly_inserted_nodes(
3167        no_gc: &NoGC,
3168        parent: &Node,
3169        inserted_nodes: &[&Node],
3170    ) {
3171        let Some(selection) = parent.owner_document_unrooted(no_gc).selection() else {
3172            return;
3173        };
3174
3175        for node in inserted_nodes {
3176            match node.parent_in_flat_tree(no_gc) {
3177                FlatTreeParent::RootNode | FlatTreeParent::NotInFlatTree => {},
3178                FlatTreeParent::Parent(parent) => {
3179                    if parent.get_flag(NodeFlags::OVERLAPS_DOCUMENT_SELECTION) {
3180                        selection.set_visible_selection_dirty();
3181                        return;
3182                    }
3183                },
3184            }
3185        }
3186    }
3187
3188    /// <https://dom.spec.whatwg.org/#concept-node-replace-all>
3189    pub(crate) fn replace_all(cx: &mut JSContext, node: Option<&Node>, parent: &Node) {
3190        let document = parent.owner_document();
3191        document.add_script_and_layout_blocker();
3192
3193        // Step 1. Let removedNodes be parent’s children.
3194        rooted_vec!(let removed_nodes <- parent.children().map(|child| DomRoot::as_traced(&child)));
3195
3196        // Step 2. Let addedNodes be the empty set.
3197        // Step 3. If node is a DocumentFragment node, then set addedNodes to node’s children.
3198        // Step 4. Otherwise, if node is non-null, set addedNodes to « node ».
3199        rooted_vec!(let mut added_nodes);
3200        let added_nodes = if let Some(node) = node.as_ref() {
3201            if let NodeTypeId::DocumentFragment(_) = node.type_id() {
3202                added_nodes.extend(node.children().map(|child| Dom::from_ref(&*child)));
3203                added_nodes.as_ref_slice()
3204            } else {
3205                from_ref(node)
3206            }
3207        } else {
3208            &[] as &[&Node]
3209        };
3210
3211        // Step 5. Remove all parent’s children, in tree order, with suppressObservers set to true.
3212        for child in &*removed_nodes {
3213            Node::remove(cx, child, parent, SuppressObserver::Suppressed);
3214        }
3215
3216        // Step 6. If node is non-null, then insert node into parent before null with suppressObservers set to true.
3217        if let Some(node) = node {
3218            Node::insert(cx, node, parent, None, SuppressObserver::Suppressed);
3219        }
3220
3221        vtable_for(parent).children_changed(cx, &ChildrenMutation::ReplaceAll);
3222
3223        // Step 7. If either addedNodes or removedNodes is not empty, then queue a tree mutation record
3224        // for parent with addedNodes, removedNodes, null, and null.
3225        if !removed_nodes.is_empty() || !added_nodes.is_empty() {
3226            let mutation = LazyCell::new(|| Mutation::ChildList {
3227                added: Some(added_nodes),
3228                removed: Some(removed_nodes.as_ref_slice()),
3229                prev: None,
3230                next: None,
3231            });
3232            MutationObserver::queue_a_mutation_record(cx, parent, mutation);
3233        }
3234        document.remove_script_and_layout_blocker(cx);
3235    }
3236
3237    /// <https://dom.spec.whatwg.org/multipage/#string-replace-all>
3238    pub(crate) fn string_replace_all(cx: &mut JSContext, string: DOMString, parent: &Node) {
3239        if string.is_empty() {
3240            Node::replace_all(cx, None, parent);
3241        } else {
3242            let text = Text::new(cx, string, &parent.owner_document());
3243            Node::replace_all(cx, Some(text.upcast::<Node>()), parent);
3244        };
3245    }
3246
3247    /// <https://dom.spec.whatwg.org/#concept-node-pre-remove>
3248    pub(super) fn pre_remove(
3249        cx: &mut JSContext,
3250        child: &Node,
3251        parent: &Node,
3252    ) -> Fallible<DomRoot<Node>> {
3253        // Step 1.
3254        match child.GetParentNode() {
3255            Some(ref node) if &**node != parent => {
3256                return Err(Error::NotFound(Some(
3257                    "Child's parent does not match the parent node provided".into(),
3258                )));
3259            },
3260            None => {
3261                return Err(Error::NotFound(Some(
3262                    "Child does not have a parent node".into(),
3263                )));
3264            },
3265            _ => (),
3266        }
3267
3268        // Step 2.
3269        Node::remove(cx, child, parent, SuppressObserver::Unsuppressed);
3270
3271        // Step 3.
3272        Ok(DomRoot::from_ref(child))
3273    }
3274
3275    /// <https://dom.spec.whatwg.org/#concept-node-remove>
3276    pub(super) fn remove(
3277        cx: &mut JSContext,
3278        node: &Node,
3279        parent: &Node,
3280        suppress_observers: SuppressObserver,
3281    ) {
3282        let document = parent.owner_document();
3283        document.add_script_and_layout_blocker();
3284
3285        // Step 1. Let parent be node’s parent.
3286        // Step 2. Assert: parent is non-null.
3287        // NOTE: We get parent as an argument instead
3288        assert!(
3289            node.GetParentNode()
3290                .is_some_and(|node_parent| &*node_parent == parent)
3291        );
3292
3293        // Step 3. Run the live range pre-remove steps.
3294        let mut cached_index = None;
3295        {
3296            let mut lazy_index = || *cached_index.get_or_insert_with(|| node.index());
3297            let document = parent.owner_doc_unrooted(cx.no_gc());
3298            if let Some(selection) = document.selection() {
3299                selection.pre_remove_steps(node, parent, &mut lazy_index);
3300            }
3301            document.live_range_pre_remove_steps(cx.no_gc(), node, parent, &mut lazy_index);
3302        }
3303
3304        // TODO: Step 4. Pre-removing steps for node iterators
3305
3306        // Step 5.
3307        let old_previous_sibling = node.GetPreviousSibling();
3308
3309        // Step 6.
3310        let old_next_sibling = node.GetNextSibling();
3311
3312        // Step 7. Remove node from its parent's children.
3313        // Step 11-14. Run removing steps and enqueue disconnected custom element reactions for the subtree.
3314        parent.remove_child(cx, node);
3315
3316        // Step 8. If node is assigned, then run assign slottables for node’s assigned slot.
3317        if let Some(slot) = node.assigned_slot() {
3318            slot.assign_slottables(cx);
3319        }
3320
3321        // Step 9. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list,
3322        // then run signal a slot change for parent.
3323        if parent.is_in_a_shadow_tree() &&
3324            let Some(slot_element) = parent.downcast::<HTMLSlotElement>() &&
3325            !slot_element.has_assigned_nodes()
3326        {
3327            slot_element.signal_a_slot_change(cx);
3328        }
3329
3330        // Step 10. If node has an inclusive descendant that is a slot:
3331        let has_slot_descendant = node
3332            .traverse_preorder_unrooted(cx.no_gc(), ShadowIncluding::No)
3333            .any(|elem| elem.is::<HTMLSlotElement>());
3334        if has_slot_descendant {
3335            // Step 10.1 Run assign slottables for a tree with parent’s root.
3336            parent
3337                .GetRootNode(&GetRootNodeOptions::empty())
3338                .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
3339
3340            // Step 10.2 Run assign slottables for a tree with node.
3341            node.assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Force);
3342        }
3343
3344        // TODO: Step 15. transient registered observers
3345
3346        // Step 16.
3347        if let SuppressObserver::Unsuppressed = suppress_observers {
3348            vtable_for(parent).children_changed(
3349                cx,
3350                &ChildrenMutation::replace(
3351                    old_previous_sibling.as_deref(),
3352                    &Some(node),
3353                    old_next_sibling.as_deref(),
3354                ),
3355            );
3356
3357            let removed = [node];
3358            let mutation = LazyCell::new(|| Mutation::ChildList {
3359                added: None,
3360                removed: Some(&removed),
3361                prev: old_previous_sibling.as_deref(),
3362                next: old_next_sibling.as_deref(),
3363            });
3364            MutationObserver::queue_a_mutation_record(cx, parent, mutation);
3365        }
3366        document.remove_script_and_layout_blocker(cx);
3367    }
3368
3369    /// <https://dom.spec.whatwg.org/#concept-node-clone>
3370    pub(crate) fn clone(
3371        cx: &mut JSContext,
3372        node: &Node,
3373        maybe_doc: Option<&Document>,
3374        clone_children: CloneChildrenFlag,
3375        registry: Option<DomRoot<CustomElementRegistry>>,
3376    ) -> DomRoot<Node> {
3377        // Step 1. If document is not given, let document be node’s node document.
3378        let document = match maybe_doc {
3379            Some(doc) => DomRoot::from_ref(doc),
3380            None => node.owner_doc(),
3381        };
3382
3383        // Step 2. / Step 3.
3384        // XXXabinader: clone() for each node as trait?
3385        let copy: DomRoot<Node> = match node.type_id() {
3386            NodeTypeId::DocumentType => {
3387                let doctype = node.downcast::<DocumentType>().unwrap();
3388                let doctype = DocumentType::new(
3389                    cx,
3390                    doctype.Name(),
3391                    Some(doctype.PublicId()),
3392                    Some(doctype.SystemId()),
3393                    &document,
3394                );
3395                DomRoot::upcast::<Node>(doctype)
3396            },
3397            NodeTypeId::Attr => {
3398                let attr = node.downcast::<Attr>().unwrap();
3399                let attr = Attr::new(
3400                    cx,
3401                    &document,
3402                    attr.local_name().clone(),
3403                    attr.value().clone(),
3404                    attr.name().clone(),
3405                    attr.namespace().clone(),
3406                    attr.prefix().cloned(),
3407                    None,
3408                );
3409                DomRoot::upcast::<Node>(attr)
3410            },
3411            NodeTypeId::DocumentFragment(_) => {
3412                let doc_fragment = DocumentFragment::new(cx, &document);
3413                DomRoot::upcast::<Node>(doc_fragment)
3414            },
3415            NodeTypeId::CharacterData(_) => {
3416                let cdata = node.downcast::<CharacterData>().unwrap();
3417                cdata.clone_with_data(cx, cdata.Data(), &document)
3418            },
3419            NodeTypeId::Document(_) => {
3420                // Step 1. Set copy’s encoding, content type, URL, origin, type, mode,
3421                // and allow declarative shadow roots, to those of node.
3422                let document = node.downcast::<Document>().unwrap();
3423                let is_html_doc = if document.is_html_document() {
3424                    IsHTMLDocument::HTMLDocument
3425                } else {
3426                    IsHTMLDocument::NonHTMLDocument
3427                };
3428                let window = document.window();
3429                let loader = DocumentLoader::new(&document.loader());
3430                let document = Document::new(
3431                    cx,
3432                    window,
3433                    HasBrowsingContext::No,
3434                    Some(document.url()),
3435                    None,
3436                    // https://github.com/whatwg/dom/issues/378
3437                    document.origin().clone(),
3438                    is_html_doc,
3439                    None,
3440                    None,
3441                    DocumentActivity::Inactive,
3442                    loader,
3443                    None,
3444                    document.status_code(),
3445                    false,
3446                    document.allow_declarative_shadow_roots(),
3447                    Some(document.insecure_requests_policy()),
3448                    document.has_trustworthy_ancestor_or_current_origin(),
3449                    document.custom_element_reaction_stack(),
3450                    document.creation_sandboxing_flag_set(),
3451                    document.pipeline_id(),
3452                    document.image_cache(),
3453                );
3454                // Step 2. If node’s custom element registry’s is scoped is true,
3455                // then set copy’s custom element registry to node’s custom element registry.
3456                // TODO
3457                DomRoot::upcast::<Node>(document)
3458            },
3459            // Step 2. If node is an element:
3460            NodeTypeId::Element(..) => {
3461                let element = node.downcast::<Element>().unwrap();
3462                // Step 2.1. Let registry be node’s custom element registry.
3463                // Step 2.2. If registry is null, then set registry to fallbackRegistry.
3464                let registry = element.custom_element_registry().or(registry);
3465                // Step 2.3. If registry is a global custom element registry, then
3466                // set registry to document’s effective global custom element registry.
3467                let registry =
3468                    if CustomElementRegistry::is_a_global_element_registry(registry.as_deref()) {
3469                        document.effective_global_custom_element_registry()
3470                    } else {
3471                        registry
3472                    };
3473                // Step 2.4. Set copy to the result of creating an element,
3474                // given document, node’s local name, node’s namespace,
3475                // node’s namespace prefix, node’s is value, false, and registry.
3476                let name = QualName {
3477                    prefix: element.prefix().as_ref().map(|p| Prefix::from(&**p)),
3478                    ns: element.namespace().clone(),
3479                    local: element.local_name().clone(),
3480                };
3481                let element = Element::create(
3482                    cx,
3483                    name,
3484                    element.get_is(),
3485                    &document,
3486                    ElementCreator::ScriptCreated,
3487                    CustomElementCreationMode::Asynchronous,
3488                    None,
3489                );
3490                // TODO: Move this into `Element::create`
3491                element.set_custom_element_registry(registry.as_deref(), cx.no_gc());
3492                DomRoot::upcast::<Node>(element)
3493            },
3494        };
3495
3496        // Step 4. Set copy’s node document and document to copy, if copy is a document,
3497        // and set copy’s node document to document otherwise.
3498        let document = match copy.downcast::<Document>() {
3499            Some(doc) => DomRoot::from_ref(doc),
3500            None => DomRoot::from_ref(&*document),
3501        };
3502        assert!(copy.owner_doc() == document);
3503
3504        // TODO: The spec tells us to do this in step 3.
3505        match node.type_id() {
3506            NodeTypeId::Document(_) => {
3507                let node_doc = node.downcast::<Document>().unwrap();
3508                let copy_doc = copy.downcast::<Document>().unwrap();
3509                copy_doc.set_encoding(node_doc.encoding());
3510                copy_doc.set_quirks_mode(node_doc.quirks_mode());
3511            },
3512            NodeTypeId::Element(..) => {
3513                let node_elem = node.downcast::<Element>().unwrap();
3514                let copy_elem = copy.downcast::<Element>().unwrap();
3515
3516                // Step 2.5. For each attribute of node’s attribute list:
3517                node_elem.copy_all_attributes_to_other_element(cx, copy_elem);
3518            },
3519            _ => (),
3520        }
3521
3522        // Step 5: Run any cloning steps defined for node in other applicable specifications and pass copy,
3523        // node, document, and the clone children flag if set, as parameters.
3524        vtable_for(node).cloning_steps(cx, &copy, maybe_doc, clone_children);
3525
3526        // Step 6. If the clone children flag is set, then for each child child of node, in tree order: append the
3527        // result of cloning child with document and the clone children flag set, to copy.
3528        if clone_children == CloneChildrenFlag::CloneChildren {
3529            for child in node.children() {
3530                let child_copy = Node::clone(cx, &child, Some(&document), clone_children, None);
3531                let _inserted_node = Node::pre_insert(cx, &child_copy, &copy, None);
3532            }
3533        }
3534
3535        // Step 7. If node is a shadow host whose shadow root’s clonable is true:
3536        // NOTE: Only elements can be shadow hosts
3537        if matches!(node.type_id(), NodeTypeId::Element(_)) {
3538            let node_elem = node.downcast::<Element>().unwrap();
3539            let copy_elem = copy.downcast::<Element>().unwrap();
3540
3541            if let Some(shadow_root) = node_elem.shadow_root().filter(|r| r.Clonable()) {
3542                // Step 7.1 Assert: copy is not a shadow host.
3543                assert!(!copy_elem.is_shadow_host());
3544
3545                // Step 7.2 Run attach a shadow root with copy, node’s shadow root’s mode, true,
3546                // node’s shadow root’s serializable, node’s shadow root’s delegates focus,
3547                // and node’s shadow root’s slot assignment.
3548                let copy_shadow_root =
3549                    copy_elem.attach_shadow(
3550                        cx,
3551                        IsUserAgentWidget::No,
3552                        shadow_root.Mode(),
3553                        shadow_root.Clonable(),
3554                        shadow_root.Serializable(),
3555                        shadow_root.DelegatesFocus(),
3556                        shadow_root.SlotAssignment(),
3557                    )
3558                    .expect("placement of attached shadow root must be valid, as this is a copy of an existing one");
3559
3560                // Step 7.3 Set copy’s shadow root’s declarative to node’s shadow root’s declarative.
3561                copy_shadow_root.set_declarative(shadow_root.is_declarative());
3562
3563                // Step 7.4 For each child child of node’s shadow root, in tree order: append the result of
3564                // cloning child with document and the clone children flag set, to copy’s shadow root.
3565                for child in shadow_root.upcast::<Node>().children() {
3566                    let child_copy = Node::clone(
3567                        cx,
3568                        &child,
3569                        Some(&document),
3570                        CloneChildrenFlag::CloneChildren,
3571                        None,
3572                    );
3573
3574                    // TODO: Should we handle the error case here and in step 6?
3575                    let _inserted_node =
3576                        Node::pre_insert(cx, &child_copy, copy_shadow_root.upcast::<Node>(), None);
3577                }
3578            }
3579        }
3580
3581        // Step 8. Return copy.
3582        copy
3583    }
3584
3585    /// <https://html.spec.whatwg.org/multipage/#child-text-content>
3586    pub(crate) fn child_text_content(&self) -> DOMString {
3587        Node::collect_text_contents(self.children())
3588    }
3589
3590    /// <https://html.spec.whatwg.org/multipage/#descendant-text-content>
3591    pub(crate) fn descendant_text_content(&self) -> DOMString {
3592        Node::collect_text_contents(self.traverse_preorder(ShadowIncluding::No))
3593    }
3594
3595    pub(crate) fn collect_text_contents<T: Iterator<Item = DomRoot<Node>>>(
3596        iterator: T,
3597    ) -> DOMString {
3598        let mut content = String::new();
3599        for node in iterator {
3600            if let Some(text) = node.downcast::<Text>() {
3601                content.push_str(&text.upcast::<CharacterData>().data());
3602            }
3603        }
3604        DOMString::from(content)
3605    }
3606
3607    /// <https://dom.spec.whatwg.org/#string-replace-all>
3608    pub(crate) fn set_text_content_for_element(
3609        &self,
3610        cx: &mut JSContext,
3611        value: Option<DOMString>,
3612    ) {
3613        // This should only be called for elements and document fragments when setting the
3614        // text content: https://dom.spec.whatwg.org/#set-text-content
3615        assert!(matches!(
3616            self.type_id(),
3617            NodeTypeId::DocumentFragment(_) | NodeTypeId::Element(..)
3618        ));
3619        let value = value.unwrap_or_default();
3620        let node = if value.is_empty() {
3621            // Step 1. Let node be null.
3622            None
3623        } else {
3624            // Step 2. If string is not the empty string, then set node to
3625            // a new Text node whose data is string and node document is parent’s node document.
3626            Some(DomRoot::upcast(self.owner_doc().CreateTextNode(cx, value)))
3627        };
3628
3629        // Step 3. Replace all with node within parent.
3630        Self::replace_all(cx, node.as_deref(), self);
3631    }
3632
3633    pub(crate) fn namespace_to_string(namespace: Namespace) -> Option<DOMString> {
3634        match namespace {
3635            ns!() => None,
3636            _ => Some(TracedDOMString::from(namespace).root()),
3637        }
3638    }
3639
3640    /// <https://dom.spec.whatwg.org/#locate-a-namespace>
3641    pub(crate) fn locate_namespace(node: &Node, prefix: Option<DOMString>) -> Namespace {
3642        match node.type_id() {
3643            NodeTypeId::Element(_) => node.downcast::<Element>().unwrap().locate_namespace(prefix),
3644            NodeTypeId::Attr => node
3645                .downcast::<Attr>()
3646                .unwrap()
3647                .GetOwnerElement()
3648                .as_ref()
3649                .map_or(ns!(), |elem| elem.locate_namespace(prefix)),
3650            NodeTypeId::Document(_) => node
3651                .downcast::<Document>()
3652                .unwrap()
3653                .GetDocumentElement()
3654                .as_ref()
3655                .map_or(ns!(), |elem| elem.locate_namespace(prefix)),
3656            NodeTypeId::DocumentType | NodeTypeId::DocumentFragment(_) => ns!(),
3657            _ => node
3658                .GetParentElement()
3659                .as_ref()
3660                .map_or(ns!(), |elem| elem.locate_namespace(prefix)),
3661        }
3662    }
3663
3664    /// If the given untrusted node address represents a valid DOM node in the given runtime,
3665    /// returns it.
3666    ///
3667    /// # Safety
3668    ///
3669    /// Callers should ensure they pass an UntrustedNodeAddress that points to a valid [`JSObject`]
3670    /// in memory that represents a [`Node`].
3671    #[expect(unsafe_code)]
3672    pub(crate) unsafe fn from_untrusted_node_address(
3673        candidate: UntrustedNodeAddress,
3674    ) -> &'static Self {
3675        // https://github.com/servo/servo/issues/6383
3676        let candidate = candidate.0 as usize;
3677        let object = candidate as *mut JSObject;
3678        if object.is_null() {
3679            panic!("Attempted to create a `Node` from an invalid pointer!")
3680        }
3681
3682        unsafe { &*(conversions::private_from_object(object) as *const Self) }
3683    }
3684
3685    pub(crate) fn html_serialize(
3686        &self,
3687        cx: &mut JSContext,
3688        traversal_scope: html_serialize::TraversalScope,
3689        serialize_shadow_roots: bool,
3690        shadow_roots: Vec<DomRoot<ShadowRoot>>,
3691    ) -> DOMString {
3692        let mut writer = vec![];
3693        let mut serializer = HtmlSerializer::new(
3694            &mut writer,
3695            html_serialize::SerializeOpts {
3696                traversal_scope: traversal_scope.clone(),
3697                ..Default::default()
3698            },
3699        );
3700
3701        serialize_html_fragment(
3702            cx,
3703            self,
3704            &mut serializer,
3705            traversal_scope,
3706            serialize_shadow_roots,
3707            shadow_roots,
3708        )
3709        .expect("Serializing node failed");
3710
3711        // FIXME(ajeffrey): Directly convert UTF8 to DOMString
3712        DOMString::from(String::from_utf8(writer).unwrap())
3713    }
3714
3715    /// <https://w3c.github.io/DOM-Parsing/#dfn-xml-serialization>
3716    pub(crate) fn xml_serialize(
3717        &self,
3718        traversal_scope: xml_serialize::TraversalScope,
3719    ) -> Fallible<DOMString> {
3720        let mut writer = vec![];
3721        xml_serialize::serialize(
3722            &mut writer,
3723            &HtmlSerialize::new(self),
3724            xml_serialize::SerializeOpts { traversal_scope },
3725        )
3726        .map_err(|error| {
3727            error!("Cannot serialize node: {error}");
3728            Error::InvalidState(Some("Cannot serialize node".into()))
3729        })?;
3730
3731        // FIXME(ajeffrey): Directly convert UTF8 to DOMString
3732        let string = DOMString::from(String::from_utf8(writer).map_err(|error| {
3733            error!("Cannot serialize node: {error}");
3734            Error::InvalidState(Some("Cannot serialize node".into()))
3735        })?);
3736
3737        Ok(string)
3738    }
3739
3740    /// <https://html.spec.whatwg.org/multipage/#fragment-serializing-algorithm-steps>
3741    pub(crate) fn fragment_serialization_algorithm(
3742        &self,
3743        cx: &mut JSContext,
3744        require_well_formed: bool,
3745    ) -> Fallible<DOMString> {
3746        // Step 1. Let context document be node's node document.
3747        let context_document = self.owner_document();
3748
3749        // Step 2. If context document is an HTML document, return the result of HTML fragment serialization algorithm
3750        // with node, false, and « ».
3751        if context_document.is_html_document() {
3752            return Ok(self.html_serialize(
3753                cx,
3754                html_serialize::TraversalScope::ChildrenOnly(None),
3755                false,
3756                vec![],
3757            ));
3758        }
3759
3760        // Step 3. Return the XML serialization of node given require well-formed.
3761        // TODO: xml5ever doesn't seem to want require_well_formed
3762        let _ = require_well_formed;
3763        self.xml_serialize(xml_serialize::TraversalScope::ChildrenOnly(None))
3764    }
3765
3766    pub(crate) fn get_next_sibling_unrooted<'a>(
3767        &self,
3768        no_gc: &'a NoGC,
3769    ) -> Option<UnrootedDom<'a, Node>> {
3770        self.next_sibling.get_unrooted(no_gc)
3771    }
3772
3773    pub(crate) fn next_flat_tree_sibling_unrooted<'a>(
3774        &self,
3775        no_gc: &'a NoGC,
3776    ) -> Option<UnrootedDom<'a, Node>> {
3777        if let Some(slot_element) = self.assigned_slot() {
3778            // TODO(mrobinson): When traversing this is O(n²) against the number of
3779            // slotted nodes, which isn't ideal. We could track the index of each
3780            // slottable in the `<slot>` to fix this.
3781            return slot_element
3782                .assigned_nodes()
3783                .iter()
3784                .skip_while(|slottable| &*slottable.0 != self)
3785                // Skip `self` so that this moves on the the next node in the list of slottables.
3786                .nth(1)
3787                .map(|next_slottable| next_slottable.0.as_unrooted(no_gc));
3788        }
3789        self.get_next_sibling_unrooted(no_gc)
3790    }
3791
3792    pub(crate) fn get_previous_sibling_unrooted<'a>(
3793        &self,
3794        no_gc: &'a NoGC,
3795    ) -> Option<UnrootedDom<'a, Node>> {
3796        self.prev_sibling.get_unrooted(no_gc)
3797    }
3798
3799    pub(crate) fn get_first_child_unrooted<'a>(
3800        &self,
3801        no_gc: &'a NoGC,
3802    ) -> Option<UnrootedDom<'a, Node>> {
3803        self.first_child.get_unrooted(no_gc)
3804    }
3805
3806    pub(crate) fn first_flat_tree_child_unrooted<'a>(
3807        &self,
3808        no_gc: &'a NoGC,
3809    ) -> Option<UnrootedDom<'a, Node>> {
3810        let Some(element) = self.downcast::<Element>() else {
3811            return self.get_first_child_unrooted(no_gc);
3812        };
3813        if let Some(shadow_root) = element.shadow_root_unrooted(no_gc) {
3814            return shadow_root
3815                .upcast::<Node>()
3816                .first_flat_tree_child_unrooted(no_gc);
3817        };
3818
3819        // Return the first slotted node if this is a `<slot>` that has slotted nodes.
3820        // Important here is that fallback content (`self.first_child()`) is returned
3821        // if there are no slotted nodes.
3822        if let Some(slot_element) = element.downcast::<HTMLSlotElement>() &&
3823            slot_element.has_assigned_nodes() &&
3824            let Some(assigned_node) = slot_element.assigned_nodes().first()
3825        {
3826            return Some(assigned_node.0.as_unrooted(no_gc));
3827        }
3828
3829        self.get_first_child_unrooted(no_gc)
3830    }
3831
3832    fn get_last_child_unrooted<'b>(&self, no_gc: &'b NoGC) -> Option<UnrootedDom<'b, Node>> {
3833        self.last_child.get_unrooted(no_gc)
3834    }
3835
3836    pub(crate) fn get_parent_node_unrooted<'a>(
3837        &self,
3838        no_gc: &'a NoGC,
3839    ) -> Option<UnrootedDom<'a, Node>> {
3840        self.parent_node.get_unrooted(no_gc)
3841    }
3842
3843    /// Compares `other` with `self` in [tree order](https://dom.spec.whatwg.org/#concept-tree-order).
3844    pub(crate) fn compare_dom_tree_position(
3845        &self,
3846        other: &Node,
3847        common_ancestor: &Node,
3848        shadow_including: ShadowIncluding,
3849    ) -> Ordering {
3850        debug_assert!(
3851            self.inclusive_ancestors(shadow_including)
3852                .any(|ancestor| &*ancestor == common_ancestor)
3853        );
3854        debug_assert!(
3855            other
3856                .inclusive_ancestors(shadow_including)
3857                .any(|ancestor| &*ancestor == common_ancestor)
3858        );
3859
3860        if self == other {
3861            return Ordering::Equal;
3862        }
3863
3864        if self == common_ancestor {
3865            return Ordering::Less;
3866        }
3867        if other == common_ancestor {
3868            return Ordering::Greater;
3869        }
3870
3871        let my_ancestors: Vec<_> = self
3872            .inclusive_ancestors(shadow_including)
3873            .take_while(|ancestor| &**ancestor != common_ancestor)
3874            .collect();
3875        let other_ancestors: Vec<_> = other
3876            .inclusive_ancestors(shadow_including)
3877            .take_while(|ancestor| &**ancestor != common_ancestor)
3878            .collect();
3879
3880        // Consume any ancestors that are shared between a and b
3881        let mut i = my_ancestors.len() - 1;
3882        let mut j = other_ancestors.len() - 1;
3883
3884        while my_ancestors[i] == other_ancestors[j] {
3885            if i == 0 {
3886                // self is an ancestor of other
3887                debug_assert_ne!(j, 0, "Equal inclusive ancestors but nodes are not equal?");
3888                return Ordering::Less;
3889            }
3890            if j == 0 {
3891                // other is an ancestor of self
3892                return Ordering::Greater;
3893            }
3894
3895            i -= 1;
3896            j -= 1;
3897        }
3898
3899        // Now a_ancestors[i] and b_ancestors[j] have a common parent, but are not themselves equal
3900        // => They are siblings.
3901        if my_ancestors[i]
3902            .preceding_siblings()
3903            .any(|sibling| sibling == other_ancestors[j])
3904        {
3905            // other or an ancestor is a preceding sibling of self or one of its ancestors.
3906            Ordering::Greater
3907        } else {
3908            // self or an ancestor is a preceding sibling of other or one of its ancestors.
3909            debug_assert!(
3910                other_ancestors[j]
3911                    .preceding_siblings()
3912                    .any(|sibling| sibling == my_ancestors[i])
3913            );
3914            Ordering::Less
3915        }
3916    }
3917}
3918
3919impl NodeMethods<crate::DomTypeHolder> for Node {
3920    /// <https://dom.spec.whatwg.org/#dom-node-nodetype>
3921    fn NodeType(&self) -> u16 {
3922        match self.type_id() {
3923            NodeTypeId::Attr => NodeConstants::ATTRIBUTE_NODE,
3924            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::Text)) => {
3925                NodeConstants::TEXT_NODE
3926            },
3927            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::CDATASection)) => {
3928                NodeConstants::CDATA_SECTION_NODE
3929            },
3930            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
3931                NodeConstants::PROCESSING_INSTRUCTION_NODE
3932            },
3933            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => NodeConstants::COMMENT_NODE,
3934            NodeTypeId::Document(_) => NodeConstants::DOCUMENT_NODE,
3935            NodeTypeId::DocumentType => NodeConstants::DOCUMENT_TYPE_NODE,
3936            NodeTypeId::DocumentFragment(_) => NodeConstants::DOCUMENT_FRAGMENT_NODE,
3937            NodeTypeId::Element(_) => NodeConstants::ELEMENT_NODE,
3938        }
3939    }
3940
3941    /// <https://dom.spec.whatwg.org/#dom-node-nodename>
3942    fn NodeName(&self) -> DOMString {
3943        match self.type_id() {
3944            NodeTypeId::Attr => self.downcast::<Attr>().unwrap().qualified_name(),
3945            NodeTypeId::Element(..) => self.downcast::<Element>().unwrap().TagName(),
3946            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::Text)) => {
3947                DOMString::from_static("#text")
3948            },
3949            NodeTypeId::CharacterData(CharacterDataTypeId::Text(TextTypeId::CDATASection)) => {
3950                DOMString::from_static("#cdata-section")
3951            },
3952            NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
3953                self.downcast::<ProcessingInstruction>().unwrap().Target()
3954            },
3955            NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => {
3956                DOMString::from_static("#comment")
3957            },
3958            NodeTypeId::DocumentType => self.downcast::<DocumentType>().unwrap().Name(),
3959            NodeTypeId::DocumentFragment(_) => DOMString::from_static("#document-fragment"),
3960            NodeTypeId::Document(_) => DOMString::from_static("#document"),
3961        }
3962    }
3963
3964    /// <https://dom.spec.whatwg.org/#dom-node-baseuri>
3965    fn BaseURI(&self) -> USVString {
3966        USVString(String::from(self.owner_doc().base_url().as_str()))
3967    }
3968
3969    /// <https://dom.spec.whatwg.org/#dom-node-isconnected>
3970    fn IsConnected(&self) -> bool {
3971        self.is_connected()
3972    }
3973
3974    /// <https://dom.spec.whatwg.org/#dom-node-ownerdocument>
3975    fn GetOwnerDocument(&self) -> Option<DomRoot<Document>> {
3976        match self.type_id() {
3977            NodeTypeId::Document(_) => None,
3978            _ => Some(self.owner_doc()),
3979        }
3980    }
3981
3982    /// <https://dom.spec.whatwg.org/#dom-node-getrootnode>
3983    fn GetRootNode(&self, options: &GetRootNodeOptions) -> DomRoot<Node> {
3984        if !options.composed &&
3985            let Some(shadow_root) = self.containing_shadow_root()
3986        {
3987            return DomRoot::upcast(shadow_root);
3988        }
3989
3990        if self.is_connected() {
3991            DomRoot::upcast(self.owner_document())
3992        } else {
3993            self.inclusive_ancestors(ShadowIncluding::Yes)
3994                .last()
3995                .unwrap()
3996        }
3997    }
3998
3999    /// <https://dom.spec.whatwg.org/#dom-node-parentnode>
4000    fn GetParentNode(&self) -> Option<DomRoot<Node>> {
4001        self.parent_node().get()
4002    }
4003
4004    /// <https://dom.spec.whatwg.org/#dom-node-parentelement>
4005    fn GetParentElement(&self) -> Option<DomRoot<Element>> {
4006        self.GetParentNode().and_then(DomRoot::downcast)
4007    }
4008
4009    /// <https://dom.spec.whatwg.org/#dom-node-haschildnodes>
4010    fn HasChildNodes(&self) -> bool {
4011        self.first_child().get().is_some()
4012    }
4013
4014    /// <https://dom.spec.whatwg.org/#dom-node-childnodes>
4015    fn ChildNodes(&self, cx: &mut JSContext) -> DomRoot<NodeList> {
4016        if let Some(list) = self.ensure_rare_data().child_list.get() {
4017            return list;
4018        }
4019
4020        let doc = self.owner_doc();
4021        let window = doc.window();
4022        let list = NodeList::new_child_list(cx, window, self);
4023        self.ensure_rare_data().child_list.set(Some(&list));
4024        list
4025    }
4026
4027    /// <https://dom.spec.whatwg.org/#dom-node-firstchild>
4028    fn GetFirstChild(&self) -> Option<DomRoot<Node>> {
4029        self.first_child().get()
4030    }
4031
4032    /// <https://dom.spec.whatwg.org/#dom-node-lastchild>
4033    fn GetLastChild(&self) -> Option<DomRoot<Node>> {
4034        self.last_child().get()
4035    }
4036
4037    /// <https://dom.spec.whatwg.org/#dom-node-previoussibling>
4038    fn GetPreviousSibling(&self) -> Option<DomRoot<Node>> {
4039        self.prev_sibling().get()
4040    }
4041
4042    /// <https://dom.spec.whatwg.org/#dom-node-nextsibling>
4043    fn GetNextSibling(&self) -> Option<DomRoot<Node>> {
4044        self.next_sibling().get()
4045    }
4046
4047    /// <https://dom.spec.whatwg.org/#dom-node-nodevalue>
4048    fn GetNodeValue(&self) -> Option<DOMString> {
4049        match self.type_id() {
4050            NodeTypeId::Attr => Some(self.downcast::<Attr>().unwrap().Value()),
4051            NodeTypeId::CharacterData(_) => {
4052                self.downcast::<CharacterData>().map(CharacterData::Data)
4053            },
4054            _ => None,
4055        }
4056    }
4057
4058    /// <https://dom.spec.whatwg.org/#dom-node-nodevalue>
4059    fn SetNodeValue(&self, cx: &mut JSContext, val: Option<DOMString>) -> Fallible<()> {
4060        match self.type_id() {
4061            NodeTypeId::Attr => {
4062                let attr = self.downcast::<Attr>().unwrap();
4063                attr.SetValue(cx, val.unwrap_or_default())?;
4064            },
4065            NodeTypeId::CharacterData(_) => {
4066                let character_data = self.downcast::<CharacterData>().unwrap();
4067                character_data.SetData(cx, val.unwrap_or_default());
4068            },
4069            _ => {},
4070        };
4071        Ok(())
4072    }
4073
4074    /// <https://dom.spec.whatwg.org/#dom-node-textcontent>
4075    fn GetTextContent(&self) -> Option<DOMString> {
4076        match self.type_id() {
4077            NodeTypeId::DocumentFragment(_) | NodeTypeId::Element(..) => {
4078                let content =
4079                    Node::collect_text_contents(self.traverse_preorder(ShadowIncluding::No));
4080                Some(content)
4081            },
4082            NodeTypeId::Attr => Some(self.downcast::<Attr>().unwrap().Value()),
4083            NodeTypeId::CharacterData(..) => {
4084                let characterdata = self.downcast::<CharacterData>().unwrap();
4085                Some(characterdata.Data())
4086            },
4087            NodeTypeId::DocumentType | NodeTypeId::Document(_) => None,
4088        }
4089    }
4090
4091    /// <https://dom.spec.whatwg.org/#set-text-content>
4092    fn SetTextContent(&self, cx: &mut JSContext, value: Option<DOMString>) -> Fallible<()> {
4093        match self.type_id() {
4094            NodeTypeId::DocumentFragment(_) | NodeTypeId::Element(..) => {
4095                self.set_text_content_for_element(cx, value);
4096            },
4097            NodeTypeId::Attr => {
4098                let attr = self.downcast::<Attr>().unwrap();
4099                attr.SetValue(cx, value.unwrap_or_default())?;
4100            },
4101            NodeTypeId::CharacterData(..) => {
4102                let characterdata = self.downcast::<CharacterData>().unwrap();
4103                characterdata.SetData(cx, value.unwrap_or_default());
4104            },
4105            NodeTypeId::DocumentType | NodeTypeId::Document(_) => {},
4106        };
4107        Ok(())
4108    }
4109
4110    /// <https://dom.spec.whatwg.org/#dom-node-insertbefore>
4111    fn InsertBefore(
4112        &self,
4113        cx: &mut JSContext,
4114        node: &Node,
4115        child: Option<&Node>,
4116    ) -> Fallible<DomRoot<Node>> {
4117        Node::pre_insert(cx, node, self, child)
4118    }
4119
4120    /// <https://dom.spec.whatwg.org/#dom-node-appendchild>
4121    fn AppendChild(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
4122        Node::pre_insert(cx, node, self, None)
4123    }
4124
4125    /// <https://dom.spec.whatwg.org/#concept-node-replace>
4126    fn ReplaceChild(
4127        &self,
4128        cx: &mut JSContext,
4129        node: &Node,
4130        child: &Node,
4131    ) -> Fallible<DomRoot<Node>> {
4132        // Step 1. Ensure pre-insert validity given node, parent, child, and « child ».
4133        Node::ensure_pre_insertion_validity(cx.no_gc(), node, self, Some(child), &[child])?;
4134
4135        // Step 2. Let referenceChild be child’s next sibling.
4136        // Step 3. If referenceChild is node, then set referenceChild to node’s next sibling.
4137        let child_next_sibling = child.GetNextSibling();
4138        let node_next_sibling = node.GetNextSibling();
4139        let reference_child = if child_next_sibling.as_deref() == Some(node) {
4140            node_next_sibling.as_deref()
4141        } else {
4142            child_next_sibling.as_deref()
4143        };
4144
4145        // Step 4. Let previousSibling be child’s previous sibling.
4146        let previous_sibling = child.GetPreviousSibling();
4147
4148        // Step 5. Let removedNodes be the empty set.
4149        // Step 6. Adopt node into parent’s node document.
4150        let document = self.owner_document();
4151        Node::adopt(cx, node, &document);
4152
4153        // Step 7. If child’s parent is non-null:
4154        //     1. Set removedNodes to « child ».
4155        //     2. Remove child with the suppress observers flag set.
4156        let removed_child = if node != child {
4157            Node::remove(cx, child, self, SuppressObserver::Suppressed);
4158            Some(child)
4159        } else {
4160            None
4161        };
4162
4163        // Step 8. Let nodes be node’s children if node is a DocumentFragment node; otherwise « node ».
4164        rooted_vec!(let mut nodes);
4165        let nodes = if node.type_id() ==
4166            NodeTypeId::DocumentFragment(DocumentFragmentTypeId::DocumentFragment) ||
4167            node.type_id() == NodeTypeId::DocumentFragment(DocumentFragmentTypeId::ShadowRoot)
4168        {
4169            nodes.extend(node.children().map(|node| Dom::from_ref(&*node)));
4170            nodes.as_ref_slice()
4171        } else {
4172            from_ref(&node)
4173        };
4174
4175        // Step 9. Insert node into parent before referenceChild with the suppress observers flag set.
4176        Node::insert(
4177            cx,
4178            node,
4179            self,
4180            reference_child,
4181            SuppressObserver::Suppressed,
4182        );
4183
4184        vtable_for(self).children_changed(
4185            cx,
4186            &ChildrenMutation::replace(
4187                previous_sibling.as_deref(),
4188                &removed_child,
4189                reference_child,
4190            ),
4191        );
4192
4193        // Step 10. Queue a tree mutation record for parent with nodes, removedNodes,
4194        // previousSibling, and referenceChild.
4195        let removed = removed_child.map(|r| [r]);
4196        let mutation = LazyCell::new(|| Mutation::ChildList {
4197            added: Some(nodes),
4198            removed: removed.as_ref().map(|r| &r[..]),
4199            prev: previous_sibling.as_deref(),
4200            next: reference_child,
4201        });
4202
4203        MutationObserver::queue_a_mutation_record(cx, self, mutation);
4204
4205        // Step 11. Return child.
4206        Ok(DomRoot::from_ref(child))
4207    }
4208
4209    /// <https://dom.spec.whatwg.org/#dom-node-removechild>
4210    fn RemoveChild(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
4211        Node::pre_remove(cx, node, self)
4212    }
4213
4214    /// <https://dom.spec.whatwg.org/#dom-node-normalize>
4215    fn Normalize(&self, cx: &mut JSContext) {
4216        let mut children = self.children().peekable();
4217
4218        let document = self.owner_document();
4219        let selection = document.selection();
4220        while let Some(node) = children.next() {
4221            // The normalize() method steps are to run these steps for each descendant
4222            // exclusive Text node node of this:
4223            let Some(text) = node.downcast::<Text>() else {
4224                node.Normalize(cx);
4225                continue;
4226            };
4227            if text.is::<CDATASection>() {
4228                continue;
4229            }
4230
4231            // Step 1: Let length be node’s length.
4232            let cdata = text.upcast::<CharacterData>();
4233            let mut length = cdata.Length();
4234
4235            // Step 2: If length is zero, then remove node and continue with the next
4236            // exclusive Text node, if any.
4237            if length == 0 {
4238                Node::remove(cx, &node, self, SuppressObserver::Unsuppressed);
4239                continue;
4240            }
4241
4242            // Collect siblings that need to be merged ahead of time so that we can
4243            // avoid multiple mutation records.
4244            let mut siblings_to_merge: SmallVec<[DomRoot<CharacterData>; 4]> = SmallVec::new();
4245            let mut new_data_length = 0;
4246            while let Some(sibling) = children.peek() {
4247                if !sibling.is::<Text>() || sibling.is::<CDATASection>() {
4248                    break;
4249                }
4250
4251                let sibling: DomRoot<CharacterData> =
4252                    DomRoot::downcast(children.next().expect("Guaranteed by the peek above"))
4253                        .expect("Guaranteed by check above");
4254                new_data_length += sibling.data().len();
4255                siblings_to_merge.push(sibling);
4256            }
4257
4258            if siblings_to_merge.is_empty() {
4259                continue;
4260            }
4261
4262            // Step 3: Let data be the concatenation of the data of node’s contiguous
4263            // exclusive Text nodes (excluding itself), in tree order.
4264            let mut data = String::with_capacity(new_data_length);
4265            for sibling in &siblings_to_merge {
4266                data.push_str(sibling.data().as_str());
4267            }
4268
4269            // Step 4: Replace data of node with length, 0, and data.
4270            cdata.append_data(cx, &data);
4271
4272            // Step 5: Let currentNode be node’s next sibling.
4273            // Step 6: While currentNode is an exclusive Text node:
4274            // Note: Condition guaranteed by collection loop above.
4275            let first_sibling_index = LazyCell::new(|| node.index() + 1);
4276            for (current_node_index, current_node) in siblings_to_merge.iter().enumerate() {
4277                let index = &|| *first_sibling_index + current_node_index as u32;
4278                // Steps 6.1-6.4: The live range update steps.
4279                if let Some(selection) = &selection {
4280                    selection.normalization_steps(
4281                        self,
4282                        &node,
4283                        current_node.upcast(),
4284                        &index,
4285                        length,
4286                    );
4287                }
4288                document.live_range_normalization_steps(
4289                    cx.no_gc(),
4290                    self,
4291                    &node,
4292                    current_node.upcast(),
4293                    &index,
4294                    length,
4295                );
4296                // Step 6.5:  Add currentNode’s length to length.
4297                length += current_node.Length();
4298                // Step 6.6 Set currentNode to its next sibling.
4299                // This is handled by the loop.
4300            }
4301
4302            // Step 7: Remove node’s contiguous exclusive Text nodes (excluding itself),
4303            // in tree order.
4304            for current_node in siblings_to_merge.into_iter() {
4305                Node::remove(
4306                    cx,
4307                    current_node.upcast(),
4308                    self,
4309                    SuppressObserver::Unsuppressed,
4310                );
4311            }
4312        }
4313    }
4314
4315    /// <https://dom.spec.whatwg.org/#dom-node-clonenode>
4316    fn CloneNode(&self, cx: &mut JSContext, subtree: bool) -> Fallible<DomRoot<Node>> {
4317        // Step 1. If this is a shadow root, then throw a "NotSupportedError" DOMException.
4318        if self.is::<ShadowRoot>() {
4319            return Err(Error::NotSupported(Some(
4320                "Cannot clone a shadow root".into(),
4321            )));
4322        }
4323
4324        // Step 2. Return the result of cloning a node given this with subtree set to subtree.
4325        let result = Node::clone(
4326            cx,
4327            self,
4328            None,
4329            if subtree {
4330                CloneChildrenFlag::CloneChildren
4331            } else {
4332                CloneChildrenFlag::DoNotCloneChildren
4333            },
4334            None,
4335        );
4336        Ok(result)
4337    }
4338
4339    /// <https://dom.spec.whatwg.org/#dom-node-isequalnode>
4340    fn IsEqualNode(&self, maybe_node: Option<&Node>) -> bool {
4341        fn is_equal_doctype(node: &Node, other: &Node) -> bool {
4342            let doctype = node.downcast::<DocumentType>().unwrap();
4343            let other_doctype = other.downcast::<DocumentType>().unwrap();
4344            (*doctype.name() == *other_doctype.name()) &&
4345                (*doctype.public_id() == *other_doctype.public_id()) &&
4346                (*doctype.system_id() == *other_doctype.system_id())
4347        }
4348        fn is_equal_element(node: &Node, other: &Node) -> bool {
4349            let element = node.downcast::<Element>().unwrap();
4350            let other_element = other.downcast::<Element>().unwrap();
4351            (*element.namespace() == *other_element.namespace()) &&
4352                (*element.prefix() == *other_element.prefix()) &&
4353                (*element.local_name() == *other_element.local_name()) &&
4354                (element.attrs().borrow().len() == other_element.attrs().borrow().len())
4355        }
4356        fn is_equal_processinginstruction(node: &Node, other: &Node) -> bool {
4357            let pi = node.downcast::<ProcessingInstruction>().unwrap();
4358            let other_pi = other.downcast::<ProcessingInstruction>().unwrap();
4359            (*pi.target() == *other_pi.target()) &&
4360                (*pi.upcast::<CharacterData>().data() ==
4361                    *other_pi.upcast::<CharacterData>().data())
4362        }
4363        fn is_equal_characterdata(node: &Node, other: &Node) -> bool {
4364            let characterdata = node.downcast::<CharacterData>().unwrap();
4365            let other_characterdata = other.downcast::<CharacterData>().unwrap();
4366            *characterdata.data() == *other_characterdata.data()
4367        }
4368        fn is_equal_attr(node: &Node, other: &Node) -> bool {
4369            let attr = node.downcast::<Attr>().unwrap();
4370            let other_attr = other.downcast::<Attr>().unwrap();
4371            (*attr.namespace() == *other_attr.namespace()) &&
4372                (attr.local_name() == other_attr.local_name()) &&
4373                (**attr.value() == **other_attr.value())
4374        }
4375        fn is_equal_element_attrs(node: &Node, other: &Node) -> bool {
4376            let element = node.downcast::<Element>().unwrap();
4377            let other_element = other.downcast::<Element>().unwrap();
4378            assert!(element.attrs().borrow().len() == other_element.attrs().borrow().len());
4379            element.attrs().borrow().iter().all(|attr| {
4380                other_element.attrs().borrow().iter().any(|other_attr| {
4381                    (*attr.namespace() == *other_attr.namespace()) &&
4382                        (attr.local_name() == other_attr.local_name()) &&
4383                        (**attr.value() == **other_attr.value())
4384                })
4385            })
4386        }
4387
4388        fn is_equal_node(this: &Node, node: &Node) -> bool {
4389            // Step 2.
4390            if this.NodeType() != node.NodeType() {
4391                return false;
4392            }
4393
4394            match node.type_id() {
4395                // Step 3.
4396                NodeTypeId::DocumentType if !is_equal_doctype(this, node) => return false,
4397                NodeTypeId::Element(..) if !is_equal_element(this, node) => return false,
4398                NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction)
4399                    if !is_equal_processinginstruction(this, node) =>
4400                {
4401                    return false;
4402                },
4403                NodeTypeId::CharacterData(CharacterDataTypeId::Text(_)) |
4404                NodeTypeId::CharacterData(CharacterDataTypeId::Comment)
4405                    if !is_equal_characterdata(this, node) =>
4406                {
4407                    return false;
4408                },
4409                // Step 4.
4410                NodeTypeId::Element(..) if !is_equal_element_attrs(this, node) => return false,
4411                NodeTypeId::Attr if !is_equal_attr(this, node) => return false,
4412
4413                _ => (),
4414            }
4415
4416            // Step 5.
4417            if this.children_count() != node.children_count() {
4418                return false;
4419            }
4420
4421            // Step 6.
4422            this.children()
4423                .zip(node.children())
4424                .all(|(child, other_child)| is_equal_node(&child, &other_child))
4425        }
4426        match maybe_node {
4427            // Step 1.
4428            None => false,
4429            // Step 2-6.
4430            Some(node) => is_equal_node(self, node),
4431        }
4432    }
4433
4434    /// <https://dom.spec.whatwg.org/#dom-node-issamenode>
4435    fn IsSameNode(&self, other_node: Option<&Node>) -> bool {
4436        match other_node {
4437            Some(node) => self == node,
4438            None => false,
4439        }
4440    }
4441
4442    /// <https://dom.spec.whatwg.org/#dom-node-comparedocumentposition>
4443    fn CompareDocumentPosition(&self, no_gc: &NoGC, other: &Node) -> u16 {
4444        // Step 1. If this is other, then return zero.
4445        if self == other {
4446            return 0;
4447        }
4448
4449        // Step 2. Let node1 be other and node2 be this.
4450        let mut node1 = Some(other);
4451        let mut node2 = Some(self);
4452
4453        // Step 3. Let attr1 and attr2 be null.
4454        let mut attr1: Option<&Attr> = None;
4455        let mut attr2: Option<&Attr> = None;
4456
4457        // step 4: spec says to operate on node1 here,
4458        // node1 is definitely Some(other) going into this step
4459        // The compiler doesn't know the lifetime of attr1.GetOwnerElement
4460        // is guaranteed by the lifetime of attr1, so we hold it explicitly
4461        let attr1owner;
4462        if let Some(a) = other.downcast::<Attr>() {
4463            attr1 = Some(a);
4464            attr1owner = a.GetOwnerElement();
4465            node1 = match attr1owner {
4466                Some(ref e) => Some(e.upcast()),
4467                None => None,
4468            }
4469        }
4470
4471        // step 5.1: spec says to operate on node2 here,
4472        // node2 is definitely just Some(self) going into this step
4473        let attr2owner;
4474        if let Some(a) = self.downcast::<Attr>() {
4475            attr2 = Some(a);
4476            attr2owner = a.GetOwnerElement();
4477            node2 = match attr2owner {
4478                Some(ref e) => Some(e.upcast()),
4479                None => None,
4480            }
4481        }
4482
4483        // Step 5.2
4484        // This substep seems lacking in test coverage.
4485        // We hit this when comparing two attributes that have the
4486        // same owner element.
4487        if let Some(node2) = node2 &&
4488            Some(node2) == node1 &&
4489            let (Some(a1), Some(a2)) = (attr1, attr2)
4490        {
4491            let attrs = node2.downcast::<Element>().unwrap().attrs();
4492            // go through the attrs in order to see if self
4493            // or other is first; spec is clear that we
4494            // want value-equality, not reference-equality
4495            for attr in attrs.borrow().iter() {
4496                if (*attr.namespace() == *a1.namespace()) &&
4497                    (attr.local_name() == a1.local_name()) &&
4498                    (**attr.value() == **a1.value())
4499                {
4500                    return NodeConstants::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC +
4501                        NodeConstants::DOCUMENT_POSITION_PRECEDING;
4502                }
4503                if (*attr.namespace() == *a2.namespace()) &&
4504                    (attr.local_name() == a2.local_name()) &&
4505                    (**attr.value() == **a2.value())
4506                {
4507                    return NodeConstants::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC +
4508                        NodeConstants::DOCUMENT_POSITION_FOLLOWING;
4509                }
4510            }
4511            // both attrs have node2 as their owner element, so
4512            // we can't have left the loop without seeing them
4513            unreachable!();
4514        }
4515
4516        // Step 6. If node1 or node2 is null, or node1’s root is not node2’s root, then
4517        // return the result of adding DOCUMENT_POSITION_DISCONNECTED,
4518        // DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, and either
4519        // DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING, with the constraint
4520        // that this is to be consistent, together.
4521        let options = GetRootNodeOptions { composed: false };
4522        let node1_root = node1.map(|node| node.GetRootNode(&options));
4523        let node2_root = node2.map(|node| node.GetRootNode(&options));
4524        if node1_root.is_none() || node2_root.is_none() || node1_root != node2_root {
4525            // Auto-deref and compare the addresses of GC-owned `&Node`s,
4526            // more stable than addresses of SmallVec-owned `&Root<Dom<Node>>`
4527            let pointer1 = node1.map(as_uintptr::<Node>).unwrap_or_default();
4528            let pointer2 = node2.map(as_uintptr::<Node>).unwrap_or_default();
4529            let arbitrary_order = if pointer1 < pointer2 {
4530                NodeConstants::DOCUMENT_POSITION_PRECEDING
4531            } else {
4532                NodeConstants::DOCUMENT_POSITION_FOLLOWING
4533            };
4534
4535            return arbitrary_order +
4536                NodeConstants::DOCUMENT_POSITION_DISCONNECTED +
4537                NodeConstants::DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
4538        }
4539
4540        // Comparison goes here:
4541        let (ordering, containment_flags) = match (node1, node2) {
4542            (Some(node1), Some(node2)) => {
4543                compare_dom_positions::<LightDomNoGcTraversal>(no_gc, node1, 0, node2, 0)
4544            },
4545            _ => (None, DomPositionContainment::empty()),
4546        };
4547
4548        // Step 7. If node1 is an ancestor of node2 and attr1 is null, or node1 is node2
4549        // and attr2 is non-null, then return the result of adding
4550        // DOCUMENT_POSITION_CONTAINS to DOCUMENT_POSITION_PRECEDING.
4551        if (containment_flags.contains(DomPositionContainment::AContainsB) && attr1.is_none()) ||
4552            (node1 == node2 && attr2.is_some())
4553        {
4554            return NodeConstants::DOCUMENT_POSITION_CONTAINS +
4555                NodeConstants::DOCUMENT_POSITION_PRECEDING;
4556        }
4557
4558        // Step 8. If node1 is a descendant of node2 and attr2 is null, or node1 is node2
4559        // and attr1 is non-null, then return the result of adding
4560        // DOCUMENT_POSITION_CONTAINED_BY to DOCUMENT_POSITION_FOLLOWING.
4561        if (containment_flags.contains(DomPositionContainment::BContainsA) && attr2.is_none()) ||
4562            (node1 == node2 && attr1.is_some())
4563        {
4564            return NodeConstants::DOCUMENT_POSITION_CONTAINED_BY +
4565                NodeConstants::DOCUMENT_POSITION_FOLLOWING;
4566        }
4567
4568        // Step 9. If node1 is preceding node2, then return DOCUMENT_POSITION_PRECEDING.
4569        if ordering == Some(Ordering::Less) {
4570            return NodeConstants::DOCUMENT_POSITION_PRECEDING;
4571        }
4572
4573        // Step 10. Return DOCUMENT_POSITION_FOLLOWING.
4574        NodeConstants::DOCUMENT_POSITION_FOLLOWING
4575    }
4576
4577    /// <https://dom.spec.whatwg.org/#dom-node-contains>
4578    fn Contains(&self, maybe_other: Option<&Node>) -> bool {
4579        match maybe_other {
4580            None => false,
4581            Some(other) => self.is_inclusive_ancestor_of(other),
4582        }
4583    }
4584
4585    /// <https://dom.spec.whatwg.org/#dom-node-lookupprefix>
4586    fn LookupPrefix(&self, namespace: Option<DOMString>) -> Option<DOMString> {
4587        let namespace = namespace_from_domstring(namespace);
4588
4589        // Step 1.
4590        if namespace == ns!() {
4591            return None;
4592        }
4593
4594        // Step 2.
4595        match self.type_id() {
4596            NodeTypeId::Element(..) => self.downcast::<Element>().unwrap().lookup_prefix(namespace),
4597            NodeTypeId::Document(_) => self
4598                .downcast::<Document>()
4599                .unwrap()
4600                .GetDocumentElement()
4601                .and_then(|element| element.lookup_prefix(namespace)),
4602            NodeTypeId::DocumentType | NodeTypeId::DocumentFragment(_) => None,
4603            NodeTypeId::Attr => self
4604                .downcast::<Attr>()
4605                .unwrap()
4606                .GetOwnerElement()
4607                .and_then(|element| element.lookup_prefix(namespace)),
4608            _ => self
4609                .GetParentElement()
4610                .and_then(|element| element.lookup_prefix(namespace)),
4611        }
4612    }
4613
4614    /// <https://dom.spec.whatwg.org/#dom-node-lookupnamespaceuri>
4615    fn LookupNamespaceURI(&self, prefix: Option<DOMString>) -> Option<DOMString> {
4616        // Step 1. If prefix is the empty string, then set it to null.
4617        let prefix = prefix.filter(|prefix| !prefix.is_empty());
4618
4619        // Step 2. Return the result of running locate a namespace for this using prefix.
4620        Node::namespace_to_string(Node::locate_namespace(self, prefix))
4621    }
4622
4623    /// <https://dom.spec.whatwg.org/#dom-node-isdefaultnamespace>
4624    fn IsDefaultNamespace(&self, namespace: Option<DOMString>) -> bool {
4625        // Step 1.
4626        let namespace = namespace_from_domstring(namespace);
4627        // Steps 2 and 3.
4628        Node::locate_namespace(self, None) == namespace
4629    }
4630}
4631
4632pub(crate) trait NodeTraits {
4633    /// Get the [`Document`] that owns this node. Note that this may differ from the
4634    /// [`Document`] that the node was created in if it was adopted by a different
4635    /// [`Document`] (the owner).
4636    fn owner_document(&self) -> DomRoot<Document>;
4637    /// Get the [`Document`] that owns this node. Note that this may differ from the
4638    /// [`Document`] that the node was created in if it was adopted by a different
4639    /// [`Document`] (the owner).
4640    fn owner_document_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC)
4641    -> UnrootedDom<'no_gc, Document>;
4642    /// Get the [`Window`] of the [`Document`] that owns this node. Note that this may
4643    /// differ from the [`Document`] that the node was created in if it was adopted by a
4644    /// different [`Document`] (the owner).
4645    fn owner_window(&self) -> DomRoot<Window>;
4646    /// Get the [`Window`] of the [`Document`] that owns this node. Note that this may
4647    /// differ from the [`Document`] that the node was created in if it was adopted by a
4648    /// different [`Document`] (the owner).
4649    fn owner_window_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, Window>;
4650    /// Get the [`GlobalScope`] of the [`Document`] that owns this node. Note that this may
4651    /// differ from the [`GlobalScope`] that the node was created in if it was adopted by a
4652    /// different [`Document`] (the owner).
4653    fn owner_global(&self) -> DomRoot<GlobalScope>;
4654    /// If this [`Node`] is contained in a [`ShadowRoot`] return it, otherwise `None`.
4655    fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>>;
4656    /// Get the stylesheet owner for this node: either the [`Document`] or the [`ShadowRoot`]
4657    /// of the node.
4658    fn stylesheet_list_owner(&self) -> StyleSheetListOwner;
4659}
4660
4661impl<T: DerivedFrom<Node> + DomObject> NodeTraits for T {
4662    fn owner_document(&self) -> DomRoot<Document> {
4663        self.upcast().owner_doc()
4664    }
4665
4666    fn owner_document_unrooted<'no_gc>(
4667        &self,
4668        no_gc: &'no_gc NoGC,
4669    ) -> UnrootedDom<'no_gc, Document> {
4670        self.upcast().owner_doc_unrooted(no_gc)
4671    }
4672
4673    fn owner_window(&self) -> DomRoot<Window> {
4674        DomRoot::from_ref(self.owner_document().window())
4675    }
4676
4677    fn owner_window_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, Window> {
4678        UnrootedDom::from_ref(self.owner_document_unrooted(no_gc).window(), no_gc)
4679    }
4680
4681    fn owner_global(&self) -> DomRoot<GlobalScope> {
4682        DomRoot::from_ref(self.owner_window().upcast())
4683    }
4684
4685    fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>> {
4686        Node::containing_shadow_root(self.upcast())
4687    }
4688
4689    fn stylesheet_list_owner(&self) -> StyleSheetListOwner {
4690        self.containing_shadow_root()
4691            .map(|shadow_root| StyleSheetListOwner::ShadowRoot(Dom::from_ref(&*shadow_root)))
4692            .unwrap_or_else(|| {
4693                StyleSheetListOwner::Document(Dom::from_ref(&*self.owner_document()))
4694            })
4695    }
4696}
4697
4698impl VirtualMethods for Node {
4699    fn super_type(&self) -> Option<&dyn VirtualMethods> {
4700        Some(self.upcast::<EventTarget>() as &dyn VirtualMethods)
4701    }
4702
4703    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
4704        if let Some(s) = self.super_type() {
4705            s.children_changed(cx, mutation);
4706        }
4707
4708        if let Some(data) = self.rare_data.borrow().as_ref() &&
4709            let Some(list) = data.child_list.get()
4710        {
4711            list.as_children_list().children_changed(mutation);
4712        }
4713
4714        self.owner_doc_unrooted(cx.no_gc())
4715            .content_and_heritage_changed(cx.no_gc(), self);
4716    }
4717
4718    fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
4719        if let Some(super_type) = self.super_type() {
4720            super_type.moving_steps(cx, context);
4721        }
4722
4723        self.owner_doc_unrooted(cx.no_gc())
4724            .content_and_heritage_changed(cx.no_gc(), self);
4725
4726        if let Some(parent) = self.GetParentNode() {
4727            Self::maybe_dirty_visible_selection_for_newly_inserted_nodes(
4728                cx.no_gc(),
4729                &parent,
4730                &[self],
4731            );
4732        }
4733    }
4734
4735    fn handle_event(&self, cx: &mut JSContext, event: &Event) {
4736        if event.DefaultPrevented() || event.flags().contains(EventFlags::Handled) {
4737            return;
4738        }
4739
4740        if event.type_() == atom!("keydown") &&
4741            let Some(event) = event.downcast::<KeyboardEvent>()
4742        {
4743            self.owner_document()
4744                .event_handler()
4745                .maybe_dispatch_simulated_click(cx, self, event);
4746        }
4747    }
4748}
4749
4750/// A summary of the changes that happened to a node.
4751#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
4752pub(crate) enum NodeDamage {
4753    /// The node's `style` attribute changed.
4754    Style,
4755    /// The node's content or heritage changed, such as the addition or removal of
4756    /// children.
4757    ContentOrHeritage,
4758    /// Other parts of a node changed; attributes, text content, etc.
4759    Other,
4760}
4761
4762/// Helper trait to insert an element into vector whose elements
4763/// are maintained in tree order
4764pub(crate) trait VecPreOrderInsertionHelper<T> {
4765    fn insert_pre_order(&mut self, elem: &T, tree_root: &Node);
4766}
4767
4768impl<T> VecPreOrderInsertionHelper<T> for Vec<Dom<T>>
4769where
4770    T: DerivedFrom<Node> + DomObject,
4771{
4772    /// This algorithm relies on the following assumptions:
4773    /// * any elements inserted in this vector share the same tree root
4774    /// * any time an element is removed from the tree root, it is also removed from this array
4775    /// * any time an element is moved within the tree, it is removed from this array and re-inserted
4776    fn insert_pre_order(&mut self, node: &T, tree_root: &Node) {
4777        let Err(insertion_index) = self.binary_search_by(|candidate| {
4778            candidate.upcast().compare_dom_tree_position(
4779                node.upcast(),
4780                tree_root,
4781                ShadowIncluding::No,
4782            )
4783        }) else {
4784            // The element is already in the vector. We assume that users of this method generally
4785            // expect no duplicates, so there's nothing more to do.
4786            return;
4787        };
4788
4789        self.insert(insertion_index, Dom::from_ref(node));
4790    }
4791}
4792
4793/// The return value of [`Node::parent_in_flat_tree`].
4794pub(crate) enum FlatTreeParent<'a> {
4795    /// The parent in the flat tree.
4796    Parent(UnrootedDom<'a, Node>),
4797    /// This node has a parent (it's not the root), but it does not share a flat tree
4798    /// relationship with its parent.
4799    NotInFlatTree,
4800    /// This node is in the flat tree, but has no parent node because it is the root node.
4801    RootNode,
4802}
4803
4804impl<'a> FlatTreeParent<'a> {
4805    pub(crate) fn into_parent(self) -> Option<UnrootedDom<'a, Node>> {
4806        match self {
4807            FlatTreeParent::Parent(parent) => Some(parent),
4808            FlatTreeParent::NotInFlatTree | FlatTreeParent::RootNode => None,
4809        }
4810    }
4811}
4812
4813enum MoveOrInsert {
4814    Move,
4815    Insert,
4816}