Skip to main content

script/dom/html/document_metadata/
htmllinkelement.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::borrow::{Borrow, ToOwned};
6use std::cell::Cell;
7use std::default::Default;
8use std::str::FromStr;
9
10use bytes::{Bytes, BytesMut};
11use dom_struct::dom_struct;
12use html5ever::{LocalName, Prefix, local_name};
13use js::context::{JSContext, NoGC};
14use js::rust::HandleObject;
15use net_traits::image_cache::{
16    Image, ImageCache, ImageCacheResponseCallback, ImageCacheResult, ImageLoadListener,
17    ImageOrMetadataAvailable, ImageResponse, PendingImageId,
18};
19use net_traits::request::{Destination, Initiator, ParserMetadata, RequestBuilder, RequestId};
20use net_traits::{
21    FetchMetadata, FetchResponseMsg, NetworkError, ReferrerPolicy, ResourceFetchTiming,
22};
23use pixels::PixelFormat;
24use script_bindings::cell::DomRefCell;
25use script_bindings::root::Dom;
26use servo_arc::Arc;
27use servo_base::generic_channel::GenericSharedMemory;
28use servo_url::ServoUrl;
29use style::attr::AttrValue;
30use style::media_queries::MediaList as StyleMediaList;
31use style::stylesheets::Stylesheet;
32use stylo_atoms::Atom;
33use webrender_api::units::DeviceIntSize;
34
35use crate::css::stylesheet_loader::{
36    ElementStylesheetLoader, StylesheetContextSource, StylesheetOwner,
37};
38use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenList_Binding::DOMTokenListMethods;
39use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding::HTMLLinkElementMethods;
40use crate::dom::bindings::inheritance::Castable;
41use crate::dom::bindings::refcounted::Trusted;
42use crate::dom::bindings::reflector::DomGlobal;
43use crate::dom::bindings::root::{DomRoot, MutNullableDom};
44use crate::dom::bindings::str::{DOMString, USVString};
45use crate::dom::csp::{GlobalCspReporting, Violation};
46use crate::dom::css::cssstylesheet::CSSStyleSheet;
47use crate::dom::css::stylesheet::StyleSheet as DOMStyleSheet;
48use crate::dom::document::Document;
49use crate::dom::documentorshadowroot::StylesheetSource;
50use crate::dom::domtokenlist::DOMTokenList;
51use crate::dom::element::attributes::storage::AttrRef;
52use crate::dom::element::{
53    AttributeMutation, Element, ElementCreator, cors_setting_for_element,
54    cors_settings_attribute_credential_mode, referrer_policy_for_element,
55    reflect_cross_origin_attribute, reflect_referrer_policy_attribute, set_cross_origin_attribute,
56};
57use crate::dom::html::document_metadata::processingoptions::{
58    LinkFetchContext, LinkFetchContextType, LinkProcessingOptions,
59};
60use crate::dom::html::htmlelement::HTMLElement;
61use crate::dom::html::links::relations::LinkRelations;
62use crate::dom::medialist::MediaList;
63use crate::dom::node::virtualmethods::VirtualMethods;
64use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
65use crate::dom::performance::performanceresourcetiming::InitiatorType;
66use crate::dom::srcset::SourceSet;
67use crate::dom::types::{EventTarget, GlobalScope};
68use crate::fetch::network_listener::{
69    FetchResponseListener, ResourceTimingListener, submit_timing,
70};
71use crate::scripting::fetching_options::ScriptFetchOptions;
72use crate::scripting::script_module::fetch_a_modulepreload_module;
73use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
74
75#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
76pub(crate) struct RequestGenerationId(u32);
77
78impl RequestGenerationId {
79    fn increment(self) -> RequestGenerationId {
80        RequestGenerationId(self.0 + 1)
81    }
82}
83
84#[dom_struct]
85pub(crate) struct HTMLLinkElement {
86    htmlelement: HTMLElement,
87    /// The relations as specified by the "rel" attribute
88    rel_list: MutNullableDom<DOMTokenList>,
89
90    /// The link relations as they are used in practice.
91    ///
92    /// The reason this is separate from [HTMLLinkElement::rel_list] is that
93    /// a literal list is a bit unwieldy and that there are corner cases to consider
94    /// (Like `rev="made"` implying an author relationship that is not represented in rel_list)
95    #[no_trace]
96    relations: Cell<LinkRelations>,
97
98    #[conditional_malloc_size_of]
99    #[no_trace]
100    stylesheet: DomRefCell<Option<Arc<Stylesheet>>>,
101    cssom_stylesheet: MutNullableDom<CSSStyleSheet>,
102
103    /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts>
104    parser_inserted: Cell<bool>,
105    /// Whether any of the loads have failed.
106    any_failed_load: Cell<bool>,
107    /// <https://html.spec.whatwg.org/multipage/#explicitly-enabled>
108    is_explicitly_enabled: Cell<bool>,
109    /// Whether the previous type matched with the destination
110    previous_type_matched: Cell<bool>,
111    /// The number of loads that this link element has triggered (could be more
112    /// than one because of imports) and have not yet finished.
113    pending_loads: Cell<u32>,
114    /// A monotonically increasing counter that keeps track of which stylesheet to apply.
115    request_generation_id: Cell<RequestGenerationId>,
116
117    /// Whether the previous media environment matched with the media query
118    previous_media_environment_matched: Cell<bool>,
119    /// Line number this element was created on
120    line_number: u64,
121    /// <https://html.spec.whatwg.org/multipage/#source-set>
122    source_set: DomRefCell<SourceSet>,
123    /// <https://html.spec.whatwg.org/multipage/#dom-link-blocking>
124    blocking: MutNullableDom<DOMTokenList>,
125}
126
127impl HTMLLinkElement {
128    fn new_inherited(
129        local_name: LocalName,
130        prefix: Option<Prefix>,
131        document: &Document,
132        creator: ElementCreator,
133    ) -> HTMLLinkElement {
134        HTMLLinkElement {
135            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
136            rel_list: Default::default(),
137            relations: Cell::new(LinkRelations::empty()),
138            parser_inserted: Cell::new(creator.is_parser_created()),
139            stylesheet: DomRefCell::new(None),
140            cssom_stylesheet: MutNullableDom::new(None),
141            pending_loads: Cell::new(0),
142            any_failed_load: Cell::new(false),
143            request_generation_id: Cell::new(RequestGenerationId(0)),
144            is_explicitly_enabled: Cell::new(false),
145            previous_type_matched: Cell::new(true),
146            previous_media_environment_matched: Cell::new(true),
147            line_number: creator.return_line_number(),
148            source_set: DomRefCell::new(SourceSet::new()),
149            blocking: Default::default(),
150        }
151    }
152
153    pub(crate) fn new(
154        cx: &mut js::context::JSContext,
155        local_name: LocalName,
156        prefix: Option<Prefix>,
157        document: &Document,
158        proto: Option<HandleObject>,
159        creator: ElementCreator,
160    ) -> DomRoot<HTMLLinkElement> {
161        Node::reflect_node_with_proto(
162            cx,
163            Box::new(HTMLLinkElement::new_inherited(
164                local_name, prefix, document, creator,
165            )),
166            document,
167            proto,
168        )
169    }
170
171    pub(crate) fn get_request_generation_id(&self) -> RequestGenerationId {
172        self.request_generation_id.get()
173    }
174
175    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
176    fn remove_stylesheet(&self, no_gc: &NoGC) {
177        if let Some(stylesheet) = self.stylesheet.safe_borrow_mut(no_gc).take() {
178            let owner = self.stylesheet_list_owner();
179            owner.remove_stylesheet(
180                StylesheetSource::Element(Dom::from_ref(self.upcast())),
181                &stylesheet,
182            );
183            self.clean_stylesheet_ownership();
184            owner.invalidate_stylesheets(no_gc);
185        }
186    }
187
188    // FIXME(emilio): These methods are duplicated with
189    // HTMLStyleElement::set_stylesheet.
190    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
191    pub(crate) fn set_stylesheet(&self, no_gc: &NoGC, new_stylesheet: Arc<Stylesheet>) {
192        let owner = self.stylesheet_list_owner();
193        if let Some(old_stylesheet) = self
194            .stylesheet
195            .safe_borrow_mut(no_gc)
196            .replace(new_stylesheet.clone())
197        {
198            owner.remove_stylesheet(
199                StylesheetSource::Element(Dom::from_ref(self.upcast())),
200                &old_stylesheet,
201            );
202        }
203        owner.add_owned_stylesheet(no_gc, self.upcast(), new_stylesheet);
204    }
205
206    pub(crate) fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
207        self.stylesheet.borrow().clone()
208    }
209
210    pub(crate) fn get_cssom_stylesheet(
211        &self,
212        cx: &mut JSContext,
213    ) -> Option<DomRoot<CSSStyleSheet>> {
214        self.get_stylesheet().map(|sheet| {
215            self.cssom_stylesheet.or_init(|| {
216                CSSStyleSheet::new(
217                    cx,
218                    &self.owner_window(),
219                    Some(self.upcast::<Element>()),
220                    DOMString::from_static("text/css"),
221                    Some(self.Href().into()),
222                    sheet,
223                    None, // constructor_document
224                )
225            })
226        })
227    }
228
229    pub(crate) fn is_alternate(&self) -> bool {
230        self.relations.get().contains(LinkRelations::ALTERNATE) &&
231            !self
232                .upcast::<Element>()
233                .get_string_attribute(&local_name!("title"))
234                .is_empty()
235    }
236
237    pub(crate) fn is_effectively_disabled(&self) -> bool {
238        (self.is_alternate() && !self.is_explicitly_enabled.get()) ||
239            self.upcast::<Element>()
240                .has_attribute(&local_name!("disabled"))
241    }
242
243    fn clean_stylesheet_ownership(&self) {
244        if let Some(cssom_stylesheet) = self.cssom_stylesheet.get() {
245            cssom_stylesheet.set_owner_node(None);
246        }
247        self.cssom_stylesheet.set(None);
248    }
249}
250
251impl VirtualMethods for HTMLLinkElement {
252    fn super_type(&self) -> Option<&dyn VirtualMethods> {
253        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
254    }
255
256    fn attribute_mutated(
257        &self,
258        cx: &mut js::context::JSContext,
259        attr: AttrRef<'_>,
260        mutation: AttributeMutation,
261    ) {
262        self.super_type()
263            .unwrap()
264            .attribute_mutated(cx, attr, mutation);
265
266        let local_name = attr.local_name();
267        let is_removal = mutation.is_removal();
268        match *local_name {
269            local_name!("disabled") => {
270                self.handle_disabled_attribute_change(cx.no_gc(), is_removal);
271                return;
272            },
273            local_name!("rel") | local_name!("rev") => {
274                let previous_relations = self.relations.get();
275                self.relations
276                    .set(LinkRelations::for_element(self.upcast()));
277
278                // If relations haven't changed, we shouldn't do anything
279                if previous_relations == self.relations.get() {
280                    return;
281                }
282            },
283            _ => {},
284        }
285
286        let node = self.upcast::<Node>();
287        if !node.is_connected() {
288            return;
289        }
290
291        // For stylesheets, we should only refetch when the actual attribute value
292        // has been changed.
293        if self.relations.get().contains(LinkRelations::STYLESHEET) &&
294            let AttributeMutation::Set(Some(previous_value)) = mutation &&
295            **previous_value == **attr.value()
296        {
297            return;
298        }
299
300        match *local_name {
301            local_name!("rel") | local_name!("rev") => {
302                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
303                // > When the external resource link is created on a link element that is already browsing-context connected.
304                if self.relations.get().contains(LinkRelations::STYLESHEET) {
305                    self.handle_stylesheet_url(cx);
306                } else {
307                    self.remove_stylesheet(cx.no_gc());
308                }
309
310                if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
311                    self.fetch_and_process_modulepreload(cx);
312                }
313            },
314            local_name!("href") => {
315                // https://html.spec.whatwg.org/multipage/#attr-link-href
316                // > If both the href and imagesrcset attributes are absent, then the element does not define a link.
317                if is_removal {
318                    if self.relations.get().contains(LinkRelations::STYLESHEET) {
319                        self.remove_stylesheet(cx.no_gc());
320                    }
321                    return;
322                }
323                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
324                // > When the href attribute of the link element of an external resource link
325                // > that is already browsing-context connected is changed.
326                if self.relations.get().contains(LinkRelations::STYLESHEET) {
327                    self.handle_stylesheet_url(cx);
328                }
329
330                if self.relations.get().contains(LinkRelations::ICON) {
331                    self.handle_favicon_url(&attr.value());
332                }
333
334                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
335                // When the href attribute of the link element of an external resource link
336                // that is already browsing-context connected is changed.
337                if self.relations.get().contains(LinkRelations::PREFETCH) {
338                    self.fetch_and_process_prefetch_link(&attr.value());
339                }
340
341                // https://html.spec.whatwg.org/multipage/#link-type-preload
342                // When the href attribute of the link element of an external resource link
343                // that is already browsing-context connected is changed.
344                if self.relations.get().contains(LinkRelations::PRELOAD) {
345                    self.handle_preload_url(cx.no_gc());
346                }
347
348                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
349                if self.relations.get().contains(LinkRelations::MODULE_PRELOAD) {
350                    self.fetch_and_process_modulepreload(cx);
351                }
352            },
353            local_name!("imagesrcset") => {
354                self.source_set
355                    .safe_borrow_mut(cx.no_gc())
356                    .update_source_set(cx.no_gc(), self.upcast::<Element>());
357            },
358            local_name!("imagesizes") => {
359                if self
360                    .upcast::<Element>()
361                    .has_attribute(&local_name!("imagesrcset"))
362                {
363                    self.source_set
364                        .safe_borrow_mut(cx.no_gc())
365                        .update_source_set(cx.no_gc(), self.upcast::<Element>());
366                }
367            },
368            local_name!("sizes") if self.relations.get().contains(LinkRelations::ICON) => {
369                self.handle_favicon_url(&attr.value());
370            },
371            local_name!("crossorigin") => {
372                // https://html.spec.whatwg.org/multipage/#link-type-prefetch
373                // When the crossorigin attribute of the link element of an external resource link
374                // that is already browsing-context connected is set, changed, or removed.
375                if self.relations.get().contains(LinkRelations::PREFETCH) {
376                    self.fetch_and_process_prefetch_link(&attr.value());
377                }
378
379                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
380                // When the crossorigin attribute of the link element of an external resource link
381                // that is already browsing-context connected is set, changed, or removed.
382                if self.relations.get().contains(LinkRelations::STYLESHEET) {
383                    self.handle_stylesheet_url(cx);
384                }
385            },
386            local_name!("as") => {
387                // https://html.spec.whatwg.org/multipage/#link-type-preload
388                // When the as attribute of the link element of an external resource link
389                // that is already browsing-context connected is changed.
390                if self.relations.get().contains(LinkRelations::PRELOAD) &&
391                    let AttributeMutation::Set(Some(_)) = mutation
392                {
393                    self.handle_preload_url(cx.no_gc());
394                }
395            },
396            local_name!("type") => {
397                // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
398                // When the type attribute of the link element of an external resource link that
399                // is already browsing-context connected is set or changed to a value that does
400                // not or no longer matches the Content-Type metadata of the previous obtained
401                // external resource, if any.
402                //
403                // TODO: Match Content-Type metadata to check if it needs to be updated
404                if self.relations.get().contains(LinkRelations::STYLESHEET) {
405                    self.handle_stylesheet_url(cx);
406                }
407
408                // https://html.spec.whatwg.org/multipage/#link-type-preload
409                // When the type attribute of the link element of an external resource link that
410                // is already browsing-context connected, but was previously not obtained due to
411                // the type attribute specifying an unsupported type for the request destination,
412                // is set, removed, or changed.
413                if self.relations.get().contains(LinkRelations::PRELOAD) &&
414                    !self.previous_type_matched.get()
415                {
416                    self.handle_preload_url(cx.no_gc());
417                }
418            },
419            local_name!("media") => {
420                // https://html.spec.whatwg.org/multipage/#link-type-preload
421                // When the media attribute of the link element of an external resource link that
422                // is already browsing-context connected, but was previously not obtained due to
423                // the media attribute not matching the environment, is changed or removed.
424                if self.relations.get().contains(LinkRelations::PRELOAD) &&
425                    !self.previous_media_environment_matched.get()
426                {
427                    match mutation {
428                        AttributeMutation::Removed | AttributeMutation::Set(Some(_)) => {
429                            self.handle_preload_url(cx.no_gc())
430                        },
431                        _ => {},
432                    };
433                } else if self.relations.get().contains(LinkRelations::STYLESHEET) &&
434                    let Some(ref stylesheet) = *self.stylesheet.safe_borrow_mut(cx.no_gc())
435                {
436                    let document = self.owner_document();
437                    let shared_lock = document.style_shared_author_lock().clone();
438                    let mut guard = shared_lock.write();
439                    let media = stylesheet.media.write_with(&mut guard);
440                    match mutation {
441                        AttributeMutation::Set(_) => {
442                            *media = MediaList::parse_media_list(&attr.value(), document.window())
443                        },
444                        AttributeMutation::Removed => *media = StyleMediaList::empty(),
445                    };
446                    self.owner_document().invalidate_stylesheets(cx.no_gc());
447                }
448
449                let matches_media_environment =
450                    MediaList::matches_environment(&self.owner_document(), &attr.value());
451                self.previous_media_environment_matched
452                    .set(matches_media_environment);
453            },
454            _ => {},
455        }
456    }
457
458    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
459        match name {
460            &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
461            _ => self
462                .super_type()
463                .unwrap()
464                .parse_plain_attribute(name, value),
465        }
466    }
467
468    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
469        if let Some(s) = self.super_type() {
470            s.bind_to_tree(cx, context);
471        }
472
473        let element = self.upcast::<Element>();
474        let href = element.get_attribute_string_value(&local_name!("href"));
475
476        if context.tree_connected &&
477            (href.as_ref().is_some_and(|x| !x.is_empty()) ||
478                element.has_attribute(&local_name!("imagesrcset")))
479        {
480            let relations = self.relations.get();
481            // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:fetch-and-process-the-linked-resource
482            // > When the external resource link's link element becomes browsing-context connected.
483            if let Some(href) = href {
484                if relations.contains(LinkRelations::STYLESHEET) {
485                    self.handle_stylesheet_url(cx);
486                }
487
488                if relations.contains(LinkRelations::ICON) {
489                    self.handle_favicon_url(&href);
490                }
491
492                if relations.contains(LinkRelations::PREFETCH) {
493                    self.fetch_and_process_prefetch_link(&href);
494                }
495
496                // https://html.spec.whatwg.org/multipage/#link-type-modulepreload
497                if relations.contains(LinkRelations::MODULE_PRELOAD) {
498                    let link = DomRoot::from_ref(self);
499                    self.owner_document().add_delayed_task(
500                        task!(FetchModulePreload: |cx, link: DomRoot<HTMLLinkElement>| {
501                            link.fetch_and_process_modulepreload(cx);
502                        }),
503                    );
504                }
505            }
506
507            if relations.contains(LinkRelations::PRELOAD) {
508                self.handle_preload_url(cx.no_gc());
509            }
510        }
511    }
512
513    fn unbind_from_tree(&self, cx: &mut js::context::JSContext, context: &UnbindContext) {
514        if let Some(s) = self.super_type() {
515            s.unbind_from_tree(cx, context);
516        }
517
518        self.remove_stylesheet(cx.no_gc());
519    }
520}
521
522impl HTMLLinkElement {
523    fn compute_destination_for_attribute(&self) -> Option<Destination> {
524        // Let destination be the result of translating the keyword
525        // representing the state of el's as attribute.
526        let element = self.upcast::<Element>();
527        element
528            .get_attribute_string_ref(&local_name!("as"))
529            .and_then(|attr| {
530                let attr = attr.as_attr_ref().value();
531                LinkProcessingOptions::translate_a_preload_destination(&attr)
532            })
533    }
534
535    /// <https://html.spec.whatwg.org/multipage/#create-link-options-from-element>
536    fn processing_options(&self) -> LinkProcessingOptions {
537        let element = self.upcast::<Element>();
538
539        // Step 1. Let document be el's node document.
540        let document = self.upcast::<Node>().owner_doc();
541        let global = document.owner_global();
542
543        // Step 2. Let options be a new link processing options
544        let mut options = LinkProcessingOptions {
545            href: String::new(),
546            destination: Destination::None,
547            integrity: String::new(),
548            link_type: String::new(),
549            cryptographic_nonce_metadata: self.upcast::<Element>().nonce_value(),
550            cross_origin: cors_setting_for_element(element),
551            referrer_policy: referrer_policy_for_element(element),
552            policy_container: document.policy_container().clone(),
553            source_set: Some(self.source_set.borrow().clone()),
554            origin: document.borrow().origin().immutable().to_owned(),
555            base_url: document.borrow().base_url(),
556            request_client: global.request_client(None),
557            referrer: global.get_referrer(),
558        };
559
560        // Step 3. If el has an href attribute, then set options's href to the value of el's href attribute.
561        if let Some(href_attribute) = element.get_attribute_string_value(&local_name!("href")) {
562            options.href = href_attribute;
563        }
564
565        // Step 4. If el has an integrity attribute, then set options's integrity
566        //         to the value of el's integrity content attribute.
567        if let Some(integrity_attribute) =
568            element.get_attribute_string_value(&local_name!("integrity"))
569        {
570            options.integrity = integrity_attribute;
571        }
572
573        // Step 5. If el has a type attribute, then set options's type to the value of el's type attribute.
574        if let Some(type_attribute) = element.get_attribute_string_value(&local_name!("type")) {
575            options.link_type = type_attribute;
576        }
577
578        // Step 6. Assert: options's href is not the empty string, or options's source set is not null.
579        assert!(!options.href.is_empty() || options.source_set.is_some());
580
581        // Step 7. Return options.
582        options
583    }
584
585    /// <https://html.spec.whatwg.org/multipage/#default-fetch-and-process-the-linked-resource>
586    ///
587    /// This method does not implement Step 7 (fetching the request) and instead returns the [RequestBuilder],
588    /// as the fetch context that should be used depends on the link type.
589    fn default_fetch_and_process_the_linked_resource(&self) -> Option<RequestBuilder> {
590        // Step 1. Let options be the result of creating link options from el.
591        let options = self.processing_options();
592
593        // Step 2. Let request be the result of creating a link request given options.
594        let Some(request) =
595            options.create_link_request(self.owner_window().webview_id(), &self.owner_global())
596        else {
597            // Step 3. If request is null, then return.
598            return None;
599        };
600        // Step 4. Set request's synchronous flag.
601        let mut request = request.synchronous(true);
602
603        // Step 5. Run the linked resource fetch setup steps, given el and request. If the result is false, then return.
604        if !self.linked_resource_fetch_setup(&mut request) {
605            return None;
606        }
607
608        // TODO Step 6. Set request's initiator type to "css" if el's rel attribute
609        // contains the keyword stylesheet; "link" otherwise.
610
611        // Step 7. Fetch request with processResponseConsumeBody set to the following steps given response response and null,
612        // failure, or a byte sequence bodyBytes: [..]
613        Some(request)
614    }
615
616    /// <https://html.spec.whatwg.org/multipage/#linked-resource-fetch-setup-steps>
617    fn linked_resource_fetch_setup(&self, request: &mut RequestBuilder) -> bool {
618        // https://html.spec.whatwg.org/multipage/#rel-icon:linked-resource-fetch-setup-steps
619        if self.relations.get().contains(LinkRelations::ICON) {
620            // Step 1. Set request's destination to "image".
621            request.destination = Destination::Image;
622
623            // Step 2. Return true.
624            //
625            // Fall-through
626        }
627
628        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:linked-resource-fetch-setup-steps
629        if self.relations.get().contains(LinkRelations::STYLESHEET) {
630            // Step 1. If el's disabled attribute is set, then return false.
631            if self
632                .upcast::<Element>()
633                .has_attribute(&local_name!("disabled"))
634            {
635                return false;
636            }
637            // Step 2. If el contributes a script-blocking style sheet, append el to its node document's script-blocking style sheet set.
638            //
639            // Implemented in `ElementStylesheetLoader::load_with_element`.
640
641            // Step 3. If el's media attribute's value matches the environment and el is potentially render-blocking, then block rendering on el.
642            //
643            // Implemented in `ElementStylesheetLoader::load_with_element`.
644
645            // Step 4. If el is currently render-blocking, then set request's render-blocking to true.
646            // TODO
647
648            // Step 5. Return true.
649            //
650            // Fall-through
651        }
652
653        true
654    }
655
656    /// The `fetch and process the linked resource` algorithm for [`rel="prefetch"`](https://html.spec.whatwg.org/multipage/#link-type-prefetch)
657    fn fetch_and_process_prefetch_link(&self, href: &str) {
658        // Step 1. If el's href attribute's value is the empty string, then return.
659        if href.is_empty() {
660            return;
661        }
662
663        // Step 2. Let options be the result of creating link options from el.
664        let mut options = self.processing_options();
665
666        // Step 3. Set options's destination to the empty string.
667        options.destination = Destination::None;
668
669        // Step 4. Let request be the result of creating a link request given options.
670        let Some(request) =
671            options.create_link_request(self.owner_window().webview_id(), &self.owner_global())
672        else {
673            // Step 5. If request is null, then return.
674            return;
675        };
676        let url = request.url.url();
677
678        // Step 6. Set request's initiator to "prefetch".
679        let request = request.initiator(Initiator::Prefetch);
680
681        // (Step 7, firing load/error events is handled in the FetchResponseListener impl for LinkFetchContext)
682
683        // Step 8. The user agent should fetch request, with processResponseConsumeBody set to processPrefetchResponse.
684        let document = self.upcast::<Node>().owner_doc();
685        let fetch_context = LinkFetchContext {
686            url,
687            link: Some(Trusted::new(self)),
688            type_: LinkFetchContextType::Prefetch,
689            response_body: BytesMut::new(),
690        };
691
692        document.fetch_background(request, fetch_context);
693    }
694
695    /// <https://html.spec.whatwg.org/multipage/#concept-link-obtain>
696    fn handle_stylesheet_url(&self, cx: &mut js::context::JSContext) {
697        let document = self.owner_document();
698        if document.browsing_context().is_none() {
699            return;
700        }
701
702        let element = self.upcast::<Element>();
703
704        // https://html.spec.whatwg.org/multipage/#processing-the-type-attribute
705        // > If the UA does not support the given MIME type for the given link relationship,
706        // > then the UA should not fetch and process the linked resource
707        //
708        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet
709        // > The default type for resources given by the stylesheet keyword is text/css.
710        let type_ = element.get_string_attribute(&local_name!("type"));
711        if !type_.is_empty() && type_ != "text/css" {
712            return;
713        }
714
715        // Step 1.
716        let href = element.get_string_attribute(&local_name!("href"));
717        if href.is_empty() {
718            return;
719        }
720
721        // Step 2.
722        let link_url = match document.base_url().join(&href.str()) {
723            Ok(url) => url,
724            Err(e) => {
725                debug!("Parsing url {} failed: {}", href, e);
726                return;
727            },
728        };
729
730        // Step 3
731        let cors_setting = cors_setting_for_element(element);
732
733        let media_query_string = element
734            .get_attribute_string_ref(&local_name!("media"))
735            .unwrap_or_default();
736        let media = MediaList::parse_media_list(
737            &media_query_string.as_attr_ref().value(),
738            document.window(),
739        );
740        let media = Arc::new(document.style_shared_author_lock().wrap(media));
741
742        let integrity_metadata = element
743            .get_attribute_string_value(&local_name!("integrity"))
744            .unwrap_or_default();
745
746        self.request_generation_id
747            .set(self.request_generation_id.get().increment());
748        self.pending_loads.set(0);
749
750        ElementStylesheetLoader::load_with_element(
751            cx,
752            self.upcast(),
753            StylesheetContextSource::LinkElement,
754            media,
755            link_url,
756            cors_setting,
757            integrity_metadata,
758        );
759    }
760
761    /// <https://html.spec.whatwg.org/multipage/#attr-link-disabled>
762    fn handle_disabled_attribute_change(&self, no_gc: &NoGC, is_removal: bool) {
763        // > Whenever the disabled attribute is removed, set the link element's explicitly enabled attribute to true.
764        if is_removal {
765            self.is_explicitly_enabled.set(true);
766        }
767        if let Some(stylesheet) = self.get_stylesheet() &&
768            stylesheet.set_disabled(!is_removal)
769        {
770            self.stylesheet_list_owner().invalidate_stylesheets(no_gc);
771        }
772    }
773
774    fn handle_favicon_url(&self, href: &str) {
775        // If el's href attribute's value is the empty string, then return.
776        if href.is_empty() {
777            return;
778        }
779
780        // The spec does not specify this, but we don't fetch favicons for iframes, as
781        // they won't be displayed anyways.
782        let window = self.owner_window();
783        if !window.is_top_level() {
784            return;
785        }
786        let Ok(href) = self.Href().parse() else {
787            return;
788        };
789
790        // Ignore all previous fetch operations
791        self.request_generation_id
792            .set(self.request_generation_id.get().increment());
793
794        let cache_result = window.image_cache().get_cached_image_status(
795            href,
796            window.origin().immutable(),
797            cors_setting_for_element(self.upcast()),
798        );
799
800        match cache_result {
801            ImageCacheResult::Available(ImageOrMetadataAvailable::ImageAvailable {
802                image, ..
803            }) => {
804                self.process_favicon_response(image);
805            },
806            ImageCacheResult::Available(ImageOrMetadataAvailable::MetadataAvailable(_, id)) |
807            ImageCacheResult::Pending(id) => {
808                let sender = self.register_image_cache_callback(id);
809                window.image_cache().add_listener(ImageLoadListener::new(
810                    sender,
811                    window.pipeline_id(),
812                    id,
813                ));
814            },
815            ImageCacheResult::ReadyForRequest(id) => {
816                let Some(request) = self.default_fetch_and_process_the_linked_resource() else {
817                    return;
818                };
819
820                let sender = self.register_image_cache_callback(id);
821                window.image_cache().add_listener(ImageLoadListener::new(
822                    sender,
823                    window.pipeline_id(),
824                    id,
825                ));
826
827                let document = self.upcast::<Node>().owner_doc();
828                let fetch_context = FaviconFetchContext {
829                    url: self.owner_document().base_url(),
830                    image_cache: window.image_cache(),
831                    id,
832                };
833                document.fetch_background(request, fetch_context);
834            },
835            ImageCacheResult::FailedToLoadOrDecode => {},
836        };
837    }
838
839    fn register_image_cache_callback(&self, id: PendingImageId) -> ImageCacheResponseCallback {
840        let trusted_node = Trusted::new(self);
841        let window = self.owner_window();
842        let request_generation_id = self.get_request_generation_id();
843        window.register_image_cache_listener(id, move |response, _| {
844            let trusted_node = trusted_node.clone();
845            let link_element = trusted_node.root();
846            let window = link_element.owner_window();
847
848            let ImageResponse::Loaded(image, _) = response.response else {
849                // We don't care about metadata and such for favicons.
850                return;
851            };
852
853            if request_generation_id != link_element.get_request_generation_id() {
854                // This load is no longer relevant.
855                return;
856            };
857
858            window
859                .as_global_scope()
860                .task_manager()
861                .networking_task_source()
862                .queue(task!(process_favicon_response: move || {
863                    let element = trusted_node.root();
864
865                    if request_generation_id != element.get_request_generation_id() {
866                        // This load is no longer relevant.
867                        return;
868                    };
869
870                    element.process_favicon_response(image);
871                }));
872        })
873    }
874
875    /// Rasterizes a loaded favicon file if necessary and notifies the embedder about it.
876    fn process_favicon_response(&self, image: Image) {
877        // TODO: Include the size attribute here
878        let window = self.owner_window();
879        let document = self.owner_document();
880
881        let send_rasterized_favicon_to_embedder = |raster_image: &pixels::RasterImage| {
882            // Let's not worry about animated favicons...
883            let frame = raster_image.first_frame();
884
885            let format = match raster_image.format {
886                PixelFormat::K8 => embedder_traits::PixelFormat::K8,
887                PixelFormat::KA8 => embedder_traits::PixelFormat::KA8,
888                PixelFormat::RGB8 => embedder_traits::PixelFormat::RGB8,
889                PixelFormat::RGBA8 => embedder_traits::PixelFormat::RGBA8,
890                PixelFormat::BGRA8 => embedder_traits::PixelFormat::BGRA8,
891            };
892
893            let embedder_image = embedder_traits::Image::new(
894                frame.width,
895                frame.height,
896                std::sync::Arc::new(GenericSharedMemory::from_arc_vec(
897                    raster_image.bytes.clone(),
898                )),
899                raster_image.frames[0].byte_range.clone(),
900                format,
901            );
902            document.set_favicon(embedder_image);
903        };
904
905        match image {
906            Image::Raster(raster_image) => send_rasterized_favicon_to_embedder(&raster_image),
907            Image::Vector(vector_image) => {
908                // This size is completely arbitrary.
909                let size = DeviceIntSize::new(250, 250);
910
911                let image_cache = window.image_cache();
912                if let Some(raster_image) =
913                    image_cache.rasterize_vector_image(vector_image.id, size, None)
914                {
915                    send_rasterized_favicon_to_embedder(&raster_image);
916                } else {
917                    // The rasterization callback will end up calling "process_favicon_response" again,
918                    // but this time with a raster image.
919                    let image_cache_sender = self.register_image_cache_callback(vector_image.id);
920                    image_cache.add_rasterization_complete_listener(
921                        window.pipeline_id(),
922                        vector_image.id,
923                        size,
924                        image_cache_sender,
925                    );
926                }
927            },
928        }
929    }
930
931    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
932    /// and type matching destination steps of <https://html.spec.whatwg.org/multipage/#preload>
933    fn handle_preload_url(&self, no_gc: &NoGC) {
934        // Step 1. Update the source set for el.
935        self.source_set
936            .safe_borrow_mut(no_gc)
937            .update_source_set(no_gc, self.upcast::<Element>());
938        // Step 2. Let options be the result of creating link options from el.
939        let mut options = self.processing_options();
940        // Step 3. Let destination be the result of translating the keyword
941        // representing the state of el's as attribute.
942        let Some(destination) = self.compute_destination_for_attribute() else {
943            // Step 4. If destination is null, then return.
944            return;
945        };
946        // Step 5. Set options's destination to destination.
947        options.destination = destination;
948        // Steps for https://html.spec.whatwg.org/multipage/#preload
949        {
950            // Step 1. If options's type doesn't match options's destination, then return.
951            let type_matches_destination = options.type_matches_destination();
952            self.previous_type_matched.set(type_matches_destination);
953            if !type_matches_destination {
954                return;
955            }
956        }
957        // Step 6. Preload options, with the following steps given a response response:
958        let document = self.upcast::<Node>().owner_doc();
959        options.preload(
960            self.owner_window_unrooted(no_gc).webview_id(),
961            Some(Trusted::new(self)),
962            &document,
963        );
964    }
965
966    /// <https://html.spec.whatwg.org/multipage/#link-type-preload:fetch-and-process-the-linked-resource-2>
967    pub(crate) fn fire_event_after_response(
968        &self,
969        cx: &mut JSContext,
970        response: Result<(), NetworkError>,
971    ) {
972        // Step 3.1 If response is a network error, fire an event named error at el.
973        // Otherwise, fire an event named load at el.
974        if response.is_err() {
975            self.upcast::<EventTarget>().fire_event(cx, atom!("error"));
976        } else {
977            self.upcast::<EventTarget>().fire_event(cx, atom!("load"));
978        }
979    }
980
981    /// <https://html.spec.whatwg.org/multipage/#link-type-modulepreload:fetch-and-process-the-linked-resource-2>
982    fn fetch_and_process_modulepreload(&self, cx: &mut JSContext) {
983        let el = self.upcast::<Element>();
984        let href_attribute_value = el.get_string_attribute(&local_name!("href"));
985
986        // Step 1. If el's href attribute's value is the empty string, then return.
987        if href_attribute_value.is_empty() {
988            return;
989        }
990
991        // Step 2. Let destination be the current state of el's as attribute (a destination), or "script" if it is in no state.
992        let destination = el
993            .get_attribute_string_value(&local_name!("as"))
994            .map(|mut value| {
995                value.make_ascii_lowercase();
996                value
997            })
998            .and_then(|value| match value.as_str() {
999                // `Destination::from_str` will map an empty string to `Destination::None`
1000                "" => None,
1001                // "fetch" is a valid preload destination, but not for modules
1002                "fetch" => Some(Destination::None),
1003                _ => Destination::from_str(&value).ok(),
1004            })
1005            .unwrap_or(Destination::Script);
1006
1007        let document = self.owner_document();
1008        let global = document.global();
1009
1010        // A module preload destination is "json", "style", "text" or a script-like destination.
1011        let is_a_modulepreload_destination = match destination {
1012            Destination::Json | Destination::Style | Destination::Text => true,
1013            // https://fetch.spec.whatwg.org/#ref-for-request-destination-script-like
1014            // While "xslt" can cause script execution, it is not relevant here.
1015            Destination::Xslt => false,
1016            d => d.is_script_like(),
1017        };
1018
1019        // Step 3. If destination is not a module preload destination, then queue an element task on the
1020        // networking task source given el to fire an event named error at el, and return.
1021        if !is_a_modulepreload_destination {
1022            return global
1023                .task_manager()
1024                .networking_task_source()
1025                .queue_simple_event(self.upcast(), atom!("error"));
1026        }
1027
1028        // Step 4. Let url be the result of encoding-parsing a URL given el's href attribute's value, relative to el's node document.
1029        // Step 5. If url is failure, then return.
1030        let Ok(url) = document.encoding_parse_a_url(&href_attribute_value.str()) else {
1031            return;
1032        };
1033        let url = ensure_blob_referenced_by_url_is_kept_alive(&global, url);
1034
1035        // Step 6. Let settings object be el's node document's relevant settings object.
1036
1037        // Step 7. Let credentials mode be the CORS settings attribute credentials mode for el's crossorigin attribute.
1038        let credentials_mode = cors_settings_attribute_credential_mode(el);
1039
1040        // Step 8. Let cryptographic nonce be el.[[CryptographicNonce]].
1041        let cryptographic_nonce = el.nonce_value();
1042
1043        // Step 9. Let integrity metadata be the value of el's integrity attribute, if it is specified, or the empty string otherwise.
1044        // Step 10. If el does not have an integrity attribute, then set integrity metadata to
1045        // the result of resolving a module integrity metadata with url and settings object.
1046        let integrity_metadata = el
1047            .get_attribute_string_value(&local_name!("integrity"))
1048            .unwrap_or_else(|| {
1049                global
1050                    .import_map()
1051                    .resolve_a_module_integrity_metadata(&url.url())
1052            });
1053
1054        // Step 11. Let referrer policy be the current state of el's referrerpolicy attribute.
1055        let referrer_policy = referrer_policy_for_element(el);
1056
1057        // TODO Step 12. Let fetch priority be the current state of el's fetchpriority attribute.
1058
1059        // Step 13. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce,
1060        // integrity metadata is integrity metadata, parser metadata is "not-parser-inserted",
1061        // credentials mode is credentials mode, referrer policy is referrer policy, and fetch priority is fetch priority.
1062        let options = ScriptFetchOptions {
1063            cryptographic_nonce,
1064            integrity_metadata,
1065            parser_metadata: ParserMetadata::NotParserInserted,
1066            credentials_mode,
1067            referrer_policy,
1068            render_blocking: false,
1069        };
1070
1071        let link = DomRoot::from_ref(self);
1072
1073        // Step 14. Fetch a modulepreload module script graph given url, destination, settings object, options,
1074        // and with the following steps given result:
1075        fetch_a_modulepreload_module(
1076            cx,
1077            url,
1078            destination,
1079            &global,
1080            options,
1081            move |cx, fetch_failed| {
1082                // Step 1. If result is null, then fire an event named error at el, and return.
1083                // Step 2. Fire an event named load at el.
1084                let event = match fetch_failed {
1085                    true => atom!("error"),
1086                    false => atom!("load"),
1087                };
1088
1089                link.upcast::<EventTarget>().fire_event(cx, event);
1090            },
1091        );
1092    }
1093}
1094
1095impl StylesheetOwner for HTMLLinkElement {
1096    fn increment_pending_loads_count(&self) {
1097        self.pending_loads.set(self.pending_loads.get() + 1)
1098    }
1099
1100    fn load_finished(&self, succeeded: bool) -> Option<bool> {
1101        assert!(self.pending_loads.get() > 0, "What finished?");
1102        if !succeeded {
1103            self.any_failed_load.set(true);
1104        }
1105
1106        self.pending_loads.set(self.pending_loads.get() - 1);
1107        if self.pending_loads.get() != 0 {
1108            return None;
1109        }
1110
1111        let any_failed = self.any_failed_load.get();
1112        self.any_failed_load.set(false);
1113        Some(any_failed)
1114    }
1115
1116    fn parser_inserted(&self) -> bool {
1117        self.parser_inserted.get()
1118    }
1119
1120    /// <https://html.spec.whatwg.org/multipage/#potentially-render-blocking>
1121    fn potentially_render_blocking(&self) -> bool {
1122        // An element is potentially render-blocking if its blocking tokens set contains "render",
1123        // or if it is implicitly potentially render-blocking, which will be defined at the individual elements.
1124        // By default, an element is not implicitly potentially render-blocking.
1125        //
1126        // https://html.spec.whatwg.org/multipage/#link-type-stylesheet:implicitly-potentially-render-blocking
1127        // > A link element of this type is implicitly potentially render-blocking if the element was created by its node document's parser.
1128        self.parser_inserted() ||
1129            self.blocking
1130                .get()
1131                .is_some_and(|list| list.Contains(DOMString::from_static("render")))
1132    }
1133
1134    fn referrer_policy(&self, cx: &mut js::context::JSContext) -> ReferrerPolicy {
1135        if self
1136            .RelList(cx)
1137            .Contains(DOMString::from_static("noreferrer"))
1138        {
1139            return ReferrerPolicy::NoReferrer;
1140        }
1141
1142        ReferrerPolicy::EmptyString
1143    }
1144
1145    fn set_origin_clean(&self, cx: &mut js::context::JSContext, origin_clean: bool) {
1146        if let Some(stylesheet) = self.get_cssom_stylesheet(cx) {
1147            stylesheet.set_origin_clean(origin_clean);
1148        }
1149    }
1150}
1151
1152impl HTMLLinkElementMethods<crate::DomTypeHolder> for HTMLLinkElement {
1153    // https://html.spec.whatwg.org/multipage/#dom-link-href
1154    make_url_getter!(Href, "href");
1155
1156    // https://html.spec.whatwg.org/multipage/#dom-link-href
1157    make_url_setter!(SetHref, "href");
1158
1159    // https://html.spec.whatwg.org/multipage/#dom-link-rel
1160    make_getter!(Rel, "rel");
1161
1162    /// <https://html.spec.whatwg.org/multipage/#dom-link-rel>
1163    fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
1164        self.upcast::<Element>()
1165            .set_tokenlist_attribute(cx, &local_name!("rel"), rel);
1166    }
1167
1168    // https://html.spec.whatwg.org/multipage/#dom-link-as
1169    make_enumerated_getter!(
1170        As,
1171        "as",
1172        "fetch" | "audio" | "audioworklet" | "document" | "embed" | "font" | "frame"
1173            | "iframe" | "image" | "json" | "manifest" | "object" | "paintworklet"
1174            | "report" | "script" | "serviceworker" | "sharedworker" | "style" | "track"
1175            | "video" | "webidentity" | "worker" | "xslt",
1176        missing => "",
1177        invalid => ""
1178    );
1179
1180    // https://html.spec.whatwg.org/multipage/#dom-link-as
1181    make_setter!(SetAs, "as");
1182
1183    // https://html.spec.whatwg.org/multipage/#dom-link-media
1184    make_getter!(Media, "media");
1185
1186    // https://html.spec.whatwg.org/multipage/#dom-link-media
1187    make_setter!(SetMedia, "media");
1188
1189    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1190    make_getter!(Integrity, "integrity");
1191
1192    // https://html.spec.whatwg.org/multipage/#dom-link-integrity
1193    make_setter!(SetIntegrity, "integrity");
1194
1195    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1196    make_getter!(Hreflang, "hreflang");
1197
1198    // https://html.spec.whatwg.org/multipage/#dom-link-hreflang
1199    make_setter!(SetHreflang, "hreflang");
1200
1201    // https://html.spec.whatwg.org/multipage/#dom-link-type
1202    make_getter!(Type, "type");
1203
1204    // https://html.spec.whatwg.org/multipage/#dom-link-type
1205    make_setter!(SetType, "type");
1206
1207    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1208    make_url_getter!(ImageSrcset, "imagesrcset");
1209
1210    // https://html.spec.whatwg.org/multipage/#dom-link-imagesrcset
1211    make_url_setter!(SetImageSrcset, "imagesrcset");
1212
1213    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1214    make_getter!(ImageSizes, "imagesizes");
1215
1216    // https://html.spec.whatwg.org/multipage/#dom-link-imagesizes
1217    make_setter!(SetImageSizes, "imagesizes");
1218
1219    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1220    make_bool_getter!(Disabled, "disabled");
1221
1222    // https://html.spec.whatwg.org/multipage/#dom-link-disabled
1223    make_bool_setter!(SetDisabled, "disabled");
1224
1225    /// <https://html.spec.whatwg.org/multipage/#dom-link-rellist>
1226    fn RelList(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1227        self.rel_list.or_init(|| {
1228            DOMTokenList::new(
1229                cx,
1230                self.upcast(),
1231                &local_name!("rel"),
1232                Some(vec![
1233                    Atom::from("alternate"),
1234                    Atom::from("apple-touch-icon"),
1235                    Atom::from("apple-touch-icon-precomposed"),
1236                    Atom::from("canonical"),
1237                    Atom::from("dns-prefetch"),
1238                    Atom::from("icon"),
1239                    Atom::from("import"),
1240                    Atom::from("manifest"),
1241                    Atom::from("modulepreload"),
1242                    Atom::from("next"),
1243                    Atom::from("preconnect"),
1244                    Atom::from("prefetch"),
1245                    Atom::from("preload"),
1246                    Atom::from("prerender"),
1247                    Atom::from("stylesheet"),
1248                ]),
1249            )
1250        })
1251    }
1252
1253    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1254    make_getter!(Charset, "charset");
1255
1256    // https://html.spec.whatwg.org/multipage/#dom-link-charset
1257    make_setter!(SetCharset, "charset");
1258
1259    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1260    make_getter!(Rev, "rev");
1261
1262    // https://html.spec.whatwg.org/multipage/#dom-link-rev
1263    make_setter!(SetRev, "rev");
1264
1265    // https://html.spec.whatwg.org/multipage/#dom-link-target
1266    make_getter!(Target, "target");
1267
1268    // https://html.spec.whatwg.org/multipage/#dom-link-target
1269    make_setter!(SetTarget, "target");
1270
1271    /// <https://html.spec.whatwg.org/multipage/#attr-link-blocking>
1272    fn Blocking(&self, cx: &mut js::context::JSContext) -> DomRoot<DOMTokenList> {
1273        self.blocking.or_init(|| {
1274            DOMTokenList::new(
1275                cx,
1276                self.upcast(),
1277                &local_name!("blocking"),
1278                Some(vec![Atom::from("render")]),
1279            )
1280        })
1281    }
1282
1283    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1284    fn GetCrossOrigin(&self) -> Option<DOMString> {
1285        reflect_cross_origin_attribute(self.upcast::<Element>())
1286    }
1287
1288    /// <https://html.spec.whatwg.org/multipage/#dom-link-crossorigin>
1289    fn SetCrossOrigin(&self, cx: &mut JSContext, value: Option<DOMString>) {
1290        set_cross_origin_attribute(cx, self.upcast::<Element>(), value);
1291    }
1292
1293    /// <https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy>
1294    fn ReferrerPolicy(&self) -> DOMString {
1295        reflect_referrer_policy_attribute(self.upcast::<Element>())
1296    }
1297
1298    // https://html.spec.whatwg.org/multipage/#dom-link-referrerpolicy
1299    make_setter!(SetReferrerPolicy, "referrerpolicy");
1300
1301    /// <https://drafts.csswg.org/cssom/#dom-linkstyle-sheet>
1302    fn GetSheet(&self, cx: &mut JSContext) -> Option<DomRoot<DOMStyleSheet>> {
1303        self.get_cssom_stylesheet(cx).map(DomRoot::upcast)
1304    }
1305}
1306
1307struct FaviconFetchContext {
1308    image_cache: std::sync::Arc<dyn ImageCache>,
1309    id: PendingImageId,
1310
1311    /// The base url of the document that the `<link>` element belongs to.
1312    url: ServoUrl,
1313}
1314
1315impl FetchResponseListener for FaviconFetchContext {
1316    fn process_request_body(&mut self, _: &GlobalScope, _: RequestId) {}
1317
1318    fn process_response(
1319        &mut self,
1320        _: &mut js::context::JSContext,
1321        _: &GlobalScope,
1322        request_id: RequestId,
1323        metadata: Result<FetchMetadata, NetworkError>,
1324    ) {
1325        self.image_cache.notify_pending_response(
1326            self.id,
1327            FetchResponseMsg::ProcessResponse(request_id, metadata),
1328        );
1329    }
1330
1331    fn process_response_chunk(
1332        &mut self,
1333        _: &mut js::context::JSContext,
1334        _: &GlobalScope,
1335        request_id: RequestId,
1336        chunk: Bytes,
1337    ) {
1338        self.image_cache.notify_pending_response(
1339            self.id,
1340            FetchResponseMsg::ProcessResponseChunk(request_id, chunk),
1341        );
1342    }
1343
1344    fn process_response_eof(
1345        self,
1346        cx: &mut js::context::JSContext,
1347        global: &GlobalScope,
1348        request_id: RequestId,
1349        response: Result<(), NetworkError>,
1350        timing: ResourceFetchTiming,
1351    ) {
1352        self.image_cache.notify_pending_response(
1353            self.id,
1354            FetchResponseMsg::ProcessResponseEOF(request_id, response.clone(), timing.clone()),
1355        );
1356        submit_timing(cx, global, &self, &response, &timing);
1357    }
1358
1359    fn process_csp_violations(
1360        &mut self,
1361        cx: &mut js::context::JSContext,
1362        global: &GlobalScope,
1363        _request_id: RequestId,
1364        violations: Vec<Violation>,
1365    ) {
1366        global.report_csp_violations(cx, violations, None, None);
1367    }
1368
1369    fn process_content_length(&mut self, request_id: RequestId, size: usize) {
1370        self.image_cache.notify_pending_response(
1371            self.id,
1372            FetchResponseMsg::ProcessContentLength(request_id, size),
1373        )
1374    }
1375}
1376
1377impl ResourceTimingListener for FaviconFetchContext {
1378    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
1379        (InitiatorType::LocalName("link".into()), self.url.clone())
1380    }
1381}