script/dom/html/
htmlanchorelement.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::default::Default;
7
8use dom_struct::dom_struct;
9use html5ever::{LocalName, Prefix, local_name};
10use js::rust::HandleObject;
11use num_traits::ToPrimitive;
12use servo_url::ServoUrl;
13use style::attr::AttrValue;
14use stylo_atoms::Atom;
15use stylo_dom::ElementState;
16use xml5ever::ns;
17
18use crate::dom::activation::Activatable;
19use crate::dom::attr::Attr;
20use crate::dom::bindings::cell::DomRefCell;
21use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
22use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
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, USVString};
27use crate::dom::document::Document;
28use crate::dom::domtokenlist::DOMTokenList;
29use crate::dom::element::{AttributeMutation, Element, reflect_referrer_policy_attribute};
30use crate::dom::event::Event;
31use crate::dom::eventtarget::EventTarget;
32use crate::dom::html::htmlelement::HTMLElement;
33use crate::dom::html::htmlhyperlinkelementutils::{HyperlinkElement, HyperlinkElementTraits};
34use crate::dom::html::htmlimageelement::HTMLImageElement;
35use crate::dom::mouseevent::MouseEvent;
36use crate::dom::node::{BindContext, Node, NodeTraits};
37use crate::dom::virtualmethods::VirtualMethods;
38use crate::links::{LinkRelations, follow_hyperlink};
39use crate::script_runtime::CanGc;
40
41#[dom_struct]
42pub(crate) struct HTMLAnchorElement {
43    htmlelement: HTMLElement,
44    rel_list: MutNullableDom<DOMTokenList>,
45    #[no_trace]
46    relations: Cell<LinkRelations>,
47    #[no_trace]
48    url: DomRefCell<Option<ServoUrl>>,
49}
50
51impl HTMLAnchorElement {
52    fn new_inherited(
53        local_name: LocalName,
54        prefix: Option<Prefix>,
55        document: &Document,
56    ) -> HTMLAnchorElement {
57        HTMLAnchorElement {
58            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
59            rel_list: Default::default(),
60            relations: Cell::new(LinkRelations::empty()),
61            url: DomRefCell::new(None),
62        }
63    }
64
65    pub(crate) fn new(
66        local_name: LocalName,
67        prefix: Option<Prefix>,
68        document: &Document,
69        proto: Option<HandleObject>,
70        can_gc: CanGc,
71    ) -> DomRoot<HTMLAnchorElement> {
72        Node::reflect_node_with_proto(
73            Box::new(HTMLAnchorElement::new_inherited(
74                local_name, prefix, document,
75            )),
76            document,
77            proto,
78            can_gc,
79        )
80    }
81
82    /// Get the full URL of the `href` attribute of this `<a>` element, returning `None` if
83    /// the URL could not be joined with the `Document` URL.
84    pub(crate) fn full_href_url_for_user_interface(&self) -> Option<ServoUrl> {
85        self.upcast::<Element>()
86            .get_attribute(&ns!(), &local_name!("href"))?;
87        self.owner_document().base_url().join(&self.Href()).ok()
88    }
89}
90
91impl HyperlinkElement for HTMLAnchorElement {
92    fn get_url(&self) -> &DomRefCell<Option<ServoUrl>> {
93        &self.url
94    }
95}
96
97impl VirtualMethods for HTMLAnchorElement {
98    fn super_type(&self) -> Option<&dyn VirtualMethods> {
99        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
100    }
101
102    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
103        match name {
104            &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
105            _ => self
106                .super_type()
107                .unwrap()
108                .parse_plain_attribute(name, value),
109        }
110    }
111
112    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation, can_gc: CanGc) {
113        self.super_type()
114            .unwrap()
115            .attribute_mutated(attr, mutation, can_gc);
116
117        match *attr.local_name() {
118            local_name!("href") => self
119                .upcast::<Element>()
120                .set_state(ElementState::UNVISITED, !mutation.is_removal()),
121            local_name!("rel") | local_name!("rev") => {
122                self.relations
123                    .set(LinkRelations::for_element(self.upcast()));
124            },
125            _ => {},
126        }
127    }
128
129    fn bind_to_tree(&self, context: &BindContext, can_gc: CanGc) {
130        if let Some(s) = self.super_type() {
131            s.bind_to_tree(context, can_gc);
132        }
133
134        self.relations
135            .set(LinkRelations::for_element(self.upcast()));
136    }
137}
138
139impl HTMLAnchorElementMethods<crate::DomTypeHolder> for HTMLAnchorElement {
140    /// <https://html.spec.whatwg.org/multipage/#dom-a-text>
141    fn Text(&self) -> DOMString {
142        self.upcast::<Node>().GetTextContent().unwrap()
143    }
144
145    /// <https://html.spec.whatwg.org/multipage/#dom-a-text>
146    fn SetText(&self, value: DOMString, can_gc: CanGc) {
147        self.upcast::<Node>()
148            .set_text_content_for_element(Some(value), can_gc)
149    }
150
151    // https://html.spec.whatwg.org/multipage/#dom-a-rel
152    make_getter!(Rel, "rel");
153
154    /// <https://html.spec.whatwg.org/multipage/#dom-a-rel>
155    fn SetRel(&self, rel: DOMString, can_gc: CanGc) {
156        self.upcast::<Element>()
157            .set_tokenlist_attribute(&local_name!("rel"), rel, can_gc);
158    }
159
160    /// <https://html.spec.whatwg.org/multipage/#dom-a-rellist>
161    fn RelList(&self, can_gc: CanGc) -> DomRoot<DOMTokenList> {
162        self.rel_list.or_init(|| {
163            DOMTokenList::new(
164                self.upcast(),
165                &local_name!("rel"),
166                Some(vec![
167                    Atom::from("noopener"),
168                    Atom::from("noreferrer"),
169                    Atom::from("opener"),
170                ]),
171                can_gc,
172            )
173        })
174    }
175
176    // https://html.spec.whatwg.org/multipage/#dom-a-coords
177    make_getter!(Coords, "coords");
178
179    // https://html.spec.whatwg.org/multipage/#dom-a-coords
180    make_setter!(SetCoords, "coords");
181
182    // https://html.spec.whatwg.org/multipage/#dom-a-name
183    make_getter!(Name, "name");
184
185    // https://html.spec.whatwg.org/multipage/#dom-a-name
186    make_atomic_setter!(SetName, "name");
187
188    // https://html.spec.whatwg.org/multipage/#dom-a-rev
189    make_getter!(Rev, "rev");
190
191    // https://html.spec.whatwg.org/multipage/#dom-a-rev
192    make_setter!(SetRev, "rev");
193
194    // https://html.spec.whatwg.org/multipage/#dom-a-shape
195    make_getter!(Shape, "shape");
196
197    // https://html.spec.whatwg.org/multipage/#dom-a-shape
198    make_setter!(SetShape, "shape");
199
200    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
201    make_getter!(Target, "target");
202
203    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
204    make_setter!(SetTarget, "target");
205
206    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-href>
207    fn Href(&self) -> USVString {
208        self.get_href()
209    }
210
211    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-href>
212    fn SetHref(&self, value: USVString, can_gc: CanGc) {
213        self.set_href(value, can_gc);
214    }
215
216    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-origin>
217    fn Origin(&self) -> USVString {
218        self.get_origin()
219    }
220
221    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol>
222    fn Protocol(&self) -> USVString {
223        self.get_protocol()
224    }
225
226    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol>
227    fn SetProtocol(&self, value: USVString, can_gc: CanGc) {
228        self.set_protocol(value, can_gc);
229    }
230
231    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-password>
232    fn Password(&self) -> USVString {
233        self.get_password()
234    }
235
236    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-password>
237    fn SetPassword(&self, value: USVString, can_gc: CanGc) {
238        self.set_password(value, can_gc);
239    }
240
241    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash>
242    fn Hash(&self) -> USVString {
243        self.get_hash()
244    }
245
246    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash>
247    fn SetHash(&self, value: USVString, can_gc: CanGc) {
248        self.set_hash(value, can_gc);
249    }
250
251    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-host>
252    fn Host(&self) -> USVString {
253        self.get_host()
254    }
255
256    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-host>
257    fn SetHost(&self, value: USVString, can_gc: CanGc) {
258        self.set_host(value, can_gc);
259    }
260
261    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname>
262    fn Hostname(&self) -> USVString {
263        self.get_hostname()
264    }
265
266    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname>
267    fn SetHostname(&self, value: USVString, can_gc: CanGc) {
268        self.set_hostname(value, can_gc);
269    }
270
271    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-port>
272    fn Port(&self) -> USVString {
273        self.get_port()
274    }
275
276    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-port>
277    fn SetPort(&self, value: USVString, can_gc: CanGc) {
278        self.set_port(value, can_gc);
279    }
280
281    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname>
282    fn Pathname(&self) -> USVString {
283        self.get_pathname()
284    }
285
286    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname>
287    fn SetPathname(&self, value: USVString, can_gc: CanGc) {
288        self.set_pathname(value, can_gc);
289    }
290
291    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-search>
292    fn Search(&self) -> USVString {
293        self.get_search()
294    }
295
296    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-search>
297    fn SetSearch(&self, value: USVString, can_gc: CanGc) {
298        self.set_search(value, can_gc);
299    }
300
301    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-username>
302    fn Username(&self) -> USVString {
303        self.get_username()
304    }
305
306    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-username>
307    fn SetUsername(&self, value: USVString, can_gc: CanGc) {
308        self.set_username(value, can_gc);
309    }
310
311    /// <https://html.spec.whatwg.org/multipage/#dom-a-referrerpolicy>
312    fn ReferrerPolicy(&self) -> DOMString {
313        reflect_referrer_policy_attribute(self.upcast::<Element>())
314    }
315
316    // https://html.spec.whatwg.org/multipage/#dom-script-referrerpolicy
317    make_setter!(SetReferrerPolicy, "referrerpolicy");
318}
319
320impl Activatable for HTMLAnchorElement {
321    fn as_element(&self) -> &Element {
322        self.upcast::<Element>()
323    }
324
325    fn is_instance_activatable(&self) -> bool {
326        // https://html.spec.whatwg.org/multipage/#hyperlink
327        // "a [...] element[s] with an href attribute [...] must [..] create a
328        // hyperlink"
329        // https://html.spec.whatwg.org/multipage/#the-a-element
330        // "The activation behaviour of a elements *that create hyperlinks*"
331        self.as_element().has_attribute(&local_name!("href"))
332    }
333
334    /// <https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour>
335    fn activation_behavior(&self, event: &Event, target: &EventTarget, _: CanGc) {
336        let element = self.as_element();
337        let mouse_event = event.downcast::<MouseEvent>().unwrap();
338        let mut ismap_suffix = None;
339
340        // Step 1: If the target of the click event is an img element with an ismap attribute
341        // specified, then server-side image map processing must be performed.
342        if let Some(element) = target.downcast::<Element>() {
343            if target.is::<HTMLImageElement>() && element.has_attribute(&local_name!("ismap")) {
344                let target_node = element.upcast::<Node>();
345                let rect = target_node.border_box().unwrap_or_default();
346                ismap_suffix = Some(format!(
347                    "?{},{}",
348                    mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
349                    mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px()
350                ))
351            }
352        }
353
354        // Step 2.
355        // TODO: Download the link is `download` attribute is set.
356        follow_hyperlink(element, self.relations.get(), ismap_suffix);
357    }
358}