-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathelement-router.js
132 lines (113 loc) · 4.16 KB
/
element-router.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
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
export const ROUTERS = [];
const EMPTY = {};
export const routeTo = (url) => {
if (url === getCurrentUrl()) {
return;
}
history.pushState(null, null, url);
return ROUTERS[0].routeTo(url);
};
export function getCurrentUrl() {
return `${location.pathname || ''}${location.search || ''}`;
}
function createPathSegments(url) {
return url.replace(/(^\/+|\/+$)/g, '').split('/');
}
export const active = (url, className = 'active') => {
return url === getCurrentUrl() ? className : '';
}
export class ElementRouter extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
if (ROUTERS.length) {
throw new DOMException("Only instantiable in a top-level browsing context", "SecurityError");
}
ROUTERS.push(this);
this.routeTo(getCurrentUrl());
addEventListener('popstate', () => {
this.routeTo(getCurrentUrl());
});
}
async routeTo(url) {
this.url = url;
this.shadowRoot.innerHTML = '';
const element = await this.getMatchingChild([...this.children], this.url);
element && this.shadowRoot.appendChild(element);
this.dispatchEvent(new CustomEvent('routechange',{detail:{url:getCurrentUrl()}}))
}
async resolveElement(routeEle, properties = {}) {
let returnEle;
let importAttr = routeEle.getAttribute('import');
if (importAttr) {
await import(importAttr);
}
let elementAttr = routeEle.getAttribute('element');
if (elementAttr) {
returnEle = document.createElement(elementAttr);
}
let redirectAttr = routeEle.getAttribute('redirect');
if (redirectAttr) {
routeTo(redirectAttr);
return null;
}
let template = routeEle.children[0];
if (template && template.nodeName === 'TEMPLATE') {
return document.importNode(template.content, true);
}
for (let prop in properties) {
returnEle[prop] = properties[prop];
}
return returnEle;
}
getMatchingChild(children, url) {
const queryRegex = /(?:\?([^#]*))?(#.*)?$/;
//const queryParams = url.match(queryRegex);
url = url.replace(queryRegex, '');
const urlSegments = createPathSegments(url);
for (let child of children) {
const path = child.getAttribute('path');
if (!path || child.nodeName !== "ELEMENT-ROUTE") {
break;
}
if (path === '*') {
return this.resolveElement(child);
}
if (path === url) {
/** Fast exit if direct match */
return this.resolveElement(child);
}
const pathSegments = createPathSegments(path);
const matches = {};
let max = Math.max(urlSegments.length, pathSegments.length);
let ret;
for (let i = 0; i < max; i++) {
if (pathSegments[i] && pathSegments[i].charAt(0) === ':') {
let param = pathSegments[i].replace(/(^\:|[+*?]+$)/g, ''),
flags = (pathSegments[i].match(/[+*?]+$/) || EMPTY)[0] || '',
plus = ~flags.indexOf('+'),
star = ~flags.indexOf('*'),
val = urlSegments[i] || '';
if (!val && !star && (flags.indexOf('?') < 0 || plus)) {
ret = false;
break;
}
matches[param] = decodeURIComponent(val);
if (plus || star) {
matches[param] = urlSegments.slice(i).map(decodeURIComponent).join('/');
break;
}
}
else if (pathSegments[i] !== urlSegments[i]) {
ret = false;
break;
}
ret = true;
}
if (ret) {
return this.resolveElement(child, matches);
}
}
}
}
customElements.define('element-router', ElementRouter);