Skip to main content

script/dom/document/
documentorshadowroot.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::collections::HashSet;
6use std::ffi::c_void;
7use std::fmt;
8
9use embedder_traits::UntrustedNodeAddress;
10use js::context::JSContext;
11use layout_api::HitTestFlags;
12use script_bindings::codegen::GenericBindings::DocumentBinding::DocumentMethods;
13use script_bindings::codegen::GenericBindings::ShadowRootBinding::ShadowRootMethods;
14use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
15use script_bindings::error::{Error, ErrorResult};
16use servo_arc::Arc;
17use servo_config::pref;
18use style::media_queries::MediaList;
19use style::shared_lock::{SharedRwLock as StyleSharedRwLock, SharedRwLockReadGuard};
20use style::stylesheets::scope_rule::ImplicitScopeRoot;
21use style::stylesheets::{Stylesheet, StylesheetContents};
22use webrender_api::units::LayoutPoint;
23
24use crate::css::stylesheet_set::StylesheetSetRef;
25use crate::dom::Document;
26use crate::dom::bindings::codegen::Bindings::NodeBinding::GetRootNodeOptions;
27use crate::dom::bindings::codegen::Bindings::NodeBinding::Node_Binding::NodeMethods;
28use crate::dom::bindings::inheritance::Castable;
29use crate::dom::bindings::num::Finite;
30use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
31use crate::dom::css::stylesheetlist::StyleSheetListOwner;
32use crate::dom::customelementregistry::CustomElementRegistry;
33use crate::dom::element::Element;
34use crate::dom::node::{self, Node};
35use crate::dom::types::{CSSStyleSheet, EventTarget, ShadowRoot};
36use crate::dom::window::Window;
37
38/// Stylesheet could be constructed by a CSSOM object CSSStylesheet or parsed
39/// from HTML element such as `<style>` or `<link>`.
40#[derive(Clone, JSTraceable, MallocSizeOf)]
41#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
42pub(crate) enum StylesheetSource {
43    Element(Dom<Element>),
44    Constructed(Dom<CSSStyleSheet>),
45}
46
47impl StylesheetSource {
48    pub(crate) fn get_cssom_object(&self, cx: &mut JSContext) -> Option<DomRoot<CSSStyleSheet>> {
49        match self {
50            StylesheetSource::Element(el) => el.upcast::<Node>().get_cssom_stylesheet(cx),
51            StylesheetSource::Constructed(ss) => Some(ss.as_rooted()),
52        }
53    }
54
55    pub(crate) fn is_a_valid_owner(&self) -> bool {
56        match self {
57            StylesheetSource::Element(el) => el.as_stylesheet_owner().is_some(),
58            StylesheetSource::Constructed(ss) => ss.is_constructed(),
59        }
60    }
61
62    pub(crate) fn is_constructed(&self) -> bool {
63        matches!(self, StylesheetSource::Constructed(_))
64    }
65}
66
67#[derive(Clone, JSTraceable, MallocSizeOf)]
68#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
69pub(crate) struct ServoStylesheetInDocument {
70    #[ignore_malloc_size_of = "Stylo"]
71    #[no_trace]
72    pub(crate) sheet: Arc<Stylesheet>,
73    /// The object that owns this stylesheet. For constructed stylesheet, it would be the
74    /// CSSOM object itself, and for stylesheet generated by an element, it would be the
75    /// html element. This is used to get the CSSOM Stylesheet within a DocumentOrShadowDOM.
76    pub(crate) owner: StylesheetSource,
77}
78
79// This is necessary because this type is contained within a Stylo type which needs
80// Stylo's version of MallocSizeOf.
81impl stylo_malloc_size_of::MallocSizeOf for ServoStylesheetInDocument {
82    fn size_of(&self, ops: &mut stylo_malloc_size_of::MallocSizeOfOps) -> usize {
83        <ServoStylesheetInDocument as malloc_size_of::MallocSizeOf>::size_of(self, ops)
84    }
85}
86
87impl fmt::Debug for ServoStylesheetInDocument {
88    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
89        self.sheet.fmt(formatter)
90    }
91}
92
93impl PartialEq for ServoStylesheetInDocument {
94    fn eq(&self, other: &Self) -> bool {
95        Arc::ptr_eq(&self.sheet, &other.sheet)
96    }
97}
98
99impl ::style::stylesheets::StylesheetInDocument for ServoStylesheetInDocument {
100    fn enabled(&self) -> bool {
101        self.sheet.enabled()
102    }
103
104    fn media<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> Option<&'a MediaList> {
105        self.sheet.media(guard)
106    }
107
108    fn contents<'a>(&'a self, guard: &'a SharedRwLockReadGuard) -> &'a StylesheetContents {
109        self.sheet.contents(guard)
110    }
111
112    fn implicit_scope_root(&self) -> Option<ImplicitScopeRoot> {
113        None
114    }
115}
116
117// https://w3c.github.io/webcomponents/spec/shadow/#extensions-to-the-documentorshadowroot-mixin
118#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
119#[derive(JSTraceable, MallocSizeOf)]
120pub(crate) struct DocumentOrShadowRoot {
121    window: Dom<Window>,
122    custom_element_registry: MutNullableDom<CustomElementRegistry>,
123}
124
125impl DocumentOrShadowRoot {
126    pub(crate) fn new(window: &Window) -> Self {
127        Self {
128            window: Dom::from_ref(window),
129            custom_element_registry: MutNullableDom::new(None),
130        }
131    }
132
133    /// <https://dom.spec.whatwg.org/#dom-documentorshadowroot-customelementregistry>
134    pub(crate) fn custom_element_registry(&self) -> Option<DomRoot<CustomElementRegistry>> {
135        self.custom_element_registry.get()
136    }
137
138    pub(crate) fn set_custom_element_registry(&self, registry: Option<&CustomElementRegistry>) {
139        self.custom_element_registry.set(registry);
140    }
141
142    /// Retarget the result of `elementsFromPoint` or `elementFromPoint` according to the
143    /// resolution in <https://github.com/w3c/csswg-drafts/issues/556>.
144    pub(crate) fn retarget_hit_test_result(
145        &self,
146        this: &Node,
147        node: &Node,
148    ) -> Option<DomRoot<Element>> {
149        let retargeted_node =
150            DomRoot::downcast::<Node>(node.upcast::<EventTarget>().retarget(this.upcast()))?;
151        DomRoot::downcast::<Element>(retargeted_node.clone()).or_else(|| {
152            let parent_node = retargeted_node.GetParentNode()?;
153
154            // This node has already been retargeted, but if it is the direct descendant of
155            // a shadow root and it isn't an element, the only reasonable thing to return is
156            // the shadow host (even though that is outside of `this`.) This is a surprising
157            // behavior, but this is what browsers do.
158            if let Some(shadow_root) = parent_node.downcast::<ShadowRoot>() {
159                Some(shadow_root.Host())
160            } else {
161                retargeted_node.GetParentElement()
162            }
163        })
164    }
165
166    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint>
167    #[expect(unsafe_code)]
168    pub(crate) fn element_from_point(
169        &self,
170        cx: &mut JSContext,
171        this: &Node,
172        x: Finite<f64>,
173        y: Finite<f64>,
174        document_element: Option<DomRoot<Element>>,
175        has_browsing_context: bool,
176    ) -> Option<DomRoot<Element>> {
177        let x = *x as f32;
178        let y = *y as f32;
179        let viewport = self.window.viewport_details().size;
180
181        if !has_browsing_context {
182            return None;
183        }
184
185        if x < 0.0 || y < 0.0 || x > viewport.width || y > viewport.height {
186            return None;
187        }
188
189        let flags = HitTestFlags::empty();
190        let result = self
191            .window
192            .elements_from_point_query(cx, flags, LayoutPoint::new(x, y));
193        let Some(result) = result.items.first() else {
194            return document_element;
195        };
196
197        // SAFETY: This is safe because `Self::query_elements_from_point` has ensured that
198        // layout has run and any OpaqueNodes that no longer refer to real nodes are gone.
199        let address = UntrustedNodeAddress(result.node.0 as *const c_void);
200        let node = unsafe { node::from_untrusted_node_address(address) };
201
202        self.retarget_hit_test_result(this, &node)
203    }
204
205    /// <https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint>
206    #[expect(unsafe_code)]
207    pub(crate) fn elements_from_point(
208        &self,
209        cx: &mut JSContext,
210        this: &Node,
211        x: Finite<f64>,
212        y: Finite<f64>,
213        document_element: Option<DomRoot<Element>>,
214        has_browsing_context: bool,
215    ) -> Vec<DomRoot<Element>> {
216        let x = *x as f32;
217        let y = *y as f32;
218        let viewport = self.window.viewport_details().size;
219
220        if !has_browsing_context {
221            return vec![];
222        }
223
224        // Step 2
225        if x < 0.0 || y < 0.0 || x > viewport.width || y > viewport.height {
226            return vec![];
227        }
228
229        // Step 1: Let sequence be a new empty sequence.
230        // Step 3: For each box in the viewport, in paint order, starting with the topmost
231        // box, that would be a target for hit testing at coordinates x,y even if nothing
232        // would be overlapping it, when applying the transforms that apply to the
233        // descendants of the viewport, append the associated element to sequence.
234        let flags = HitTestFlags::empty();
235        let result = self
236            .window
237            .elements_from_point_query(cx, flags, LayoutPoint::new(x, y));
238
239        let mut elements: Vec<_> = result
240            .items
241            .iter()
242            .flat_map(|result| {
243                // SAFETY: This is safe because `Self::query_elements_from_point` has ensured that
244                // layout has run and any OpaqueNodes that no longer refer to real nodes are gone.
245                let address = UntrustedNodeAddress(result.node.0 as *const c_void);
246                let node = unsafe { node::from_untrusted_node_address(address) };
247                self.retarget_hit_test_result(this, &node)
248            })
249            .collect();
250
251        // Now remove consecutive duplicates. This isn't in the specification, but it
252        // follows browser behavior. See https://github.com/w3c/csswg-drafts/issues/556.
253        let mut last_seen = None;
254        elements.retain(|element| {
255            if Some(element) == last_seen.as_ref() {
256                return false;
257            }
258            last_seen = Some(element.clone());
259            true
260        });
261
262        // Step 4: If the document has a root element, and the last item in sequence is
263        // not the root element, append the root element to sequence.
264        if let Some(root_element) = document_element &&
265            elements.last() != Some(&root_element)
266        {
267            elements.push(root_element);
268        }
269
270        // Step 5: Return sequence.
271        elements
272    }
273
274    /// <https://html.spec.whatwg.org/multipage/#dom-documentorshadowroot-activeelement-dev>
275    pub(crate) fn active_element(&self, this: &Node) -> Option<DomRoot<Element>> {
276        // Step 1. Let candidate be this's node document's focused area's DOM anchor.
277        let document = self.window.Document();
278        let candidate = document
279            .focus_handler()
280            .focused_area()
281            .dom_anchor(&document);
282
283        // Step 2. Set candidate to the result of retargeting candidate against this.
284        //
285        // Note: `retarget()` operates on `EventTarget`, but we can be assured that we are
286        // only dealing with various kinds of `Node`s here.
287        let candidate =
288            DomRoot::downcast::<Node>(candidate.upcast::<EventTarget>().retarget(this.upcast()))?;
289
290        // Step 3. If candidate's root is not this, then return null.
291        if this != &*candidate.GetRootNode(&GetRootNodeOptions::empty()) {
292            return None;
293        }
294
295        // Step 4. If candidate is not a Document object, then return candidate.
296        if let Some(candidate) = DomRoot::downcast::<Element>(candidate.clone()) {
297            return Some(candidate);
298        }
299        assert!(candidate.is::<Document>());
300
301        // Step 5. If candidate has a body element, then return that body element.
302        if let Some(body) = document.GetBody() {
303            return Some(DomRoot::upcast(body));
304        }
305
306        // Step 6. If candidate's document element is non-null, then return that document element.
307        if let Some(document_element) = document.GetDocumentElement() {
308            return Some(document_element);
309        }
310
311        // Step 7. Return null.
312        None
313    }
314
315    /// Remove a stylesheet owned by `owner` from the list of document sheets.
316    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
317    pub(crate) fn remove_stylesheet(
318        owner: StylesheetSource,
319        s: &Arc<Stylesheet>,
320        mut stylesheets: StylesheetSetRef<ServoStylesheetInDocument>,
321    ) {
322        let guard = s.shared_lock.read();
323
324        // FIXME(emilio): Would be nice to remove the clone, etc.
325        stylesheets.remove_stylesheet(
326            None,
327            ServoStylesheetInDocument {
328                sheet: s.clone(),
329                owner,
330            },
331            &guard,
332        );
333    }
334
335    /// Add a stylesheet owned by `owner` to the list of document sheets, in the
336    /// correct tree position.
337    #[cfg_attr(crown, expect(crown::unrooted_must_root))] // Owner needs to be rooted already necessarily.
338    pub(crate) fn add_stylesheet(
339        owner: StylesheetSource,
340        mut stylesheets: StylesheetSetRef<ServoStylesheetInDocument>,
341        sheet: Arc<Stylesheet>,
342        insertion_point: Option<ServoStylesheetInDocument>,
343        style_shared_lock: &StyleSharedRwLock,
344    ) {
345        debug_assert!(owner.is_a_valid_owner(), "Wat");
346
347        if owner.is_constructed() && !pref!(dom_adoptedstylesheet_enabled) {
348            return;
349        }
350
351        let sheet = ServoStylesheetInDocument { sheet, owner };
352
353        let guard = style_shared_lock.read();
354
355        match insertion_point {
356            Some(ip) => {
357                stylesheets.insert_stylesheet_before(sheet, ip, &guard);
358            },
359            None => {
360                stylesheets.append_stylesheet(sheet, &guard);
361            },
362        }
363    }
364
365    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
366    ///
367    /// To replace the DOM-side adopted stylesheet list:
368    /// 1. Validate each incoming stylesheet against the owner document.
369    /// 2. Remove the old effective constructed stylesheets from the style set.
370    /// 3. Rebuild the effective constructed stylesheet order from `incoming_stylesheets`.
371    fn set_adopted_stylesheets(
372        adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
373        incoming_stylesheets: &[Dom<CSSStyleSheet>],
374        owner: &StyleSheetListOwner,
375    ) -> ErrorResult {
376        if !pref!(dom_adoptedstylesheet_enabled) {
377            return Ok(());
378        }
379
380        let owner_doc = match owner {
381            StyleSheetListOwner::Document(doc) => doc,
382            StyleSheetListOwner::ShadowRoot(root) => root.owner_doc(),
383        };
384
385        for sheet in incoming_stylesheets {
386            // > If value’s constructed flag is not set, or its constructor document is not equal
387            // > to this DocumentOrShadowRoot’s node document, throw a "NotAllowedError" DOMException.
388            if !sheet.constructor_document_matches(owner_doc) {
389                return Err(Error::NotAllowed(Some(
390                    "Stylesheet is not constructed or its constructor document does not match"
391                        .into(),
392                )));
393            }
394        }
395
396        // The set to check for the duplicates when removing the old stylesheets.
397        let mut stylesheet_remove_set = HashSet::with_capacity(adopted_stylesheets.len());
398
399        // Remove the old stylesheets from the StyleSet. This workflow is limited by utilities
400        // Stylo StyleSet given to us.
401        for sheet_to_remove in adopted_stylesheets.iter() {
402            // Check for duplicates, only proceed with the removal if the stylesheet is not removed yet.
403            if stylesheet_remove_set.insert(sheet_to_remove) {
404                owner.remove_stylesheet(
405                    StylesheetSource::Constructed(sheet_to_remove.clone()),
406                    &sheet_to_remove.style_stylesheet(),
407                );
408                sheet_to_remove.remove_adopter(owner);
409            }
410        }
411
412        // The set to check for the duplicates when adding a new stylesheet.
413        let mut stylesheet_add_set = HashSet::with_capacity(incoming_stylesheets.len());
414
415        // Readd all stylesheet to the StyleSet. This workflow is limited by the utilities
416        // Stylo StyleSet given to us.
417        for sheet in incoming_stylesheets {
418            // Check for duplicates.
419            if !stylesheet_add_set.insert(sheet) {
420                // The idea is that this case is rare, so we pay the price of removing the
421                // old sheet from the styles and append it later rather than the other way
422                // around.
423                owner.remove_stylesheet(
424                    StylesheetSource::Constructed(sheet.clone()),
425                    &sheet.style_stylesheet(),
426                );
427            } else {
428                sheet.add_adopter(owner.clone());
429            }
430
431            owner.append_constructed_stylesheet(sheet);
432        }
433
434        *adopted_stylesheets = incoming_stylesheets.to_vec();
435        Ok(())
436    }
437
438    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
439    pub(crate) fn on_set_adopted_stylesheets(
440        adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
441        value: &CSSStyleSheet,
442        index: u32,
443        owner: &StyleSheetListOwner,
444    ) -> ErrorResult {
445        rooted_vec!(let mut incoming_stylesheets <- adopted_stylesheets.iter().cloned());
446        incoming_stylesheets.insert(index as usize, Dom::from_ref(value));
447        Self::set_adopted_stylesheets(adopted_stylesheets, &incoming_stylesheets, owner)
448    }
449
450    /// <https://drafts.csswg.org/cssom/#dom-documentorshadowroot-adoptedstylesheets>
451    pub(crate) fn on_delete_adopted_stylesheets(
452        adopted_stylesheets: &mut Vec<Dom<CSSStyleSheet>>,
453        index: u32,
454        owner: &StyleSheetListOwner,
455    ) -> ErrorResult {
456        rooted_vec!(let mut incoming_stylesheets <- adopted_stylesheets.iter().cloned());
457        incoming_stylesheets.remove(index as usize);
458        Self::set_adopted_stylesheets(adopted_stylesheets, &incoming_stylesheets, owner)
459    }
460
461    /// <https://fullscreen.spec.whatwg.org/#dom-document-fullscreenelement>
462    pub(crate) fn get_fullscreen_element(
463        node: &Node,
464        fullscreen_element: Option<DomRoot<Element>>,
465    ) -> Option<DomRoot<Element>> {
466        // Step 1. If this is a shadow root and its host is not connected, then return null.
467        if let Some(shadow_root) = node.downcast::<ShadowRoot>() &&
468            !shadow_root.Host().is_connected()
469        {
470            return None;
471        }
472
473        // Step 2. Let candidate be the result of retargeting fullscreen element against this.
474        let retargeted = fullscreen_element?
475            .upcast::<EventTarget>()
476            .retarget(node.upcast());
477        // It's safe to unwrap downcasting to `Element` because `retarget` either returns `fullscreen_element` or a host of `fullscreen_element` and hosts are always elements.
478        let candidate = DomRoot::downcast::<Element>(retargeted).unwrap();
479
480        // Step 3. If candidate and this are in the same tree, then return candidate.
481        if *candidate
482            .upcast::<Node>()
483            .GetRootNode(&GetRootNodeOptions::empty()) ==
484            *node
485        {
486            return Some(candidate);
487        }
488
489        // Step 4. Return null.
490        None
491    }
492}