1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use std::cell::Cell;
use std::default::Default;

use dom_struct::dom_struct;
use html5ever::{local_name, namespace_url, ns, LocalName, Prefix};
use js::rust::HandleObject;
use num_traits::ToPrimitive;
use servo_atoms::Atom;
use servo_url::ServoUrl;
use style::attr::AttrValue;

use crate::dom::activation::Activatable;
use crate::dom::attr::Attr;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods;
use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods;
use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::root::{DomRoot, MutNullableDom};
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::document::Document;
use crate::dom::domtokenlist::DOMTokenList;
use crate::dom::element::{AttributeMutation, Element};
use crate::dom::event::Event;
use crate::dom::eventtarget::EventTarget;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::htmlimageelement::HTMLImageElement;
use crate::dom::mouseevent::MouseEvent;
use crate::dom::node::{document_from_node, BindContext, Node};
use crate::dom::urlhelper::UrlHelper;
use crate::dom::virtualmethods::VirtualMethods;
use crate::links::{follow_hyperlink, LinkRelations};
use crate::script_runtime::CanGc;

#[dom_struct]
pub struct HTMLAnchorElement {
    htmlelement: HTMLElement,
    rel_list: MutNullableDom<DOMTokenList>,

    #[no_trace]
    relations: Cell<LinkRelations>,
    #[no_trace]
    url: DomRefCell<Option<ServoUrl>>,
}

impl HTMLAnchorElement {
    fn new_inherited(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
    ) -> HTMLAnchorElement {
        HTMLAnchorElement {
            htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
            rel_list: Default::default(),
            relations: Cell::new(LinkRelations::empty()),
            url: DomRefCell::new(None),
        }
    }

    #[allow(crown::unrooted_must_root)]
    pub fn new(
        local_name: LocalName,
        prefix: Option<Prefix>,
        document: &Document,
        proto: Option<HandleObject>,
        can_gc: CanGc,
    ) -> DomRoot<HTMLAnchorElement> {
        Node::reflect_node_with_proto(
            Box::new(HTMLAnchorElement::new_inherited(
                local_name, prefix, document,
            )),
            document,
            proto,
            can_gc,
        )
    }

    /// <https://html.spec.whatwg.org/multipage/#concept-hyperlink-url-set>
    fn set_url(&self) {
        // Step 1. Set this element's url to null.
        *self.url.borrow_mut() = None;

        // Step 2. If this element's href content attribute is absent, then return.
        let attribute = self
            .upcast::<Element>()
            .get_attribute(&ns!(), &local_name!("href"));

        let Some(attribute) = attribute else {
            return;
        };

        // Step 3. Let url be the result of encoding-parsing a URL given this element's
        // href content attribute's value, relative to this element's node document.
        let document = document_from_node(self);
        let url = document.encoding_parse_a_url(&attribute.value());

        // Step 4. If url is not failure, then set this element's url to url.
        if let Ok(url) = url {
            *self.url.borrow_mut() = Some(url);
        }
    }

    // https://html.spec.whatwg.org/multipage/#reinitialise-url
    fn reinitialize_url(&self) {
        // Step 1.
        match *self.url.borrow() {
            Some(ref url) if url.scheme() == "blob" && url.cannot_be_a_base() => return,
            _ => (),
        }

        // Step 2.
        self.set_url();
    }

    // https://html.spec.whatwg.org/multipage/#update-href
    fn update_href(&self, url: DOMString, can_gc: CanGc) {
        self.upcast::<Element>()
            .set_string_attribute(&local_name!("href"), url, can_gc);
    }
}

impl VirtualMethods for HTMLAnchorElement {
    fn super_type(&self) -> Option<&dyn VirtualMethods> {
        Some(self.upcast::<HTMLElement>() as &dyn VirtualMethods)
    }

    fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
        match name {
            &local_name!("rel") => AttrValue::from_serialized_tokenlist(value.into()),
            _ => self
                .super_type()
                .unwrap()
                .parse_plain_attribute(name, value),
        }
    }

    fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
        self.super_type().unwrap().attribute_mutated(attr, mutation);

        match *attr.local_name() {
            local_name!("rel") | local_name!("rev") => {
                self.relations
                    .set(LinkRelations::for_element(self.upcast()));
            },
            _ => {},
        }
    }

    fn bind_to_tree(&self, context: &BindContext) {
        if let Some(s) = self.super_type() {
            s.bind_to_tree(context);
        }

        self.relations
            .set(LinkRelations::for_element(self.upcast()));
    }
}

