-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathapp.component.ts
460 lines (420 loc) · 14.3 KB
/
app.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
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
import { Platform } from '@angular/cdk/platform';
import { DOCUMENT } from '@angular/common';
import { ChangeDetectorRef, Component, Inject, NgZone, OnInit, Renderer2 } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { NavigationEnd, NavigationStart, Router } from '@angular/router';
import { en_US, NzI18nService, zh_CN } from 'ng-zorro-antd/i18n';
import { NzMessageRef, NzMessageService } from 'ng-zorro-antd/message';
import { VERSION } from 'ng-zorro-antd/version';
import { fromEvent } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { environment } from '../environments/environment';
import { AppService } from './app.service';
import { ROUTER_LIST } from './router';
import { loadScript } from './utils/load-script';
import { NzConfigService } from 'ng-zorro-antd/core/config';
interface DocPageMeta {
path: string;
label: string;
order?: number;
zh: string;
description: string;
}
type SiteTheme = 'default' | 'dark' | 'compact' | 'aliyun';
const defaultKeywords =
'angular, ant design, ant, angular ant design, web, ui, components, ng, zorro, responsive, typescript, css, mobile web, open source, 组件库, 组件, UI 框架';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styles: [
`
@media (max-width: 767px) {
.main-menu {
display: none;
}
}
`
]
})
export class AppComponent implements OnInit {
/**
* When the screen size is smaller that 768 pixel, show the drawer and hide
* the navigation on the side.
**/
showDrawer = false;
isDrawerOpen = false;
page: 'docs' | 'components' | 'experimental' | string = 'docs';
windowWidth = 1400;
routerList = ROUTER_LIST;
componentList: DocPageMeta[] = [];
searchComponent = null;
theme: SiteTheme = 'default';
language: 'zh' | 'en' = 'en';
direction: 'ltr' | 'rtl' = 'ltr';
currentVersion = VERSION.full;
switchLanguage(language: string): void {
const url = this.router.url.split('/');
url.splice(-1);
this.router.navigateByUrl(`${url.join('/')}/${language}`).then();
}
switchDirection(direction: 'ltr' | 'rtl'): void {
this.direction = direction;
if (direction === 'rtl') {
this.renderer.setAttribute(document.body, 'dir', 'rtl');
} else {
this.renderer.removeAttribute(document.body, 'dir');
}
this.cdr.detectChanges();
}
initTheme(): void {
if (!this.platform.isBrowser) {
return;
}
const theme = (localStorage.getItem('site-theme') as SiteTheme) || 'default';
this.onThemeChange(theme, false);
}
onThemeChange(theme: string, notification: boolean = true): void {
if (!this.platform.isBrowser) {
return;
}
if (theme === 'compact') {
this.nzConfigService.set('select', {
nzOptionHeightPx: 28
});
} else {
this.nzConfigService.set('select', {
nzOptionHeightPx: 32
});
}
let loading: NzMessageRef | null = null;
if (notification) {
loading = this.nzMessageService.loading(this.language === 'en' ? `Switching theme...` : `切换主题中...`, {
nzDuration: 0
});
}
this.renderer.addClass(this.document.activeElement, 'preload');
const successLoaded = () => {
this.theme = theme as SiteTheme;
this.appService.theme$.next(theme);
this.renderer.setAttribute(document.body, 'data-theme', theme);
localStorage.removeItem('site-theme');
localStorage.setItem('site-theme', theme);
['dark', 'compact', 'aliyun']
.filter(item => item !== theme)
.forEach(item => {
const dom = document.getElementById(`site-theme-${item}`);
if (dom) {
dom.remove();
}
});
setTimeout(() => this.renderer.removeClass(this.document.activeElement, 'preload'));
if (notification) {
this.nzMessageService.remove(loading?.messageId);
this.nzMessageService.success(this.language === 'en' ? `Switching theme successfully` : `切换主题成功`);
}
};
if (theme !== 'default') {
const style = document.createElement('link');
style.type = 'text/css';
style.rel = 'stylesheet';
style.id = `site-theme-${theme}`;
style.href = `assets/${theme}.css`;
document.body.append(style);
style.onload = () => {
successLoaded();
};
style.onerror = () => {
this.nzMessageService.remove(loading?.messageId);
this.nzMessageService.error(this.language === 'en' ? `Switching theme failed` : `切换主题失败`);
document.getElementById(style.id)?.remove();
};
} else {
successLoaded();
}
}
constructor(
private appService: AppService,
private router: Router,
private title: Title,
private nzI18nService: NzI18nService,
private nzMessageService: NzMessageService,
private ngZone: NgZone,
private platform: Platform,
private meta: Meta,
private renderer: Renderer2,
private cdr: ChangeDetectorRef,
private nzConfigService: NzConfigService,
// tslint:disable-next-line:no-any
@Inject(DOCUMENT) private document: any
) {}
navigateToPage(url: string): void {
if (url) {
this.router.navigateByUrl(url).then();
}
}
setPage(url: string): void {
const match = url.match(/\/(\w+)/);
if (match && match[1]) {
this.page = match[1];
}
}
navigateToVersion(version: string): void {
if (!this.platform.isBrowser) {
return;
}
if (version !== this.currentVersion) {
window.location.href = `${window.location.origin}/version/${version}`;
} else {
window.location.href = window.location.origin;
}
this.currentVersion = version;
}
private getLanguageFromURL(url: string): 'en' | 'zh' | null {
const language = url.split('/')[url.split('/').length - 1].split('#')[0].split('?')[0];
if (['zh', 'en'].indexOf(language) !== -1) {
return language as 'en' | 'zh';
}
return null;
}
ngOnInit(): void {
if (this.platform.isBrowser) {
this.renderer.removeClass(this.document.activeElement, 'preload');
this.addWindowWidthListener();
}
this.routerList.components.forEach(group => {
this.componentList = this.componentList.concat([...group.children]);
});
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
const language = this.getLanguageFromURL(event.url);
if (language) {
this.language = language;
this.setPage(event.url);
}
}
if (event instanceof NavigationEnd) {
this.language = this.getLanguageFromURL(this.router.url)!;
this.appService.language$.next(this.language);
this.nzI18nService.setLocale(this.language === 'en' ? en_US : zh_CN);
const currentDemoComponent = this.componentList.find(component => `/${component.path}` === this.router.url);
if (currentDemoComponent) {
const path = currentDemoComponent.path.replace(/\/(en|zh)/, '');
if (this.language === 'en') {
this.updateMateTitle(`${currentDemoComponent.label} | NG-ZORRO`);
} else {
this.updateMateTitle(`${currentDemoComponent.zh}(${currentDemoComponent.label}) | NG-ZORRO`);
}
this.updateDocMetaAndLocale(
currentDemoComponent.description,
`${currentDemoComponent.label}, ${currentDemoComponent.zh}`,
path
);
}
const currentIntroComponent = this.routerList.intro.find(component => `/${component.path}` === this.router.url);
if (currentIntroComponent) {
const path = currentIntroComponent.path.replace(/\/(en|zh)/, '');
if (/docs\/introduce/.test(this.router.url)) {
if (this.language === 'en') {
this.updateMateTitle(`NG-ZORRO - Angular UI component library`);
} else {
this.updateMateTitle(`NG-ZORRO - 企业级 UI 设计语言和 Angular 组件库`);
}
} else {
this.updateMateTitle(`${currentIntroComponent.label} | NG-ZORRO`);
}
this.updateDocMetaAndLocale(currentIntroComponent.description, currentIntroComponent.label, path);
}
if (!currentIntroComponent && !currentDemoComponent) {
if (/components\/overview/.test(this.router.url)) {
if (this.language === 'en') {
this.updateMateTitle('Components | NG-ZORRO');
this.updateDocMetaAndLocale(
'NG-ZORRO provides plenty of UI components to enrich your web applications, and we will improve components experience consistently.',
'overview',
'components/overview'
);
} else {
this.updateMateTitle('组件(Components) | NG-ZORRO');
this.updateDocMetaAndLocale(
'NG-ZORRO 为 Web 应用提供了丰富的基础 UI 组件,我们还将持续探索企业级应用的最佳 UI 实践。',
'overview, 预览',
'components/overview'
);
}
} else {
this.updateMateTitle(`NG-ZORRO - Angular UI component library`);
this.updateDocMetaAndLocale();
}
}
if (this.router.url !== '/' + this.searchComponent) {
this.searchComponent = null;
}
this.setPage(this.router.url);
if (environment.production && this.platform.isBrowser) {
window.scrollTo(0, 0);
}
setTimeout(() => {
const toc = this.router.parseUrl(this.router.url).fragment || '';
if (toc) {
if (this.platform.isBrowser) {
document.querySelector(`#${toc}`)!.scrollIntoView();
}
}
}, 200);
}
});
this.initColor();
this.initTheme();
this.detectLanguage();
}
updateMateTitle(title: string = 'NG-ZORRO | Angular UI component library'): void {
this.title.setTitle(title);
this.meta.updateTag({
property: 'og:title',
content: title
});
this.meta.updateTag({
name: 'twitter:title',
content: title
});
}
updateDocMetaAndLocale(description?: string, keywords?: string, path?: string): void {
const isEn = this.language === 'en';
const enDescription =
'An enterprise-class UI design language and Angular-based implementation with a set of high-quality Angular components, one of best Angular UI library for enterprises';
const zhDescription =
'Ant Design 的 Angular 实现,开发和服务于企业级后台产品,开箱即用的高质量 Angular UI 组件库。';
let descriptionContent = isEn ? enDescription : zhDescription;
if (description) {
descriptionContent = description;
}
if (path) {
this.addHreflang(path);
}
this.meta.updateTag({
name: 'keywords',
content: keywords ? `${defaultKeywords}, ${keywords}` : defaultKeywords
});
this.meta.updateTag({
name: 'description',
content: descriptionContent
});
this.meta.updateTag({
name: 'twitter:description',
content: descriptionContent
});
this.meta.updateTag({
property: 'og:description',
content: descriptionContent
});
this.meta.updateTag({
property: 'og:locale',
content: isEn ? 'en_US' : 'zh_CN'
});
const doc = this.document as Document;
this.renderer.setAttribute(doc.documentElement, 'lang', isEn ? 'en' : 'zh-Hans');
}
private addHreflang(href: string): void {
if (!this.platform.isBrowser) {
const hreflangs = [
{
hreflang: 'en',
suffix: 'en'
},
{
hreflang: 'x-default',
suffix: 'en'
},
{
hreflang: 'zh',
suffix: 'zh'
}
];
hreflangs.forEach(hreflang => {
const link = this.renderer.createElement('link');
this.renderer.setAttribute(link, 'rel', 'alternate');
this.renderer.setAttribute(link, 'hreflang', hreflang.hreflang);
this.renderer.setAttribute(link, 'href', `https://ng.ant.design/${href}/${hreflang.suffix}`);
this.renderer.appendChild(this.document.head, link);
});
}
}
// region: color
color = `#1890ff`;
initColor(): void {
if (!this.platform.isBrowser) {
return;
}
const node = document.createElement('link');
node.rel = 'stylesheet/less';
node.type = 'text/css';
node.href = '/assets/color.less';
document.getElementsByTagName('head')[0].appendChild(node);
}
lessLoaded = false;
changeColor(res: any): void {
if (!this.platform.isBrowser) {
return;
}
const loading = this.nzMessageService.loading(this.language === 'en' ? `Switching color...` : `切换主题中...`, {
nzDuration: 0
});
const changeColor = () => {
(window as any).less
.modifyVars({
'@primary-color': res.color.hex
})
.then(() => {
this.nzMessageService.remove(loading.messageId);
this.nzMessageService.success(this.language === 'en' ? `Switching color successfully` : `应用成功`);
this.color = res.color.hex;
window.scrollTo(0, 0);
});
};
const lessUrl = 'https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js';
if (this.lessLoaded) {
changeColor();
} else {
(window as any).less = {
async: true
};
loadScript(lessUrl).then(() => {
this.lessLoaded = true;
changeColor();
});
}
}
// endregion
private addWindowWidthListener(): void {
if (!this.platform.isBrowser) {
return;
}
this.setShowDrawer();
this.ngZone.runOutsideAngular(() => {
fromEvent(window, 'resize')
.pipe(debounceTime(50))
.subscribe(() => {
this.setShowDrawer();
});
});
}
setShowDrawer(): void {
if (this.platform.isBrowser) {
const width = window.innerWidth;
this.windowWidth = width;
this.showDrawer = width <= 768;
}
}
private detectLanguage(): void {
if (!this.platform.isBrowser) {
return;
}
const language = navigator.language.toLowerCase();
const pathname = location.pathname;
const hasLanguage = pathname.match(/(en|zh)(\/?)$/);
if (language === 'zh-cn' && !hasLanguage) {
this.nzI18nService.setLocale(zh_CN);
this.router.navigate(['docs', 'introduce', 'zh']);
}
}
}