script/dom/
shadowroot.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::collections::HashMap;
7use std::collections::hash_map::Entry;
8
9use dom_struct::dom_struct;
10use html5ever::serialize::TraversalScope;
11use js::rust::{HandleValue, MutableHandleValue};
12use script_bindings::error::{ErrorResult, Fallible};
13use script_bindings::script_runtime::JSContext;
14use servo_arc::Arc;
15use style::author_styles::AuthorStyles;
16use style::invalidation::element::restyle_hints::RestyleHint;
17use style::shared_lock::SharedRwLockReadGuard;
18use style::stylesheets::Stylesheet;
19use style::stylist::{CascadeData, Stylist};
20use stylo_atoms::Atom;
21
22use crate::conversions::Convert;
23use crate::dom::bindings::cell::{DomRefCell, RefMut};
24use crate::dom::bindings::codegen::Bindings::ElementBinding::GetHTMLOptions;
25use crate::dom::bindings::codegen::Bindings::HTMLSlotElementBinding::HTMLSlotElement_Binding::HTMLSlotElementMethods;
26use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
27use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
28    ShadowRootMode, SlotAssignmentMode,
29};
30use crate::dom::bindings::codegen::UnionTypes::{
31    TrustedHTMLOrNullIsEmptyString, TrustedHTMLOrString,
32};
33use crate::dom::bindings::frozenarray::CachedFrozenArray;
34use crate::dom::bindings::inheritance::Castable;
35use crate::dom::bindings::num::Finite;
36use crate::dom::bindings::reflector::reflect_dom_object;
37use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
38use crate::dom::bindings::str::DOMString;
39use crate::dom::css::cssstylesheet::CSSStyleSheet;
40use crate::dom::css::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
41use crate::dom::document::Document;
42use crate::dom::documentfragment::{DocumentFragment, LayoutDocumentFragmentHelpers};
43use crate::dom::documentorshadowroot::{
44    DocumentOrShadowRoot, ServoStylesheetInDocument, StylesheetSource,
45};
46use crate::dom::element::Element;
47use crate::dom::html::htmlslotelement::HTMLSlotElement;
48use crate::dom::htmldetailselement::DetailsNameGroups;
49use crate::dom::node::{
50    BindContext, IsShadowTree, Node, NodeDamage, NodeFlags, NodeTraits, ShadowIncluding,
51    UnbindContext, VecPreOrderInsertionHelper,
52};
53use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
54use crate::dom::types::EventTarget;
55use crate::dom::virtualmethods::{VirtualMethods, vtable_for};
56use crate::dom::window::Window;
57use crate::script_runtime::CanGc;
58use crate::stylesheet_set::StylesheetSetRef;
59
60/// Whether a shadow root hosts an User Agent widget.
61#[derive(JSTraceable, MallocSizeOf, PartialEq)]
62pub(crate) enum IsUserAgentWidget {
63    No,
64    Yes,
65}
66
67/// <https://dom.spec.whatwg.org/#interface-shadowroot>
68#[dom_struct]
69pub(crate) struct ShadowRoot {
70    document_fragment: DocumentFragment,
71    document_or_shadow_root: DocumentOrShadowRoot,
72    document: Dom<Document>,
73    /// List of author styles associated with nodes in this shadow tree.
74    #[custom_trace]
75    author_styles: DomRefCell<AuthorStyles<ServoStylesheetInDocument>>,
76    stylesheet_list: MutNullableDom<StyleSheetList>,
77    window: Dom<Window>,
78
79    /// <https://dom.spec.whatwg.org/#dom-shadowroot-mode>
80    mode: ShadowRootMode,
81
82    /// <https://dom.spec.whatwg.org/#dom-shadowroot-slotassignment>
83    slot_assignment_mode: SlotAssignmentMode,
84
85    /// <https://dom.spec.whatwg.org/#dom-shadowroot-clonable>
86    clonable: bool,
87
88    /// <https://dom.spec.whatwg.org/#shadowroot-available-to-element-internals>
89    available_to_element_internals: Cell<bool>,
90
91    slots: DomRefCell<HashMap<DOMString, Vec<Dom<HTMLSlotElement>>>>,
92
93    is_user_agent_widget: bool,
94
95    /// <https://dom.spec.whatwg.org/#shadowroot-declarative>
96    declarative: Cell<bool>,
97
98    /// <https://dom.spec.whatwg.org/#shadowroot-serializable>
99    serializable: Cell<bool>,
100
101    /// <https://dom.spec.whatwg.org/#shadowroot-delegates-focus>
102    delegates_focus: Cell<bool>,
103
104    /// The constructed stylesheet that is adopted by this [ShadowRoot].
105    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
106    adopted_stylesheets: DomRefCell<Vec<Dom<CSSStyleSheet>>>,
107
108    /// Cached frozen array of [`Self::adopted_stylesheets`]
109    #[ignore_malloc_size_of = "mozjs"]
110    adopted_stylesheets_frozen_types: CachedFrozenArray,
111
112    details_name_groups: DomRefCell<Option<DetailsNameGroups>>,
113}
114
115impl ShadowRoot {
116    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
117    fn new_inherited(
118        host: &Element,
119        document: &Document,
120        mode: ShadowRootMode,
121        slot_assignment_mode: SlotAssignmentMode,
122        clonable: bool,
123        is_user_agent_widget: IsUserAgentWidget,
124    ) -> ShadowRoot {
125        let document_fragment = DocumentFragment::new_inherited(document, Some(host));
126        let node = document_fragment.upcast::<Node>();
127        node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
128        node.set_flag(
129            NodeFlags::IS_CONNECTED,
130            host.upcast::<Node>().is_connected(),
131        );
132
133        ShadowRoot {
134            document_fragment,
135            document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
136            document: Dom::from_ref(document),
137            author_styles: DomRefCell::new(AuthorStyles::new()),
138            stylesheet_list: MutNullableDom::new(None),
139            window: Dom::from_ref(document.window()),
140            mode,
141            slot_assignment_mode,
142            clonable,
143            available_to_element_internals: Cell::new(false),
144            slots: Default::default(),
145            is_user_agent_widget: is_user_agent_widget == IsUserAgentWidget::Yes,
146            declarative: Cell::new(false),
147            serializable: Cell::new(false),
148            delegates_focus: Cell::new(false),
149            adopted_stylesheets: Default::default(),
150            adopted_stylesheets_frozen_types: CachedFrozenArray::new(),
151            details_name_groups: Default::default(),
152        }
153    }
154
155    pub(crate) fn new(
156        host: &Element,
157        document: &Document,
158        mode: ShadowRootMode,
159        slot_assignment_mode: SlotAssignmentMode,
160        clonable: bool,
161        is_user_agent_widget: IsUserAgentWidget,
162        can_gc: CanGc,
163    ) -> DomRoot<ShadowRoot> {
164        reflect_dom_object(
165            Box::new(ShadowRoot::new_inherited(
166                host,
167                document,
168                mode,
169                slot_assignment_mode,
170                clonable,
171                is_user_agent_widget,
172            )),
173            document.window(),
174            can_gc,
175        )
176    }
177
178    pub(crate) fn owner_doc(&self) -> &Document {
179        &self.document
180    }
181
182    pub(crate) fn stylesheet_count(&self) -> usize {
183        self.author_styles.borrow().stylesheets.len()
184    }
185
186    pub(crate) fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> {
187        let stylesheets = &self.author_styles.borrow().stylesheets;
188
189        stylesheets
190            .get(index)
191            .and_then(|s| s.owner.get_cssom_object())
192    }
193
194    /// Add a stylesheet owned by `owner_node` to the list of shadow root sheets, in the
195    /// correct tree position. Additionally, ensure that owned stylesheet is inserted before
196    /// any constructed stylesheet.
197    ///
198    /// <https://drafts.csswg.org/cssom/#documentorshadowroot-final-css-style-sheets>
199    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
200    pub(crate) fn add_owned_stylesheet(&self, owner_node: &Element, sheet: Arc<Stylesheet>) {
201        let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
202
203        // FIXME(stevennovaryo): This is almost identical with the one in Document::add_stylesheet.
204        let insertion_point = stylesheets
205            .iter()
206            .find(|sheet_in_shadow| {
207                match &sheet_in_shadow.owner {
208                    StylesheetSource::Element(other_node) => {
209                        owner_node.upcast::<Node>().is_before(other_node.upcast())
210                    },
211                    // Non-constructed stylesheet should be ordered before the
212                    // constructed ones.
213                    StylesheetSource::Constructed(_) => true,
214                }
215            })
216            .cloned();
217
218        if self.document.has_browsing_context() {
219            let document_context = self.window.web_font_context();
220            self.window
221                .layout_mut()
222                .load_web_fonts_from_stylesheet(&sheet, &document_context);
223        }
224
225        DocumentOrShadowRoot::add_stylesheet(
226            StylesheetSource::Element(Dom::from_ref(owner_node)),
227            StylesheetSetRef::Author(stylesheets),
228            sheet,
229            insertion_point,
230            self.document.style_shared_lock(),
231        );
232    }
233
234    /// Append a constructed stylesheet to the back of shadow root stylesheet set.
235    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
236    pub(crate) fn append_constructed_stylesheet(&self, cssom_stylesheet: &CSSStyleSheet) {
237        debug_assert!(cssom_stylesheet.is_constructed());
238
239        let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
240        let sheet = cssom_stylesheet.style_stylesheet().clone();
241
242        let insertion_point = stylesheets.iter().last().cloned();
243
244        if self.document.has_browsing_context() {
245            let document_context = self.window.web_font_context();
246            self.window
247                .layout_mut()
248                .load_web_fonts_from_stylesheet(&sheet, &document_context);
249        }
250
251        DocumentOrShadowRoot::add_stylesheet(
252            StylesheetSource::Constructed(Dom::from_ref(cssom_stylesheet)),
253            StylesheetSetRef::Author(stylesheets),
254            sheet,
255            insertion_point,
256            self.document.style_shared_lock(),
257        );
258    }
259
260    /// Remove a stylesheet owned by `owner` from the list of shadow root sheets.
261    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
262    pub(crate) fn remove_stylesheet(&self, owner: StylesheetSource, s: &Arc<Stylesheet>) {
263        DocumentOrShadowRoot::remove_stylesheet(
264            owner,
265            s,
266            StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
267        )
268    }
269
270    pub(crate) fn invalidate_stylesheets(&self) {
271        self.document.invalidate_shadow_roots_stylesheets();
272        self.author_styles.borrow_mut().stylesheets.force_dirty();
273        // Mark the host element dirty so a reflow will be performed.
274        self.Host().upcast::<Node>().dirty(NodeDamage::Style);
275
276        // Also mark the host element with `RestyleHint::restyle_subtree` so a reflow
277        // can traverse into the shadow tree.
278        let mut restyle = self.document.ensure_pending_restyle(&self.Host());
279        restyle.hint.insert(RestyleHint::restyle_subtree());
280    }
281
282    /// Remove any existing association between the provided id and any elements
283    /// in this shadow tree.
284    pub(crate) fn unregister_element_id(&self, to_unregister: &Element, id: Atom, _can_gc: CanGc) {
285        self.document_or_shadow_root.unregister_named_element(
286            self.document_fragment.id_map(),
287            to_unregister,
288            &id,
289        );
290    }
291
292    /// Associate an element present in this shadow tree with the provided id.
293    pub(crate) fn register_element_id(&self, element: &Element, id: Atom, _can_gc: CanGc) {
294        let root = self
295            .upcast::<Node>()
296            .inclusive_ancestors(ShadowIncluding::No)
297            .last()
298            .unwrap();
299        self.document_or_shadow_root.register_named_element(
300            self.document_fragment.id_map(),
301            element,
302            &id,
303            root,
304        );
305    }
306
307    pub(crate) fn register_slot(&self, slot: &HTMLSlotElement) {
308        debug!("Registering slot with name={:?}", slot.Name().str());
309
310        let mut slots = self.slots.borrow_mut();
311
312        let slots_with_the_same_name = slots.entry(slot.Name()).or_default();
313
314        // Insert the slot before the first element that comes after it in tree order
315        slots_with_the_same_name.insert_pre_order(slot, self.upcast::<Node>());
316    }
317
318    pub(crate) fn unregister_slot(&self, name: DOMString, slot: &HTMLSlotElement) {
319        debug!("Unregistering slot with name={:?}", name.str());
320
321        let mut slots = self.slots.borrow_mut();
322        let Entry::Occupied(mut entry) = slots.entry(name) else {
323            panic!("slot is not registered");
324        };
325        entry.get_mut().retain(|s| slot != &**s);
326    }
327
328    /// Find the first slot with the given name among this root's descendants in tree order
329    pub(crate) fn slot_for_name(&self, name: &DOMString) -> Option<DomRoot<HTMLSlotElement>> {
330        self.slots
331            .borrow()
332            .get(name)
333            .and_then(|slots| slots.first())
334            .map(|slot| slot.as_rooted())
335    }
336
337    pub(crate) fn has_slot_descendants(&self) -> bool {
338        !self.slots.borrow().is_empty()
339    }
340
341    pub(crate) fn set_available_to_element_internals(&self, value: bool) {
342        self.available_to_element_internals.set(value);
343    }
344
345    /// <https://dom.spec.whatwg.org/#shadowroot-available-to-element-internals>
346    pub(crate) fn is_available_to_element_internals(&self) -> bool {
347        self.available_to_element_internals.get()
348    }
349
350    pub(crate) fn is_user_agent_widget(&self) -> bool {
351        self.is_user_agent_widget
352    }
353
354    pub(crate) fn set_declarative(&self, declarative: bool) {
355        self.declarative.set(declarative);
356    }
357
358    pub(crate) fn is_declarative(&self) -> bool {
359        self.declarative.get()
360    }
361
362    pub(crate) fn shadow_root_mode(&self) -> ShadowRootMode {
363        self.mode
364    }
365
366    pub(crate) fn set_serializable(&self, serializable: bool) {
367        self.serializable.set(serializable);
368    }
369
370    pub(crate) fn set_delegates_focus(&self, delegates_focus: bool) {
371        self.delegates_focus.set(delegates_focus);
372    }
373
374    pub(crate) fn details_name_groups(&self) -> RefMut<'_, DetailsNameGroups> {
375        RefMut::map(
376            self.details_name_groups.borrow_mut(),
377            |details_name_groups| details_name_groups.get_or_insert_default(),
378        )
379    }
380}
381
382impl ShadowRootMethods<crate::DomTypeHolder> for ShadowRoot {
383    /// <https://html.spec.whatwg.org/multipage/#dom-document-activeelement>
384    fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
385        self.document_or_shadow_root.active_element(self.upcast())
386    }
387
388    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint>
389    fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
390        // Return the result of running the retargeting algorithm with context object
391        // and the original result as input.
392        match self.document_or_shadow_root.element_from_point(
393            x,
394            y,
395            None,
396            self.document.has_browsing_context(),
397        ) {
398            Some(e) => {
399                let retargeted_node = e.upcast::<EventTarget>().retarget(self.upcast());
400                retargeted_node.downcast::<Element>().map(DomRoot::from_ref)
401            },
402            None => None,
403        }
404    }
405
406    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint>
407    fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
408        // Return the result of running the retargeting algorithm with context object
409        // and the original result as input
410        let mut elements = Vec::new();
411        for e in self
412            .document_or_shadow_root
413            .elements_from_point(x, y, None, self.document.has_browsing_context())
414            .iter()
415        {
416            let retargeted_node = e.upcast::<EventTarget>().retarget(self.upcast());
417            if let Some(element) = retargeted_node.downcast::<Element>().map(DomRoot::from_ref) {
418                elements.push(element);
419            }
420        }
421        elements
422    }
423
424    /// <https://dom.spec.whatwg.org/#dom-shadowroot-mode>
425    fn Mode(&self) -> ShadowRootMode {
426        self.mode
427    }
428
429    /// <https://dom.spec.whatwg.org/#dom-delegates-focus>
430    fn DelegatesFocus(&self) -> bool {
431        self.delegates_focus.get()
432    }
433
434    /// <https://dom.spec.whatwg.org/#dom-shadowroot-clonable>
435    fn Clonable(&self) -> bool {
436        self.clonable
437    }
438
439    /// <https://dom.spec.whatwg.org/#dom-serializable>
440    fn Serializable(&self) -> bool {
441        self.serializable.get()
442    }
443
444    /// <https://dom.spec.whatwg.org/#dom-shadowroot-host>
445    fn Host(&self) -> DomRoot<Element> {
446        self.upcast::<DocumentFragment>()
447            .host()
448            .expect("ShadowRoot always has an element as host")
449    }
450
451    /// <https://drafts.csswg.org/cssom/#dom-document-stylesheets>
452    fn StyleSheets(&self) -> DomRoot<StyleSheetList> {
453        self.stylesheet_list.or_init(|| {
454            StyleSheetList::new(
455                &self.window,
456                StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
457                CanGc::note(),
458            )
459        })
460    }
461
462    /// <https://html.spec.whatwg.org/multipage/#dom-shadowroot-gethtml>
463    fn GetHTML(&self, cx: &mut js::context::JSContext, options: &GetHTMLOptions) -> DOMString {
464        // > ShadowRoot's getHTML(options) method steps are to return the result of HTML fragment serialization
465        // >  algorithm with this, options["serializableShadowRoots"], and options["shadowRoots"].
466        self.upcast::<Node>().html_serialize(
467            cx,
468            TraversalScope::ChildrenOnly(None),
469            options.serializableShadowRoots,
470            options.shadowRoots.clone(),
471        )
472    }
473
474    /// <https://html.spec.whatwg.org/multipage/#dom-shadowroot-innerhtml>
475    fn GetInnerHTML(
476        &self,
477        cx: &mut js::context::JSContext,
478    ) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
479        // ShadowRoot's innerHTML getter steps are to return the result of running fragment serializing
480        // algorithm steps with this and true.
481        self.upcast::<Node>()
482            .fragment_serialization_algorithm(cx, true)
483            .map(TrustedHTMLOrNullIsEmptyString::NullIsEmptyString)
484    }
485
486    /// <https://html.spec.whatwg.org/multipage/#dom-shadowroot-innerhtml>
487    fn SetInnerHTML(
488        &self,
489        cx: &mut js::context::JSContext,
490        value: TrustedHTMLOrNullIsEmptyString,
491    ) -> ErrorResult {
492        // Step 1. Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm
493        // with TrustedHTML, this's relevant global object, the given value, "ShadowRoot innerHTML", and "script".
494        let value = TrustedHTML::get_trusted_type_compliant_string(
495            cx,
496            &self.owner_global(),
497            value.convert(),
498            "ShadowRoot innerHTML",
499        )?;
500
501        // Step 2. Let context be this's host.
502        let context = self.Host();
503
504        // Step 3. Let fragment be the result of invoking the fragment parsing algorithm steps with context and
505        // compliantString.
506        //
507        // NOTE: The spec doesn't strictly tell us to bail out here, but
508        // we can't continue if parsing failed
509        let frag = context.parse_fragment(value, cx)?;
510
511        // Step 4. Replace all with fragment within this.
512        Node::replace_all(cx, Some(frag.upcast()), self.upcast());
513        Ok(())
514    }
515
516    /// <https://dom.spec.whatwg.org/#dom-shadowroot-slotassignment>
517    fn SlotAssignment(&self) -> SlotAssignmentMode {
518        self.slot_assignment_mode
519    }
520
521    /// <https://html.spec.whatwg.org/multipage/#dom-shadowroot-sethtmlunsafe>
522    fn SetHTMLUnsafe(
523        &self,
524        cx: &mut js::context::JSContext,
525        value: TrustedHTMLOrString,
526    ) -> ErrorResult {
527        // Step 1. Let compliantHTML be the result of invoking the
528        // Get Trusted Type compliant string algorithm with TrustedHTML,
529        // this's relevant global object, html, "ShadowRoot setHTMLUnsafe", and "script".
530        let value = TrustedHTML::get_trusted_type_compliant_string(
531            cx,
532            &self.owner_global(),
533            value,
534            "ShadowRoot setHTMLUnsafe",
535        )?;
536        // Step 2. Unsafely set HTMl given this, this's shadow host, and complaintHTML
537        let target = self.upcast::<Node>();
538        let context_element = self.Host();
539
540        Node::unsafely_set_html(target, &context_element, value, cx);
541        Ok(())
542    }
543
544    // https://dom.spec.whatwg.org/#dom-shadowroot-onslotchange
545    event_handler!(onslotchange, GetOnslotchange, SetOnslotchange);
546
547    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
548    fn AdoptedStyleSheets(&self, context: JSContext, can_gc: CanGc, retval: MutableHandleValue) {
549        self.adopted_stylesheets_frozen_types.get_or_init(
550            || {
551                self.adopted_stylesheets
552                    .borrow()
553                    .clone()
554                    .iter()
555                    .map(|sheet| sheet.as_rooted())
556                    .collect()
557            },
558            context,
559            retval,
560            can_gc,
561        );
562    }
563
564    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
565    fn SetAdoptedStyleSheets(
566        &self,
567        context: JSContext,
568        val: HandleValue,
569        can_gc: CanGc,
570    ) -> ErrorResult {
571        let result = DocumentOrShadowRoot::set_adopted_stylesheet_from_jsval(
572            context,
573            self.adopted_stylesheets.borrow_mut().as_mut(),
574            val,
575            &StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
576            can_gc,
577        );
578
579        // If update is successful, clear the FrozenArray cache.
580        if result.is_ok() {
581            self.adopted_stylesheets_frozen_types.clear();
582        }
583
584        result
585    }
586
587    /// <https://fullscreen.spec.whatwg.org/#dom-document-fullscreenelement>
588    fn GetFullscreenElement(&self) -> Option<DomRoot<Element>> {
589        DocumentOrShadowRoot::get_fullscreen_element(
590            self.upcast::<Node>(),
591            self.document.fullscreen_element(),
592        )
593    }
594}
595
596impl VirtualMethods for ShadowRoot {
597    fn super_type(&self) -> Option<&dyn VirtualMethods> {
598        Some(self.upcast::<DocumentFragment>() as &dyn VirtualMethods)
599    }
600
601    fn bind_to_tree(&self, cx: &mut js::context::JSContext, context: &BindContext) {
602        if let Some(s) = self.super_type() {
603            s.bind_to_tree(cx, context);
604        }
605
606        // TODO(stevennovaryo): Handle adoptedStylesheet to deal with different
607        //                      constructor document.
608        if context.tree_connected {
609            let document = self.owner_document();
610            document.register_shadow_root(self);
611        }
612
613        let shadow_root = self.upcast::<Node>();
614
615        shadow_root.set_flag(NodeFlags::IS_CONNECTED, context.tree_connected);
616
617        let inner_context = BindContext::new(shadow_root, IsShadowTree::Yes);
618
619        // avoid iterate over the shadow root itself
620        for node in shadow_root.traverse_preorder(ShadowIncluding::No).skip(1) {
621            node.set_flag(NodeFlags::IS_CONNECTED, inner_context.tree_connected);
622
623            // Out-of-document elements never have the descendants flag set
624            debug_assert!(!node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS));
625            vtable_for(&node).bind_to_tree(cx, &inner_context);
626        }
627    }
628
629    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
630        if let Some(s) = self.super_type() {
631            s.unbind_from_tree(context, can_gc);
632        }
633
634        if context.tree_connected {
635            let document = self.owner_document();
636            document.unregister_shadow_root(self);
637        }
638    }
639}
640
641#[expect(unsafe_code)]
642pub(crate) trait LayoutShadowRootHelpers<'dom> {
643    fn get_host_for_layout(self) -> LayoutDom<'dom, Element>;
644    fn get_style_data_for_layout(self) -> &'dom CascadeData;
645    fn is_ua_widget(&self) -> bool;
646    unsafe fn flush_stylesheets(self, stylist: &mut Stylist, guard: &SharedRwLockReadGuard);
647}
648
649impl<'dom> LayoutShadowRootHelpers<'dom> for LayoutDom<'dom, ShadowRoot> {
650    #[inline]
651    fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
652        self.upcast::<DocumentFragment>()
653            .shadowroot_host_for_layout()
654    }
655
656    #[inline]
657    #[expect(unsafe_code)]
658    fn get_style_data_for_layout(self) -> &'dom CascadeData {
659        fn is_sync<T: Sync>() {}
660        let _ = is_sync::<CascadeData>;
661        unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
662    }
663
664    #[inline]
665    fn is_ua_widget(&self) -> bool {
666        self.unsafe_get().is_user_agent_widget()
667    }
668
669    // FIXME(nox): This uses the dreaded borrow_mut_for_layout so this should
670    // probably be revisited.
671    #[inline]
672    #[expect(unsafe_code)]
673    unsafe fn flush_stylesheets(self, stylist: &mut Stylist, guard: &SharedRwLockReadGuard) {
674        let author_styles = unsafe { self.unsafe_get().author_styles.borrow_mut_for_layout() };
675        if author_styles.stylesheets.dirty() {
676            author_styles.flush(stylist, guard);
677        }
678    }
679}
680
681impl Convert<devtools_traits::ShadowRootMode> for ShadowRootMode {
682    fn convert(self) -> devtools_traits::ShadowRootMode {
683        match self {
684            ShadowRootMode::Open => devtools_traits::ShadowRootMode::Open,
685            ShadowRootMode::Closed => devtools_traits::ShadowRootMode::Closed,
686        }
687    }
688}