Skip to main content

script/dom/css/
cssstylesheet.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, Ref};
6
7use dom_struct::dom_struct;
8use js::context::{JSContext, NoGC};
9use js::realm::CurrentRealm;
10use js::rust::HandleObject;
11use script_bindings::cell::DomRefCell;
12use script_bindings::codegen::GenericBindings::StyleSheetBinding::StyleSheetMethods;
13use script_bindings::inheritance::Castable;
14use script_bindings::reflector::{reflect_dom_object, reflect_dom_object_with_proto};
15use script_bindings::root::Dom;
16use servo_arc::Arc;
17use servo_url::ServoUrl;
18use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard};
19use style::stylesheets::{
20    AllowImportRules, Origin, Stylesheet as StyleStyleSheet, StylesheetContents,
21    StylesheetInDocument, UrlExtraData,
22};
23
24use super::cssrulelist::{CSSRuleList, RulesSource};
25use super::stylesheet::StyleSheet;
26use super::stylesheetlist::StyleSheetListOwner;
27use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::{
28    CSSStyleSheetInit, CSSStyleSheetMethods,
29};
30use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods;
31use crate::dom::bindings::codegen::GenericBindings::CSSRuleListBinding::CSSRuleList_Binding::CSSRuleListMethods;
32use crate::dom::bindings::codegen::UnionTypes::MediaListOrString;
33use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
34use crate::dom::bindings::refcounted::{Trusted, TrustedPromise};
35use crate::dom::bindings::reflector::DomGlobal;
36use crate::dom::bindings::root::{DomRoot, MutNullableDom};
37use crate::dom::bindings::str::{DOMString, USVString};
38use crate::dom::document::Document;
39use crate::dom::element::Element;
40use crate::dom::html::htmlstyleelement::HTMLStyleElement;
41use crate::dom::medialist::MediaList;
42use crate::dom::node::NodeTraits;
43use crate::dom::promise::RootedPromise;
44use crate::dom::types::Promise;
45use crate::dom::window::Window;
46
47#[dom_struct]
48pub(crate) struct CSSStyleSheet {
49    stylesheet: StyleSheet,
50
51    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-owner-node>
52    owner_node: MutNullableDom<Element>,
53
54    /// <https://drafts.csswg.org/cssom/#ref-for-concept-css-style-sheet-css-rules>
55    rule_list: MutNullableDom<CSSRuleList>,
56
57    /// The inner Stylo's [Stylesheet].
58    #[ignore_malloc_size_of = "Stylo"]
59    #[no_trace]
60    style_stylesheet: DomRefCell<Arc<StyleStyleSheet>>,
61
62    /// The inner Stylo's [SharedRwLock], stored at here to avoid referencing
63    /// temporary variables.
64    #[no_trace]
65    style_shared_lock: SharedRwLock,
66
67    /// In which [Document] that this stylesheet was constructed.
68    ///
69    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-constructor-document>
70    constructor_document: Option<Dom<Document>>,
71
72    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-disallow-modification-flag>
73    disallow_modification: Cell<bool>,
74
75    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-origin-clean-flag>
76    origin_clean: Cell<bool>,
77
78    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-stylesheet-base-url>
79    #[no_trace]
80    stylesheet_base_url: DomRefCell<Option<ServoUrl>>,
81
82    /// Documents or shadow DOMs thats adopt this stylesheet, they will be notified whenever
83    /// the stylesheet is modified.
84    adopters: DomRefCell<Vec<StyleSheetListOwner>>,
85}
86
87impl CSSStyleSheet {
88    fn new_inherited(
89        owner: Option<&Element>,
90        type_: DOMString,
91        href: Option<DOMString>,
92        stylesheet: Arc<StyleStyleSheet>,
93        constructor_document: Option<&Document>,
94    ) -> CSSStyleSheet {
95        CSSStyleSheet {
96            stylesheet: StyleSheet::new_inherited(type_, href),
97            owner_node: MutNullableDom::new(owner),
98            rule_list: MutNullableDom::new(None),
99            style_shared_lock: stylesheet.shared_lock.clone(),
100            style_stylesheet: DomRefCell::new(stylesheet),
101            origin_clean: Cell::new(true),
102            constructor_document: constructor_document.map(Dom::from_ref),
103            adopters: Default::default(),
104            disallow_modification: Cell::new(false),
105            stylesheet_base_url: Default::default(),
106        }
107    }
108
109    pub(crate) fn new(
110        cx: &mut JSContext,
111        window: &Window,
112        owner: Option<&Element>,
113        type_: DOMString,
114        href: Option<DOMString>,
115        stylesheet: Arc<StyleStyleSheet>,
116        constructor_document: Option<&Document>,
117    ) -> DomRoot<CSSStyleSheet> {
118        reflect_dom_object(
119            cx,
120            Box::new(CSSStyleSheet::new_inherited(
121                owner,
122                type_,
123                href,
124                stylesheet,
125                constructor_document,
126            )),
127            window,
128        )
129    }
130
131    #[expect(clippy::too_many_arguments)]
132    fn new_with_proto(
133        cx: &mut JSContext,
134        window: &Window,
135        proto: Option<HandleObject>,
136        owner: Option<&Element>,
137        type_: DOMString,
138        href: Option<DOMString>,
139        stylesheet: Arc<StyleStyleSheet>,
140        constructor_document: Option<&Document>,
141    ) -> DomRoot<CSSStyleSheet> {
142        reflect_dom_object_with_proto(
143            cx,
144            Box::new(CSSStyleSheet::new_inherited(
145                owner,
146                type_,
147                href,
148                stylesheet,
149                constructor_document,
150            )),
151            window,
152            proto,
153        )
154    }
155
156    pub(crate) fn rulelist(&self, cx: &mut JSContext) -> DomRoot<CSSRuleList> {
157        self.rule_list.or_init(|| {
158            let sheet = self.style_stylesheet.borrow();
159            let guard = sheet.shared_lock.read();
160            let rules = sheet.contents(&guard).rules.clone();
161            CSSRuleList::new(
162                cx,
163                self.global().as_window(),
164                None,
165                self,
166                RulesSource::Rules(rules),
167            )
168        })
169    }
170
171    pub(crate) fn disabled(&self) -> bool {
172        self.style_stylesheet.borrow().disabled()
173    }
174
175    pub(crate) fn href(&self) -> Option<DOMString> {
176        self.upcast::<StyleSheet>().GetHref()
177    }
178
179    pub(crate) fn title(&self) -> DOMString {
180        self.upcast::<StyleSheet>().GetTitle().unwrap_or_default()
181    }
182
183    #[cfg(feature = "devtools")]
184    pub(crate) fn get_rule_count(&self) -> u32 {
185        let sheet = self.style_stylesheet.borrow();
186        let guard = sheet.shared_lock.read();
187        sheet.contents(&guard).rules.read_with(&guard).0.len() as u32
188    }
189
190    pub(crate) fn origin(&self) -> Origin {
191        let guard = self.style_shared_lock.read();
192        self.style_stylesheet()
193            .clone()
194            .contents
195            .read_with(&guard)
196            .origin
197    }
198
199    pub(crate) fn owner_node(&self) -> Option<DomRoot<Element>> {
200        self.owner_node.get()
201    }
202
203    pub(crate) fn set_disabled(&self, no_gc: &NoGC, disabled: bool) {
204        if self.style_stylesheet.borrow().set_disabled(disabled) {
205            self.notify_invalidations(no_gc);
206        }
207    }
208
209    pub(crate) fn set_owner_node(&self, value: Option<&Element>) {
210        self.owner_node.set(value);
211    }
212
213    pub(crate) fn shared_lock(&self) -> &SharedRwLock {
214        &self.style_shared_lock
215    }
216
217    pub(crate) fn style_stylesheet(&self) -> Ref<'_, Arc<StyleStyleSheet>> {
218        self.style_stylesheet.borrow()
219    }
220
221    pub(crate) fn set_origin_clean(&self, origin_clean: bool) {
222        self.origin_clean.set(origin_clean);
223    }
224
225    pub(crate) fn medialist(&self, cx: &mut JSContext) -> DomRoot<MediaList> {
226        MediaList::new(
227            cx,
228            self.global().as_window(),
229            self,
230            self.style_stylesheet().media.clone(),
231        )
232    }
233
234    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-constructed-flag>
235    #[inline]
236    pub(crate) fn is_constructed(&self) -> bool {
237        self.constructor_document.is_some()
238    }
239
240    pub(crate) fn constructor_document_matches(&self, other_doc: &Document) -> bool {
241        match &self.constructor_document {
242            Some(doc) => *doc == other_doc,
243            None => false,
244        }
245    }
246
247    /// Add a [StyleSheetListOwner] as an adopter to be notified whenever this stylesheet is
248    /// modified.
249    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
250    pub(crate) fn add_adopter(&self, owner: StyleSheetListOwner) {
251        debug_assert!(self.is_constructed());
252        self.adopters.borrow_mut().push(owner);
253    }
254
255    pub(crate) fn remove_adopter(&self, owner: &StyleSheetListOwner) {
256        let adopters = &mut *self.adopters.borrow_mut();
257        if let Some(index) = adopters.iter().position(|o| o == owner) {
258            adopters.swap_remove(index);
259        }
260    }
261
262    pub(crate) fn will_modify(&self, no_gc: &NoGC) {
263        let Some(node) = self.owner_node.get() else {
264            return;
265        };
266
267        let Some(node) = node.downcast::<HTMLStyleElement>() else {
268            return;
269        };
270
271        node.will_modify_stylesheet(no_gc);
272    }
273
274    pub(crate) fn update_style_stylesheet(
275        &self,
276        style_stylesheet: &Arc<StyleStyleSheet>,
277        guard: &SharedRwLockReadGuard,
278    ) {
279        // When the shared `StylesheetContents` is about to be modified,
280        // `CSSStyleSheet::owner_node` performs a copy-on-write to avoid
281        // affecting other sharers, see `CSSStyleSheet::will_modify`. And
282        // then updates the references to `CssRule` or `PropertyDeclarationBlock`
283        // stored in the CSSOMs to ensure that modifications are made only
284        // on the new copy.
285        *self.style_stylesheet.borrow_mut() = style_stylesheet.clone();
286        if let Some(rulelist) = self.rule_list.get() {
287            let rules = style_stylesheet.contents(guard).rules.clone();
288            rulelist.update_rules(RulesSource::Rules(rules), guard);
289        }
290    }
291
292    /// Invalidate all stylesheet set this stylesheet is a part on.
293    pub(crate) fn notify_invalidations(&self, no_gc: &NoGC) {
294        if let Some(owner) = self.owner_node() {
295            owner.stylesheet_list_owner().invalidate_stylesheets(no_gc);
296        }
297        for adopter in self.adopters.borrow().iter() {
298            adopter.invalidate_stylesheets(no_gc);
299        }
300    }
301
302    /// <https://drafts.csswg.org/cssom/#concept-css-style-sheet-disallow-modification-flag>
303    pub(crate) fn disallow_modification(&self) -> bool {
304        self.disallow_modification.get()
305    }
306
307    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync> Steps 2+
308    fn do_replace_sync(&self, no_gc: &NoGC, text: USVString) {
309        // Step 2. Let rules be the result of running parse a stylesheet’s contents from text.
310        let global = self.global();
311        let window = global.as_window();
312
313        self.will_modify(no_gc);
314
315        let _span = profile_traits::trace_span!("ParseStylesheet").entered();
316        let sheet = self.style_stylesheet();
317        let stylesheet_base_url = self
318            .stylesheet_base_url
319            .borrow()
320            .clone()
321            .unwrap_or(window.get_url());
322
323        let new_contents = StylesheetContents::from_str(
324            &text,
325            UrlExtraData(stylesheet_base_url.get_arc()),
326            Origin::Author,
327            &self.style_shared_lock,
328            None,
329            Some(window.css_error_reporter()),
330            window.Document().quirks_mode(),
331            AllowImportRules::No, // Step 3.If rules contains one or more @import rules, remove those rules from rules.
332            /* sanitization_data = */ None,
333        );
334
335        {
336            let mut write_guard = self.style_shared_lock.write();
337            *sheet.contents.write_with(&mut write_guard) = new_contents;
338        }
339
340        // Step 4. Set sheet’s CSS rules to rules.
341        // We reset our rule list, which will be initialized properly
342        // at the next getter access.
343        self.rule_list.set(None);
344
345        // Notify invalidation to update the styles immediately.
346        self.notify_invalidations(no_gc);
347    }
348}
349
350impl CSSStyleSheetMethods<crate::DomTypeHolder> for CSSStyleSheet {
351    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssstylesheet>
352    fn Constructor(
353        cx: &mut JSContext,
354        window: &Window,
355        proto: Option<HandleObject>,
356        options: &CSSStyleSheetInit,
357    ) -> DomRoot<Self> {
358        let doc = window.Document();
359        let shared_lock = doc.style_shared_author_lock().clone();
360        let media = Arc::new(shared_lock.wrap(match &options.media {
361            MediaListOrString::MediaList(media_list) => media_list.clone_media_list(),
362            MediaListOrString::String(str) => MediaList::parse_media_list(&str.str(), window),
363        }));
364
365        let stylesheet = Arc::new(StyleStyleSheet::from_str(
366            "",
367            UrlExtraData(window.get_url().get_arc()),
368            Origin::Author,
369            media,
370            shared_lock,
371            None,
372            Some(window.css_error_reporter()),
373            doc.quirks_mode(),
374            AllowImportRules::No,
375        ));
376        if options.disabled {
377            stylesheet.set_disabled(true);
378        }
379
380        // Step 1. Construct a new CSSStyleSheet object sheet.
381        // Note: Subsequent steps are implicitly handled by the arguments passed down.
382        let sheet = Self::new_with_proto(
383            cx,
384            window,
385            proto,
386            None, // owner
387            DOMString::from_static("text/css"),
388            None, // href
389            stylesheet,
390            Some(&window.Document()), // constructor_document
391        );
392
393        let base_url = options
394            .baseURL
395            .as_ref()
396            .and_then(|url| ServoUrl::parse(&url.str()).ok());
397        // Step 3. Set sheet’s stylesheet base URL to the baseURL attribute value from options.
398        *sheet.stylesheet_base_url.safe_borrow_mut(cx) = base_url;
399
400        // Step 14. Return sheet.
401        sheet
402    }
403
404    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-cssrules>
405    fn GetCssRules(&self, cx: &mut JSContext) -> Fallible<DomRoot<CSSRuleList>> {
406        // If the origin-clean flag is unset, we throw an error as the API implicitly allows modification of CSS rules.
407        if !self.origin_clean.get() {
408            return Err(Error::Security(Some(
409                "Not allowed to access cross-origin style sheet".to_string(),
410            )));
411        }
412        Ok(self.rulelist(cx))
413    }
414
415    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-insertrule>
416    fn InsertRule(&self, cx: &mut JSContext, rule: DOMString, index: u32) -> Fallible<u32> {
417        // Step 1. If the origin-clean flag is unset, throw a SecurityError exception.
418        if !self.origin_clean.get() {
419            return Err(Error::Security(Some(
420                "Not allowed to access cross-origin style sheet".to_string(),
421            )));
422        }
423
424        // Step 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
425        if self.disallow_modification() {
426            return Err(Error::NotAllowed(Some(
427                "This method can only be called on modifiable style sheets".to_string(),
428            )));
429        }
430
431        self.rulelist(cx).insert_rule(cx, &rule, index)
432    }
433
434    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-deleterule>
435    fn DeleteRule(&self, cx: &mut JSContext, index: u32) -> ErrorResult {
436        // Step 1. If the origin-clean flag is unset, throw a SecurityError exception.
437        if !self.origin_clean.get() {
438            return Err(Error::Security(Some(
439                "Not allowed to access cross-origin style sheet".to_string(),
440            )));
441        }
442
443        // Step 2. If the disallow modification flag is set, throw a NotAllowedError DOMException.
444        if self.disallow_modification() {
445            return Err(Error::NotAllowed(Some(
446                "This method can only be called on modifiable style sheets".to_string(),
447            )));
448        }
449        self.rulelist(cx).remove_rule(cx, index)
450    }
451
452    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-rules>
453    fn GetRules(&self, cx: &mut JSContext) -> Fallible<DomRoot<CSSRuleList>> {
454        self.GetCssRules(cx)
455    }
456
457    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-removerule>
458    fn RemoveRule(&self, cx: &mut JSContext, index: u32) -> ErrorResult {
459        self.DeleteRule(cx, index)
460    }
461
462    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-addrule>
463    fn AddRule(
464        &self,
465        cx: &mut js::context::JSContext,
466        selector: DOMString,
467        block: DOMString,
468        optional_index: Option<u32>,
469    ) -> Fallible<i32> {
470        // > 1. Let *rule* be an empty string.
471        // > 2. Append *selector* to *rule*.
472        let mut rule = selector;
473
474        // > 3. Append " { " to *rule*.
475        // > 4. If *block* is not empty, append *block*, followed by a space, to *rule*.
476        // > 5. Append "}" to *rule*.
477        if block.is_empty() {
478            rule.push_str(" { }");
479        } else {
480            rule.push_str(" { ");
481            rule.push_str(&block.str());
482            rule.push_str(" }");
483        };
484
485        // > 6. Let *index* be *optionalIndex* if provided, or the number of CSS rules in the stylesheet otherwise.
486        let index = optional_index.unwrap_or_else(|| self.rulelist(cx).Length());
487
488        // > 7. Call `insertRule()`, with *rule* and *index* as arguments.
489        self.InsertRule(cx, rule, index)?;
490
491        // > 8. Return -1.
492        Ok(-1)
493    }
494
495    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replace>
496    fn Replace(&self, cx: &mut CurrentRealm, text: USVString) -> Fallible<RootedPromise> {
497        // Step 1. Let promise be a promise.
498        let promise = Promise::new_in_realm(cx);
499
500        // Step 2. If the constructed flag is not set, or the disallow modification flag is set,
501        // reject promise with a NotAllowedError DOMException and return promise.
502        if !self.is_constructed() {
503            return Err(Error::NotAllowed(Some(
504                "This method can only be called on constructed style sheets".to_string(),
505            )));
506        }
507        if self.disallow_modification() {
508            return Err(Error::NotAllowed(Some(
509                "This method can only be called on modifiable style sheets".to_string(),
510            )));
511        }
512
513        // Step 3. Set the disallow modification flag.
514        self.disallow_modification.set(true);
515
516        // Step 4. In parallel, do these steps:
517        let trusted_sheet = Trusted::new(self);
518        let trusted_promise = TrustedPromise::from(&promise);
519
520        self.global()
521            .task_manager()
522            .dom_manipulation_task_source()
523            .queue(task!(cssstylesheet_replace: move |cx| {
524                let sheet = trusted_sheet.root();
525
526                // Step 4.1..4.3
527                sheet.do_replace_sync(cx.no_gc(), text);
528
529                // Step 4.4. Unset sheet’s disallow modification flag.
530                sheet.disallow_modification.set(false);
531
532                // Step 4.5. Resolve promise with sheet.
533                trusted_promise.root(cx).resolve_native(cx, &sheet);
534            }));
535
536        Ok(promise)
537    }
538
539    /// <https://drafts.csswg.org/cssom/#dom-cssstylesheet-replacesync>
540    fn ReplaceSync(&self, no_gc: &NoGC, text: USVString) -> Result<(), Error> {
541        // Step 1. If the constructed flag is not set, or the disallow modification flag is set,
542        // throw a NotAllowedError DOMException.
543        if !self.is_constructed() || self.disallow_modification() {
544            return Err(Error::NotAllowed(Some(
545                "This method can only be called on constructed style sheets".to_string(),
546            )));
547        }
548        if self.disallow_modification() {
549            return Err(Error::NotAllowed(Some(
550                "This method can only be called on modifiable style sheets".to_string(),
551            )));
552        }
553        self.do_replace_sync(no_gc, text);
554        Ok(())
555    }
556}