-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
index.ts
731 lines (676 loc) · 18.9 KB
/
index.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
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/**
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
*/
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import {
Component,
Inject,
Input,
OnDestroy,
OnInit,
PLATFORM_ID,
TemplateRef,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { of, Subscription } from 'rxjs';
import { manifest, ThemeType } from '@ant-design/icons-angular';
import { AccountBookFill } from '@ant-design/icons-angular/icons';
import { PREFIX } from 'ng-zorro-antd/core/logger';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzIconService } from 'ng-zorro-antd/icon';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam, NzUploadFile, NzUploadXHRArgs } from 'ng-zorro-antd/upload';
export interface Categories {
direction: string[];
suggestion: string[];
logo: string[];
data: string[];
edit: string[];
other?: string[];
}
declare global {
interface Window {
antdIconClassifier: AntdIconClassifier;
}
}
interface AntdIconClassifier {
load: Function;
predict: Function;
}
interface Result {
className: string;
score: number;
}
interface Icon {
type: string;
score: number;
}
const direction = [
'StepBackward',
'StepForward',
'FastBackward',
'FastForward',
'Shrink',
'ArrowsAlt',
'Down',
'Up',
'Left',
'Right',
'CaretUp',
'CaretDown',
'CaretLeft',
'CaretRight',
'UpCircle',
'DownCircle',
'LeftCircle',
'RightCircle',
'DoubleRight',
'DoubleLeft',
'VerticalLeft',
'VerticalRight',
'VerticalAlignTop',
'VerticalAlignMiddle',
'VerticalAlignBottom',
'Forward',
'Backward',
'Rollback',
'Enter',
'Retweet',
'Swap',
'SwapLeft',
'SwapRight',
'ArrowUp',
'ArrowDown',
'ArrowLeft',
'ArrowRight',
'PlayCircle',
'UpSquare',
'DownSquare',
'LeftSquare',
'RightSquare',
'Login',
'Logout',
'MenuFold',
'MenuUnfold',
'BorderBottom',
'BorderHorizontal',
'BorderInner',
'BorderOuter',
'BorderLeft',
'BorderRight',
'BorderTop',
'BorderVerticle',
'PicCenter',
'PicLeft',
'PicRight',
'RadiusBottomleft',
'RadiusBottomright',
'RadiusUpleft',
'RadiusUpright',
'Fullscreen',
'FullscreenExit'
];
const suggestion = [
'Question',
'QuestionCircle',
'Plus',
'PlusCircle',
'Pause',
'PauseCircle',
'Minus',
'MinusCircle',
'PlusSquare',
'MinusSquare',
'Info',
'InfoCircle',
'Exclamation',
'ExclamationCircle',
'Close',
'CloseCircle',
'CloseSquare',
'Check',
'CheckCircle',
'CheckSquare',
'ClockCircle',
'Warning',
'IssuesClose',
'Stop'
];
const edit = [
'Edit',
'Form',
'Copy',
'Scissor',
'Delete',
'Snippets',
'Diff',
'Highlight',
'AlignCenter',
'AlignLeft',
'AlignRight',
'BgColors',
'Bold',
'Italic',
'Underline',
'Strikethrough',
'Redo',
'Undo',
'ZoomIn',
'ZoomOut',
'FontColors',
'FontSize',
'LineHeight',
'Dash',
'SmallDash',
'SortAscending',
'SortDescending',
'Drag',
'OrderedList',
'UnorderedList',
'RadiusSetting',
'ColumnWidth',
'ColumnHeight'
];
const data = [
'AreaChart',
'PieChart',
'BarChart',
'DotChart',
'LineChart',
'RadarChart',
'HeatMap',
'Fall',
'Rise',
'Stock',
'BoxPlot',
'Fund',
'Sliders'
];
const logo = [
'Android',
'Apple',
'Windows',
'Ie',
'Chrome',
'Github',
'Aliwangwang',
'Dingding',
'WeiboSquare',
'WeiboCircle',
'TaobaoCircle',
'Html5',
'Weibo',
'Twitter',
'Wechat',
'Youtube',
'AlipayCircle',
'Taobao',
'Skype',
'Qq',
'MediumWorkmark',
'Gitlab',
'Medium',
'Linkedin',
'GooglePlus',
'Dropbox',
'Facebook',
'Codepen',
'CodeSandbox',
'CodeSandboxCircle',
'Amazon',
'Google',
'CodepenCircle',
'Alipay',
'AntDesign',
'AntCloud',
'Aliyun',
'Zhihu',
'Slack',
'SlackSquare',
'Behance',
'BehanceSquare',
'Dribbble',
'DribbbleSquare',
'Instagram',
'Yuque',
'Alibaba',
'Yahoo',
'Reddit',
'Sketch'
];
const categories: Categories = {
direction,
suggestion,
edit,
data,
logo
};
const newIconNames: string[] = [
// direction
'border-outter',
'radius-upright',
// suggestion
// edit
'colum-width',
// data
// other
'eye-invisible',
'batch-folding',
// logo
'code-sandbox',
'code-sandbox-circle'
];
declare const locale: NzSafeAny;
@Component({
selector: 'nz-page-demo-icon',
template: `
<h3>{{ localeObj.chooseTheme }}</h3>
<div class="icon-selector">
<nz-radio-group [ngModel]="currentTheme" (ngModelChange)="setIconsShouldBeDisplayed($event)">
<label nz-radio-button nzValue="outline">
<span nz-icon>
<svg>
<path
d="M864 64H160C107 64 64 107 64 160v704c0 53 43 96 96 96h704c53 0 96-43 96-96V160c0-53-43-96-96-96z m-12 800H172c-6.6 0-12-5.4-12-12V172c0-6.6 5.4-12 12-12h680c6.6 0 12 5.4 12 12v680c0 6.6-5.4 12-12 12z"
></path>
</svg>
</span>
Outlined
</label>
<label nz-radio-button nzValue="fill">
<span nz-icon>
<svg>
<path
d="M864 64H160C107 64 64 107 64 160v704c0 53 43 96 96 96h704c53 0 96-43 96-96V160c0-53-43-96-96-96z"
></path>
</svg>
</span>
Filled
</label>
<label nz-radio-button nzValue="twotone">
<span nz-icon>
<svg>
<path
d="M16 512c0 273.932 222.066 496 496 496s496-222.068 496-496S785.932 16 512 16 16 238.066 16 512z m496 368V144c203.41 0 368 164.622 368 368 0 203.41-164.622 368-368 368z"
></path>
</svg>
</span>
Two Tone
</label>
</nz-radio-group>
<nz-input-group nzSearch [nzSuffix]="suffixIconCamera" [nzAddOnAfter]="addOnAfterIconSearch">
<input
nz-input
[placeholder]="localeObj.search"
[(ngModel)]="searchingString"
(ngModelChange)="onSearchChange()"
/>
</nz-input-group>
<ng-template #suffixIconCamera>
<div class="icon-pic-searcher">
<span
class="icon-pic-btn"
nz-icon
nz-popover
[nzPopoverTrigger]="null"
[(nzPopoverVisible)]="popoverVisible"
[nzPopoverContent]="localeObj.picSearcherIntro"
(click)="toggleModal()"
>
<svg viewBox="64 64 896 896">
<path
d="M864 248H728l-32.4-90.8a32.07 32.07 0 00-30.2-21.2H358.6c-13.5 0-25.6 8.5-30.1 21.2L296 248H160c-44.2 0-80 35.8-80 80v456c0 44.2 35.8 80 80 80h704c44.2 0 80-35.8 80-80V328c0-44.2-35.8-80-80-80zm8 536c0 4.4-3.6 8-8 8H160c-4.4 0-8-3.6-8-8V328c0-4.4 3.6-8 8-8h186.7l17.1-47.8 22.9-64.2h250.5l22.9 64.2 17.1 47.8H864c4.4 0 8 3.6 8 8v456zM512 384c-88.4 0-160 71.6-160 160s71.6 160 160 160 160-71.6 160-160-71.6-160-160-160zm0 256c-53 0-96-43-96-96s43-96 96-96 96 43 96 96-43 96-96 96z"
></path>
</svg>
</span>
</div>
</ng-template>
<ng-template #addOnAfterIconSearch>
<button nz-button nzType="default" nzSearch>
<span nz-icon nzType="search"></span>
</button>
</ng-template>
</div>
@for (category of categoryNames; track category; let i = $index) {
<h3>{{ localeObj[category] }}</h3>
<ul class="anticons-list">
@for (icon of displayedNames[i].icons; track trackByFn) {
<li (click)="onIconClick($event, icon)">
<span nz-icon [nzType]="kebabCase(icon)" [nzTheme]="currentTheme"></span>
<span class="anticon-class">
@if (isNewIcon(icon)) {
<nz-badge nzDot>
{{ icon }}
</nz-badge>
} @else {
{{ icon }}
}
</span>
</li>
}
</ul>
}
<nz-modal
[nzTitle]="localeObj.picSearcherTitle"
[(nzVisible)]="modalVisible"
(nzOnCancel)="toggleModal()"
[nzFooter]="null"
>
<ng-container *nzModalContent>
@if (modelLoaded) {
<nz-upload
nzType="drag"
nzAccept="image/jpeg, image/png"
nzListType="picture"
[nzCustomRequest]="customRequestUploadFile"
[nzFileList]="fileList"
[nzShowUploadList]="{ showPreviewIcon: false, showRemoveIcon: false }"
>
<p class="ant-upload-drag-icon">
<span nz-icon nzType="inbox" nzTheme="outline"></span>
</p>
<p class="ant-upload-text">{{ localeObj.picSearcherUploadText }}</p>
<p class="ant-upload-hint">{{ localeObj.picSearcherUploadHint }}</p>
</nz-upload>
<nz-spin [nzSpinning]="loading" [nzTip]="localeObj.picSearcherMatching">
<div class="icon-pic-search-result">
@if (icons.length) {
<div class="result-tip">
{{ localeObj.picSearcherResultTip }}
</div>
<table>
<thead>
<tr>
<th class="col-icon">
{{ localeObj.picSearcherThIcon }}
</th>
<th>{{ localeObj.picSearcherThScore }}</th>
</tr>
</thead>
<tbody>
@for (icon of icons; track icon) {
<tr>
<td class="col-icon">
<span
nz-icon
nz-tooltip
[nzTooltipTitle]="icon.type"
nzTooltipPlacement="right"
[nzType]="icon.type"
[nzTheme]="currentTheme"
(click)="onIconClick($event, icon.type)"
>
</span>
</td>
<td>
<nz-progress nzStrokeLinecap="round" [nzPercent]="icon.score"></nz-progress>
</td>
</tr>
}
</tbody>
</table>
}
@if (error) {
<nz-result nzStatus="500" nzTitle="503" [nzSubTitle]="localeObj.picSearcherServerError" />
}
</div>
</nz-spin>
} @else {
<nz-spin [nzTip]="localeObj.picSearcherModelLoading">
<div style="height: 100px;"></div>
</nz-spin>
}
</ng-container>
</nz-modal>
`,
styles: [
`
h3 {
margin: 1.6em 0 0.6em;
font-size: 18px;
}
`,
`
ul.anticons-list li .anticon {
font-size: 24px;
}
`,
`
.icon-selector {
display: flex;
justify-content: space-between;
}
nz-input-group {
margin-left: 10px;
flex: 1 1 0%;
}
`
]
})
export class NzPageDemoIconComponent implements OnInit, OnDestroy {
displayedNames: Array<{ name: string; icons: string[] }> = [];
categoryNames: string[] = [];
currentTheme: ThemeType = 'outline';
localeObj: { [key: string]: string } = locale;
searchingString = '';
error = false;
loading = false;
modelLoaded = false;
modalVisible = false;
popoverVisible = false;
fileList: NzUploadFile[] = [];
icons: Icon[] = [];
trackByFn = (_index: number, item: string): string => `${item}-${this.currentTheme}`;
kebabCase = (str: string): string => kebabCase(str);
isNewIcon = (name: string): boolean => newIconNames.indexOf(name) > -1;
onIconClick(e: MouseEvent, icon: string): void {
const target = e.target as HTMLElement;
const copiedString = `<span nz-icon nzType="${kebabCase(icon)}" nzTheme="${this.currentTheme}"></span>`;
target.classList.add('copied');
this._copy(copiedString).then(() => {
setTimeout(() => {
target.classList.remove('copied');
}, 1000);
});
const content = this.getCopiedStringTemplateRef(copiedString);
this.message.success(content);
}
private _copy(value: string): Promise<string> {
const promise = new Promise<string>((resolve): void => {
let copyTextArea: HTMLTextAreaElement | null = null;
try {
copyTextArea = this.dom.createElement('textarea') as HTMLTextAreaElement;
copyTextArea.style.height = '0px';
copyTextArea.style.opacity = '0';
copyTextArea.style.width = '0px';
this.dom.body.appendChild(copyTextArea);
copyTextArea.value = value;
copyTextArea.select();
this.dom.execCommand('copy');
resolve(value);
} finally {
if (copyTextArea && copyTextArea.parentNode) {
copyTextArea.parentNode.removeChild(copyTextArea);
}
}
});
return promise;
}
prepareIcons(): void {
const theme = this.currentTheme;
const currentThemeIcons = (manifest[theme] as string[])
.filter((name: string) => !['interation', 'canlendar'].includes(name))
.map(name => upperCamelCase(name));
let notEmptyCategories = Object.keys(categories).map(category => ({
name: category,
icons: categories[category as keyof Categories]!.filter(
(name: string) =>
currentThemeIcons.indexOf(name) > -1 && name.toLowerCase().includes(this.searchingString.toLowerCase())
)
}));
const otherIcons = currentThemeIcons
.filter(icon => notEmptyCategories.filter(({ name }) => name !== 'all').every(item => !item.icons.includes(icon)))
.filter(name => name.toLowerCase().includes(this.searchingString.toLocaleLowerCase()));
notEmptyCategories.push({ name: 'other', icons: otherIcons });
notEmptyCategories = notEmptyCategories.filter(({ icons }) => Boolean(icons.length));
this.displayedNames = notEmptyCategories;
this.categoryNames = notEmptyCategories.map(({ name }) => name);
}
setIconsShouldBeDisplayed(theme: ThemeType): void {
this.currentTheme = theme;
this.prepareIcons();
}
onSearchChange(): void {
this.prepareIcons();
}
private getCopiedStringTemplateRef(copiedString: string): TemplateRef<void> {
this.viewContainerRef.clear();
const componentRef = this.viewContainerRef.createComponent(NzPageDemoIconCopiedCodeComponent);
componentRef.instance.copiedCode = copiedString;
return componentRef.instance.templateRef;
}
private loadModel(): void {
if (window.antdIconClassifier) {
this.onLoad();
return;
}
const script = this.dom.createElement('script');
const source = 'https://cdn.jsdelivr.net/gh/lewis617/antd-icon-classifier@0.0/dist/main.js';
script.type = 'text/javascript';
script.src = source;
script.onload = async () => {
await window.antdIconClassifier?.load();
this.onLoad();
};
script.onerror = () => {
throw new Error(`${PREFIX} cannot load assets of antd icon classifier from source "${source}".`);
};
this.dom.head.appendChild(script);
}
private onLoad(): void {
this.modelLoaded = true;
this.dom.addEventListener('paste', this.onPaste as EventListener);
}
private onPaste = (event: ClipboardEvent): void => {
const items = event.clipboardData && event.clipboardData.items;
let file = null;
if (items && items.length) {
for (let i = 0; i < items.length; i += 1) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
}
if (file) this.uploadFile(file);
};
// We don't need to upload it, so just fake api here
customRequestUploadFile = (o: NzUploadXHRArgs): Subscription => {
return of(true).subscribe(() => {
this.uploadFile(o.file);
});
};
private uploadFile = (file: File | NzUploadFile): void => {
this.loading = true;
const reader: FileReader = new FileReader();
reader.onload = () => {
this.toImage(reader.result as string).then(this.predict);
this.fileList = [{ uid: '1', name: file.name, status: 'done', url: reader.result as string }];
};
reader.readAsDataURL(file as File);
};
private toImage(url: string): Promise<HTMLImageElement> {
return new Promise(resolve => {
const img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
img.onload = function onload() {
resolve(img);
};
});
}
private predict = (imgEl: HTMLImageElement): void => {
try {
const results = window.antdIconClassifier?.predict(imgEl);
this.icons = results.map((r: Result) => ({
score: Math.ceil(r.score * 100),
type: r.className.replace(/\s/g, '-')
}));
this.loading = false;
this.error = false;
} catch (err) {
this.loading = false;
this.error = true;
}
};
toggleModal(): void {
this.modalVisible = !this.modalVisible;
this.popoverVisible = false;
this.fileList = [];
this.icons = [];
if (!localStorage.getItem('disableIconTip')) {
localStorage.setItem('disableIconTip', 'true');
}
}
handleChange({ file, fileList }: NzUploadChangeParam): void {
if (file.status === 'uploading' || file.status === 'error') {
this.fileList = fileList;
} else if (file.status === 'done') {
this.uploadFile(file.originFileObj!);
}
}
constructor(
/* eslint-disable @typescript-eslint/no-explicit-any */
@Inject(DOCUMENT) private dom: any,
@Inject(PLATFORM_ID) private platformId: any,
/* eslint-enable @typescript-eslint/no-explicit-any */
private _iconService: NzIconService,
private message: NzMessageService,
private viewContainerRef: ViewContainerRef
) {
// This is to test that tree shake works!
this._iconService.addIcon(AccountBookFill);
}
ngOnInit(): void {
this.setIconsShouldBeDisplayed('outline');
// load model in browser
if (isPlatformBrowser(this.platformId)) {
this.loadModel();
this.popoverVisible = !localStorage.getItem('disableIconTip');
}
}
ngOnDestroy(): void {
this.dom.removeEventListener('paste', this.onPaste as EventListener);
this.viewContainerRef.clear();
}
}
@Component({
selector: 'nz-page-demo-icon-copied-code',
template: `
<ng-template #templateRef>
<span>
<code class="copied-code">{{ copiedCode }}</code> copied 🎉
</span>
</ng-template>
`
})
export class NzPageDemoIconCopiedCodeComponent {
@Input() copiedCode!: string;
@ViewChild('templateRef', { static: true }) templateRef!: TemplateRef<void>;
}
function camelCase(value: string): string {
return value.replace(/-\w/g, (_r, i) => value.charAt(i + 1).toUpperCase());
}
function upperCamelCase(value: string): string {
const camelCased = camelCase(value);
return camelCased.charAt(0).toUpperCase() + camelCased.slice(1);
}
function kebabCase(value: string): string {
return value
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/([0-9])([a-zA-Z]+)$/g, '-$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase();
}