Skip to main content

script/dom/html/documentmetadata/
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;
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::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::attributes::storage::AttrRef;
36use crate::dom::element::{AttributeMutation, Element, ElementCreator};
37use crate::dom::html::htmlelement::HTMLElement;
38use crate::dom::medialist::MediaList;
39use crate::dom::node::virtualmethods::VirtualMethods;
40use crate::dom::node::{BindContext, ChildrenMutation, Node, NodeTraits, UnbindContext};
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        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();
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                cx,
140                global,
141                self.upcast(),
142                InlineCheckType::Style,
143                &node.child_text_content().str(),
144                doc.get_current_parser_line(),
145            )
146        {
147            return;
148        }
149
150        // Step 6. Create a CSS style sheet with the following properties:
151        let data = node
152            .GetTextContent()
153            .expect("Element.textContent must be a string");
154        let shared_lock = node.owner_doc().style_shared_author_lock().clone();
155        let mq = Arc::new(shared_lock.wrap(self.create_media_list(&self.Media().str())));
156
157        // For duplicate style sheets with identical content, `StylesheetContents` can be reused
158        // to avoid reedundant parsing of the style sheets. Additionally, the cache hit rate of
159        // stylo's `CascadeDataCache` can now be significantly improved. When shared `StylesheetContents`
160        // is modified, copy-on-write will occur, see `CSSStyleSheet::will_modify`.
161        let (cache_key, contents) = StylesheetContentsCache::get_or_insert_with(
162            &data.str(),
163            &shared_lock,
164            UrlExtraData(doc.base_url().get_arc()),
165            doc.quirks_mode(),
166            self.upcast(),
167        );
168
169        let sheet = Arc::new(Stylesheet {
170            contents: shared_lock.wrap(contents),
171            shared_lock,
172            media: mq,
173            disabled: AtomicBool::new(false),
174        });
175
176        // From here we differ from the spec. Since we have a cache,
177        // we have two situations:
178        //
179        // 1. We hit the cache. No fetch ever runs, hence we don't
180        // need to muddy with render-/load-blocking
181        // 2. We don't hit the cache. In this scenario, we once again
182        // have two sub-scenarios:
183        //   a. We synchronously parse the contents without any `@import`.
184        //      This means we can proceed as in situation 1
185        //   b. We synchronously parse the contents and we encounter 1+
186        //      `@import` rules. In that case, we do start to load urls.
187        //
188        // For situation 1 and 2a, we can immediately fire the load event
189        // since we are done.
190        if self.pending_loads.get() == 0 {
191            // Step 4 of https://html.spec.whatwg.org/multipage/#the-style-element:critical-subresources
192            //
193            // Step 4. Queue an element task on the networking task source given element and the following steps:
194            // Step 4.1. If success is true, fire an event named load at element.
195            self.owner_global()
196                .task_manager()
197                .networking_task_source()
198                .queue_simple_event(self.upcast(), atom!("load"));
199        }
200
201        // For situation 2b, we need to do more work.
202        // Therefore, the following steps are actually implemented in
203        // `ElementStylesheetLoader::load_with_element`.
204        //
205        //     Step 7. If element contributes a script-blocking style sheet,
206        //     append element to its node document's script-blocking style sheet set.
207        //
208        //     Step 8. If element's media attribute's value matches the environment
209        //     and element is potentially render-blocking, then block rendering on element.
210
211        // Finally, update our stylesheet, regardless of which scenario we ran into
212        self.clean_stylesheet_ownership();
213        self.set_stylesheet(cx, sheet, cache_key);
214    }
215
216    // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet.
217    //
218    // With the reuse of `StylesheetContent` for same stylesheet string content,
219    // this function has a bit difference with `HTMLLinkElement::set_stylesheet` now.
220    pub(crate) fn set_stylesheet(
221        &self,
222        cx: &mut JSContext,
223        s: Arc<Stylesheet>,
224        cache_key: Option<StylesheetContentsCacheKey>,
225    ) {
226        *self.stylesheet.borrow_mut() = Some(s.clone());
227        *self.stylesheetcontents_cache_key.borrow_mut() = cache_key;
228        self.stylesheet_list_owner()
229            .add_owned_stylesheet(cx, self.upcast(), s);
230    }
231
232    pub(crate) fn will_modify_stylesheet(&self, cx: &mut JSContext) {
233        if let Some(stylesheet_with_owned_contents) = self.create_owned_contents_stylesheet() {
234            self.remove_stylesheet();
235            if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
236                let guard = stylesheet_with_owned_contents.shared_lock.read();
237                cssom_stylesheet.update_style_stylesheet(&stylesheet_with_owned_contents, &guard);
238            }
239            self.set_stylesheet(cx, stylesheet_with_owned_contents, None);
240        }
241    }
242
243    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
244        self.stylesheet.borrow().clone()
245    }
246
247    pub(crate) fn get_cssom_stylesheet(
248        &self,
249        cx: &mut JSContext,
250    ) -> Option<DomRoot<CSSStyleSheet>> {
251        self.get_stylesheet().map(|sheet| {
252            self.cssom_stylesheet.or_init(|| {
253                CSSStyleSheet::new(
254                    cx,
255                    &self.owner_window(),
256                    Some(self.upcast::<Element>()),
257                    "text/css".into(),
258                    None, // todo handle location
259                    None, // todo handle title
260                    sheet,
261                    None, // constructor_document
262                )
263            })
264        })
265    }
266
267    fn create_owned_contents_stylesheet(&self) -> Option<Arc<Stylesheet>> {
268        let cache_key = self.stylesheetcontents_cache_key.borrow_mut().take()?;
269        if cache_key.is_uniquely_owned() {
270            StylesheetContentsCache::remove(cache_key);
271            return None;
272        }
273
274        let stylesheet_with_shared_contents = self.stylesheet.borrow().clone()?;
275        let lock = stylesheet_with_shared_contents.shared_lock.clone();
276        let guard = stylesheet_with_shared_contents.shared_lock.read();
277        let stylesheet_with_owned_contents = Arc::new(Stylesheet {
278            contents: lock.wrap(
279                stylesheet_with_shared_contents
280                    .contents(&guard)
281                    .deep_clone(&lock, None, &guard),
282            ),
283            shared_lock: lock,
284            media: stylesheet_with_shared_contents.media.clone(),
285            disabled: AtomicBool::new(
286                stylesheet_with_shared_contents
287                    .disabled
288                    .load(Ordering::SeqCst),
289            ),
290        });
291
292        Some(stylesheet_with_owned_contents)
293    }
294
295    fn clean_stylesheet_ownership(&self) {
296        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
297            // If the CSSOMs change from having an owner node to being ownerless, they may still
298            // potentially modify shared stylesheets. Thus, create an new `Stylesheet` with owned
299            // `StylesheetContents` to ensure that the potentially modifications are only made on
300            // the owned `StylesheetContents`.
301            if let Some(stylesheet) = self.create_owned_contents_stylesheet() {
302                let guard = stylesheet.shared_lock.read();
303                cssom_stylesheet.update_style_stylesheet(&stylesheet, &guard);
304            }
305            cssom_stylesheet.set_owner_node(None);
306        }
307        self.cssom_stylesheet.set(None);
308    }
309
310    fn remove_stylesheet(&self) {
311        self.clean_stylesheet_ownership();
312        if let Some(s) = self.stylesheet.borrow_mut().take() {
313            self.stylesheet_list_owner()
314                .remove_stylesheet(StylesheetSource::Element(Dom::from_ref(self.upcast())), &s);
315            let _ = self.stylesheetcontents_cache_key.borrow_mut().take();
316        }
317    }
318}
319
320impl VirtualMethods for HTMLStyleElement {
321    fn super_type(&self) -> Option<&dyn VirtualMethods> {
322        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
323    }
324
325    fn children_changed(&self, cx: &mut JSContext, mutation: &ChildrenMutation) {
326        self.super_type().unwrap().children_changed(cx, mutation);
327
328        // https://html.spec.whatwg.org/multipage/#update-a-style-block
329        // > The element is not on the stack of open elements of an HTML parser or XML parser, and its children changed steps run.
330        if !self.in_stack_of_open_elements.get() {
331            self.update_a_style_block(cx);
332        }
333    }
334
335    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
336        self.super_type().unwrap().bind_to_tree(cx, context);
337
338        // https://html.spec.whatwg.org/multipage/#update-a-style-block
339        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
340        if !self.in_stack_of_open_elements.get() {
341            self.update_a_style_block(cx);
342        }
343    }
344
345    fn pop(&self, cx: &mut js::context::JSContext) {
346        self.super_type().unwrap().pop(cx);
347        self.in_stack_of_open_elements.set(false);
348
349        // https://html.spec.whatwg.org/multipage/#update-a-style-block
350        // > The element is popped off the stack of open elements of an HTML parser or XML parser.
351        self.update_a_style_block(cx);
352    }
353
354    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
355        if let Some(s) = self.super_type() {
356            s.unbind_from_tree(cx, context);
357        }
358
359        // https://html.spec.whatwg.org/multipage/#update-a-style-block
360        // > The element is not on the stack of open elements of an HTML parser or XML parser, and it becomes connected or disconnected.
361        if !self.in_stack_of_open_elements.get() {
362            self.update_a_style_block(cx);
363        }
364    }
365
366    fn attribute_mutated(
367        &self,
368        cx: &mut js::context::JSContext,
369        attr: AttrRef<'_>,
370        mutation: AttributeMutation,
371    ) {
372        if let Some(s) = self.super_type() {
373            s.attribute_mutated(cx, attr, mutation);
374        }
375
376        let node = self.upcast::<Node>();
377        if !(node.is_in_a_document_tree() || node.is_in_a_shadow_tree()) ||
378            self.in_stack_of_open_elements.get()
379        {
380            return;
381        }
382
383        if attr.name() == "type" {
384            if let AttributeMutation::Set(Some(old_value), _) = mutation &&
385                **old_value == **attr.value()
386            {
387                return;
388            }
389            self.remove_stylesheet();
390            self.update_a_style_block(cx);
391        } else if attr.name() == "media" &&
392            let Some(ref stylesheet) = *self.stylesheet.borrow_mut()
393        {
394            let shared_lock = node.owner_doc().style_shared_author_lock().clone();
395            let mut guard = shared_lock.write();
396            let media = stylesheet.media.write_with(&mut guard);
397            match mutation {
398                AttributeMutation::Set(..) => *media = self.create_media_list(&attr.value()),
399                AttributeMutation::Removed => *media = StyleMediaList::empty(),
400            };
401            self.owner_document().invalidate_stylesheets();
402        }
403    }
404}
405
406impl StylesheetOwner for HTMLStyleElement {
407    fn increment_pending_loads_count(&self) {
408        self.pending_loads.set(self.pending_loads.get() + 1)
409    }
410
411    fn load_finished(&self, succeeded: bool) -> Option<bool> {
412        assert!(self.pending_loads.get() > 0, "What finished?");
413        if !succeeded {
414            self.any_failed_load.set(true);
415        }
416
417        self.pending_loads.set(self.pending_loads.get() - 1);
418        if self.pending_loads.get() != 0 {
419            return None;
420        }
421
422        let any_failed = self.any_failed_load.get();
423        self.any_failed_load.set(false);
424        Some(any_failed)
425    }
426
427    fn parser_inserted(&self) -> bool {
428        self.parser_inserted.get()
429    }
430
431    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
432    fn potentially_render_blocking(&self) -> bool {
433        // An element is potentially render-blocking if its blocking tokens set contains "render",
434        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
435        // By default, an element is not implicitly potentially render-blocking.
436        //
437        // https://html.spec.whatwg.org/multipage/#the-style-element:implicitly-potentially-render-blocking
438        // > A style element is implicitly potentially render-blocking if the element was created by its node document's parser.
439        self.parser_inserted() ||
440            self.blocking
441                .get()
442                .is_some_and(|list| list.Contains("render".into()))
443    }
444
445    fn referrer_policy(&self, _cx: &mut JSContext) -> ReferrerPolicy {
446        ReferrerPolicy::EmptyString
447    }
448
449    fn set_origin_clean(&self, cx: &mut JSContext, origin_clean: bool) {
450        if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
451            stylesheet.set_origin_clean(origin_clean);
452        }
453    }
454}
455
456impl HTMLStyleElementMethods<crate::DomTypeHolder> for HTMLStyleElement {
457    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
458    fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
459        self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
460    }
461
462    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
463    fn Disabled(&self, cx: &mut JSContext) -> bool {
464        self.get_cssom_stylesheet(cx)
465            .is_some_and(|sheet| sheet.disabled())
466    }
467
468    /// <https://html.spec.whatwg.org/multipage/#dom-style-disabled>
469    fn SetDisabled(&self, cx: &mut js::context::JSContext, value: bool) {
470        if let Some(sheet) = self.get_cssom_stylesheet(cx) {
471            sheet.set_disabled(value);
472        }
473    }
474
475    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
476    make_getter!(Type, "type");
477
478    // <https://html.spec.whatwg.org/multipage/#HTMLStyleElement-partial>
479    make_setter!(SetType, "type");
480
481    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
482    make_getter!(Media, "media");
483
484    // <https://html.spec.whatwg.org/multipage/#attr-style-media>
485    make_setter!(SetMedia, "media");
486
487    /// <https://html.spec.whatwg.org/multipage/#attr-style-blocking>
488    fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
489        self.blocking.or_init(|| {
490            DOMTokenList::new(
491                cx,
492                self.upcast(),
493                &local_name!("blocking"),
494                Some(vec![Atom::from("render")]),
495            )
496        })
497    }
498}