Debian Codegraph @

src/helpers/Location.ts

raw
1 /**
2 * A helper for creating a Location from either an element
3 * or a URL object/string
4 *
5 */
6 export class Location extends URL {
7 constructor(url: URL | string, base: string = document.baseURI) {
8 super(url.toString(), base);
9 // Fix Safari bug with extending native classes
10 Object.setPrototypeOf(this, Location.prototype);
11 }
12
13 /**
14 * The full local path including query params.
15 */
16 get url(): string {
17 return this.pathname + this.search;
18 }
19
20 /**
21 * Instantiate a Location from an element's href attribute
22 * @param el
23 * @returns new Location instance
24 */
25 static fromElement(el: Element): Location {
26 const href = el.getAttribute('href') || el.getAttribute('xlink:href') || '';
27 return new Location(href);
28 }
29
30 /**
31 * Instantiate a Location from a URL object or string
32 * @param url
33 * @returns new Location instance
34 */
35 static fromUrl(url: URL | string): Location {
36 return new Location(url);
37 }
38 }