-
Notifications
You must be signed in to change notification settings - Fork 1
/
RouterOutlet.ts
472 lines (360 loc) · 11 KB
/
RouterOutlet.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
import { Router } from './Router.js';
import { RouteAnimationIn, RouteAnimationOut, RoutedLocation } from './types.js';
/**
* An animation task to load a route with.
*/
type RouteTask = {
/** The location to route to. */
routedLocation: RoutedLocation;
/** The animation to apply when routing. */
animation?: RouteAnimationIn | RouteAnimationOut;
};
/**
* A web component that acts as the bounding box within which a routed web component will render.
*
* Usage:
* ```html
* <omni-router
* @navigation-started="${() => console.log(`Route '${route.name}' started to load`)}"
* @navigation-completed="${() => console.log(`Route '${route.name}' finished loading`)}">
* </omni-router>
* ```
*
* @element omni-router
*
* @fires {CustomEvent<RoutedLocation>} navigation-started - Dispatched when the a new page starts loading.
* @fires {CustomEvent<RoutedLocation>} navigation-completed - Dispatched when the new page is visible.
* ```
*/
export class RouterOutlet extends HTMLElement {
/** The routed location that is currently loaded in the outlet. */
private _currentLocation?: RoutedLocation;
/** The routed location that was previously loaded in the outlet. */
private _previousLocation?: RoutedLocation;
/** Indicator if there is a routing animation currently playing. */
private _isAnimating: boolean;
/** List of queued navigation animation tasks. */
private _animationQueue: RouteTask[] = [];
// --------------
// INITIALIZATION
// --------------
/**
* Initializes the component.
*/
constructor() {
super();
// Initialize default properties.
this._isAnimating = false;
// Create the element shadow root.
const shadow = this.attachShadow({ mode: 'open' });
// Set component styles.
const style = document.createElement('style');
style.textContent = `
:host {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
.page {
width: 100%;
height: 100%;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
/** Fade In Animation */
.fade-in {
opacity: 0;
}
.fade-in.animate {
animation: fadein var(--omni-router-animation-duration, 300ms) both;
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
/* Fade Out Animation */
.fade-out {
opacity: 1;
}
.fade-out.animate {
animation: fadeout var(--omni-router-animation-duration, 300ms) both;
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes fadeout {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
/* Slide In Animation */
.slide-in {
transform: translateX(100%);
}
.slide-in.animate {
animation: slidein var(--omni-router-animation-duration, 300ms) both;
animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes slidein {
from {
transform: translateX(100%);
}
to {
transform: translateX(0px);
}
}
/* Slide Out Animation */
.slide-out {
transform: translateX(0px);
}
.slide-out.animate {
animation: slideout var(--omni-router-animation-duration, 300ms) both;
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes slideout {
from {
transform: translateX(0px);
}
to {
transform: translateX(100%);
}
}
/* Pop In Animation */
.pop-in {
transform: translateY(100%);
}
.pop-in.animate {
animation: popin var(--omni-router-animation-duration, 300ms) both;
animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes popin {
from {
transform: translateY(100%);
}
to {
transform: translateY(0px);
}
}
/* Pop Out Animation */
.pop-out {
transform: translateY(0px);
}
.pop-out.animate {
animation: popout var(--omni-router-animation-duration, 300ms) both;
animation-timing-function: cubic-bezier(0.4, 0, 0.6, 1);
z-index: var(--omni-router-animation-z-index, 1000000);
}
@keyframes popout {
from {
transform: translateY(0px);
}
to {
transform: translateY(100%);
}
}
`;
shadow.appendChild(style);
}
/**
* Setup the component once added to the DOM.
*/
connectedCallback(): void {
// Set this outlet as the route rendering handler for the router.
Router.onNavigate = (route, animation): Promise<void> => this._loadRoute(route, animation);
}
/**
* Clean up the component once removed from the DOM.
*/
disconnectedCallback(): void {
// Stop rendering on router navigation changes.
Router.onNavigate = undefined;
}
// ----------
// PROPERTIES
// ----------
// n/a
// --------------
// PUBLIC METHODS
// --------------
// n/a
// ---------------
// PRIVATE METHODS
// ---------------
/**
* Load a route into view.
*
* Note:
* As route components are animated in, this function may be called while an previous route load animation
* is still playing. In such cases the task will be queued and completed after the first animation finishes.
*
* @param routedLocation - The the routed location to load.
* @param animation - The animation to play to bring the new route into view.
*/
private async _loadRoute(routedLocation: RoutedLocation, animation?: RouteAnimationIn | RouteAnimationOut): Promise<void> {
// Ensure a valid route is provided.
const route = routedLocation.route;
if (!route) {
return;
}
// Prevent loading the route if it is already in view.
if (this._currentLocation?.route?.name === route.name) {
return;
}
// Queue the route load task.
this._animationQueue.push({
routedLocation,
animation
});
// Start processing the queue of route load tasks, if it is not running yet.
if (!this._isAnimating) {
await this._processNextQueueItem();
}
}
/**
* Process the queue of route load tasks.
*/
private async _processNextQueueItem(): Promise<void> {
// Remove the task next available from the queue.
const routeRequest = this._animationQueue.shift();
// Stop processing the queue if it is empty.
if (!routeRequest) {
// Mark the queue as done processing.
this._isAnimating = false;
return;
}
// Mark the queue as busy processing.
this._isAnimating = true;
// Get the routing task information.
const routedLocation = routeRequest.routedLocation;
const animation = routeRequest.animation;
// Stop processing if the route provided is not vaild.
const route = routedLocation.route;
if (!route) {
// Mark the queue as done processing.
this._isAnimating = false;
return;
}
// Record the old and new routing locations.
this._previousLocation = this._currentLocation;
this._currentLocation = routedLocation;
// Notify any subscribers that the route has start to load.
this.dispatchEvent(
new CustomEvent<RoutedLocation>('navigation-started', {
detail: this._currentLocation,
bubbles: true,
composed: true
})
);
// Load the route component if required.
if (route.load) {
await route.load();
}
// Add the page component to the router display.
const oldRouteComponent = this._getCurrentRouteComponent();
const newRouteComponent = document.createElement(route.tag ?? route.name);
newRouteComponent.classList.add('page');
// Start a task to animate in the new route component and animate out the old route component.
await new Promise<void>((resolve) => {
if (animation === 'fade-in' || animation === 'slide-in' || animation === 'pop-in') {
// Set the animation type the new route component should use to animate in.
newRouteComponent.classList.add(animation);
// Clean up the animation once done.
newRouteComponent.addEventListener('animationend', () => {
// Clear the animation from the element.
newRouteComponent.classList.remove(animation, 'animate');
// Remove the old route component from view.
if (oldRouteComponent) {
oldRouteComponent.remove();
}
// Mark the routing task as complete.
resolve();
});
// Add the new route component to the top of the view stack so the the animation is visible.
this.shadowRoot?.append(newRouteComponent);
// Start the animation.
setTimeout(() => {
newRouteComponent.classList.add('animate'); // NOTE: the 10ms delay is needed on old browsers to prevent rendering the animation in the same cycle as the component is added to DOM.
}, 10);
} else if (animation === 'fade-out' || animation === 'slide-out' || animation === 'pop-out') {
if (oldRouteComponent) {
// Set the animation type the old route component should use to animate out.
oldRouteComponent.classList.add(animation);
// Clean up the animation once done.
oldRouteComponent.addEventListener('animationend', () => {
// Clear the animation from the element.
oldRouteComponent.classList.remove(animation, 'animate');
// Remove the old route component from view.
oldRouteComponent.remove();
// Mark the routing task as complete.
resolve();
});
// Add the new route component to the bottom of the view stack so the the animation is visible.
this.shadowRoot?.prepend(newRouteComponent);
// Start the animation.
setTimeout(() => {
oldRouteComponent.classList.add('animate'); // NOTE: the 10ms delay is needed on old browsers to prevent rendering the animation in the same cycle as the component is added to DOM.
}, 10);
} else {
// There is no old route component to animate out, just add the new route component instead.
this.shadowRoot?.prepend(newRouteComponent);
// Mark the routing task as complete.
resolve();
}
} else {
// No animation is set, just remove the old route component and add the new route component.
if (oldRouteComponent) {
oldRouteComponent.remove();
}
this.shadowRoot?.append(newRouteComponent);
// Mark the routing task as complete.
resolve();
}
});
// Notify any subscribers that the route has finished loading.
this.dispatchEvent(
new CustomEvent<RoutedLocation>('navigation-completed', {
detail: this._currentLocation,
bubbles: true,
composed: true
})
);
// Process the next task in the animation queue, if there is any.
await this._processNextQueueItem();
}
/**
* Get the DOM element of the currently routed to page.
*
* @returns The routed page route element.
*/
private _getCurrentRouteComponent(): Element | null {
if (!this.shadowRoot) {
return null;
}
for (let i = 0; i < this.shadowRoot.children.length; i++) {
const child = this.shadowRoot.children[i];
if (child.tagName.toLowerCase() !== 'style') {
return child;
}
}
return null;
}
}
customElements.define('omni-router', RouterOutlet);
declare global {
interface HTMLElementTagNameMap {
'omni-router': RouterOutlet;
}
}