-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
106 lines (85 loc) · 2.56 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>client-side-router</title>
<style>
h3 {
font-weight: normal;
font-size: 2em;
}
#main {
width: 500px;
height: 300px;
background-color: #cccccc;
padding: 10px;
}
</style>
</head>
<body>
<h3>Click a navigation link here:</h3>
<nav is="client-side-router" data-outlet="#main">
<a href="/page1" is="router-link" slot="link" data-template="./page1.html">page 1</a>
<a href="/page2" is="router-link" slot="link" data-template="./page2.html">page 2</a>
</nav>
<h3>Content will be rendered below:</h3>
<div id="main"></div>
<script>
class RouterLink extends HTMLAnchorElement {
constructor() {
super();
}
connectedCallback() {
this.addEventListener('click', e => {
e.preventDefault();
this.dispatchEvent(new CustomEvent('route-change', {
composed: true,
bubbles: true,
detail: {link: this}
}));
})
}
}
class ClientSideRouter extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({mode: 'open'});
shadowRoot.innerHTML = `
<style>
:host {
display: flex;
justify-content: space-between;
width: 150px;
padding: 5px;
background-color: #cccccc;
}
::slotted(a) {
display: block;
color: #000000;
text-decoration: none;
padding: 5px;
}
</style>
<slot name="link"></slot>
`;
}
connectedCallback() {
this.outlet = document.querySelector(this.dataset.outlet);
this.addEventListener('route-change', e => {
this.handleRouteChange(e.detail.link)
});
}
async handleRouteChange(link) {
const template = link.dataset.template;
const url = link.getAttribute('href');
const state = {template, url};
const html = await (await fetch(template)).text();
history.pushState(state, null, url);
this.outlet.innerHTML = html;
}
}
customElements.define('client-side-router', ClientSideRouter, {extends: 'nav'});
customElements.define('router-link', RouterLink, {extends: 'a'});
</script>
</body>
</html>