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, local_name};
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};
16use stylo_atoms::Atom;
17
18use crate::dom::attr::Attr;
19use crate::dom::bindings::cell::DomRefCell;
20use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
21use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
22use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::root::{DomRoot, MutNullableDom};
25use crate::dom::bindings::str::DOMString;
26use crate::dom::csp::{CspReporting, InlineCheckType};
27use crate::dom::css::cssstylesheet::CSSStyleSheet;
28use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
29use crate::dom::css::stylesheetcontentscache::{
30    StylesheetContentsCache, StylesheetContentsCacheKey,
31};
32use crate::dom::document::Document;
33use crate::dom::documentorshadowroot::StylesheetSource;
34use crate::dom::domtokenlist::DOMTokenList;
35use crate::dom::element::{AttributeMutation, Element, ElementCreator};
36use crate::dom::html::htmlelement::HTMLElement;
37use crate::dom::medialist::MediaList;
38use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
39use crate::dom::virtualmethods::VirtualMethods;
40use crate::script_runtime::CanGc;
41use crate::stylesheet_loader::StylesheetOwner;
42
43#[dom_struct]
44pub(crate) struct HTMLStyleElement {
45    htmlelement: HTMLElement,
46    #[conditional_malloc_size_of]
47    #[no_trace]
48    stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
49    #[no_trace]
50    stylesheetcontents_cache_key: DomRefCell<Option<StylesheetContentsCacheKey>>,
51    cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
52    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
53    parser_inserted: Cell<bool>,
54    in_stack_of_open_elements: Cell<bool>,
55    pending_loads: Cell<u32>,
56    any_failed_load: Cell<bool>,
57    /// <https://html.spec.whatwg.org/multipage/#dom-style-blocking>
58    blocking: MutNullableDom<DOMTokenList>,
59}
60
61impl HTMLStyleElement {
62    fn new_inherited(
63        local_name: LocalName,
64        prefix: Option<Prefix>,
65        document: &Document,
66        creator: ElementCreator,
67    ) -> HTMLStyleElement {
68        HTMLStyleElement {
69            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
70            stylesheet: DomRefCell::new(None),
71            stylesheetcontents_cache_key: DomRefCell::new(None),
72            cssom_stylesheet: MutNullableDom::new(None),
73            parser_inserted: Cell::new(creator.is_parser_created()),
74            in_stack_of_open_elements: Cell::new(creator.is_parser_created()),
75            pending_loads: Cell::new(0),
76            any_failed_load: Cell::new(false),
77            blocking: Default::default(),
78        }
79    }
80
81    pub(crate) fn new(
82        local_name: LocalName,
83        prefix: Option<Prefix>,
84        document: &Document,
85        proto: Option<HandleObject>,
86        creator: ElementCreator,
87        can_gc: CanGc,
88    ) -> DomRoot<HTMLStyleElement> {
89        Node::reflect_node_with_proto(
90            Box::new(HTMLStyleElement::new_inherited(
91                local_name, prefix, document, creator,
92            )),
93            document,
94            proto,
95            can_gc,
96        )
97    }
98
99    #[inline]
100    fn create_media_list(&self, mq_str: &str) -> StyleMediaList {
101        MediaList::parse_media_list(mq_str, &self.owner_window())
102    }
103
104    /// <https://html.spec.whatwg.org/multipage/#update-a-style-block>
105    pub(crate) fn update_a_style_block(&self) {
106        // Step 1. Let element be the style element.
107        //
108        // That's self
109
110        // Step 2. If element has an associated CSS style sheet, remove the CSS style sheet in question.
111        self.remove_stylesheet();
112
113        // Step 3. If element is not connected, then return.
114        let node = self.upcast::<Node>();
115        if !node.is_connected() {
116            return;
117        }
118        assert!(
119            node.is_in_a_document_tree() || node.is_in_a_shadow_tree(),
120            "This stylesheet does not have an owner, so there's no reason to parse its contents"
121        );
122
123        // Step 4. If element's type attribute is present and its value is neither the empty string
124        // nor an ASCII case-insensitive match for "text/css", then return.
125        let mut type_attribute = self.Type();
126        type_attribute.make_ascii_lowercase();
127        if !type_attribute.is_empty() && type_attribute != "text/css" {
128            return;
129        }
130
131        // Step 5: If the Should element's inline behavior be blocked by Content Security Policy? algorithm
132        // returns "Blocked" when executed upon the style element, "style",
133        // and the style element's child text content, then return. [CSP]
134        let doc = self.owner_document();
135        let global = &self.owner_global();
136        if global
137            .get_csp_list()
138            .should_elements_inline_type_behavior_be_blocked(
139                global,
140                self.upcast(),
141                InlineCheckType::Style,
142                &node.child_text_content().str(),
143                doc.get_current_parser_line(),
144            )
145        {
146            return;
147        }
148
149        // Step 6. Create a CSS style sheet with the following properties:
150        let data = node
151            .GetTextContent()
152            .expect("Element.textContent must be a string");
153        let shared_lock = node.owner_doc().style_shared_lock().clone();
154        let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media().str())));
155
156        // For duplicate style sheets with identical content, `StylesheetContents` can be reused
157        // to avoid reedundant parsing of the style sheets. Additionally, the cache hit rate of
158        // stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents`
159        // is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`.
160        let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
161            &data.str(),
162            &shared_lock,
163            UrlExtraData(doc.base_url().get_arc()),
164            doc.quirks_mode(),
165            self.upcast(),
166        );
167
168        let sheet = Arc::new(Stylesheet {
169            contents: shared_lock.wrap(contents),
170            shared_lock,
171            media: mq,
172            disabled: AtomicBool::new(false),
173        });
174
175        // From here we differ from the spec. Since we have a cache,
176        // we have two situations:
177        //
178        // 1. We hit the cache. No fetch ever runs, hence we don't
179        // need to muddy with render-/load-blocking
180        // 2. We don't hit the cache. In this scenario, we once again
181        // have two sub-scenarios:
182        //   a. We synchronously parse the contents without any `@import`.
183        //      This means we can proceed as in situation 1
184        //   b. We synchronously parse the contents and we encounter 1+
185        //      `@import` rules. In that case, we do start to load urls.
186        //
187        // For situation 1 and 2a, we can immediately fire the load event
188        // since we are done.
189        if self.pending_loads.get() == 0 {
190            // Step 4 of https://html.spec.whatwg.org/multipage/#the-style-element:critical-subresources
191            //
192            // Step 4. Queue an element task on the networking task source given element and the following steps:
193            // Step 4.1. If success is true, fire an event named load at element.
194            self.owner_global()
195                .task_manager()
196                .networking_task_source()
197                .queue_simple_event(self.upcast(), atom!("load"));
198        }
199
200        // For situation 2b, we need to do more work.
201        // Therefore, the following steps are actually implemented in
202        // `ElementStylesheetLoader::load_with_element`.
203        //
204        //     Step 7. If element contributes a script-blocking style sheet,
205        //     append element to its node document's script-blocking style sheet set.
206        //
207        //     Step 8. If element's media attribute's value matches the environment
208        //     and element is potentially render-blocking, then block rendering on element.
209
210        // Finally, update our stylesheet, regardless of which scenario we ran into
211        self.clean_stylesheet_ownership();
212        self.set_stylesheet(sheet, cache_key);
213    }
214
215    // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.
216    //
217    // With the reuse of `StylesheetContent` for same stylesheet string content,
218    // this function has a bit difference with `HTMLLinkElement::set_stylesheet` now.
219    pub(crate) fn set_stylesheet(
220        &self,
221        s: Arc<Stylesheet>,
222        cache_key: Option<StylesheetContentsCacheKey>,
223    ) {
224        *self.stylesheet.borrow_mut() = Some(s.clone());
225        *self.stylesheetcontents_cache_key.borrow_mut() = cache_key;
226        self.stylesheet_list_owner()
227            .add_owned_stylesheet(self.upcast(), s);
228    }
229
230    pub(crate) fn will_modify_stylesheet(&self) {
231        if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet() {
232            self.remove_stylesheet();
233            if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
234                let guard = stylesheet_with_owned_contents.shared_lock.read();
235                cssom_stylesheet.update_style_stylesheet(&stylesheet_with_owned_contents, &guard);
236            }
237            self.set_stylesheet(stylesheet_with_owned_contents, None);
238        }
239    }
240
241    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
242        self.stylesheet.borrow().clone()
243    }
244
245    pub(crate) fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> {
246        self.get_stylesheet().map(|sheet| {
247            self.cssom_stylesheet.or_init(|| {
248                CSSStyleSheet::new(
249                    &self.owner_window(),
250                    Some(self.upcast::<Element>()),
251                    "text/css".into(),
252                    None, // todo handle location
253                    None, // todo handle title
254                    sheet,
255                    None, // constructor_document
256                    CanGc::note(),
257                )
258            })
259        })
260    }
261
262    fn create_owned_contents_stylesheet(&self) -> Option<Arc<Stylesheet>> {
263        let cache_key = self.stylesheetcontents_cache_key.borrow_mut().take()?;
264        if cache_key.is_uniquely_owned() {
265            StylesheetContentsCache::remove(cache_key);
266            return None;
267        }
268
269        let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
270        let lock = stylesheet_with_shared_contents.shared_lock.clone();
271        let guard = stylesheet_with_shared_contents.shared_lock.read();
272        let stylesheet_with_owned_contents = Arc::new(Stylesheet {
273            contents: lock.wrap(
274                stylesheet_with_shared_contents
275                    .contents(&guard)
276                    .deep_clone(&lock, None, &guard),
277            ),
278            shared_lock: lock,
279            media: stylesheet_with_shared_contents.media.clone(),
280            disabled: AtomicBool::new(
281                stylesheet_with_shared_contents
282                    .disabled
283                    .load(Ordering::SeqCst),
284            ),
285        });
286
287        Some(stylesheet_with_owned_contents)
288    }
289
290    fn clean_stylesheet_ownership(&self) {
291        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
292            // If the CSSOMs change from having an owner node to being ownerless, they may still
293            // potentially modify shared stylesheets. Thus, create an new `Stylesheet` with owned
294            // `StylesheetContents` to ensure that the potentially modifications are only made on
295            // the owned `StylesheetContents`.
296            if let Some(stylesheet) = self.create_owned_contents_stylesheet() {
297                let guard = stylesheet.shared_lock.read();
298                cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
299            }
300            cssom_stylesheet.set_owner_node(None);
301        }
302        self.cssom_stylesheet.set(None);
303    }
304
305    fn remove_stylesheet(&self) {
306        self.clean_stylesheet_ownership();
307        if let Some(s) = self.stylesheet.borrow_mut().take() {
308            self.stylesheet_list_owner()
309                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
310            let _ = self.stylesheetcontents_cache_key.borrow_mut().take();
311        }
312    }
313}
314
315impl VirtualMethods for HTMLStyleElement {
316    fn super_type(&self) -> Option<&dyn VirtualMethods> {
317        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
318    }
319
320    fn children_changed(&self, mutation: &ChildrenMutation, can_gc: CanGc) {
321        self.super_type()
322            .unwrap()
323            .children_changed(mutation, can_gc);
324
325        // https://html.spec.whatwg.org/multipage/#update-a-style-block
326        // > The element is not on the stack of open elements of an HTML parser or XML parser, and its children changed steps run.
327        if !self.in_stack_of_open_elements.get() {
328            self.update_a_style_block();
329        }
330    }
331
332    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
333        self.super_type().unwrap().bind_to_tree(context, can_gc);
334
335        // https://html.spec.whatwg.org/multipage/#update-a-style-block
336        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
337        if !self.in_stack_of_open_elements.get() {
338            self.update_a_style_block();
339        }
340    }
341
342    fn pop(&self) {
343        self.super_type().unwrap().pop();
344        self.in_stack_of_open_elements.set(false);
345
346        // https://html.spec.whatwg.org/multipage/#update-a-style-block
347        // > The element is popped off the stack of open elements of an HTML parser or XML parser.
348        self.update_a_style_block();
349    }
350
351    fn unbind_from_tree(&self, context: &UnbindContext, can_gc: CanGc) {
352        if let Some(s) = self.super_type() {
353            s.unbind_from_tree(context, can_gc);
354        }
355
356        // https://html.spec.whatwg.org/multipage/#update-a-style-block
357        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
358        if !self.in_stack_of_open_elements.get() {
359            self.update_a_style_block();
360        }
361    }
362
363    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
364        if let Some(s) = self.super_type() {
365            s.attribute_mutated(attr, mutation, can_gc);
366        }
367
368        let node = self.upcast::<Node>();
369        if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
370            self.in_stack_of_open_elements.get()
371        {
372            return;
373        }
374
375        if attr.name() == "type" {
376            if let AttributeMutation::Set(Some(old_value), _) = mutation {
377                if **old_value == **attr.value() {
378                    return;
379                }
380            }
381            self.remove_stylesheet();
382            self.update_a_style_block();
383        } else if attr.name() == "media" {
384            if let Some(ref stylesheet) = *self.stylesheet.borrow_mut() {
385                let shared_lock = node.owner_doc().style_shared_lock().clone();
386                let mut guard = shared_lock.write();
387                let media = stylesheet.media.write_with(&mut guard);
388                match mutation {
389                    AttributeMutation::Set(..) => *media = self.create_media_list(&attr.value()),
390                    AttributeMutation::Removed => *media = StyleMediaList::empty(),
391                };
392                self.owner_document().invalidate_stylesheets();
393            }
394        }
395    }
396}
397
398impl StylesheetOwner for HTMLStyleElement {
399    fn increment_pending_loads_count(&self) {
400        self.pending_loads.set(self.pending_loads.get() + 1)
401    }
402
403    fn load_finished(&self, succeeded: bool) -> Option<bool> {
404        assert!(self.pending_loads.get() > 0, "What finished?");
405        if !succeeded {
406            self.any_failed_load.set(true);
407        }
408
409        self.pending_loads.set(self.pending_loads.get() - 1);
410        if self.pending_loads.get() != 0 {
411            return None;
412        }
413
414        let any_failed = self.any_failed_load.get();
415        self.any_failed_load.set(false);
416        Some(any_failed)
417    }
418
419    fn parser_inserted(&self) -> bool {
420        self.parser_inserted.get()
421    }
422
423    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
424    fn potentially_render_blocking(&self) -> bool {
425        // An element is potentially render-blocking if its blocking tokens set contains "render",
426        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
427        // By default, an element is not implicitly potentially render-blocking.
428        //
429        // https://html.spec.whatwg.org/multipage/#the-style-element:implicitly-potentially-render-blocking
430        // > A style element is implicitly potentially render-blocking if the element was created by its node document's parser.
431        self.parser_inserted() ||
432            self.blocking
433                .get()
434                .is_some_and(|list| list.Contains("render".into()))
435    }
436
437    fn referrer_policy(&self) -> ReferrerPolicy {
438        ReferrerPolicy::EmptyString
439    }
440
441    fn set_origin_clean(&self, origin_clean: bool) {
442        if let Some(stylesheet) = self.get_cssom_stylesheet() {
443            stylesheet.set_origin_clean(origin_clean);
444        }
445    }
446}
447
448impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
449    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
450    fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> {
451        self.get_cssom_stylesheet().map(DomRoot::upcast)
452    }
453
454    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
455    fn Disabled(&self) -> bool {
456        self.get_cssom_stylesheet()
457            .is_some_and(|sheet| sheet.disabled())
458    }
459
460    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
461    fn SetDisabled(&self, value: bool) {
462        if let Some(sheet) = self.get_cssom_stylesheet() {
463            sheet.set_disabled(value);
464        }
465    }
466
467    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
468    make_getter!(Type, "type");
469
470    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
471    make_setter!(SetType, "type");
472
473    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
474    make_getter!(Media, "media");
475
476    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
477    make_setter!(SetMedia, "media");
478
479    /// <https://html.spec.whatwg.org/multipage/#attr-style-blocking>
480    fn Blocking(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
481        self.blocking.or_init(|| {
482            DOMTokenList::new(
483                self.upcast(),
484                &local_name!("blocking"),
485                Some(vec![Atom::from("render")]),
486                can_gc,
487            )
488        })
489    }
490}