1use 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#[derive(JSTraceable, MallocSizeOf, PartialEq)]
62pub(crate) enum IsUserAgentWidget {
63 No,
64 Yes,
65}
66
67#[dom_struct]
69pub(crate) struct ShadowRoot {
70 document_fragment: DocumentFragment,
71 document_or_shadow_root: DocumentOrShadowRoot,
72 document: Dom<Document>,
73 #[custom_trace]
75 author_styles: DomRefCell<AuthorStyles<ServoStylesheetInDocument>>,
76 stylesheet_list: MutNullableDom<StyleSheetList>,
77 window: Dom<Window>,
78
79 mode: ShadowRootMode,
81
82 slot_assignment_mode: SlotAssignmentMode,
84
85 clonable: bool,
87
88 available_to_element_internals: Cell<bool>,
90
91 slots: DomRefCell<HashMap<DOMString, Vec<Dom<HTMLSlotElement>>>>,
92
93 is_user_agent_widget: bool,
94
95 declarative: Cell<bool>,
97
98 serializable: Cell<bool>,
100
101 delegates_focus: Cell<bool>,
103
104 adopted_stylesheets: DomRefCell<Vec<Dom<CSSStyleSheet>>>,
107
108 #[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 #[cfg_attr(crown, expect(crown::unrooted_must_root))] 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 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 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 #[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 #[cfg_attr(crown, expect(crown::unrooted_must_root))] 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 self.Host().upcast::<Node>().dirty(NodeDamage::Style);
275
276 let mut restyle = self.document.ensure_pending_restyle(&self.Host());
279 restyle.hint.insert(RestyleHint::restyle_subtree());
280 }
281
282 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 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 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 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 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 fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
385 self.document_or_shadow_root.active_element(self.upcast())
386 }
387
388 fn ElementFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Option<DomRoot<Element>> {
390 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 fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> {
408 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 fn Mode(&self) -> ShadowRootMode {
426 self.mode
427 }
428
429 fn DelegatesFocus(&self) -> bool {
431 self.delegates_focus.get()
432 }
433
434 fn Clonable(&self) -> bool {
436 self.clonable
437 }
438
439 fn Serializable(&self) -> bool {
441 self.serializable.get()
442 }
443
444 fn Host(&self) -> DomRoot<Element> {
446 self.upcast::<DocumentFragment>()
447 .host()
448 .expect("ShadowRoot always has an element as host")
449 }
450
451 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 fn GetHTML(&self, cx: &mut js::context::JSContext, options: &GetHTMLOptions) -> DOMString {
464 self.upcast::<Node>().html_serialize(
467 cx,
468 TraversalScope::ChildrenOnly(None),
469 options.serializableShadowRoots,
470 options.shadowRoots.clone(),
471 )
472 }
473
474 fn GetInnerHTML(
476 &self,
477 cx: &mut js::context::JSContext,
478 ) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
479 self.upcast::<Node>()
482 .fragment_serialization_algorithm(cx, true)
483 .map(TrustedHTMLOrNullIsEmptyString::NullIsEmptyString)
484 }
485
486 fn SetInnerHTML(
488 &self,
489 cx: &mut js::context::JSContext,
490 value: TrustedHTMLOrNullIsEmptyString,
491 ) -> ErrorResult {
492 let value = TrustedHTML::get_trusted_type_compliant_string(
495 cx,
496 &self.owner_global(),
497 value.convert(),
498 "ShadowRoot innerHTML",
499 )?;
500
501 let context = self.Host();
503
504 let frag = context.parse_fragment(value, cx)?;
510
511 Node::replace_all(cx, Some(frag.upcast()), self.upcast());
513 Ok(())
514 }
515
516 fn SlotAssignment(&self) -> SlotAssignmentMode {
518 self.slot_assignment_mode
519 }
520
521 fn SetHTMLUnsafe(
523 &self,
524 cx: &mut js::context::JSContext,
525 value: TrustedHTMLOrString,
526 ) -> ErrorResult {
527 let value = TrustedHTML::get_trusted_type_compliant_string(
531 cx,
532 &self.owner_global(),
533 value,
534 "ShadowRoot setHTMLUnsafe",
535 )?;
536 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 event_handler!(onslotchange, GetOnslotchange, SetOnslotchange);
546
547 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 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 result.is_ok() {
581 self.adopted_stylesheets_frozen_types.clear();
582 }
583
584 result
585 }
586
587 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 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 for node in shadow_root.traverse_preorder(ShadowIncluding::No).skip(1) {
621 node.set_flag(NodeFlags::IS_CONNECTED, inner_context.tree_connected);
622
623 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 #[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}