forked from datagouv/udata-front
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update-url.js
80 lines (73 loc) · 2.11 KB
/
update-url.js
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
/** @type {Map<string, HTMLElement>} */
const targets = new Map();
/** @type {Map<string, string>} */
const redirects = new Map();
/**
* Update UI to match hash
* @param {string} target - formatted hash
*/
function moveToCurrentHash(target) {
if(target.includes("/")) {
target = target.split("/").shift() || "";
}
let button;
if(button = targets.get(target)) {
button.click();
}
}
/**
* Try to update UI to match hash
* This assumes that `data-previous-url` start the hash.
* The rest of the hash is added at the end of the new hash to allow ids or params to pass the redirect.
* This adds a `/` between the new hash and the rest of the previous one to match new hash format.
* @param {string} target - formatted hash
*/
function tryPreviousHashes(target) {
for (const [key, newHash] of redirects) {
if(target && target.startsWith(key)) {
window.location.hash = "#/" + newHash + "/" + target.slice(key.length);
break;
}
}
}
/**
* Update UI to match hash
*/
function moveToHash() {
const hash = window.location.hash;
if(!hash) {
return;
}
if(hash.startsWith("#/")) {
moveToCurrentHash(hash.slice(2));
} else {
tryPreviousHashes(hash.slice(1));
}
globalThis._paq?.push(['trackEvent', 'navigation', 'Move page to hash', window.location.pathname, hash]);
}
export default function handleUpdateUrlButtons() {
/** @type {NodeListOf<HTMLElement>} */
const buttons = document.querySelectorAll("[data-update-url]");
buttons.forEach((button) => {
const target = button.dataset.updateUrl || button.getAttribute("aria-controls");
const previous = button.dataset.previousUrl;
if(target) {
targets.set(target, button);
if(previous) {
redirects.set(previous, target);
}
}
button.addEventListener("click", () => {
let url = new URL(window.location.href);
const targetHash = "#/" + target;
if(!url.hash.includes(targetHash)) {
url.hash = targetHash;
window.history.pushState(null, "", url);
}
});
});
moveToHash();
window.addEventListener("hashchange", () => {
moveToHash();
});
}