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::context::JSContext;
11use js::rust::HandleObject;
12use num_traits::ToPrimitive;
13use servo_url::ServoUrl;
14use style::attr::AttrValue;
15use stylo_atoms::Atom;
16use stylo_dom::ElementState;
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::{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        cx: &mut js::context::JSContext,
67        local_name: LocalName,
68        prefix: Option<Prefix>,
69        document: &Document,
70        proto: Option<HandleObject>,
71    ) -> DomRoot<HTMLAnchorElement> {
72        Node::reflect_node_with_proto(
73            cx,
74            Box::new(HTMLAnchorElement::new_inherited(
75                local_name, prefix, document,
76            )),
77            document,
78            proto,
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(&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(
113        &self,
114        cx: &mut js::context::JSContext,
115        attr: &Attr,
116        mutation: AttributeMutation,
117    ) {
118        self.super_type()
119            .unwrap()
120            .attribute_mutated(cx, attr, mutation);
121
122        match *attr.local_name() {
123            local_name!("href") => self
124                .upcast::<Element>()
125                .set_state(ElementState::UNVISITED, !mutation.is_removal()),
126            local_name!("rel") | local_name!("rev") => {
127                self.relations
128                    .set(LinkRelations::for_element(self.upcast()));
129            },
130            _ => {},
131        }
132    }
133}
134
135impl HTMLAnchorElementMethods<crate::DomTypeHolder> for HTMLAnchorElement {
136    /// <https://html.spec.whatwg.org/multipage/#dom-a-text>
137    fn Text(&self) -> DOMString {
138        self.upcast::<Node>().GetTextContent().unwrap()
139    }
140
141    /// <https://html.spec.whatwg.org/multipage/#dom-a-text>
142    fn SetText(&self, cx: &mut JSContext, value: DOMString) {
143        self.upcast::<Node>()
144            .set_text_content_for_element(cx, Some(value))
145    }
146
147    // https://html.spec.whatwg.org/multipage/#dom-a-rel
148    make_getter!(Rel, "rel");
149
150    /// <https://html.spec.whatwg.org/multipage/#dom-a-rel>
151    fn SetRel(&self, cx: &mut JSContext, rel: DOMString) {
152        self.upcast::<Element>().set_tokenlist_attribute(
153            &local_name!("rel"),
154            rel,
155            CanGc::from_cx(cx),
156        );
157    }
158
159    /// <https://html.spec.whatwg.org/multipage/#dom-a-rellist>
160    fn RelList(&self, cx: &mut JSContext) -> DomRoot<DOMTokenList> {
161        self.rel_list.or_init(|| {
162            DOMTokenList::new(
163                self.upcast(),
164                &local_name!("rel"),
165                Some(vec![
166                    Atom::from("noopener"),
167                    Atom::from("noreferrer"),
168                    Atom::from("opener"),
169                ]),
170                CanGc::from_cx(cx),
171            )
172        })
173    }
174
175    // https://html.spec.whatwg.org/multipage/#dom-a-hreflang
176    make_getter!(Hreflang, "hreflang");
177
178    // https://html.spec.whatwg.org/multipage/#dom-a-hreflang
179    make_setter!(cx, SetHreflang, "hreflang");
180
181    // https://html.spec.whatwg.org/multipage/#dom-a-type
182    make_getter!(Type, "type");
183
184    // https://html.spec.whatwg.org/multipage/#dom-a-type
185    make_setter!(cx, SetType, "type");
186
187    // https://html.spec.whatwg.org/multipage/#dom-a-coords
188    make_getter!(Coords, "coords");
189
190    // https://html.spec.whatwg.org/multipage/#dom-a-coords
191    make_setter!(cx, SetCoords, "coords");
192
193    // https://html.spec.whatwg.org/multipage/#dom-a-charset
194    make_getter!(Charset, "charset");
195
196    // https://html.spec.whatwg.org/multipage/#dom-a-charset
197    make_setter!(cx, SetCharset, "charset");
198
199    // https://html.spec.whatwg.org/multipage/#dom-a-name
200    make_getter!(Name, "name");
201
202    // https://html.spec.whatwg.org/multipage/#dom-a-name
203    make_atomic_setter!(cx, SetName, "name");
204
205    // https://html.spec.whatwg.org/multipage/#dom-a-rev
206    make_getter!(Rev, "rev");
207
208    // https://html.spec.whatwg.org/multipage/#dom-a-rev
209    make_setter!(cx, SetRev, "rev");
210
211    // https://html.spec.whatwg.org/multipage/#dom-a-shape
212    make_getter!(Shape, "shape");
213
214    // https://html.spec.whatwg.org/multipage/#dom-a-shape
215    make_setter!(cx, SetShape, "shape");
216
217    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
218    make_getter!(Target, "target");
219
220    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
221    make_setter!(cx, SetTarget, "target");
222
223    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-href>
224    fn Href(&self) -> USVString {
225        self.get_href()
226    }
227
228    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-href>
229    fn SetHref(&self, cx: &mut JSContext, value: USVString) {
230        self.set_href(cx, value);
231    }
232
233    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-origin>
234    fn Origin(&self) -> USVString {
235        self.get_origin()
236    }
237
238    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol>
239    fn Protocol(&self) -> USVString {
240        self.get_protocol()
241    }
242
243    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol>
244    fn SetProtocol(&self, cx: &mut JSContext, value: USVString) {
245        self.set_protocol(cx, value);
246    }
247
248    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-password>
249    fn Password(&self) -> USVString {
250        self.get_password()
251    }
252
253    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-password>
254    fn SetPassword(&self, cx: &mut JSContext, value: USVString) {
255        self.set_password(cx, value);
256    }
257
258    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash>
259    fn Hash(&self) -> USVString {
260        self.get_hash()
261    }
262
263    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash>
264    fn SetHash(&self, cx: &mut JSContext, value: USVString) {
265        self.set_hash(cx, value);
266    }
267
268    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-host>
269    fn Host(&self) -> USVString {
270        self.get_host()
271    }
272
273    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-host>
274    fn SetHost(&self, cx: &mut JSContext, value: USVString) {
275        self.set_host(cx, value);
276    }
277
278    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname>
279    fn Hostname(&self) -> USVString {
280        self.get_hostname()
281    }
282
283    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname>
284    fn SetHostname(&self, cx: &mut JSContext, value: USVString) {
285        self.set_hostname(cx, value);
286    }
287
288    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-port>
289    fn Port(&self) -> USVString {
290        self.get_port()
291    }
292
293    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-port>
294    fn SetPort(&self, cx: &mut JSContext, value: USVString) {
295        self.set_port(cx, value);
296    }
297
298    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname>
299    fn Pathname(&self) -> USVString {
300        self.get_pathname()
301    }
302
303    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname>
304    fn SetPathname(&self, cx: &mut JSContext, value: USVString) {
305        self.set_pathname(cx, value);
306    }
307
308    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-search>
309    fn Search(&self) -> USVString {
310        self.get_search()
311    }
312
313    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-search>
314    fn SetSearch(&self, cx: &mut JSContext, value: USVString) {
315        self.set_search(cx, value);
316    }
317
318    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-username>
319    fn Username(&self) -> USVString {
320        self.get_username()
321    }
322
323    /// <https://html.spec.whatwg.org/multipage/#dom-hyperlink-username>
324    fn SetUsername(&self, cx: &mut JSContext, value: USVString) {
325        self.set_username(cx, value);
326    }
327
328    /// <https://html.spec.whatwg.org/multipage/#dom-a-referrerpolicy>
329    fn ReferrerPolicy(&self) -> DOMString {
330        reflect_referrer_policy_attribute(self.upcast::<Element>())
331    }
332
333    // https://html.spec.whatwg.org/multipage/#dom-script-referrerpolicy
334    make_setter!(cx, SetReferrerPolicy, "referrerpolicy");
335}
336
337impl Activatable for HTMLAnchorElement {
338    fn as_element(&self) -> &Element {
339        self.upcast::<Element>()
340    }
341
342    fn is_instance_activatable(&self) -> bool {
343        // https://html.spec.whatwg.org/multipage/#hyperlink
344        // "a [...] element[s] with an href attribute [...] must [..] create a
345        // hyperlink"
346        // https://html.spec.whatwg.org/multipage/#the-a-element
347        // "The activation behaviour of a elements *that create hyperlinks*"
348        self.as_element().has_attribute(&local_name!("href"))
349    }
350
351    /// <https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour>
352    fn activation_behavior(
353        &self,
354        _cx: &mut js::context::JSContext,
355        event: &Event,
356        target: &EventTarget,
357    ) {
358        let element = self.as_element();
359        let mouse_event = event.downcast::<MouseEvent>().unwrap();
360        let mut ismap_suffix = None;
361
362        // Step 1: If the target of the click event is an img element with an ismap attribute
363        // specified, then server-side image map processing must be performed.
364        if let Some(element) = target.downcast::<Element>() {
365            if target.is::<HTMLImageElement>() && element.has_attribute(&local_name!("ismap")) {
366                let target_node = element.upcast::<Node>();
367                let rect = target_node.border_box().unwrap_or_default();
368                ismap_suffix = Some(format!(
369                    "?{},{}",
370                    mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
371                    mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px()
372                ))
373            }
374        }
375
376        // Step 2.
377        // TODO: Download the link is `download` attribute is set.
378        follow_hyperlink(element, self.relations.get(), ismap_suffix);
379    }
380}