Skip to main content

script/dom/html/document_metadata/
htmlbaseelement.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 dom_struct::dom_struct;
6use html5ever::{LocalName, Prefix, local_name};
7use js::context::JSContext;
8use js::rust::HandleObject;
9use script_bindings::cell::DomRefCell;
10use servo_url::ServoUrl;
11
12use crate::dom::MoveContext;
13use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods;
14use crate::dom::bindings::inheritance::Castable;
15use crate::dom::bindings::root::DomRoot;
16use crate::dom::bindings::str::DOMString;
17use crate::dom::document::Document;
18use crate::dom::element::attributes::storage::AttrRef;
19use crate::dom::element::{AttributeMutation, Element};
20use crate::dom::globalscope::GlobalScope;
21use crate::dom::html::htmlelement::HTMLElement;
22use crate::dom::node::virtualmethods::VirtualMethods;
23use crate::dom::node::{BindContext, Node, NodeTraits, UnbindContext};
24use crate::dom::security::csp::CspReporting;
25
26#[dom_struct]
27pub(crate) struct HTMLBaseElement {
28    htmlelement: HTMLElement,
29
30    /// <https://html.spec.whatwg.org/multipage/#frozen-base-url>
31    #[no_trace]
32    frozen_base_url: DomRefCell<Option<ServoUrl>>,
33}
34
35impl HTMLBaseElement {
36    fn new_inherited(
37        local_name: LocalName,
38        prefix: Option<Prefix>,
39        document: &Document,
40    ) -> HTMLBaseElement {
41        HTMLBaseElement {
42            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
43            frozen_base_url: Default::default(),
44        }
45    }
46
47    pub(crate) fn new(
48        cx: &mut js::context::JSContext,
49        local_name: LocalName,
50        prefix: Option<Prefix>,
51        document: &Document,
52        proto: Option<HandleObject>,
53    ) -> DomRoot<HTMLBaseElement> {
54        Node::reflect_node_with_proto(
55            cx,
56            Box::new(HTMLBaseElement::new_inherited(local_name, prefix, document)),
57            document,
58            proto,
59        )
60    }
61
62    pub(crate) fn clear_frozen_base_url(&self) {
63        *self.frozen_base_url.borrow_mut() = None;
64    }
65
66    /// <https://html.spec.whatwg.org/multipage/#set-the-frozen-base-url>
67    pub(crate) fn set_frozen_base_url(&self, cx: &mut JSContext) {
68        // Step 1. Let document be element's node document.
69        let document = self.owner_document();
70        // Step 2. Let urlRecord be the result of parsing the value of element's href content attribute
71        // with document's fallback base URL, and document's character encoding. (Thus, the base element isn't affected by itself.)
72        let href_value = self
73            .upcast::<Element>()
74            .get_attribute_string_ref(&local_name!("href"))
75            .expect("Must always have a href set when setting frozen base URL");
76        let href_value = href_value.as_attr_ref().value();
77        let document_fallback_url = document.fallback_base_url();
78        let url_record = document_fallback_url.join(&href_value).ok();
79        // Step 3. If any of the following are true:
80        if
81        // urlRecord is failure;
82        url_record.as_ref().is_none_or(|url_record|
83            // urlRecord's scheme is "data" or "javascript"; or
84            url_record.scheme() == "data" || url_record.scheme() == "javascript"
85            // running Is base allowed for Document? on urlRecord and document returns "Blocked",
86            || !document
87                .get_csp_list()
88                .is_base_allowed_for_document(
89                    cx,
90                    document.window().upcast::<GlobalScope>(),
91                    &url_record.clone().into_url(),
92                    &document.origin().immutable().clone().into_url_origin(),
93                ))
94        {
95            // then set element's frozen base URL to document's fallback base URL and return.
96            *self.frozen_base_url.safe_borrow_mut(cx.no_gc()) = Some(document_fallback_url);
97            return;
98        }
99        // Step 4. Set element's frozen base URL to urlRecord.
100        *self.frozen_base_url.safe_borrow_mut(cx.no_gc()) = url_record;
101        // Step 5. Respond to base URL changes given document.
102        // TODO
103    }
104
105    /// <https://html.spec.whatwg.org/multipage/#frozen-base-url>
106    pub(crate) fn frozen_base_url(&self) -> ServoUrl {
107        self.frozen_base_url
108            .borrow()
109            .clone()
110            .expect("Must only retrieve frozen base URL for valid base elements")
111    }
112}
113
114impl HTMLBaseElementMethods<crate::DomTypeHolder> for HTMLBaseElement {
115    /// <https://html.spec.whatwg.org/multipage/#dom-base-href>
116    fn Href(&self) -> DOMString {
117        // Step 1. Let document be element's node document.
118        let document = self.owner_document();
119
120        // Step 2. Let url be the value of the href attribute of this element, if it has one, and the empty string otherwise.
121        let url = self
122            .upcast::<Element>()
123            .get_attribute_string_value(&local_name!("href"))
124            .unwrap_or_default();
125
126        // Step 3. Let urlRecord be the result of parsing url with document's fallback base URL,
127        // and document's character encoding. (Thus, the base element isn't affected by other base elements or itself.)
128        let url_record = document.fallback_base_url().join(&url);
129
130        match url_record {
131            Err(_) => {
132                // Step 4. If urlRecord is failure, return url.
133                url.into()
134            },
135            Ok(url_record) => {
136                // Step 5. Return the serialization of urlRecord.
137                url_record.into_string().into()
138            },
139        }
140    }
141
142    // https://html.spec.whatwg.org/multipage/#dom-base-href
143    make_setter!(SetHref, "href");
144
145    // https://html.spec.whatwg.org/multipage/#dom-base-target
146    make_getter!(Target, "target");
147
148    // https://html.spec.whatwg.org/multipage/#dom-base-target
149    make_setter!(SetTarget, "target");
150}
151
152impl VirtualMethods for HTMLBaseElement {
153    fn super_type(&self) -> Option<&dyn VirtualMethods> {
154        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
155    }
156
157    fn attribute_mutated(
158        &self,
159        cx: &mut js::context::JSContext,
160        attr: AttrRef<'_>,
161        mutation: AttributeMutation,
162    ) {
163        self.super_type()
164            .unwrap()
165            .attribute_mutated(cx, attr, mutation);
166
167        // https://html.spec.whatwg.org/multipage/#frozen-base-url
168        if *attr.local_name() == local_name!("href") {
169            // > The base element is the first base element in tree order with an href content attribute in its Document,
170            // > and its href content attribute is changed.
171            if self.frozen_base_url.borrow().is_some() && !mutation.is_removal() {
172                self.set_frozen_base_url(cx);
173            } else {
174                // > The base element becomes the first base element in tree order with an href content attribute in its Document.
175                let document = self.owner_document();
176                document.refresh_base_element(cx);
177            }
178        }
179    }
180
181    fn bind_to_tree(&self, cx: &mut JSContext, context: &BindContext) {
182        self.super_type().unwrap().bind_to_tree(cx, context);
183        // https://html.spec.whatwg.org/multipage/#frozen-base-url
184        // > The base element becomes the first base element in tree order with an href content
185        // > attribute in its Document.
186        self.owner_document().refresh_base_element(cx);
187    }
188
189    fn moving_steps(&self, cx: &mut JSContext, context: &MoveContext) {
190        if let Some(super_type) = self.super_type() {
191            super_type.moving_steps(cx, context);
192        }
193        // https://html.spec.whatwg.org/multipage/#frozen-base-url
194        // > The base element becomes the first base element in tree order with an href content
195        // > attribute in its Document.
196        self.owner_document().refresh_base_element(cx);
197    }
198
199    fn unbind_from_tree(&self, cx: &mut JSContext, context: &UnbindContext) {
200        self.super_type().unwrap().unbind_from_tree(cx, context);
201        // https://html.spec.whatwg.org/multipage/#frozen-base-url
202        // > The base element becomes the first base element in tree order with an href content attribute in its Document.
203        let document = self.owner_document();
204        document.refresh_base_element(cx);
205    }
206}