-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathx-shell.component.ts
More file actions
509 lines (414 loc) · 14.7 KB
/
Copy pathx-shell.component.ts
File metadata and controls
509 lines (414 loc) · 14.7 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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import {
Component,
ElementRef,
OnInit,
PLATFORM_ID,
ViewEncapsulation,
inject,
isDevMode,
viewChild,
DOCUMENT,
ChangeDetectorRef,
} from '@angular/core';
import { isPlatformBrowser, Location, ViewportScroller } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatSidenav, MatSidenavModule } from '@angular/material/sidenav';
import { NavigationEnd, Router, RouterOutlet } from '@angular/router';
import { SwUpdate, UnrecoverableStateEvent } from '@angular/service-worker';
import { Subscription, interval, tap } from 'rxjs';
import { Theme, ThemeService, Themes } from '../../../app/shell/theme/theme.service';
import { XDialogComponent } from '../../../app/shell/x-dialog/x-dialog.component';
import { XDialogService } from '../../../app/shell/x-dialog/x-dialog.service';
import { XNavigationRailComponent } from '../../../app/shell/x-navigation-rail/x-navigation-rail.component';
import { XTopAppBarComponent } from '../../../app/shell/x-top-app-bar/x-top-app-bar.component';
import { XNavigationDrawerComponent } from '../x-navigation-drawer/x-navigation-drawer.component';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
@Component({
selector: 'x-shell',
encapsulation: ViewEncapsulation.ShadowDom,
imports: [
MatButtonModule,
MatSidenavModule,
RouterOutlet,
XDialogComponent,
XNavigationDrawerComponent,
XNavigationRailComponent,
XTopAppBarComponent,
],
template: `
<x-navigation-drawer
(drawerButton)="handleDrawerButton()"
[isBrowser]="isBrowser"
[open]="isDrawerOpen"
[hidden]="!isDrawerOpen"
></x-navigation-drawer>
@if (!isFullscreen) {
<x-navigation-rail (drawerButton)="handleDrawerButton()"></x-navigation-rail>
}
<div id="container">
@if (!isFullscreen) {
<x-top-app-bar
(drawerButton)="handleDrawerButton()"
(themeButton)="handleThemeButton($event)"
/>
}
<main>
<x-dialog></x-dialog>
@if (isOutlet) {
<router-outlet></router-outlet>
}
</main>
</div>
`,
styles: [
`
#container {
display: flex;
flex-direction: column;
flex: 1;
x-top-app-bar {
--md-sys-comp-top-app-bar-padding: 1rem;
height: var(--mat-toolbar-standard-height);
min-height: var(--mat-toolbar-standard-height);
max-height: var(--mat-toolbar-standard-height);
}
main,
main > router-outlet + * {
align-items: start;
display: flex;
flex: auto;
height: 100%;
justify-content: center;
width: 100%;
}
}
x-slide {
height: 100%;
width: 100%;
}
x-block-garden,
x-sprite-garden {
background-color: var(--x-shell-background-color);
}
x-navigation-rail {
--md-comp-navigation-rail-container-height: 100vh;
--md-comp-navigation-rail-container-width: 5rem;
display: none;
min-height: var(--md-comp-navigation-rail-container-height);
min-width: 0;
z-index: 2;
}
@media screen and (min-width: 859px) {
x-navigation-rail {
display: flex;
flex: 0 0 calc(var(--md-comp-navigation-rail-container-width, 5rem) + 1px);
}
}
`,
],
})
export class XShellComponent implements OnInit {
el: ElementRef = inject(ElementRef);
isBrowser: boolean = false;
isDialogOpen: boolean = false;
isDrawerOpen: boolean = false;
isFullscreen: boolean = false;
sidenav = viewChild.required<MatSidenav>('sidenav');
themeService: ThemeService = inject(ThemeService);
xDialogService: XDialogService = inject(XDialogService);
loc: Location = inject(Location);
get isOutlet(): boolean {
return ['/ng-app-shell', '/shell'].includes(this.loc.path()) === false;
}
private viewportScroller = inject(ViewportScroller);
private cdr = inject(ChangeDetectorRef);
private dialogResultSubscription?: Subscription;
private dialogSubscription?: Subscription;
private document: Document = inject(DOCUMENT);
private platformId: Object = inject(PLATFORM_ID);
private router: Router = inject(Router);
private swUpdate: SwUpdate = inject(SwUpdate);
private unrecoverable!: Subscription;
private versionUpdates!: Subscription;
constructor() {
this.router.events
.pipe(
takeUntilDestroyed(),
tap((event: unknown) => {
if (event instanceof NavigationEnd) {
this.viewportScroller.scrollToPosition([0, 0]);
}
}),
)
.subscribe();
this.isBrowser = isPlatformBrowser(this.platformId);
if (this.isBrowser) {
this.xDialogService.registerChangeDetector(this.cdr);
if (!isDevMode()) {
console.log('Update Service: this.swUpdate.isEnabled', this.swUpdate.isEnabled);
const TEN_SECONDS = 10000;
const FIVE_MINUTES = TEN_SECONDS * 30;
interval(FIVE_MINUTES).subscribe(() => {
console.log('UpdateService: Checking for Updates.', new Date());
this.swUpdate.checkForUpdate();
});
this.swUpdate.unrecoverable.subscribe((evt: UnrecoverableStateEvent) => {
console.log('UnrecoverableStateEvent', evt);
});
this.versionUpdates = this.swUpdate.versionUpdates.subscribe(async (evt) => {
console.log('UpdateService: versionUpdates', evt);
switch (evt.type) {
case 'VERSION_DETECTED':
console.log(`Downloading new app version: ${evt.version.hash}`);
break;
case 'VERSION_READY':
console.log(`Current app version: ${evt.currentVersion.hash}`);
console.log(`New app version ready for use: ${evt.latestVersion.hash}`);
await this.swUpdate.activateUpdate();
this.handleAppUpdate();
break;
case 'VERSION_INSTALLATION_FAILED':
console.log(`Failed to install app version '${evt.version.hash}': ${evt.error}`);
break;
}
});
this.dialogSubscription = this.xDialogService.open$.subscribe((isDialogOpen) => {
this.isDialogOpen = isDialogOpen;
});
this.dialogResultSubscription = this.xDialogService.result$.subscribe((result) => {
if (result === 'apps-update-ok') {
location.reload();
}
if (result === 'apps-update-cancel') {
console.log('cancelled.');
}
});
}
this.keepInSync();
this.watchPrefersColorScheme();
this.enableTheme(
this.getThemeFromStorage() || this.getThemeFromBrowser() || this.getThemeFromTime(),
);
}
}
ngOnInit(): void {
if (this.isBrowser) {
// clear site progress circle
const progress: HTMLProgressElement | null = this.document.querySelector('.progress');
if (progress) {
progress.style.display = 'none';
}
// slides - listen for fullscreen events
this.el.nativeElement.addEventListener('fullscreen', () => this.fullscreenListener());
this.document.addEventListener('fullscreenchange', () => this.fullscreenChangeListener());
// slides - clear persisted state
sessionStorage.removeItem('apps-slides-fullscreen');
sessionStorage.removeItem('apps-slides-mode');
sessionStorage.removeItem('apps-slides-last');
}
}
ngOnDestroy(): void {
this.unrecoverable?.unsubscribe();
this.versionUpdates?.unsubscribe();
// slides - remove fullscreen event listeners
this.el.nativeElement.removeEventListener('fullscreen', this.fullscreenListener);
this.document.removeEventListener('fullscreenchange', this.fullscreenChangeListener);
this.dialogSubscription?.unsubscribe();
this.dialogResultSubscription?.unsubscribe();
}
enableTheme(newTheme = Themes.Light, persist = true) {
const html = document.documentElement;
let otherTheme;
if (newTheme === Themes.Light) {
otherTheme = Themes.Dark;
} else {
otherTheme = Themes.Light;
}
html.classList.add(`${newTheme}-theme`);
html.classList.remove(`${otherTheme}-theme`);
if (persist) {
this.themeService.persistToStorage(this.getPreferenceKey('theme'), newTheme);
}
}
// slides - helper methods
fullscreenListener() {
this.toggleFullscreen();
}
// slides - helper methods
fullscreenChangeListener() {
this.isFullscreen = !!this.document.fullscreenElement;
sessionStorage.setItem('apps-slides-fullscreen', this.isFullscreen ? 'enabled' : 'disabled');
}
getThemeFromBrowser() {
let mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
if (mediaQueryList.matches) {
return Themes.Dark;
} else {
mediaQueryList = window.matchMedia('(prefers-color-scheme: light)');
if (mediaQueryList.matches) {
return Themes.Light;
} else {
return undefined;
}
}
}
getThemeFromStorage() {
const pref = localStorage.getItem(this.getPreferenceKey('theme'));
const lastChanged = localStorage.getItem('preference-theme-last-change');
let now: number | Date = new Date();
now = now.getTime();
const minutesPassed = (now - Number(lastChanged)) / (1000 * 60);
if (minutesPassed < 120 && pref === Themes.Light) {
return Themes.Light;
} else if (minutesPassed < 120 && pref === Themes.Dark) {
return Themes.Dark;
} else {
return undefined;
}
}
getThemeFromTime() {
const date = new Date();
const hour = date.getHours();
if (hour > 20 || hour < 5) {
return Themes.Dark;
} else {
return Themes.Light;
}
}
getTokens({ matches }: { matches: boolean }) {
return {
token: matches ? this.getThemePreference(Themes.Light) : this.getThemePreference(Themes.Dark),
newToken: matches
? this.getThemePreference(Themes.Dark)
: this.getThemePreference(Themes.Light),
};
}
getPreferenceKey(type: string) {
return `preference-${type}`;
}
getThemePreference(val: Theme) {
return `${val}-theme`;
}
handleThemeButton(theme: Theme) {
this.toggleMode(theme);
}
keepInSync() {
globalThis.addEventListener('storage', (event: any) => {
if (event.key === this.getPreferenceKey('theme')) {
if (event.newValue === Themes.Light) {
this.themeService.theme.set(Themes.Light);
this.enableTheme(Themes.Light, false);
} else if (event.newValue === Themes.Dark) {
this.themeService.theme.set(Themes.Dark);
this.enableTheme(Themes.Dark, false);
}
}
});
if (globalThis.matchMedia) {
const darkModeMediaQuery = globalThis.matchMedia('(prefers-color-scheme: dark)');
darkModeMediaQuery.addEventListener('change', (e) => {
this.replaceThemeClass(e);
const mode = e.matches ? Themes.Dark : Themes.Light;
this.themeService.theme.set(mode);
this.themeService.persistToStorage(this.getPreferenceKey('theme'), mode);
});
const storedThemePreference = localStorage.getItem(this.getPreferenceKey('theme'));
if (storedThemePreference === Themes.Light) {
this.themeService.theme.set(Themes.Light);
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Light));
return;
}
if (storedThemePreference === Themes.Dark) {
this.themeService.theme.set(Themes.Dark);
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Dark));
return;
}
if (darkModeMediaQuery.matches) {
this.themeService.theme.set(Themes.Dark);
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Dark));
return;
}
this.themeService.theme.set(Themes.Light);
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Light));
}
}
handleAppUpdate(): void {
this.xDialogService.openDialog('Apps has updated. Press OK to load the new version.', {
cancelText: 'Cancel',
cancelValue: 'apps-update-cancel',
submitText: 'OK',
submitValue: 'apps-update-ok',
});
this.cdr?.markForCheck();
}
handleCloseStart() {
this.el.nativeElement.shadowRoot.querySelector('mat-sidenav-container').style.overflow = 'auto';
}
handleDrawerButton(): void {
this.isDrawerOpen = !this.isDrawerOpen;
}
// slides - helper methods
toggleFullscreen() {
if (!this.document.fullscreenElement) {
this.document.documentElement.requestFullscreen();
} else if (this.document.exitFullscreen) {
this.document.exitFullscreen();
}
}
// @todo - revisit this, as it is really basic, and uses predefined colors
// consider using https://github.com/rodydavis/material-theme-control
toggleMode(currentTheme: Theme) {
if (currentTheme === Themes.Light) {
this.themeService.persistToStorage(this.getPreferenceKey('theme'), Themes.Dark);
this.themeService.theme.set(Themes.Dark);
if (
globalThis.document.documentElement.classList.contains(
this.getThemePreference(Themes.Light),
)
) {
globalThis.document.documentElement.classList.replace(
this.getThemePreference(Themes.Light),
this.getThemePreference(Themes.Dark),
);
return;
}
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Dark));
return;
}
this.themeService.persistToStorage(this.getPreferenceKey('theme'), Themes.Light);
this.themeService.theme.set(Themes.Light);
if (
globalThis.document.documentElement.classList.contains(this.getThemePreference(Themes.Dark))
) {
globalThis.document.documentElement.classList.replace(
this.getThemePreference(Themes.Dark),
this.getThemePreference(Themes.Light),
);
return;
}
globalThis.document.documentElement.classList.add(this.getThemePreference(Themes.Light));
}
replaceThemeClass(query: MediaQueryList | MediaQueryListEvent) {
return document.documentElement.classList.replace(
this.getTokens(query).token,
this.getTokens(query).newToken,
);
}
watchPrefersColorScheme() {
const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
if (mediaQueryList && mediaQueryList.addEventListener) {
mediaQueryList.addEventListener('change', (event) => {
const root = document.documentElement;
if (event.matches !== true) {
if (!root.classList.contains(this.getThemePreference(Themes.Light))) {
this.enableTheme(Themes.Light);
}
} else {
if (!root.classList.contains(this.getThemePreference(Themes.Dark))) {
this.enableTheme(Themes.Dark);
}
}
});
}
}
}