impl HTMLAnchorElementMethods<crate::DomTypeHolder> for HTMLAnchorElement {
    // https://html.spec.whatwg.org/multipage/#dom-a-text
    fn Text(&self) -> DOMString {
        self.upcast::<Node>().GetTextContent().unwrap()
    }

    // https://html.spec.whatwg.org/multipage/#dom-a-text
    fn SetText(&self, value: DOMString, can_gc: CanGc) {
        self.upcast::<Node>().SetTextContent(Some(value), can_gc)
    }

    // https://html.spec.whatwg.org/multipage/#dom-a-rel
    make_getter!(Rel, "rel");

    // https://html.spec.whatwg.org/multipage/#dom-a-rel
    fn SetRel(&self, rel: DOMString, can_gc: CanGc) {
        self.upcast::<Element>()
            .set_tokenlist_attribute(&local_name!("rel"), rel, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-a-rellist
    fn RelList(&self) -> DomRoot<DOMTokenList> {
        self.rel_list.or_init(|| {
            DOMTokenList::new(
                self.upcast(),
                &local_name!("rel"),
                Some(vec![
                    Atom::from("noopener"),
                    Atom::from("noreferrer"),
                    Atom::from("opener"),
                ]),
            )
        })
    }

    // https://html.spec.whatwg.org/multipage/#dom-a-coords
    make_getter!(Coords, "coords");

    // https://html.spec.whatwg.org/multipage/#dom-a-coords
    make_setter!(SetCoords, "coords");

    // https://html.spec.whatwg.org/multipage/#dom-a-name
    make_getter!(Name, "name");

    // https://html.spec.whatwg.org/multipage/#dom-a-name
    make_atomic_setter!(SetName, "name");

    // https://html.spec.whatwg.org/multipage/#dom-a-rev
    make_getter!(Rev, "rev");

    // https://html.spec.whatwg.org/multipage/#dom-a-rev
    make_setter!(SetRev, "rev");

    // https://html.spec.whatwg.org/multipage/#dom-a-shape
    make_getter!(Shape, "shape");

    // https://html.spec.whatwg.org/multipage/#dom-a-shape
    make_setter!(SetShape, "shape");

    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
    make_getter!(Target, "target");

    // https://html.spec.whatwg.org/multipage/#attr-hyperlink-target
    make_setter!(SetTarget, "target");

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash
    fn Hash(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            Some(ref url) => {
                // Steps 3-4.
                UrlHelper::Hash(url)
            },
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-hash
    fn SetHash(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.scheme() == "javascript" => return,
            None => return,
            // Steps 4-5.
            Some(url) => {
                UrlHelper::SetHash(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 6.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-host
    fn Host(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            Some(ref url) => {
                if url.host().is_none() {
                    USVString(String::new())
                } else {
                    // Steps 4-5.
                    UrlHelper::Host(url)
                }
            },
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-host
    fn SetHost(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.cannot_be_a_base() => return,
            None => return,
            // Step 4.
            Some(url) => {
                UrlHelper::SetHost(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 5.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname
    fn Hostname(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            Some(ref url) => {
                // Step 4.
                UrlHelper::Hostname(url)
            },
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-hostname
    fn SetHostname(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.cannot_be_a_base() => return,
            None => return,
            // Step 4.
            Some(url) => {
                UrlHelper::SetHostname(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 5.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-href
    fn Href(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        USVString(match *self.url.borrow() {
            None => {
                match self
                    .upcast::<Element>()
                    .get_attribute(&ns!(), &local_name!("href"))
                {
                    // Step 3.
                    None => String::new(),
                    // Step 4.
                    Some(attribute) => (**attribute.value()).to_owned(),
                }
            },
            // Step 5.
            Some(ref url) => url.as_str().to_owned(),
        })
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-href
    fn SetHref(&self, value: USVString, can_gc: CanGc) {
        self.upcast::<Element>().set_string_attribute(
            &local_name!("href"),
            DOMString::from_string(value.0),
            can_gc,
        );
        self.set_url();
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-origin
    fn Origin(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        USVString(match *self.url.borrow() {
            None => {
                // Step 2.
                "".to_owned()
            },
            Some(ref url) => {
                // Step 3.
                url.origin().ascii_serialization()
            },
        })
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-password
    fn Password(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            // Steps 3-4.
            Some(ref url) => UrlHelper::Password(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-password
    fn SetPassword(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.host().is_none() || url.cannot_be_a_base() => return,
            None => return,
            // Step 4.
            Some(url) => {
                UrlHelper::SetPassword(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 5.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname
    fn Pathname(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            // Steps 4-5.
            Some(ref url) => UrlHelper::Pathname(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-pathname
    fn SetPathname(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.cannot_be_a_base() => return,
            None => return,
            // Step 5.
            Some(url) => {
                UrlHelper::SetPathname(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 6.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-port
    fn Port(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 3.
            None => USVString(String::new()),
            // Step 4.
            Some(ref url) => UrlHelper::Port(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-port
    fn SetPort(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 3.
        let url = match self.url.borrow_mut().as_mut() {
            Some(ref url)
                if url.host().is_none() || url.cannot_be_a_base() || url.scheme() == "file" =>
            {
                return;
            },
            None => return,
            // Step 4.
            Some(url) => {
                UrlHelper::SetPort(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 5.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol
    fn Protocol(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 2.
            None => USVString(":".to_owned()),
            // Step 3.
            Some(ref url) => UrlHelper::Protocol(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-protocol
    fn SetProtocol(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        let url = match self.url.borrow_mut().as_mut() {
            // Step 2.
            None => return,
            // Step 3.
            Some(url) => {
                UrlHelper::SetProtocol(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 4.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-search
    fn Search(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 2.
            None => USVString(String::new()),
            // Step 3.
            Some(ref url) => UrlHelper::Search(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-search
    fn SetSearch(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            None => return,
            // Steps 4-5.
            // TODO add this element's node document character encoding as
            // encoding override (as described in the spec)
            Some(url) => {
                UrlHelper::SetSearch(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 6.
        self.update_href(url, can_gc);
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-username
    fn Username(&self) -> USVString {
        // Step 1.
        self.reinitialize_url();

        match *self.url.borrow() {
            // Step 2.
            None => USVString(String::new()),
            // Step 3.
            Some(ref url) => UrlHelper::Username(url),
        }
    }

    // https://html.spec.whatwg.org/multipage/#dom-hyperlink-username
    fn SetUsername(&self, value: USVString, can_gc: CanGc) {
        // Step 1.
        self.reinitialize_url();

        // Step 2.
        let url = match self.url.borrow_mut().as_mut() {
            // Step 3.
            Some(ref url) if url.host().is_none() || url.cannot_be_a_base() => return,
            None => return,
            // Step 4.
            Some(url) => {
                UrlHelper::SetUsername(url, value);
                DOMString::from(url.as_str())
            },
        };
        // Step 5.
        self.update_href(url, can_gc);
    }
}

impl Activatable for HTMLAnchorElement {
    fn as_element(&self) -> &Element {
        self.upcast::<Element>()
    }

    fn is_instance_activatable(&self) -> bool {
        // https://html.spec.whatwg.org/multipage/#hyperlink
        // "a [...] element[s] with an href attribute [...] must [..] create a
        // hyperlink"
        // https://html.spec.whatwg.org/multipage/#the-a-element
        // "The activation behaviour of a elements *that create hyperlinks*"
        self.as_element().has_attribute(&local_name!("href"))
    }

    //https://html.spec.whatwg.org/multipage/#the-a-element:activation-behaviour
    fn activation_behavior(&self, event: &Event, target: &EventTarget, _can_gc: CanGc) {
        let element = self.as_element();
        let mouse_event = event.downcast::<MouseEvent>().unwrap();
        let mut ismap_suffix = None;

        // Step 1: If the target of the click event is an img element with an ismap attribute
        // specified, then server-side image map processing must be performed.
        if let Some(element) = target.downcast::<Element>() {
            if target.is::<HTMLImageElement>() && element.has_attribute(&local_name!("ismap")) {
                let target_node = element.upcast::<Node>();
                let rect = target_node.bounding_content_box_or_zero(CanGc::note());
                ismap_suffix = Some(format!(
                    "?{},{}",
                    mouse_event.ClientX().to_f32().unwrap() - rect.origin.x.to_f32_px(),
                    mouse_event.ClientY().to_f32().unwrap() - rect.origin.y.to_f32_px()
                ))
            }
        }

        // Step 2.
        //TODO: Download the link is `download` attribute is set.
        follow_hyperlink(element, self.relations.get(), ismap_suffix);
    }
}