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::context::{JSContext, NoGC};
12use script_bindings::cell::{DomRefCell, RefMut};
13use script_bindings::dom::UnrootedDom;
14use script_bindings::domstring::TracedDOMString;
15use script_bindings::error::{ErrorResult, Fallible};
16use script_bindings::reflector::reflect_dom_object;
17use servo_arc::Arc;
18use style::author_styles::AuthorStyles;
19use style::invalidation::element::restyle_hints::RestyleHint;
20use style::shared_lock::SharedRwLockReadGuard;
21use style::stylesheets::Stylesheet;
22use style::stylist::{CascadeData, Stylist};
23use stylo_atoms::Atom;
24
25use crate::conversions::Convert;
26use crate::css::stylesheet_set::StylesheetSetRef;
27use crate::dom::bindings::codegen::Bindings::ElementBinding::GetHTMLOptions;
28use crate::dom::bindings::codegen::Bindings::HTMLSlotElementBinding::HTMLSlotElement_Binding::HTMLSlotElementMethods;
29use crate::dom::bindings::codegen::Bindings::SanitizerBinding::{
30 SetHTMLOptions, SetHTMLUnsafeOptions,
31};
32use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::ShadowRoot_Binding::ShadowRootMethods;
33use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::{
34 ShadowRootMode, SlotAssignmentMode,
35};
36use crate::dom::bindings::codegen::UnionTypes::{
37 TrustedHTMLOrNullIsEmptyString, TrustedHTMLOrString,
38};
39use crate::dom::bindings::inheritance::Castable;
40use crate::dom::bindings::num::Finite;
41use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom};
42use crate::dom::bindings::str::DOMString;
43use crate::dom::css::cssstylesheet::CSSStyleSheet;
44use crate::dom::css::stylesheetlist::{StyleSheetList, StyleSheetListOwner};
45use crate::dom::customelementregistry::CustomElementRegistry;
46use crate::dom::document::Document;
47use crate::dom::documentfragment::DocumentFragment;
48use crate::dom::documentorshadowroot::{
49 DocumentOrShadowRoot, ServoStylesheetInDocument, StylesheetSource,
50};
51use crate::dom::element::Element;
52use crate::dom::html::htmlslotelement::HTMLSlotElement;
53use crate::dom::htmldetailselement::DetailsNameGroups;
54use crate::dom::iterators::ShadowIncluding;
55use crate::dom::node::virtualmethods::{VirtualMethods, vtable_for};
56use crate::dom::node::{
57 BindContext, IsShadowTree, Node, NodeDamage, NodeFlags, NodeTraits, UnbindContext,
58 VecPreOrderInsertionHelper,
59};
60use crate::dom::sanitizer::Sanitizer;
61use crate::dom::trustedtypes::trustedhtml::TrustedHTML;
62use crate::dom::types::EventTarget;
63use crate::dom::window::Window;
64
65#[derive(JSTraceable, MallocSizeOf, PartialEq)]
67pub(crate) enum IsUserAgentWidget {
68 No,
69 Yes,
70}
71
72#[dom_struct]
74pub(crate) struct ShadowRoot {
75 document_fragment: DocumentFragment,
77 document_or_shadow_root: DocumentOrShadowRoot,
78 document: Dom<Document>,
79 #[custom_trace]
81 author_styles: DomRefCell<AuthorStyles<ServoStylesheetInDocument>>,
82 stylesheet_list: MutNullableDom<StyleSheetList>,
83 window: Dom<Window>,
84
85 mode: ShadowRootMode,
87
88 slot_assignment_mode: SlotAssignmentMode,
90
91 clonable: bool,
93
94 available_to_element_internals: Cell<bool>,
96
97 slots: DomRefCell<HashMap<TracedDOMString, Vec<Dom<HTMLSlotElement>>>>,
98
99 is_user_agent_widget: bool,
100
101 declarative: Cell<bool>,
103
104 serializable: Cell<bool>,
106
107 delegates_focus: Cell<bool>,
109
110 adopted_stylesheets: DomRefCell<Vec<Dom<CSSStyleSheet>>>,
113
114 details_name_groups: DomRefCell<Option<DetailsNameGroups>>,
115}
116
117impl ShadowRoot {
118 #[cfg_attr(crown, expect(crown::unrooted_must_root))]
119 fn new_inherited(
120 host: &Element,
121 document: &Document,
122 mode: ShadowRootMode,
123 slot_assignment_mode: SlotAssignmentMode,
124 clonable: bool,
125 is_user_agent_widget: IsUserAgentWidget,
126 ) -> ShadowRoot {
127 let document_fragment = DocumentFragment::new_inherited(document, Some(host));
128 let node = document_fragment.upcast::<Node>();
129 node.set_flag(NodeFlags::IS_IN_SHADOW_TREE, true);
130 node.set_flag(
131 NodeFlags::IS_CONNECTED,
132 host.upcast::<Node>().is_connected(),
133 );
134
135 ShadowRoot {
136 document_fragment,
137 document_or_shadow_root: DocumentOrShadowRoot::new(document.window()),
138 document: Dom::from_ref(document),
139 author_styles: DomRefCell::new(AuthorStyles::new()),
140 stylesheet_list: MutNullableDom::new(None),
141 window: Dom::from_ref(document.window()),
142 mode,
143 slot_assignment_mode,
144 clonable,
145 available_to_element_internals: Cell::new(false),
146 slots: Default::default(),
147 is_user_agent_widget: is_user_agent_widget == IsUserAgentWidget::Yes,
148 declarative: Cell::new(false),
149 serializable: Cell::new(false),
150 delegates_focus: Cell::new(false),
151 adopted_stylesheets: Default::default(),
152 details_name_groups: Default::default(),
153 }
154 }
155
156 pub(crate) fn new(
157 cx: &mut JSContext,
158 host: &Element,
159 document: &Document,
160 mode: ShadowRootMode,
161 slot_assignment_mode: SlotAssignmentMode,
162 clonable: bool,
163 is_user_agent_widget: IsUserAgentWidget,
164 ) -> DomRoot<ShadowRoot> {
165 reflect_dom_object(
166 cx,
167 Box::new(ShadowRoot::new_inherited(
168 host,
169 document,
170 mode,
171 slot_assignment_mode,
172 clonable,
173 is_user_agent_widget,
174 )),
175 document.window(),
176 )
177 }
178
179 pub(crate) fn host_unrooted<'a>(&self, no_gc: &'a NoGC) -> UnrootedDom<'a, Element> {
180 self.upcast::<DocumentFragment>()
181 .host_unrooted(no_gc)
182 .expect("ShadowRoot always has an element as host")
183 }
184
185 pub(crate) fn owner_doc(&self) -> &Document {
186 &self.document
187 }
188
189 pub(crate) fn stylesheet_count(&self) -> usize {
190 self.author_styles.borrow().stylesheets.len()
191 }
192
193 pub(crate) fn stylesheet_at(
194 &self,
195 cx: &mut JSContext,
196 index: usize,
197 ) -> Option<DomRoot<CSSStyleSheet>> {
198 let stylesheets = &self.author_styles.borrow().stylesheets;
199
200 stylesheets
201 .get(index)
202 .and_then(|s| s.owner.get_cssom_object(cx))
203 }
204
205 #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub(crate) fn add_owned_stylesheet(
212 &self,
213 no_gc: &NoGC,
214 owner_node: &Element,
215 sheet: Arc<Stylesheet>,
216 ) {
217 let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
218
219 let insertion_point = stylesheets
221 .iter()
222 .find(|sheet_in_shadow| {
223 match &sheet_in_shadow.owner {
224 StylesheetSource::Element(other_node) => owner_node
225 .upcast::<Node>()
226 .is_before(no_gc, other_node.upcast()),
227 StylesheetSource::Constructed(_) => true,
230 }
231 })
232 .cloned();
233
234 DocumentOrShadowRoot::add_stylesheet(
235 StylesheetSource::Element(Dom::from_ref(owner_node)),
236 StylesheetSetRef::Author(stylesheets),
237 sheet,
238 insertion_point,
239 self.document.style_shared_author_lock(),
240 );
241 }
242
243 pub(crate) fn append_constructed_stylesheet(&self, cssom_stylesheet: &CSSStyleSheet) {
245 debug_assert!(cssom_stylesheet.is_constructed());
246
247 let stylesheets = &mut self.author_styles.borrow_mut().stylesheets;
248 let sheet = cssom_stylesheet.style_stylesheet().clone();
249
250 DocumentOrShadowRoot::add_stylesheet(
251 StylesheetSource::Constructed(Dom::from_ref(cssom_stylesheet)),
252 StylesheetSetRef::Author(stylesheets),
253 sheet,
254 None,
255 self.document.style_shared_author_lock(),
256 );
257 }
258
259 #[cfg_attr(crown, expect(crown::unrooted_must_root))] pub(crate) fn remove_stylesheet(&self, owner: StylesheetSource, s: &Arc<Stylesheet>) {
262 DocumentOrShadowRoot::remove_stylesheet(
263 owner,
264 s,
265 StylesheetSetRef::Author(&mut self.author_styles.borrow_mut().stylesheets),
266 )
267 }
268
269 pub(crate) fn invalidate_stylesheets(&self, no_gc: &NoGC) {
270 self.document.invalidate_shadow_roots_stylesheets();
271 self.author_styles.borrow_mut().stylesheets.force_dirty();
272 self.Host().upcast::<Node>().dirty(no_gc, NodeDamage::Style);
274
275 let mut restyle = self.document.ensure_pending_restyle(&self.Host());
278 restyle.hint.insert(RestyleHint::restyle_subtree());
279 }
280
281 pub(crate) fn unregister_element_id(&self, id: &Atom) {
284 self.document_fragment.id_map().remove(id);
285 }
286
287 pub(crate) fn register_element_id(&self, element: &Element, id: &Atom) {
289 self.document_fragment.id_map().add(id, element)
290 }
291
292 pub(crate) fn register_slot(&self, slot: &HTMLSlotElement) {
293 debug!("Registering slot with name={:?}", slot.Name().str());
294
295 let mut slots = self.slots.borrow_mut();
296
297 let slots_with_the_same_name = slots.entry(slot.Name().traced()).or_default();
298
299 slots_with_the_same_name.insert_pre_order(slot, self.upcast::<Node>());
301 }
302
303 pub(crate) fn unregister_slot(&self, name: DOMString, slot: &HTMLSlotElement) {
304 debug!("Unregistering slot with name={:?}", name.str());
305
306 let mut slots = self.slots.borrow_mut();
307 let Entry::Occupied(mut entry) = slots.entry(name.traced()) else {
308 panic!("slot is not registered");
309 };
310 entry.get_mut().retain(|s| slot != &**s);
311 }
312
313 pub(crate) fn slot_for_name(&self, name: &DOMString) -> Option<DomRoot<HTMLSlotElement>> {
315 self.slots
316 .borrow()
317 .get(name)
318 .and_then(|slots| slots.first())
319 .map(|slot| slot.as_rooted())
320 }
321
322 pub(crate) fn has_slot_descendants(&self) -> bool {
323 !self.slots.borrow().is_empty()
324 }
325
326 pub(crate) fn set_available_to_element_internals(&self, value: bool) {
327 self.available_to_element_internals.set(value);
328 }
329
330 pub(crate) fn is_available_to_element_internals(&self) -> bool {
332 self.available_to_element_internals.get()
333 }
334
335 pub(crate) fn is_user_agent_widget(&self) -> bool {
336 self.is_user_agent_widget
337 }
338
339 pub(crate) fn set_declarative(&self, declarative: bool) {
340 self.declarative.set(declarative);
341 }
342
343 pub(crate) fn is_declarative(&self) -> bool {
344 self.declarative.get()
345 }
346
347 pub(crate) fn shadow_root_mode(&self) -> ShadowRootMode {
348 self.mode
349 }
350
351 pub(crate) fn set_serializable(&self, serializable: bool) {
352 self.serializable.set(serializable);
353 }
354
355 pub(crate) fn set_delegates_focus(&self, delegates_focus: bool) {
356 self.delegates_focus.set(delegates_focus);
357 }
358
359 pub(crate) fn details_name_groups<'a: 'b, 'b>(
360 &'a self,
361 no_gc: &'b NoGC,
362 ) -> RefMut<'b, DetailsNameGroups> {
363 RefMut::map(
364 self.details_name_groups.safe_borrow_mut(no_gc),
365 |details_name_groups| details_name_groups.get_or_insert_default(),
366 )
367 }
368
369 pub(crate) fn custom_element_registry(&self) -> Option<DomRoot<CustomElementRegistry>> {
370 self.document_or_shadow_root.custom_element_registry()
371 }
372
373 pub(crate) fn set_custom_element_registry(&self, registry: Option<&CustomElementRegistry>) {
374 self.document_or_shadow_root
375 .set_custom_element_registry(registry);
376 }
377}
378
379impl ShadowRootMethods<crate::DomTypeHolder> for ShadowRoot {
380 fn GetActiveElement(&self) -> Option<DomRoot<Element>> {
382 self.document_or_shadow_root.active_element(self.upcast())
383 }
384
385 fn GetCustomElementRegistry(&self) -> Option<DomRoot<CustomElementRegistry>> {
387 self.custom_element_registry()
388 }
389
390 fn ElementFromPoint(
392 &self,
393 cx: &mut JSContext,
394 x: Finite<f64>,
395 y: Finite<f64>,
396 ) -> Option<DomRoot<Element>> {
397 match self.document_or_shadow_root.element_from_point(
400 cx,
401 self.upcast(),
402 x,
403 y,
404 None,
405 self.document.has_browsing_context(),
406 ) {
407 Some(e) => {
408 let retargeted_node = e.upcast::<EventTarget>().retarget(self.upcast());
409 retargeted_node.downcast::<Element>().map(DomRoot::from_ref)
410 },
411 None => None,
412 }
413 }
414
415 fn ElementsFromPoint(
417 &self,
418 cx: &mut JSContext,
419 x: Finite<f64>,
420 y: Finite<f64>,
421 ) -> Vec<DomRoot<Element>> {
422 let mut elements = Vec::new();
425 for e in self
426 .document_or_shadow_root
427 .elements_from_point(
428 cx,
429 self.upcast(),
430 x,
431 y,
432 None,
433 self.document.has_browsing_context(),
434 )
435 .iter()
436 {
437 let retargeted_node = e.upcast::<EventTarget>().retarget(self.upcast());
438 if let Some(element) = retargeted_node.downcast::<Element>().map(DomRoot::from_ref) {
439 elements.push(element);
440 }
441 }
442 elements
443 }
444
445 fn Mode(&self) -> ShadowRootMode {
447 self.mode
448 }
449
450 fn DelegatesFocus(&self) -> bool {
452 self.delegates_focus.get()
453 }
454
455 fn Clonable(&self) -> bool {
457 self.clonable
458 }
459
460 fn Serializable(&self) -> bool {
462 self.serializable.get()
463 }
464
465 fn Host(&self) -> DomRoot<Element> {
467 self.upcast::<DocumentFragment>()
468 .host()
469 .expect("ShadowRoot always has an element as host")
470 }
471
472 fn StyleSheets(&self, cx: &mut JSContext) -> DomRoot<StyleSheetList> {
474 self.stylesheet_list.or_init(|| {
475 StyleSheetList::new(
476 cx,
477 &self.window,
478 StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
479 )
480 })
481 }
482
483 fn GetHTML(&self, cx: &mut JSContext, options: &GetHTMLOptions) -> DOMString {
485 let shadow_roots = options.shadowRoots.iter().map(Dom::as_rooted).collect();
486 self.upcast::<Node>().html_serialize(
489 cx,
490 TraversalScope::ChildrenOnly(None),
491 options.serializableShadowRoots,
492 shadow_roots,
493 )
494 }
495
496 fn GetInnerHTML(&self, cx: &mut JSContext) -> Fallible<TrustedHTMLOrNullIsEmptyString> {
498 self.upcast::<Node>()
501 .fragment_serialization_algorithm(cx, true)
502 .map(TrustedHTMLOrNullIsEmptyString::NullIsEmptyString)
503 }
504
505 fn SetInnerHTML(
507 &self,
508 cx: &mut JSContext,
509 value: TrustedHTMLOrNullIsEmptyString,
510 ) -> ErrorResult {
511 let value = TrustedHTML::get_trusted_type_compliant_string(
514 cx,
515 &self.owner_global(),
516 value.convert(),
517 "ShadowRoot innerHTML",
518 )?;
519
520 let context = self.Host();
522
523 let frag = context.parse_fragment(value, cx)?;
529
530 Node::replace_all(cx, Some(frag.upcast()), self.upcast());
532 Ok(())
533 }
534
535 fn SlotAssignment(&self) -> SlotAssignmentMode {
537 self.slot_assignment_mode
538 }
539
540 fn SetHTMLUnsafe(
542 &self,
543 cx: &mut JSContext,
544 value: TrustedHTMLOrString,
545 options: &SetHTMLUnsafeOptions,
546 ) -> ErrorResult {
547 let compliant_html = TrustedHTML::get_trusted_type_compliant_string(
551 cx,
552 &self.owner_global(),
553 value,
554 "ShadowRoot setHTMLUnsafe",
555 )?;
556
557 Sanitizer::set_and_filter_html(
560 cx,
561 self.upcast(),
562 &self.Host(),
563 compliant_html,
564 options,
565 false,
566 )?;
567
568 Ok(())
569 }
570
571 fn SetHTML(
573 &self,
574 cx: &mut JSContext,
575 html: DOMString,
576 options: &SetHTMLOptions,
577 ) -> ErrorResult {
578 let target = self.upcast::<Node>();
583 let context_element = self.Host();
584 Sanitizer::set_and_filter_html(cx, target, &context_element, html, options, true)
585 }
586
587 event_handler!(slotchange, GetOnslotchange, SetOnslotchange);
589
590 fn OnSetAdoptedStyleSheets(
592 &self,
593 cx: &mut JSContext,
594 value: DomRoot<CSSStyleSheet>,
595 index: u32,
596 ) -> ErrorResult {
597 let result = DocumentOrShadowRoot::on_set_adopted_stylesheets(
598 self.adopted_stylesheets.safe_borrow_mut(cx).as_mut(),
599 &value,
600 index,
601 &StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
602 );
603
604 if result.is_ok() && self.author_styles.borrow().stylesheets.dirty() {
605 self.invalidate_stylesheets(cx.no_gc());
606 }
607
608 result
609 }
610
611 fn OnDeleteAdoptedStyleSheets(
613 &self,
614 cx: &mut JSContext,
615 _value: DomRoot<CSSStyleSheet>,
616 index: u32,
617 ) -> ErrorResult {
618 let result = DocumentOrShadowRoot::on_delete_adopted_stylesheets(
619 self.adopted_stylesheets.safe_borrow_mut(cx).as_mut(),
620 index,
621 &StyleSheetListOwner::ShadowRoot(Dom::from_ref(self)),
622 );
623
624 if result.is_ok() && self.author_styles.borrow().stylesheets.dirty() {
625 self.invalidate_stylesheets(cx.no_gc());
626 }
627
628 result
629 }
630
631 fn GetFullscreenElement(&self) -> Option<DomRoot<Element>> {
633 DocumentOrShadowRoot::get_fullscreen_element(
634 self.upcast::<Node>(),
635 self.document.overlay_handler().fullscreen_element(),
636 )
637 }
638}
639
640impl VirtualMethods for ShadowRoot {
641 fn super_type(&self) -> Option<&dyn VirtualMethods> {
642 Some(self.upcast::<DocumentFragment>() as &dyn VirtualMethods)
643 }
644
645 fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
646 if let Some(s) = self.super_type() {
647 s.bind_to_tree(cx, context);
648 }
649
650 if context.tree_connected {
653 self.owner_document_unrooted(cx.no_gc())
654 .register_shadow_root(self);
655 }
656
657 let shadow_root = self.upcast::<Node>();
658
659 shadow_root.set_flag(NodeFlags::IS_CONNECTED, context.tree_connected);
660
661 let inner_context = BindContext::new(shadow_root, IsShadowTree::Yes);
662
663 for node in shadow_root.traverse_preorder(ShadowIncluding::No).skip(1) {
665 node.set_flag(NodeFlags::IS_CONNECTED, inner_context.tree_connected);
666
667 debug_assert!(!node.get_flag(NodeFlags::HAS_DIRTY_DESCENDANTS));
669 vtable_for(&node).bind_to_tree(cx, &inner_context);
670 }
671 }
672
673 fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
674 if let Some(s) = self.super_type() {
675 s.unbind_from_tree(cx, context);
676 }
677
678 if context.tree_connected {
679 self.owner_document_unrooted(cx.no_gc())
680 .unregister_shadow_root(self);
681 }
682 }
683}
684
685impl<'dom> LayoutDom<'dom, ShadowRoot> {
686 #[inline]
687 pub(crate) fn get_host_for_layout(self) -> LayoutDom<'dom, Element> {
688 self.upcast::<DocumentFragment>()
689 .shadowroot_host_for_layout()
690 }
691
692 #[inline]
693 #[expect(unsafe_code)]
694 pub(crate) fn get_style_data_for_layout(self) -> &'dom CascadeData {
695 fn is_sync<T: Sync>() {}
696 let _ = is_sync::<CascadeData>;
697 unsafe { &self.unsafe_get().author_styles.borrow_for_layout().data }
698 }
699
700 #[inline]
701 pub(crate) fn is_user_agent_widget(&self) -> bool {
702 self.unsafe_get().is_user_agent_widget()
703 }
704
705 #[inline]
708 #[expect(unsafe_code)]
709 pub(crate) unsafe fn flush_stylesheets_for_layout(
710 self,
711 stylist: &mut Stylist,
712 guard: &SharedRwLockReadGuard,
713 ) {
714 unsafe {
715 debug_assert!(self.upcast::<Node>().get_flag(NodeFlags::IS_CONNECTED));
716 };
717 let author_styles = unsafe { self.unsafe_get().author_styles.borrow_mut_for_layout() };
718 if author_styles.stylesheets.dirty() {
719 author_styles.flush(stylist, guard);
720 }
721 }
722}
723
724#[cfg(feature = "devtools")]
725impl Convert<devtools_traits::ShadowRootMode> for ShadowRootMode {
726 fn convert(self) -> devtools_traits::ShadowRootMode {
727 match self {
728 ShadowRootMode::Open => devtools_traits::ShadowRootMode::Open,
729 ShadowRootMode::Closed => devtools_traits::ShadowRootMode::Closed,
730 }
731 }
732}