-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathrouters.js
More file actions
66 lines (54 loc) · 1.45 KB
/
routers.js
File metadata and controls
66 lines (54 loc) · 1.45 KB
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
// router.js
import { getCurrentPath, resolvePath } from "../util/path.js";
export class Router {
constructor(vm) {
this.vm = vm;
this.history = window.history;
this.listenLinkClicks();
}
listenLinkClicks() {
document.addEventListener("click", (event) => {
const link = event.target.closest("a");
if (!link || link.getAttribute("target") === "_blank") {
return;
}
const href = link.getAttribute("href");
const current = this.getCurrentURL();
// Prevent default link behavior
event.preventDefault();
// If same URL, do nothing to avoid history clutter
if (current === href) {
this.scrollToHash(href);
return;
}
// Otherwise push new state
this.push(href);
});
}
getCurrentURL() {
return window.location.pathname + window.location.hash;
}
push(href) {
try {
this.history.pushState({ path: href }, "", href);
} catch (err) {
// Fallback if pushState fails
this.history.replaceState({ path: href }, "", href);
}
this.handleNavigation(href);
}
handleNavigation(href) {
// Handles updating the view
this.vm.router.load(href);
}
scrollToHash(href) {
// Scroll into view if a hash is provided
const hash = href.split("#")[1];
if (hash) {
const el = document.getElementById(hash);
if (el) {
el.scrollIntoView({ behavior: "smooth", block: "start" });
}
}
}
}