1use 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#[dom_struct]
135pub struct Node {
136 eventtarget: EventTarget,
138
139 parent_node: MutNullableDom<Node>,
141
142 first_child: MutNullableDom<Node>,
144
145 last_child: MutNullableDom<Node>,
147
148 next_sibling: MutNullableDom<Node>,
150
151 prev_sibling: MutNullableDom<Node>,
153
154 owner_doc: MutNullableDom<Document>,
156
157 rare_data: DomRefCell<Option<Box<NodeRareData>>>,
159
160 children_count: Cell<u32>,
162
163 flags: Cell<NodeFlags>,
165
166 inclusive_descendants_version: Cell<u64>,
168
169 #[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#[derive(Clone, Copy, JSTraceable, MallocSizeOf)]
189pub(crate) struct NodeFlags(u16);
190
191bitflags! {
192 impl NodeFlags: u16 {
193 const IS_IN_A_DOCUMENT_TREE = 1 << 0;
197
198 const HAS_DIRTY_DESCENDANTS = 1 << 1;
200
201 const CLICK_IN_PROGRESS = 1 << 2;
204
205 const HAS_EVER_ANIMATED = 1 << 3;
208
209 const HAS_RESOLVED_PRESENTATIONAL_HINTS = 1 << 5;
214
215 const PARSER_ASSOCIATED_FORM_OWNER = 1 << 6;
218
219 const HAS_SNAPSHOT = 1 << 7;
224
225 const HANDLED_SNAPSHOT = 1 << 8;
227
228 const IS_IN_SHADOW_TREE = 1 << 9;
230
231 const IS_CONNECTED = 1 << 10;
235
236 const HAS_WEIRD_PARSER_INSERTION_MODE = 1 << 11;
239
240 const IS_IN_UA_WIDGET = 1 << 12;
243
244 const USES_ATTR_IN_CONTENT_ATTRIBUTE = 1 << 13;
246
247 const OVERLAPS_DOCUMENT_SELECTION = 1 << 14;
254
255 const SELECTION_INHIBITED = 1 << 15;
258 }
259}
260
261#[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 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 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 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 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 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 pub(crate) fn complete_remove_subtree(
420 cx: &mut JSContext,
421 root: &Node,
422 context: &UnbindContext,
423 ) {
424 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 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 let is_parent_connected = context.parent.is_connected();
450 let custom_element_reaction_stack = ScriptThread::custom_element_reaction_stack();
451
452 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 vtable_for(node).unbind_from_tree(cx, context);
464
465 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 if node.containing_shadow_root().is_some() {
482 node.set_containing_shadow_root(None);
485 }
486
487 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 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 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 if node_was_in_tree && let Some(element) = node.downcast::<Element>() {
530 element.unregister_current_id_and_name_attribute(cx);
531 }
532
533 if node.containing_shadow_root().is_some() {
536 node.set_containing_shadow_root(None);
539 }
540
541 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 node.set_flag(RESET_FLAGS, false);
552 document.clean_up_style_and_layout_data_for_node(&node);
553 }
554 }
555 }
556 }
557
558 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 pub(crate) fn fire_synthetic_pointer_event_not_trusted(
635 &self,
636 cx: &mut JSContext,
637 event_type: Atom,
638 ) {
639 let window = self.owner_window();
643
644 let pointer_event = PointerEvent::new(
646 cx,
647 &window, event_type,
649 EventBubbles::Bubbles, EventCancelable::Cancelable, Some(&window), 0, Point2D::zero(), Point2D::zero(), Point2D::zero(), Modifiers::empty(), MouseButton::Primary, MouseButtons::empty(), None, None, PointerId::NonPointerDevice as i32, 1, 1, 0.5, 0.0, 0, 0, 0, PI / 2.0, 0.0, DOMString::new(), false, &[], &[], );
676
677 pointer_event.upcast::<Event>().set_composed(true);
679
680 pointer_event.upcast::<Event>().set_trusted(false);
682
683 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 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 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 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 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 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 #[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 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 pub(crate) fn debug_str(&self) -> String {
819 format!("{:?}", self.type_id())
820 }
821
822 pub(crate) fn is_in_a_document_tree(&self) -> bool {
824 self.flags.get().contains(NodeFlags::IS_IN_A_DOCUMENT_TREE)
825 }
826
827 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 pub(crate) fn is_connected(&self) -> bool {
844 self.flags.get().contains(NodeFlags::IS_CONNECTED)
845 }
846
847 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 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 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 self.len() == 0
894 }
895
896 pub(crate) fn index(&self) -> u32 {
898 self.preceding_siblings().count() as u32
899 }
900
901 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 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 *self.layout_data.borrow_mut() = None;
963
964 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 pub(crate) fn inclusive_descendants_version(&self) -> u64 {
988 self.inclusive_descendants_version.get()
989 }
990
991 pub(crate) fn traverse_preorder(&self, shadow_including: ShadowIncluding) -> TreeIterator {
993 TreeIterator::new(self, shadow_including)
994 }
995
996 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 pub(crate) fn is_inclusive_ancestor_of(&self, child: &Node) -> bool {
1069 self == child || self.is_ancestor_of(child)
1071 }
1072
1073 pub(crate) fn is_ancestor_of(&self, possible_descendant: &Node) -> bool {
1075 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 fn is_host_including_inclusive_ancestor(&self, child: &Node) -> bool {
1093 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 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 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 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 pub(crate) fn scroll_area(&self, cx: &mut JSContext) -> Rect<i32, CSSPixel> {
1234 let document = self.owner_doc();
1236
1237 if !document.is_active() {
1239 return Rect::zero();
1240 }
1241
1242 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 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 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 pub(crate) fn before(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1283 let parent = &self.parent_node;
1285
1286 let parent = match parent.get() {
1288 None => return Ok(()),
1289 Some(parent) => parent,
1290 };
1291
1292 let viable_previous_sibling = first_node_not_in(self.preceding_siblings(), &nodes);
1294
1295 let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1297
1298 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 Node::pre_insert(cx, &node, &parent, viable_previous_sibling.as_deref())?;
1306
1307 Ok(())
1308 }
1309
1310 pub(crate) fn after(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1312 let parent = &self.parent_node;
1314
1315 let parent = match parent.get() {
1317 None => return Ok(()),
1318 Some(parent) => parent,
1319 };
1320
1321 let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
1323
1324 let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1326
1327 Node::pre_insert(cx, &node, &parent, viable_next_sibling.as_deref())?;
1329
1330 Ok(())
1331 }
1332
1333 pub(crate) fn replace_with(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1335 let Some(parent) = self.GetParentNode() else {
1337 return Ok(());
1339 };
1340
1341 let viable_next_sibling = first_node_not_in(self.following_siblings(), &nodes);
1343
1344 let node = self.owner_doc().node_from_nodes_and_strings(cx, nodes)?;
1346
1347 if self.parent_node == Some(&*parent) {
1348 parent.ReplaceChild(cx, &node, self)?;
1350 } else {
1351 Node::pre_insert(cx, &node, &parent, viable_next_sibling.as_deref())?;
1353 }
1354 Ok(())
1355 }
1356
1357 pub(crate) fn prepend(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1359 let doc = self.owner_doc();
1361 let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1362 let first_child = self.first_child.get();
1364 Node::pre_insert(cx, &node, self, first_child.as_deref()).map(|_| ())
1365 }
1366
1367 pub(crate) fn append(&self, cx: &mut JSContext, nodes: Vec<NodeOrString>) -> ErrorResult {
1369 let doc = self.owner_doc();
1371 let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1372 self.AppendChild(cx, &node).map(|_| ())
1374 }
1375
1376 pub(crate) fn replace_children(
1378 &self,
1379 cx: &mut JSContext,
1380 nodes: Vec<NodeOrString>,
1381 ) -> ErrorResult {
1382 let doc = self.owner_doc();
1385 let node = doc.node_from_nodes_and_strings(cx, nodes)?;
1386
1387 Node::ensure_pre_insertion_validity(cx.no_gc(), &node, self, None, &[])?;
1389
1390 Node::replace_all(cx, Some(&node), self);
1392 Ok(())
1393 }
1394
1395 pub(crate) fn move_before(
1397 &self,
1398 cx: &mut JSContext,
1399 node: &Node,
1400 child: Option<&Node>,
1401 ) -> ErrorResult {
1402 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 Node::move_fn(cx, node, self, reference_child)
1415 }
1416
1417 fn move_fn(
1419 cx: &mut JSContext,
1420 node: &Node,
1421 new_parent: &Node,
1422 child: Option<&Node>,
1423 ) -> ErrorResult {
1424 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 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 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 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 if new_parent.is::<Document>() && node.is::<Element>() {
1484 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 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 let old_parent = node
1507 .parent_node
1508 .get()
1509 .expect("old_parent should always be initialized");
1510
1511 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 let old_previous_sibling = node.prev_sibling.get();
1525
1526 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 old_parent.move_child(cx, node);
1558
1559 if let Some(slot) = node.assigned_slot() {
1561 slot.assign_slottables(cx);
1562 }
1563
1564 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 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 old_parent
1580 .GetRootNode(&GetRootNodeOptions::empty())
1581 .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1582
1583 node.assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1585 }
1586
1587 if let Some(child) = child {
1592 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 let new_previous_sibling = child.map_or_else(
1603 || new_parent.last_child.get(),
1604 |child| child.prev_sibling.get(),
1605 );
1606
1607 new_parent.add_child(cx, MoveOrInsert::Move, node, child);
1610
1611 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 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 node.GetRootNode(&GetRootNodeOptions::empty())
1634 .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
1635
1636 for descendant in node.traverse_preorder(ShadowIncluding::Yes) {
1639 let is_subtree_root = descendant.deref() == node;
1641 vtable_for(&descendant)
1643 .moving_steps(cx, &MoveContext::new(&old_parent, is_subtree_root));
1644
1645 if let Some(descendant) = descendant.downcast::<Element>() &&
1647 descendant.is_custom() &&
1648 new_parent.is_connected()
1649 {
1650 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 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 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 #[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 let document_url = self.owner_document().url().get_arc();
1697
1698 self.owner_document()
1701 .id_map()
1702 .resolve_all(no_gc, self.owner_doc().upcast());
1703
1704 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 #[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 let document_url = self.owner_document().url().get_arc();
1727
1728 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 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 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 pub(crate) fn owner_doc(&self) -> DomRoot<Document> {
1820 self.owner_doc.get().unwrap()
1821 }
1822
1823 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 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 #[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 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 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 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 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 pub(crate) fn get_lang(&self) -> Option<String> {
2108 self.inclusive_ancestors(ShadowIncluding::Yes)
2116 .find_map(|node| {
2117 node.downcast::<Element>().and_then(|element| {
2118 element
2121 .get_attribute_string_value_with_namespace(&ns!(xml), &local_name!("lang"))
2122 .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 .or_else(|| self.owner_document().default_language())
2149 }
2150
2151 pub(crate) fn assign_slottables_for_a_tree(
2153 &self,
2154 cx: &JSContext,
2155 force: ForceSlottableNodeReconciliation,
2156 ) {
2157 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 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 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 pub(crate) fn set_implemented_pseudo_element(&self, pseudo_element: PseudoElement) {
2270 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 pub(crate) fn editing_host_of(&self) -> Option<DomRoot<Node>> {
2285 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 pub(crate) fn is_editing_host(&self) -> bool {
2308 self.downcast::<HTMLElement>()
2309 .is_some_and(HTMLElement::is_editing_host)
2310 }
2311
2312 pub(crate) fn is_editable(&self, cx: &mut JSContext) -> bool {
2314 if self.is_inert(cx) {
2317 return false;
2318 }
2319
2320 if self.is_editing_host() {
2322 return false;
2323 }
2324 let html_element = self.downcast::<HTMLElement>();
2326 if html_element.is_some_and(|el| el.ContentEditable().str() == "false") {
2327 return false;
2328 }
2329 let Some(parent) = self.GetParentNode() else {
2331 return false;
2332 };
2333 if !parent.is_editable_or_editing_host() {
2334 return false;
2335 }
2336 html_element.is_some() || (!self.is::<Element>() && parent.is::<HTMLElement>())
2338 }
2339
2340 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 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 pub(crate) fn nearest_inclusive_open_popover(
2361 &self,
2362 cx: &mut JSContext,
2363 ) -> Option<DomRoot<HTMLElement>> {
2364 self.inclusive_ancestors_in_flat_tree_unrooted(cx.no_gc())
2369 .find_map(|current_node| {
2370 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 pub(crate) fn topmost_clicked_popover(
2387 &self,
2388 cx: &mut JSContext,
2389 ) -> Option<DomRoot<HTMLElement>> {
2390 let clicked_popover = self.nearest_inclusive_open_popover(cx);
2392
2393 let target_popover = self.nearest_inclusive_target_popover(cx);
2395
2396 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 if clicked_popover.popover_stack_position(cx) > target_popover.popover_stack_position(cx) {
2409 return Some(clicked_popover);
2410 }
2411
2412 Some(target_popover)
2414 }
2415
2416 pub(crate) fn nearest_inclusive_target_popover(
2418 &self,
2419 cx: &mut JSContext,
2420 ) -> Option<DomRoot<HTMLElement>> {
2421 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 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 fn target_popover(&self, cx: &mut JSContext) -> Option<DomRoot<HTMLElement>> {
2446 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 if button
2455 .upcast::<HTMLElement>()
2456 .is_form_element_disabled(cx.no_gc())
2457 {
2458 return None;
2459 }
2460
2461 let target = button.GetCommandForElement(cx);
2463
2464 let Some(target) = target else {
2466 return button.upcast::<HTMLElement>().popover_target_element(cx);
2467 };
2468
2469 if button.form_owner().is_some() {
2471 if button.is_submit_button() {
2473 return None;
2474 }
2475
2476 if matches!(button.button_type(), ButtonType::Reset | ButtonType::Auto) {
2479 return None;
2480 }
2481 }
2482
2483 let command = button.command_state();
2485
2486 if !matches!(
2488 command,
2489 CommandState::TogglePopover | CommandState::HidePopover | CommandState::ShowPopover
2490 ) {
2491 return None;
2492 }
2493
2494 let target = DomRoot::downcast::<HTMLElement>(target)?;
2496 if target.popover_state() == PopoverState::NoPopover {
2497 return None;
2498 }
2499
2500 Some(target)
2502 }
2503}
2504
2505fn 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#[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#[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 pub(crate) fn adopt(cx: &mut JSContext, node: &Node, document: &Document) {
2615 document.add_script_and_layout_blocker();
2616
2617 let old_doc = node.owner_doc();
2619 old_doc.add_script_and_layout_blocker();
2620
2621 node.remove_self(cx);
2623
2624 if &*old_doc != document {
2628 for descendant in node.traverse_preorder(ShadowIncluding::Yes) {
2629 descendant.set_owner_doc(document);
2631
2632 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 else if let Some(element) = descendant.downcast::<Element>() {
2658 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 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 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 vtable_for(&descendant).adopting_steps(cx, &old_doc);
2698 }
2699
2700 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 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 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 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 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 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 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 if parent.is::<Document>() {
2784 match node.type_id() {
2785 NodeTypeId::DocumentFragment(_) => {
2786 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 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 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 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 NodeTypeId::Document(_) | NodeTypeId::Attr => unreachable!(),
2885 }
2886 }
2887 Ok(())
2888 }
2889
2890 pub(crate) fn pre_insert(
2892 cx: &mut JSContext,
2893 node: &Node,
2894 parent: &Node,
2895 child: Option<&Node>,
2896 ) -> Fallible<DomRoot<Node>> {
2897 Node::ensure_pre_insertion_validity(cx.no_gc(), node, parent, child, &[])?;
2899
2900 let reference_child_root;
2902 let reference_child = match child {
2903 Some(child) if child == node => {
2905 reference_child_root = node.GetNextSibling();
2906 reference_child_root.as_deref()
2907 },
2908 _ => child,
2909 };
2910
2911 Node::insert(
2913 cx,
2914 node,
2915 parent,
2916 reference_child,
2917 SuppressObserver::Unsuppressed,
2918 );
2919
2920 Ok(DomRoot::from_ref(node))
2922 }
2923
2924 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 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 let count = new_nodes.len();
2948
2949 if count == 0 {
2951 return;
2952 }
2953
2954 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 if let NodeTypeId::DocumentFragment(_) = node.type_id() {
2963 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 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 if let Some(child) = child {
2981 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 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 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 for kid in new_nodes {
3011 Node::adopt(cx, kid, &parent_document);
3013
3014 parent.add_child(cx, MoveOrInsert::Insert, kid, child);
3017
3018 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 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 kid.GetRootNode(&GetRootNodeOptions::empty())
3039 .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
3040
3041 for descendant in kid.traverse_preorder(ShadowIncluding::Yes) {
3044 if let Some(element) = descendant.downcast::<Element>() &&
3050 !element.is_custom()
3051 {
3052 try_upgrade_element(cx, element);
3053 }
3054
3055 if !descendant.is_connected() {
3057 continue;
3058 }
3059
3060 if let Some(element) = descendant.downcast::<Element>() {
3062 if let Some(registry) = element.custom_element_registry() {
3064 if registry.is_scoped() {
3069 registry
3070 .add_scoped_document(&element.owner_document_unrooted(cx.no_gc()));
3071 }
3072 }
3073 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 else {
3090 try_upgrade_element(cx, element);
3091 }
3092 }
3093 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 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 vtable_for(parent).children_changed(
3121 cx,
3122 &ChildrenMutation::insert(previous_sibling.as_deref(), child),
3123 );
3124
3125 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 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 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 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 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 rooted_vec!(let removed_nodes <- parent.children().map(|child| DomRoot::as_traced(&child)));
3195
3196 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 for child in &*removed_nodes {
3213 Node::remove(cx, child, parent, SuppressObserver::Suppressed);
3214 }
3215
3216 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 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 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 pub(super) fn pre_remove(
3249 cx: &mut JSContext,
3250 child: &Node,
3251 parent: &Node,
3252 ) -> Fallible<DomRoot<Node>> {
3253 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 Node::remove(cx, child, parent, SuppressObserver::Unsuppressed);
3270
3271 Ok(DomRoot::from_ref(child))
3273 }
3274
3275 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 assert!(
3289 node.GetParentNode()
3290 .is_some_and(|node_parent| &*node_parent == parent)
3291 );
3292
3293 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 let old_previous_sibling = node.GetPreviousSibling();
3308
3309 let old_next_sibling = node.GetNextSibling();
3311
3312 parent.remove_child(cx, node);
3315
3316 if let Some(slot) = node.assigned_slot() {
3318 slot.assign_slottables(cx);
3319 }
3320
3321 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 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 parent
3337 .GetRootNode(&GetRootNodeOptions::empty())
3338 .assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Skip);
3339
3340 node.assign_slottables_for_a_tree(cx, ForceSlottableNodeReconciliation::Force);
3342 }
3343
3344 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 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 let document = match maybe_doc {
3379 Some(doc) => DomRoot::from_ref(doc),
3380 None => node.owner_doc(),
3381 };
3382
3383 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 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 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 DomRoot::upcast::<Node>(document)
3458 },
3459 NodeTypeId::Element(..) => {
3461 let element = node.downcast::<Element>().unwrap();
3462 let registry = element.custom_element_registry().or(registry);
3465 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 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 element.set_custom_element_registry(registry.as_deref(), cx.no_gc());
3492 DomRoot::upcast::<Node>(element)
3493 },
3494 };
3495
3496 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 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 node_elem.copy_all_attributes_to_other_element(cx, copy_elem);
3518 },
3519 _ => (),
3520 }
3521
3522 vtable_for(node).cloning_steps(cx, ©, maybe_doc, clone_children);
3525
3526 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, ©, None);
3532 }
3533 }
3534
3535 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 assert!(!copy_elem.is_shadow_host());
3544
3545 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 copy_shadow_root.set_declarative(shadow_root.is_declarative());
3562
3563 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 let _inserted_node =
3576 Node::pre_insert(cx, &child_copy, copy_shadow_root.upcast::<Node>(), None);
3577 }
3578 }
3579 }
3580
3581 copy
3583 }
3584
3585 pub(crate) fn child_text_content(&self) -> DOMString {
3587 Node::collect_text_contents(self.children())
3588 }
3589
3590 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 pub(crate) fn set_text_content_for_element(
3609 &self,
3610 cx: &mut JSContext,
3611 value: Option<DOMString>,
3612 ) {
3613 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 None
3623 } else {
3624 Some(DomRoot::upcast(self.owner_doc().CreateTextNode(cx, value)))
3627 };
3628
3629 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 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 #[expect(unsafe_code)]
3672 pub(crate) unsafe fn from_untrusted_node_address(
3673 candidate: UntrustedNodeAddress,
3674 ) -> &'static Self {
3675 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 DOMString::from(String::from_utf8(writer).unwrap())
3713 }
3714
3715 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 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 pub(crate) fn fragment_serialization_algorithm(
3742 &self,
3743 cx: &mut JSContext,
3744 require_well_formed: bool,
3745 ) -> Fallible<DOMString> {
3746 let context_document = self.owner_document();
3748
3749 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 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 return slot_element
3782 .assigned_nodes()
3783 .iter()
3784 .skip_while(|slottable| &*slottable.0 != self)
3785 .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 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 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 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 debug_assert_ne!(j, 0, "Equal inclusive ancestors but nodes are not equal?");
3888 return Ordering::Less;
3889 }
3890 if j == 0 {
3891 return Ordering::Greater;
3893 }
3894
3895 i -= 1;
3896 j -= 1;
3897 }
3898
3899 if my_ancestors[i]
3902 .preceding_siblings()
3903 .any(|sibling| sibling == other_ancestors[j])
3904 {
3905 Ordering::Greater
3907 } else {
3908 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 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 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 fn BaseURI(&self) -> USVString {
3966 USVString(String::from(self.owner_doc().base_url().as_str()))
3967 }
3968
3969 fn IsConnected(&self) -> bool {
3971 self.is_connected()
3972 }
3973
3974 fn GetOwnerDocument(&self) -> Option<DomRoot<Document>> {
3976 match self.type_id() {
3977 NodeTypeId::Document(_) => None,
3978 _ => Some(self.owner_doc()),
3979 }
3980 }
3981
3982 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 fn GetParentNode(&self) -> Option<DomRoot<Node>> {
4001 self.parent_node().get()
4002 }
4003
4004 fn GetParentElement(&self) -> Option<DomRoot<Element>> {
4006 self.GetParentNode().and_then(DomRoot::downcast)
4007 }
4008
4009 fn HasChildNodes(&self) -> bool {
4011 self.first_child().get().is_some()
4012 }
4013
4014 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 fn GetFirstChild(&self) -> Option<DomRoot<Node>> {
4029 self.first_child().get()
4030 }
4031
4032 fn GetLastChild(&self) -> Option<DomRoot<Node>> {
4034 self.last_child().get()
4035 }
4036
4037 fn GetPreviousSibling(&self) -> Option<DomRoot<Node>> {
4039 self.prev_sibling().get()
4040 }
4041
4042 fn GetNextSibling(&self) -> Option<DomRoot<Node>> {
4044 self.next_sibling().get()
4045 }
4046
4047 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 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 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 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 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 fn AppendChild(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
4122 Node::pre_insert(cx, node, self, None)
4123 }
4124
4125 fn ReplaceChild(
4127 &self,
4128 cx: &mut JSContext,
4129 node: &Node,
4130 child: &Node,
4131 ) -> Fallible<DomRoot<Node>> {
4132 Node::ensure_pre_insertion_validity(cx.no_gc(), node, self, Some(child), &[child])?;
4134
4135 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 let previous_sibling = child.GetPreviousSibling();
4147
4148 let document = self.owner_document();
4151 Node::adopt(cx, node, &document);
4152
4153 let removed_child = if node != child {
4157 Node::remove(cx, child, self, SuppressObserver::Suppressed);
4158 Some(child)
4159 } else {
4160 None
4161 };
4162
4163 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 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 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 Ok(DomRoot::from_ref(child))
4207 }
4208
4209 fn RemoveChild(&self, cx: &mut JSContext, node: &Node) -> Fallible<DomRoot<Node>> {
4211 Node::pre_remove(cx, node, self)
4212 }
4213
4214 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 let Some(text) = node.downcast::<Text>() else {
4224 node.Normalize(cx);
4225 continue;
4226 };
4227 if text.is::<CDATASection>() {
4228 continue;
4229 }
4230
4231 let cdata = text.upcast::<CharacterData>();
4233 let mut length = cdata.Length();
4234
4235 if length == 0 {
4238 Node::remove(cx, &node, self, SuppressObserver::Unsuppressed);
4239 continue;
4240 }
4241
4242 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 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 cdata.append_data(cx, &data);
4271
4272 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 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 length += current_node.Length();
4298 }
4301
4302 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 fn CloneNode(&self, cx: &mut JSContext, subtree: bool) -> Fallible<DomRoot<Node>> {
4317 if self.is::<ShadowRoot>() {
4319 return Err(Error::NotSupported(Some(
4320 "Cannot clone a shadow root".into(),
4321 )));
4322 }
4323
4324 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 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 if this.NodeType() != node.NodeType() {
4391 return false;
4392 }
4393
4394 match node.type_id() {
4395 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 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 if this.children_count() != node.children_count() {
4418 return false;
4419 }
4420
4421 this.children()
4423 .zip(node.children())
4424 .all(|(child, other_child)| is_equal_node(&child, &other_child))
4425 }
4426 match maybe_node {
4427 None => false,
4429 Some(node) => is_equal_node(self, node),
4431 }
4432 }
4433
4434 fn IsSameNode(&self, other_node: Option<&Node>) -> bool {
4436 match other_node {
4437 Some(node) => self == node,
4438 None => false,
4439 }
4440 }
4441
4442 fn CompareDocumentPosition(&self, no_gc: &NoGC, other: &Node) -> u16 {
4444 if self == other {
4446 return 0;
4447 }
4448
4449 let mut node1 = Some(other);
4451 let mut node2 = Some(self);
4452
4453 let mut attr1: Option<&Attr> = None;
4455 let mut attr2: Option<&Attr> = None;
4456
4457 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 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 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 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 unreachable!();
4514 }
4515
4516 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 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 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 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 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 if ordering == Some(Ordering::Less) {
4570 return NodeConstants::DOCUMENT_POSITION_PRECEDING;
4571 }
4572
4573 NodeConstants::DOCUMENT_POSITION_FOLLOWING
4575 }
4576
4577 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 fn LookupPrefix(&self, namespace: Option<DOMString>) -> Option<DOMString> {
4587 let namespace = namespace_from_domstring(namespace);
4588
4589 if namespace == ns!() {
4591 return None;
4592 }
4593
4594 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 fn LookupNamespaceURI(&self, prefix: Option<DOMString>) -> Option<DOMString> {
4616 let prefix = prefix.filter(|prefix| !prefix.is_empty());
4618
4619 Node::namespace_to_string(Node::locate_namespace(self, prefix))
4621 }
4622
4623 fn IsDefaultNamespace(&self, namespace: Option<DOMString>) -> bool {
4625 let namespace = namespace_from_domstring(namespace);
4627 Node::locate_namespace(self, None) == namespace
4629 }
4630}
4631
4632pub(crate) trait NodeTraits {
4633 fn owner_document(&self) -> DomRoot<Document>;
4637 fn owner_document_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC)
4641 -> UnrootedDom<'no_gc, Document>;
4642 fn owner_window(&self) -> DomRoot<Window>;
4646 fn owner_window_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, Window>;
4650 fn owner_global(&self) -> DomRoot<GlobalScope>;
4654 fn containing_shadow_root(&self) -> Option<DomRoot<ShadowRoot>>;
4656 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#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
4752pub(crate) enum NodeDamage {
4753 Style,
4755 ContentOrHeritage,
4758 Other,
4760}
4761
4762pub(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 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 return;
4787 };
4788
4789 self.insert(insertion_index, Dom::from_ref(node));
4790 }
4791}
4792
4793pub(crate) enum FlatTreeParent<'a> {
4795 Parent(UnrootedDom<'a, Node>),
4797 NotInFlatTree,
4800 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}