script/dom/html/
htmlstyleelement.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::sync::atomic::{AtomicBool, Ordering};
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix};
10use js::rust::HandleObject;
11use net_traits::ReferrerPolicy;
12use script_bindings::root::Dom;
13use servo_arc::Arc;
14use style::media_queries::MediaList as StyleMediaList;
15use style::stylesheets::{Stylesheet, StylesheetInDocument, UrlExtraData};
16
17use crate::dom::attr::Attr;
18use crate::dom::bindings::cell::DomRefCell;
19use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
20use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
21use crate::dom::bindings::inheritance::Castable;
22use crate::dom::bindings::root::{DomRoot, MutNullableDom};
23use crate::dom::bindings::str::DOMString;
24use crate::dom::csp::{CspReporting, InlineCheckType};
25use crate::dom::css::cssstylesheet::CSSStyleSheet;
26use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
27use crate::dom::css::stylesheetcontentscache::{
28    StylesheetContentsCache, StylesheetContentsCacheKey,
29};
30use crate::dom::document::Document;
31use crate::dom::documentorshadowroot::StylesheetSource;
32use crate::dom::element::{AttributeMutation, Element, ElementCreator};
33use crate::dom::html::htmlelement::HTMLElement;
34use crate::dom::medialist::MediaList;
35use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
36use crate::dom::virtualmethods::VirtualMethods;
37use crate::script_runtime::CanGc;
38use crate::stylesheet_loader::StylesheetOwner;
39
40#[dom_struct]
41pub(crate) struct HTMLStyleElement {
42    htmlelement: HTMLElement,
43    #[conditional_malloc_size_of]
44    #[no_trace]
45    stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
46    #[no_trace]
47    stylesheetcontents_cache_key: DomRefCell<Option<StylesheetContentsCacheKey>>,
48    cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
49    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
50    parser_inserted: Cell<bool>,
51    in_stack_of_open_elements: Cell<bool>,
52    pending_loads: Cell<u32>,
53    any_failed_load: Cell<bool>,
54}
55
56impl HTMLStyleElement {
57    fn new_inherited(
58        local_name: LocalName,
59        prefix: Option<Prefix>,
60        document: &Document,
61        creator: ElementCreator,
62    ) -> HTMLStyleElement {
63        HTMLStyleElement {
64            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
65            stylesheet: DomRefCell::new(None),
66            stylesheetcontents_cache_key: DomRefCell::new(None),
67            cssom_stylesheet: MutNullableDom::new(None),
68            parser_inserted: Cell::new(creator.is_parser_created()),
69            in_stack_of_open_elements: Cell::new(creator.is_parser_created()),
70            pending_loads: Cell::new(0),
71            any_failed_load: Cell::new(false),
72        }
73    }
74
75    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
76    pub(crate) fn new(
77        local_name: LocalName,
78        prefix: Option<Prefix>,
79        document: &Document,
80        proto: Option<HandleObject>,
81        creator: ElementCreator,
82        can_gc: CanGc,
83    ) -> DomRoot<HTMLStyleElement> {
84        Node::reflect_node_with_proto(
85            Box::new(HTMLStyleElement::new_inherited(
86                local_name, prefix, document, creator,
87            )),
88            document,
89            proto,
90            can_gc,
91        )
92    }
93
94    #[inline]
95    fn create_media_list(&self, mq_str: &str) -> StyleMediaList {
96        MediaList::parse_media_list(mq_str, &self.owner_window())
97    }
98
99    pub(crate) fn parse_own_css(&self) {
100        let node = self.upcast::<Node>();
101        assert!(
102            node.is_in_a_document_tree() || node.is_in_a_shadow_tree(),
103            "This stylesheet does not have an owner, so there's no reason to parse its contents"
104        );
105
106        // Step 4. of <https://html.spec.whatwg.org/multipage/#the-style-element%3Aupdate-a-style-block>
107        let mut type_attribute = self.Type();
108        type_attribute.make_ascii_lowercase();
109        if !type_attribute.is_empty() && type_attribute != "text/css" {
110            return;
111        }
112
113        let doc = self.owner_document();
114        let global = &self.owner_global();
115
116        // Step 5: If the Should element's inline behavior be blocked by Content Security Policy? algorithm
117        // returns "Blocked" when executed upon the style element, "style",
118        // and the style element's child text content, then return. [CSP]
119        if global
120            .get_csp_list()
121            .should_elements_inline_type_behavior_be_blocked(
122                global,
123                self.upcast(),
124                InlineCheckType::Style,
125                &node.child_text_content().str(),
126                doc.get_current_parser_line(),
127            )
128        {
129            return;
130        }
131
132        let data = node
133            .GetTextContent()
134            .expect("Element.textContent must be a string");
135        let shared_lock = node.owner_doc().style_shared_lock().clone();
136        let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media().str())));
137
138        // For duplicate style sheets with identical content, `StylesheetContents` can be reused
139        // to avoid reedundant parsing of the style sheets. Additionally, the cache hit rate of
140        // stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents`
141        // is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`.
142        let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
143            &data.str(),
144            &shared_lock,
145            UrlExtraData(doc.base_url().get_arc()),
146            doc.quirks_mode(),
147            self.upcast(),
148        );
149
150        let sheet = Arc::new(Stylesheet {
151            contents: shared_lock.wrap(contents),
152            shared_lock,
153            media: mq,
154            disabled: AtomicBool::new(false),
155        });
156
157        // No subresource loads were triggered, queue load event
158        if self.pending_loads.get() == 0 {
159            self.owner_global()
160                .task_manager()
161                .dom_manipulation_task_source()
162                .queue_simple_event(self.upcast(), atom!("load"));
163        }
164
165        self.set_stylesheet(sheet, cache_key, true);
166    }
167
168    // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.
169    //
170    // With the reuse of `StylesheetContent` for same stylesheet string content,
171    // this function has a bit difference with `HTMLLinkElement::set_stylesheet` now.
172    #[cfg_attr(crown, allow(crown::unrooted_must_root))]
173    pub(crate) fn set_stylesheet(
174        &self,
175        s: Arc<Stylesheet>,
176        cache_key: Option<StylesheetContentsCacheKey>,
177        need_clean_cssom: bool,
178    ) {
179        let stylesheets_owner = self.stylesheet_list_owner();
180        if let Some(ref s) = *self.stylesheet.borrow() {
181            stylesheets_owner
182                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), s);
183        }
184
185        if need_clean_cssom {
186            self.clean_stylesheet_ownership();
187        } else if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
188            let guard = s.shared_lock.read();
189            cssom_stylesheet.update_style_stylesheet(&s, &guard);
190        }
191
192        *self.stylesheet.borrow_mut() = Some(s.clone());
193        *self.stylesheetcontents_cache_key.borrow_mut() = cache_key;
194        stylesheets_owner.add_owned_stylesheet(self.upcast(), s);
195    }
196
197    pub(crate) fn will_modify_stylesheet(&self) {
198        if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet() {
199            self.set_stylesheet(stylesheet_with_owned_contents, None, false);
200        }
201    }
202
203    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
204        self.stylesheet.borrow().clone()
205    }
206
207    pub(crate) fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> {
208        self.get_stylesheet().map(|sheet| {
209            self.cssom_stylesheet.or_init(|| {
210                CSSStyleSheet::new(
211                    &self.owner_window(),
212                    Some(self.upcast::<Element>()),
213                    "text/css".into(),
214                    None, // todo handle location
215                    None, // todo handle title
216                    sheet,
217                    None, // constructor_document
218                    CanGc::note(),
219                )
220            })
221        })
222    }
223
224    fn create_owned_contents_stylesheet(&self) -> Option<Arc<Stylesheet>> {
225        let cache_key = self.stylesheetcontents_cache_key.borrow_mut().take()?;
226        if cache_key.is_uniquely_owned() {
227            StylesheetContentsCache::remove(cache_key);
228            return None;
229        }
230
231        let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
232        let lock = stylesheet_with_shared_contents.shared_lock.clone();
233        let guard = stylesheet_with_shared_contents.shared_lock.read();
234        let stylesheet_with_owned_contents = Arc::new(Stylesheet {
235            contents: lock.wrap(
236                stylesheet_with_shared_contents
237                    .contents(&guard)
238                    .deep_clone(&lock, None, &guard),
239            ),
240            shared_lock: lock,
241            media: stylesheet_with_shared_contents.media.clone(),
242            disabled: AtomicBool::new(
243                stylesheet_with_shared_contents
244                    .disabled
245                    .load(Ordering::SeqCst),
246            ),
247        });
248
249        Some(stylesheet_with_owned_contents)
250    }
251
252    fn clean_stylesheet_ownership(&self) {
253        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
254            // If the CSSOMs change from having an owner node to being ownerless, they may still
255            // potentially modify shared stylesheets. Thus, create an new `Stylesheet` with owned
256            // `StylesheetContents` to ensure that the potentially modifications are only made on
257            // the owned `StylesheetContents`.
258            if let Some(stylesheet) = self.create_owned_contents_stylesheet() {
259                let guard = stylesheet.shared_lock.read();
260                cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
261            }
262            cssom_stylesheet.set_owner_node(None);
263        }
264        self.cssom_stylesheet.set(None);
265    }
266
267    fn remove_stylesheet(&self) {
268        self.clean_stylesheet_ownership();
269        if let Some(s) = self.stylesheet.borrow_mut().take() {
270            self.stylesheet_list_owner()
271                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
272            let _ = self.stylesheetcontents_cache_key.borrow_mut().take();
273        }
274    }
275}
276
277impl VirtualMethods for HTMLStyleElement {
278    fn super_type(&self) -> Option<&dyn VirtualMethods> {
279        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
280    }
281
282    fn children_changed(&self, mutation: &ChildrenMutation, can_gc: CanGc) {
283        self.super_type()
284            .unwrap()
285            .children_changed(mutation, can_gc);
286
287        // https://html.spec.whatwg.org/multipage/#update-a-style-block
288        // Handles the case when:
289        // "The element is not on the stack of open elements of an HTML parser or XML parser,
290        // and one of its child nodes is modified by a script."
291        // TODO: Handle Text child contents being mutated.
292        let node = self.upcast::<Node>();
293        if (node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) &&
294            !self.in_stack_of_open_elements.get()
295        {
296            self.parse_own_css();
297        }
298    }
299
300    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
301        self.super_type().unwrap().bind_to_tree(context, can_gc);
302
303        // https://html.spec.whatwg.org/multipage/#update-a-style-block
304        // Handles the case when:
305        // "The element is not on the stack of open elements of an HTML parser or XML parser,
306        // and it becomes connected or disconnected."
307        if context.tree_connected && !self.in_stack_of_open_elements.get() {
308            self.parse_own_css();
309        }
310    }
311
312    fn pop(&self) {
313        self.super_type().unwrap().pop();
314
315        // https://html.spec.whatwg.org/multipage/#update-a-style-block
316        // Handles the case when:
317        // "The element is popped off the stack of open elements of an HTML parser or XML parser."
318        self.in_stack_of_open_elements.set(false);
319        if self.upcast::<Node>().is_in_a_document_tree() {
320            self.parse_own_css();
321        }
322    }
323
324    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
325        if let Some(s) = self.super_type() {
326            s.unbind_from_tree(context, can_gc);
327        }
328
329        if context.tree_connected {
330            self.remove_stylesheet();
331        }
332    }
333
334    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
335        if let Some(s) = self.super_type() {
336            s.attribute_mutated(attr, mutation, can_gc);
337        }
338
339        let node = self.upcast::<Node>();
340        if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
341            self.in_stack_of_open_elements.get()
342        {
343            return;
344        }
345
346        if attr.name() == "type" {
347            if let AttributeMutation::Set(Some(old_value), _) = mutation {
348                if **old_value == **attr.value() {
349                    return;
350                }
351            }
352            self.remove_stylesheet();
353            self.parse_own_css();
354        } else if attr.name() == "media" {
355            if let Some(ref stylesheet) = *self.stylesheet.borrow_mut() {
356                let shared_lock = node.owner_doc().style_shared_lock().clone();
357                let mut guard = shared_lock.write();
358                let media = stylesheet.media.write_with(&mut guard);
359                match mutation {
360                    AttributeMutation::Set(..) => *media = self.create_media_list(&attr.value()),
361                    AttributeMutation::Removed => *media = StyleMediaList::empty(),
362                };
363                self.owner_document().invalidate_stylesheets();
364            }
365        }
366    }
367}
368
369impl StylesheetOwner for HTMLStyleElement {
370    fn increment_pending_loads_count(&self) {
371        self.pending_loads.set(self.pending_loads.get() + 1)
372    }
373
374    fn load_finished(&self, succeeded: bool) -> Option<bool> {
375        assert!(self.pending_loads.get() > 0, "What finished?");
376        if !succeeded {
377            self.any_failed_load.set(true);
378        }
379
380        self.pending_loads.set(self.pending_loads.get() - 1);
381        if self.pending_loads.get() != 0 {
382            return None;
383        }
384
385        let any_failed = self.any_failed_load.get();
386        self.any_failed_load.set(false);
387        Some(any_failed)
388    }
389
390    fn parser_inserted(&self) -> bool {
391        self.parser_inserted.get()
392    }
393
394    fn referrer_policy(&self) -> ReferrerPolicy {
395        ReferrerPolicy::EmptyString
396    }
397
398    fn set_origin_clean(&self, origin_clean: bool) {
399        if let Some(stylesheet) = self.get_cssom_stylesheet() {
400            stylesheet.set_origin_clean(origin_clean);
401        }
402    }
403}
404
405impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
406    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
407    fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> {
408        self.get_cssom_stylesheet().map(DomRoot::upcast)
409    }
410
411    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
412    fn Disabled(&self) -> bool {
413        self.get_cssom_stylesheet()
414            .is_some_and(|sheet| sheet.disabled())
415    }
416
417    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
418    fn SetDisabled(&self, value: bool) {
419        if let Some(sheet) = self.get_cssom_stylesheet() {
420            sheet.set_disabled(value);
421        }
422    }
423
424    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
425    make_getter!(Type, "type");
426
427    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
428    make_setter!(SetType, "type");
429
430    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
431    make_getter!(Media, "media");
432
433    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
434    make_setter!(SetMedia, "media");
435}