-
Notifications
You must be signed in to change notification settings - Fork 8
/
router-component.ts
367 lines (331 loc) · 12 KB
/
router-component.ts
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import { querySelectorDeep } from 'query-selector-shadow-dom';
export function extractPathParams(pattern: string, path: string): string[] {
const regex = new RegExp(pattern);
const matches = regex.exec(path);
if (!matches) {
return [];
} else {
const groups = [...matches];
// remove first result since its not a capture group
groups.shift();
return groups;
}
}
function delay(milliseconds: string | number = 0) {
return new Promise<void>((resolve) => {
const timer = setTimeout(() => {
resolve();
clearTimeout(timer);
}, Number(milliseconds));
});
}
const routeComponents: Set<RouterComponent> = new Set();
export class RouterComponent extends HTMLElement {
private fragment: DocumentFragment;
private popStateChangedListener: () => void;
private routeElements = [];
private shownRouteElements: Map<string, Element> = new Map();
private previousLocation: Location;
private clickedLinkListener: (e: any) => void;
// TODO: fix below so that we are using pushState and replaceState method signatures on History type
private historyChangeStates: Map<
typeof history.pushState | typeof history.replaceState,
'pushState' | 'replaceState'
>;
private originalDocumentTitle: string;
private invalid: boolean;
constructor() {
super();
routeComponents.add(this);
this.fragment = document.createDocumentFragment();
const children: HTMLCollection = this.children;
while (children.length > 0) {
const element = children[0];
this.routeElements.push(element);
this.fragment.appendChild(element);
}
}
connectedCallback(): void {
this.popStateChangedListener = this.popStateChanged.bind(this);
window.addEventListener('popstate', this.popStateChangedListener);
this.bindLinks();
// we must hijack pushState and replaceState because we need to
// detect when consumer attempts to use and trigger a page load
this.historyChangeStates = new Map([
[window.history.pushState, 'pushState'],
[window.history.replaceState, 'replaceState'],
]);
for (const [method, name] of this.historyChangeStates) {
window.history[name] = (
state: Record<'triggerRouteChange', boolean> | never,
title: string,
url?: string | null
) => {
const triggerRouteChange =
!state || state.triggerRouteChange !== false;
if (!triggerRouteChange) {
delete state.triggerRouteChange;
}
method.call(history, state, title, url);
if (!triggerRouteChange) {
return;
}
if (this.previousLocation) {
this.hideRoute(this.previousLocation.pathname);
}
this.showRoute(url);
};
}
this.showRoute(this.getFullPathname(this.location));
}
getRouteElementByPath(pathname: string): Element | undefined {
let element: Element;
if (!pathname) return;
for (const child of this.routeElements) {
let path = pathname;
const search = child.getAttribute('search-params');
if (search) {
path = `${pathname}?${search}`;
}
if (this.matchPathWithRegex(path, child.getAttribute('path'))) {
element = child;
break;
}
}
return element;
}
private get storedScrollPosition(): number | undefined {
const positionString = sessionStorage.getItem('currentScrollPosition');
return positionString && Number(positionString);
}
private set storedScrollPosition(value: number) {
sessionStorage.setItem('currentScrollPosition', value.toString());
}
private scrollToHash(hash: string = this.location.hash): void {
const behaviorAttribute = this.getAttribute(
'hash-scroll-behavior'
) as ScrollBehavior;
const hashId = hash.replace('#', '');
try {
const hashElement = querySelectorDeep(
`[id=${hashId}]`,
this
) as HTMLElement;
if (hashElement) {
hashElement.scrollIntoView({
behavior: behaviorAttribute || 'auto',
});
}
} catch (e) {
// id attributes can only have valid characters, if invalid, skip
console.warn(
`Cannot scroll to element with the id of "${hashId}".`
);
return;
}
}
private handleHash(hash = '', wait = false): void {
const delayAttribute = this.getAttribute('hash-scroll-delay');
const delay = delayAttribute ? Number(delayAttribute) : 1;
if (!wait) {
this.scrollToHash(hash);
} else {
// wait for custom element to connect to the DOM so we
// can scroll to it, on certain browsers this takes a while
const timer = setTimeout(() => {
this.scrollToHash(hash);
clearTimeout(timer);
}, delay);
}
}
/**
* @deprecated since 0.15.0
* TODO: remove this in next major version
*/
show = this.showRoute;
async showRoute(location: string): Promise<void> {
if (!location) return;
const [pathname, hashString] = location.split('#');
const routeElement = this.getRouteElementByPath(pathname);
this.previousLocation = { ...this.location };
if (!routeElement) {
return console.warn(
`Navigated to path "${pathname}" but there is no matching element with a path ` +
`that matches. Maybe you should implement a catch-all route with the path attribute of ".*"?`
);
}
const child = this.children[0];
if (
child &&
this.previousLocation.href !== this.location.href &&
!querySelectorDeep('router-component', child)
) {
this.hideRoute(this.previousLocation.pathname);
}
if (!this.shownRouteElements.has(pathname)) {
this.shownRouteElements.set(pathname, routeElement);
}
this.dispatchEvent(new CustomEvent('route-changed'));
this.appendChild(routeElement);
this.dispatchEvent(
new CustomEvent('showing-page', {
detail: routeElement,
})
);
const showDelayAttribute = this.getAttribute('show-delay');
if (showDelayAttribute) {
await delay(showDelayAttribute);
}
this.setupElement(routeElement);
let scrollToPosition = 0;
if (
this.storedScrollPosition &&
window.history.scrollRestoration === 'manual'
) {
scrollToPosition = this.storedScrollPosition;
sessionStorage.removeItem('currentScrollPosition');
}
if (hashString) {
this.handleHash(`#${hashString}`);
} else {
window.scrollTo({
top: scrollToPosition,
behavior: 'auto', // we dont wanna scroll here
});
}
}
async hideRoute(location = ''): Promise<void> {
if (!location) {
return;
}
const [pathname] = location.split('#');
const routeElement = this.getRouteElementByPath(pathname);
if (!routeElement) {
return;
}
this.dispatchEvent(
new CustomEvent('hiding-page', {
detail: routeElement,
})
);
const hideDelayAttribute = this.getAttribute('hide-delay');
if (hideDelayAttribute) {
await delay(hideDelayAttribute);
}
this.fragment.appendChild(routeElement);
this.teardownElement(routeElement);
}
get location(): Location {
return window.location;
}
disconnectedCallback(): void {
window.removeEventListener('popstate', this.popStateChangedListener);
for (const [method, name] of this.historyChangeStates) {
window.history[name] = method;
}
this.unbindLinks();
this.shownRouteElements.clear();
this.previousLocation = undefined;
}
clickedLink(link: HTMLAnchorElement, e: Event): void {
const { href } = link;
if (!href || href.indexOf('mailto:') !== -1) return;
const { location } = this;
const origin =
location.origin || location.protocol + '//' + location.host;
if (href.indexOf(origin) !== 0 || link.origin !== location.origin) {
// external links
window.history.scrollRestoration = 'manual';
sessionStorage.setItem(
'currentScrollPosition',
document.documentElement.scrollTop.toString()
);
return;
}
e.preventDefault();
const state: any = {};
if (link.hash && link.pathname === location.pathname) {
this.scrollToHash(link.hash);
state.triggerRouteChange = false;
}
window.history.pushState(
state,
document.title,
`${link.pathname}${link.search}${link.hash}`
);
}
bindLinks(): void {
// TODO: update this to be more performant
// listening to body to allow detection inside of shadow roots
this.clickedLinkListener = (e) => {
if (e.defaultPrevented) return;
const link = e
.composedPath()
.filter((n) => (n as HTMLElement).tagName === 'A')[0] as
| HTMLAnchorElement
| undefined;
if (!link) {
return;
}
this.clickedLink(link, e);
};
document.body.addEventListener('click', this.clickedLinkListener);
}
unbindLinks(): void {
document.body.removeEventListener('click', this.clickedLinkListener);
}
private matchPathWithRegex(pathname = '', regex: string): RegExpMatchArray {
if (!pathname.startsWith('/')) {
pathname = `${pathname.replace(/^\//, '')}`;
}
return pathname.match(regex);
}
/**
* Returns href without the hostname and stuff.
* @param location
* @returns
*/
private getFullPathname(location: Location): string {
if (!location) {
return '';
}
const { pathname, search, hash } = location;
return `${pathname}${search}${hash}`;
}
private async popStateChanged() {
const path = this.getFullPathname(this.location);
// although popstate was called we still need to trigger
// replaceState so all stateful operations can be performed
window.history.replaceState({}, document.title, path);
}
private setupElement(routeElement: Element) {
const { pathname } = this.location;
this.originalDocumentTitle = document.title;
const title = routeElement.getAttribute('document-title');
if (title) {
document.title = title;
} else {
document.title = this.originalDocumentTitle;
}
const nestedRouterComponent: RouterComponent =
routeElement.querySelector('router-component');
if (nestedRouterComponent) {
nestedRouterComponent.showRoute(pathname);
}
}
// eslint-disable-next-line no-unused-vars
private teardownElement(element: Element) {
document.title = this.originalDocumentTitle;
}
private getExternalRouterByPath(
pathname: string
): RouterComponent | undefined {
for (const component of routeComponents) {
const routeElement = component.getRouteElementByPath(pathname);
if (routeElement) {
return component;
}
}
}
}
customElements.define('router-component', RouterComponent);