Skip to main content

script/dom/html/document_metadata/
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::context::{JSContext, NoGC};
11use js::rust::HandleObject;
12use net_traits::ReferrerPolicy;
13use script_bindings::cell::DomRefCell;
14use script_bindings::root::Dom;
15use servo_arc::Arc;
16use style::media_queries::MediaList as StyleMediaList;
17use style::stylesheets::{Stylesheet, StylesheetInDocument, UrlExtraData};
18use stylo_atoms::Atom;
19
20use crate::css::stylesheet_loader::StylesheetOwner;
21use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
22use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
23use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
24use crate::dom::bindings::inheritance::Castable;
25use crate::dom::bindings::root::{DomRoot, MutNullableDom};
26use crate::dom::bindings::str::DOMString;
27use crate::dom::csp::{CspReporting, InlineCheckType};
28use crate::dom::css::cssstylesheet::CSSStyleSheet;
29use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
30use crate::dom::css::stylesheetcontentscache::{
31    StylesheetContentsCache, StylesheetContentsCacheKey,
32};
33use crate::dom::document::Document;
34use crate::dom::documentorshadowroot::StylesheetSource;
35use crate::dom::domtokenlist::DOMTokenList;
36use crate::dom::element::attributes::storage::AttrRef;
37use crate::dom::element::{AttributeMutation, Element, ElementCreator};
38use crate::dom::html::htmlelement::HTMLElement;
39use crate::dom::medialist::MediaList;
40use crate::dom::node::virtualmethods::VirtualMethods;
41use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
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        cx: &mut JSContext,
83        local_name: LocalName,
84        prefix: Option<Prefix>,
85        document: &Document,
86        proto: Option<HandleObject>,
87        creator: ElementCreator,
88    ) -> DomRoot<HTMLStyleElement> {
89        Node::reflect_node_with_proto(
90            cx,
91            Box::new(HTMLStyleElement::new_inherited(
92                local_name, prefix, document, creator,
93            )),
94            document,
95            proto,
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, cx: &mut JSContext) {
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(cx.no_gc());
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.call_on_csp_list(|csp_list| {
137            csp_list.should_elements_inline_type_behavior_be_blocked(
138                cx,
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_author_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(cx.no_gc());
212        self.set_stylesheet(cx.no_gc(), 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        no_gc: &NoGC,
222        stylesheet: Arc<Stylesheet>,
223        cache_key: Option<StylesheetContentsCacheKey>,
224    ) {
225        *self.stylesheet.safe_borrow_mut(no_gc) = Some(stylesheet.clone());
226        *self.stylesheetcontents_cache_key.safe_borrow_mut(no_gc) = cache_key;
227        self.stylesheet_list_owner()
228            .add_owned_stylesheet(no_gc, self.upcast(), stylesheet);
229    }
230
231    pub(crate) fn will_modify_stylesheet(&self, no_gc: &NoGC) {
232        if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet(no_gc) {
233            self.remove_stylesheet(no_gc);
234            if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
235                let guard = stylesheet_with_owned_contents.shared_lock.read();
236                cssom_stylesheet.update_style_stylesheet(&stylesheet_with_owned_contents, &guard);
237            }
238            self.set_stylesheet(no_gc, stylesheet_with_owned_contents, None);
239        }
240    }
241
242    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
243        self.stylesheet.borrow().clone()
244    }
245
246    pub(crate) fn get_cssom_stylesheet(
247        &self,
248        cx: &mut JSContext,
249    ) -> Option<DomRoot<CSSStyleSheet>> {
250        let element = self.upcast::<Element>();
251        self.get_stylesheet().map(|sheet| {
252            self.cssom_stylesheet.or_init(|| {
253                CSSStyleSheet::new(
254                    cx,
255                    &self.owner_window(),
256                    Some(element),
257                    DOMString::from_static("text/css"),
258                    None,
259                    sheet,
260                    None, // constructor_document
261                )
262            })
263        })
264    }
265
266    fn create_owned_contents_stylesheet(&self, no_gc: &NoGC) -> Option<Arc<Stylesheet>> {
267        let cache_key = self
268            .stylesheetcontents_cache_key
269            .safe_borrow_mut(no_gc)
270            .take()?;
271        if cache_key.is_uniquely_owned() {
272            StylesheetContentsCache::remove(cache_key);
273            return None;
274        }
275
276        let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
277        let lock = stylesheet_with_shared_contents.shared_lock.clone();
278        let guard = stylesheet_with_shared_contents.shared_lock.read();
279        let stylesheet_with_owned_contents = Arc::new(Stylesheet {
280            contents: lock.wrap(
281                stylesheet_with_shared_contents
282                    .contents(&guard)
283                    .deep_clone(&lock, None, &guard),
284            ),
285            shared_lock: lock,
286            media: stylesheet_with_shared_contents.media.clone(),
287            disabled: AtomicBool::new(
288                stylesheet_with_shared_contents
289                    .disabled
290                    .load(Ordering::SeqCst),
291            ),
292        });
293
294        Some(stylesheet_with_owned_contents)
295    }
296
297    fn clean_stylesheet_ownership(&self, no_gc: &NoGC) {
298        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
299            // If the CSSOMs change from having an owner node to being ownerless, they may still
300            // potentially modify shared stylesheets. Thus, create an new `Stylesheet` with owned
301            // `StylesheetContents` to ensure that the potentially modifications are only made on
302            // the owned `StylesheetContents`.
303            if let Some(stylesheet) = self.create_owned_contents_stylesheet(no_gc) {
304                let guard = stylesheet.shared_lock.read();
305                cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
306            }
307            cssom_stylesheet.set_owner_node(None);
308        }
309        self.cssom_stylesheet.set(None);
310    }
311
312    fn remove_stylesheet(&self, no_gc: &NoGC) {
313        self.clean_stylesheet_ownership(no_gc);
314        if let Some(s) = self.stylesheet.safe_borrow_mut(no_gc).take() {
315            self.stylesheet_list_owner()
316                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
317            let _ = self
318                .stylesheetcontents_cache_key
319                .safe_borrow_mut(no_gc)
320                .take();
321        }
322    }
323}
324
325impl VirtualMethods for HTMLStyleElement {
326    fn super_type(&self) -> Option<&dyn VirtualMethods> {
327        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
328    }
329
330    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
331        self.super_type().unwrap().children_changed(cx, mutation);
332
333        // https://html.spec.whatwg.org/multipage/#update-a-style-block
334        // > The element is not on the stack of open elements of an HTML parser or XML parser, and its children changed steps run.
335        if !self.in_stack_of_open_elements.get() {
336            self.update_a_style_block(cx);
337        }
338    }
339
340    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
341        self.super_type().unwrap().bind_to_tree(cx, context);
342
343        // https://html.spec.whatwg.org/multipage/#update-a-style-block
344        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
345        if !self.in_stack_of_open_elements.get() {
346            self.update_a_style_block(cx);
347        }
348    }
349
350    fn pop(&self, cx: &mut js::context::JSContext) {
351        self.super_type().unwrap().pop(cx);
352        self.in_stack_of_open_elements.set(false);
353
354        // https://html.spec.whatwg.org/multipage/#update-a-style-block
355        // > The element is popped off the stack of open elements of an HTML parser or XML parser.
356        self.update_a_style_block(cx);
357    }
358
359    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
360        if let Some(s) = self.super_type() {
361            s.unbind_from_tree(cx, context);
362        }
363
364        // https://html.spec.whatwg.org/multipage/#update-a-style-block
365        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
366        if !self.in_stack_of_open_elements.get() {
367            self.update_a_style_block(cx);
368        }
369    }
370
371    fn attribute_mutated(
372        &self,
373        cx: &mut js::context::JSContext,
374        attr: AttrRef<'_>,
375        mutation: AttributeMutation,
376    ) {
377        if let Some(s) = self.super_type() {
378            s.attribute_mutated(cx, attr, mutation);
379        }
380
381        let node = self.upcast::<Node>();
382        if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
383            self.in_stack_of_open_elements.get()
384        {
385            return;
386        }
387
388        if attr.name() == "type" {
389            if let AttributeMutation::Set(Some(old_value)) = mutation &&
390                **old_value == **attr.value()
391            {
392                return;
393            }
394            self.remove_stylesheet(cx.no_gc());
395            self.update_a_style_block(cx);
396        } else if attr.name() == "media" &&
397            let Some(ref stylesheet) = *self.stylesheet.safe_borrow_mut(cx.no_gc())
398        {
399            let shared_lock = node.owner_doc().style_shared_author_lock().clone();
400            let mut guard = shared_lock.write();
401            let media = stylesheet.media.write_with(&mut guard);
402            match mutation {
403                AttributeMutation::Set(_) => *media = self.create_media_list(&attr.value()),
404                AttributeMutation::Removed => *media = StyleMediaList::empty(),
405            };
406            self.owner_document().invalidate_stylesheets(cx.no_gc());
407        }
408    }
409}
410
411impl StylesheetOwner for HTMLStyleElement {
412    fn increment_pending_loads_count(&self) {
413        self.pending_loads.set(self.pending_loads.get() + 1)
414    }
415
416    fn load_finished(&self, succeeded: bool) -> Option<bool> {
417        assert!(self.pending_loads.get() > 0, "What finished?");
418        if !succeeded {
419            self.any_failed_load.set(true);
420        }
421
422        self.pending_loads.set(self.pending_loads.get() - 1);
423        if self.pending_loads.get() != 0 {
424            return None;
425        }
426
427        let any_failed = self.any_failed_load.get();
428        self.any_failed_load.set(false);
429        Some(any_failed)
430    }
431
432    fn parser_inserted(&self) -> bool {
433        self.parser_inserted.get()
434    }
435
436    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
437    fn potentially_render_blocking(&self) -> bool {
438        // An element is potentially render-blocking if its blocking tokens set contains "render",
439        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
440        // By default, an element is not implicitly potentially render-blocking.
441        //
442        // https://html.spec.whatwg.org/multipage/#the-style-element:implicitly-potentially-render-blocking
443        // > A style element is implicitly potentially render-blocking if the element was created by its node document's parser.
444        self.parser_inserted() ||
445            self.blocking
446                .get()
447                .is_some_and(|list| list.Contains(DOMString::from_static("render")))
448    }
449
450    fn referrer_policy(&self, _cx: &mut JSContext) -> ReferrerPolicy {
451        ReferrerPolicy::EmptyString
452    }
453
454    fn set_origin_clean(&self, cx: &mut JSContext, origin_clean: bool) {
455        if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
456            stylesheet.set_origin_clean(origin_clean);
457        }
458    }
459}
460
461impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
462    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
463    fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
464        self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
465    }
466
467    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
468    fn Disabled(&self, cx: &mut JSContext) -> bool {
469        self.get_cssom_stylesheet(cx)
470            .is_some_and(|sheet| sheet.disabled())
471    }
472
473    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
474    fn SetDisabled(&self, cx: &mut js::context::JSContext, value: bool) {
475        if let Some(sheet) = self.get_cssom_stylesheet(cx) {
476            sheet.set_disabled(cx.no_gc(), value);
477        }
478    }
479
480    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
481    make_getter!(Type, "type");
482
483    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
484    make_setter!(SetType, "type");
485
486    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
487    make_getter!(Media, "media");
488
489    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
490    make_setter!(SetMedia, "media");
491
492    /// <https://html.spec.whatwg.org/multipage/#attr-style-blocking>
493    fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
494        self.blocking.or_init(|| {
495            DOMTokenList::new(
496                cx,
497                self.upcast(),
498                &local_name!("blocking"),
499                Some(vec![Atom::from("render")]),
500            )
501        })
502    }
503}