forked from syncfusion/ej2-javascript-ui-controls
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchip-list.ts
1068 lines (970 loc) · 40.5 KB
/
chip-list.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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Component, NotifyPropertyChanges, INotifyPropertyChanged, Property, append, isNullOrUndefined } from '@syncfusion/ej2-base';
import { removeClass, KeyboardEventArgs, rippleEffect, closest, MouseEventArgs } from '@syncfusion/ej2-base';
import { EventHandler, detach, EmitType, Event, addClass, compile} from '@syncfusion/ej2-base';
import { ChipListModel } from './chip-list-model';
import { ChipModel } from './chip';
export const classNames: ClassNames = {
chipSet: 'e-chip-set',
chip: 'e-chip',
avatar: 'e-chip-avatar',
text: 'e-chip-text',
icon: 'e-chip-icon',
delete: 'e-chip-delete',
deleteIcon: 'e-dlt-btn',
multiSelection: 'e-multi-selection',
singleSelection: 'e-selection',
active: 'e-active',
chipWrapper: 'e-chip-avatar-wrap',
iconWrapper: 'e-chip-icon-wrap',
focused: 'e-focused',
disabled: 'e-disabled',
rtl: 'e-rtl',
template: 'e-chip-template'
};
/**
* ```props
* index :- Refers to the position of the selected chip in the list of chips
* value :- Refers to the underlying data value associated with the selected chip.
* text :-Refers to the displayed text on the selected chip.
* ```
*/
export type selectionType = 'index' | 'value' | 'text';
/**
* ```props
* Single :- Allows the user to select single chip at the same time.
* Multiple :- Allows the user to select multiple chips at the same time.
* None :- Chips are displayed as read-only.
* ```
*/
export type Selection = 'Single' | 'Multiple' | 'None';
export interface ClassNames {
chipSet: string;
chip: string;
avatar: string;
text: string;
icon: string;
delete: string;
deleteIcon: string;
multiSelection: string;
singleSelection: string;
active: string;
chipWrapper: string;
iconWrapper: string;
focused: string;
disabled: string;
rtl: string;
template: string;
}
interface ChipFields {
text: string;
cssClass: string;
avatarText: string;
avatarIconCss: string;
htmlAttributes: { [key: string]: string };
leadingIconCss: string;
trailingIconCss: string;
enabled: boolean;
value: string | number | null;
leadingIconUrl: string;
trailingIconUrl: string;
template: string | Function;
}
export interface SelectedItems {
/**
* It denotes the selected items text.
*/
texts: string[];
/**
* It denotes the selected items index.
*/
Indexes: number[];
/**
* It denotes the selected items data.
*/
data: string[] | number[] | ChipModel[];
/**
* It denotes the selected items element.
*/
elements: HTMLElement[];
}
export interface SelectedItem {
/**
* It denotes the selected item text.
*/
text: string;
/**
* It denotes the selected item index.
*/
index: number;
/**
* It denotes the selected item data.
*/
data: string | number | ChipModel;
/**
* It denotes the selected item element.
*/
element: HTMLElement;
}
export interface ClickEventArgs {
/**
* It denotes the clicked item text.
*/
text: string;
/**
* It denotes the clicked item index.
*/
index?: number;
/**
* It denotes the clicked item data.
*/
data: string | number | ChipModel;
/**
* It denotes the clicked item element.
*/
element: HTMLElement;
/**
* It denotes whether the clicked item is selected or not.
*/
selected?: boolean;
/**
* It denotes whether the item can be clicked or not.
*/
cancel: boolean;
/**
* It denotes the event.
*/
event: MouseEventArgs | KeyboardEventArgs;
}
export interface DeleteEventArgs {
/**
* It denotes the deleted item text.
*/
text: string;
/**
* It denotes the deleted item index.
*/
index: number;
/**
* It denotes the deleted item data.
*/
data: string | number | ChipModel;
/**
* It denotes the deleted Item element.
*/
element: HTMLElement;
/**
* It denotes whether the item can be deleted or not.
*/
cancel: boolean;
/**
* It denotes the event.
*/
event: MouseEventArgs | KeyboardEventArgs;
}
export interface ChipDeletedEventArgs {
/**
* Specifies the text value of the deleted chip item.
*/
text: string;
/**
* Specifies the index value of the deleted chip item.
*/
index: number;
/**
* Specifies the data of the deleted chip item.
*/
data: string | number | ChipModel;
}
export interface ChipDataArgs {
/**
* It denotes the item text.
*/
text: string | undefined;
/**
* It denotes the Item index.
*/
index: number;
/**
* It denotes the item data.
*/
data: string | number | ChipModel;
/**
* It denotes the item element.
*/
element: HTMLElement;
}
/**
* A chip component is a small block of essential information, mostly used on contacts or filter tags.
* ```html
* <div id="chip"></div>
* ```
* ```typescript
* <script>
* var chipObj = new ChipList();
* chipObj.appendTo("#chip");
* </script>
* ```
*/
@NotifyPropertyChanges
export class ChipList extends Component<HTMLElement> implements INotifyPropertyChanged {
/**
* This chips property helps to render ChipList component.
* {% codeBlock src='chips/chips/index.md' %}{% endcodeBlock %}
*
* @default []
*
*/
@Property([])
public chips: string[] | number[] | ChipModel[];
/**
* Specifies the text content for the chip.
* {% codeBlock src='chips/text/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public text: string;
/**
* Specifies the customized text value for the avatar in the chip.
* {% codeBlock src='chips/avatarText/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public avatarText: string;
/**
* Specifies the icon CSS class for the avatar in the chip.
* {% codeBlock src='chips/avatarIconCss/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public avatarIconCss: string;
/**
* Allows additional HTML attributes such as aria labels, title, name, etc., and
* accepts n number of attributes in a key-value pair format.
* {% codeBlock src='chiplist/htmlAttributes/index.md' %}{% endcodeBlock %}
*
* @default {}
*/
@Property('')
public htmlAttributes: { [key: string]: string };
/**
* Specifies the leading icon CSS class for the chip.
* {% codeBlock src='chips/leadingIconCss/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public leadingIconCss: string;
/**
* Specifies the trailing icon CSS class for the chip.
* {% codeBlock src='chips/trailingIconCss/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public trailingIconCss: string;
/**
* Specifies the leading icon url for the chip.
*
* @default ''
*/
@Property('')
public leadingIconUrl: string;
/**
* Specifies the trailing icon url for the chip.
*
* @default ''
*/
@Property('')
public trailingIconUrl: string;
/**
* Specifies the custom classes to be added to the chip element used to customize the ChipList component.
* {% codeBlock src='chips/cssClass/index.md' %}{% endcodeBlock %}
*
* @default ''
*/
@Property('')
public cssClass: string;
/**
* Specifies a value that indicates whether the chip component is enabled or not.
*
* @default true
*/
@Property(true)
public enabled: boolean;
/**
* Sets or gets the selected chip items in the chip list.
* {% codeBlock src='chips/selectedChips/index.md' %}{% endcodeBlock %}
*
* @default []
*/
@Property([])
public selectedChips: string[] | number[] | number;
/**
* Defines the selection type of the chip. The available types are:
* 1. Input chip
* 2. Choice chip
* 3. Filter chip
* 4. Action chip
*
* @default 'None'
*/
@Property('None')
public selection: Selection;
/**
* Enables or disables the delete functionality of a chip.
* {% codeBlock src='chips/enableDelete/index.md' %}{% endcodeBlock %}
*
* @default false
*/
@Property(false)
public enableDelete: boolean;
/**
* Triggers when the component is created successfully.
* {% codeBlock src='chips/created/index.md' %}{% endcodeBlock %}
*
* @event created
*/
@Event()
public created: EmitType<Event>;
/**
* Triggers when a chip is clicked.
* {% codeBlock src='chips/click/index.md' %}{% endcodeBlock %}
*
* @event click
*/
@Event()
public click: EmitType<ClickEventArgs>;
/**
* Triggers before the click event of the chip is fired.
* This event can be used to prevent the further process and restrict the click action over a chip.
*
* {% codeBlock src='chips/beforeClick/index.md' %}{% endcodeBlock %}
*
* @event beforeClick
*/
@Event()
public beforeClick: EmitType<ClickEventArgs>;
/**
* Fires before removing the chip element.
* {% codeBlock src='chips/delete/index.md' %}{% endcodeBlock %}
*
* @event delete
*/
@Event()
public delete: EmitType<DeleteEventArgs>;
/**
* Triggers when the chip item is removed.
* {% codeBlock src='chips/deleted/index.md' %}{% endcodeBlock %}
*
* @event deleted
*/
@Event()
public deleted: EmitType<ChipDeletedEventArgs>;
constructor(options?: ChipListModel, element?: string | HTMLElement) {
super(options, element);
}
private rippleFunction: Function;
private type: string;
private innerText: string;
public multiSelectedChip: number[] = [];
/**
* Initialize the event handler
*
* @private
*/
protected preRender(): void {
//prerender
}
/**
* To find the chips length.
*
* @returns boolean
* @private
*/
protected chipType(): boolean {
return (this.chips && this.chips.length && this.chips.length > 0) as boolean;
}
/**
* To Initialize the control rendering.
*
* @returns void
* @private
*/
protected render(): void {
this.type = (!isNullOrUndefined(this.chips) && this.chips.length) ? 'chipset' : (this.text || this.element.innerText ? 'chip' : 'chipset');
this.setAttributes();
this.createChip();
this.setRtl();
this.select(this.selectedChips);
this.wireEvent(false);
this.rippleFunction = rippleEffect(this.element, {
selector: '.e-chip'
});
this.renderComplete();
}
private createChip(): void {
this.innerText = (this.element.innerText && this.element.innerText.length !== 0)
? this.element.innerText.trim() : this.element.innerText;
this.element.innerHTML = '';
this.chipCreation(this.type === 'chip' ? [this.innerText ? this.innerText : this.text] : this.chips);
}
private setAttributes(): void {
if (this.type === 'chip') {
if (this.enabled) {this.element.tabIndex = 0; }
this.element.setAttribute('role', 'button');
} else {
this.element.classList.add(classNames.chipSet);
this.element.setAttribute('role', 'listbox');
if (this.selection === 'Multiple') {
this.element.classList.add(classNames.multiSelection);
this.element.setAttribute('aria-multiselectable', 'true');
} else if (this.selection === 'Single') {
this.element.classList.add(classNames.singleSelection);
this.element.setAttribute('aria-multiselectable', 'false');
} else {
this.element.setAttribute('aria-multiselectable', 'false');
}
}
}
private setRtl(): void {
this.element.classList[this.enableRtl ? 'add' : 'remove'](classNames.rtl);
}
private renderTemplates(): void {
if ((this as any).isReact) {
this.renderReactTemplates();
}
}
private templateParser(template: string | Function): Function {
if (template) {
try {
if (typeof template !== 'function' && document.querySelectorAll(template).length) {
return compile(document.querySelector(template).innerHTML.trim());
} else {
return compile(template);
}
} catch (error) {
return compile(template);
}
}
return undefined;
}
private chipCreation(data: string[] | number[] | ChipModel[]): void {
if (isNullOrUndefined(data)) { return; }
let chipListArray: HTMLElement[] = [];
const attributeArray: { [key: string]: string; }[] = [];
for (let i: number = 0; i < data.length; i++) {
const fieldsData: ChipFields = this.getFieldValues(data[i as number]);
const attributesValue: { [key: string]: string; } = fieldsData.htmlAttributes;
attributeArray.push(attributesValue);
const chipArray: HTMLElement[] = this.elementCreation(fieldsData);
const className: string[] = (classNames.chip + ' ' + (fieldsData.enabled ? ' ' : classNames.disabled) + ' ' +
(fieldsData.avatarIconCss || fieldsData.avatarText ? classNames.chipWrapper : (fieldsData.leadingIconCss ?
classNames.iconWrapper : ' ')) + ' ' + fieldsData.cssClass).split(' ').filter((css: string) => css);
if (!this.chipType() || this.type === 'chip') {
chipListArray = chipArray;
addClass([this.element], className);
this.element.setAttribute('aria-label', fieldsData.text);
if (fieldsData.value) {
this.element.setAttribute('data-value', fieldsData.value.toString());
}
} else {
const wrapper: HTMLElement = this.createElement('DIV', {
className: className.join(' '), attrs: {
tabIndex: '0', role: 'option',
'aria-label': fieldsData.text, 'aria-selected': 'false'
}
});
if (this.enableDelete) { wrapper.setAttribute('aria-keyshortcuts', 'Press delete or backspace key to delete'); }
if (fieldsData.value) {
wrapper.setAttribute('data-value', fieldsData.value.toString());
}
if (fieldsData.enabled) { wrapper.setAttribute('aria-disabled', 'false'); }
else {
wrapper.removeAttribute('tabindex');
wrapper.setAttribute('aria-disabled', 'true');
}
if (!isNullOrUndefined(attributeArray[i as number])) {
if (attributeArray.length > i && Object.keys(attributeArray[i as number]).length) {
let htmlAttr: string[] = [];
htmlAttr = (Object.keys(attributeArray[i as number]));
for (let j: number = 0; j < htmlAttr.length; j++) {
wrapper.setAttribute(htmlAttr[j as number], attributeArray[i as number][htmlAttr[j as number]]);
}
}
}
append(chipArray, wrapper);
chipListArray.push(wrapper);
}
}
append(chipListArray, this.element);
}
private getFieldValues(data: string | number | ChipModel): ChipFields {
const chipEnabled: boolean = !(this.enabled.toString() === 'false');
const fields: ChipFields = {
text: typeof data === 'object' ? (data.text ? data.text.toString() : this.text.toString()) :
(!this.chipType() ? (this.innerText ? this.innerText : this.text.toString()) : data.toString()),
cssClass: typeof data === 'object' ? (data.cssClass ? data.cssClass.toString() : this.cssClass.toString()) :
(this.cssClass.toString()),
leadingIconCss: typeof data === 'object' ? (data.leadingIconCss ? data.leadingIconCss.toString() :
this.leadingIconCss.toString()) : (this.leadingIconCss.toString()),
avatarIconCss: typeof data === 'object' ? (data.avatarIconCss ? data.avatarIconCss.toString() :
this.avatarIconCss.toString()) : (this.avatarIconCss.toString()),
avatarText: typeof data === 'object' ? (data.avatarText ? data.avatarText.toString() : this.avatarText.toString()) :
(this.avatarText.toString()),
trailingIconCss: typeof data === 'object' ? (data.trailingIconCss ? data.trailingIconCss.toString() :
this.trailingIconCss.toString()) : (this.trailingIconCss.toString()),
enabled: typeof data === 'object' ? (data.enabled !== undefined ? (data.enabled.toString() === 'false' ? false : true) :
chipEnabled) : (chipEnabled),
value: typeof data === 'object' ? ((data.value ? data.value.toString() : null)) : null,
leadingIconUrl: typeof data === 'object' ? (data.leadingIconUrl ? data.leadingIconUrl.toString() : this.leadingIconUrl) :
this.leadingIconUrl,
trailingIconUrl: typeof data === 'object' ? (data.trailingIconUrl ? data.trailingIconUrl.toString() : this.trailingIconUrl) :
this.trailingIconUrl,
htmlAttributes: typeof data === 'object' ? (data.htmlAttributes ? data.htmlAttributes : this.htmlAttributes) : this.htmlAttributes,
template: typeof data === 'object' ? (data.template ? data.template : null) : null
};
return fields;
}
private elementCreation(fields: ChipFields): HTMLElement[] {
const chipArray: HTMLElement[] = [];
if (fields.avatarText || fields.avatarIconCss) {
const className: string = (classNames.avatar + ' ' + fields.avatarIconCss).trim();
const chipAvatarElement: HTMLElement = this.createElement('span', { className: className });
chipAvatarElement.innerText = fields.avatarText;
chipArray.push(chipAvatarElement);
} else if (fields.leadingIconCss) {
const className: string = (classNames.icon + ' ' + fields.leadingIconCss).trim();
const chipIconElement: HTMLElement = this.createElement('span', { className: className });
chipArray.push(chipIconElement);
} else if (fields.leadingIconUrl) {
const className: string = (classNames.avatar + ' ' + 'image-url').trim();
const chipIconElement: HTMLElement = this.createElement('span', { className: className});
chipIconElement.style.backgroundImage = 'url(' + fields.leadingIconUrl + ')';
chipArray.push(chipIconElement);
}
const chipTextElement: HTMLElement = this.createElement('span', { className: classNames.text });
chipTextElement.innerText = fields.text;
chipArray.push(chipTextElement);
if (fields.template) {
const templateWrapper: HTMLElement = this.createElement('div', { className: classNames.template });
const templateContent: HTMLElement[] = this.templateParser(fields.template)(fields, this, 'template', this.element.id + '_template', false);
append(templateContent, templateWrapper);
chipArray.push(templateWrapper);
this.renderTemplates();
}
if (fields.trailingIconCss || (this.chipType() && this.enableDelete)) {
const className: string = (classNames.delete + ' ' +
(fields.trailingIconCss ? fields.trailingIconCss : classNames.deleteIcon)).trim();
const chipdeleteElement: HTMLElement = this.createElement('span', { className: className });
chipArray.push(chipdeleteElement);
} else if (fields.trailingIconUrl) {
const className: string = ('trailing-icon-url').trim();
const chipIconsElement: HTMLElement = this.createElement('span', { className: className });
chipIconsElement.style.backgroundImage = 'url(' + fields.trailingIconUrl + ')';
chipArray.push(chipIconsElement);
}
return chipArray;
}
/**
* A function that finds chip based on given input.
*
* @param {number | HTMLElement } fields - We can pass index number or element of chip.
* {% codeBlock src='chips/find/index.md' %}{% endcodeBlock %}
*
* @returns {void}
*/
public find(fields: number | HTMLElement): ChipDataArgs {
const chipData : ChipDataArgs = {text: '', index: -1, element: this.element, data: ''};
const chipElement: HTMLElement = fields instanceof HTMLElement ?
fields as HTMLElement : this.element.querySelectorAll('.' + classNames.chip)[fields as number] as HTMLElement;
if (chipElement && this.chipType()) {
chipData.index = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.chip)).indexOf(chipElement);
const chip: string | number | ChipModel = this.chips[chipData.index as number];
if (typeof chip === 'object' && chip !== null) {
const chipModel: ChipModel = chip as ChipModel;
if (chipModel.text !== undefined) {
chipData.text = chipModel.text.toString();
}
} else if (chip !== undefined) {
chipData.text = chip.toString();
}
chipData.data = chip;
chipData.element = chipElement;
}
return chipData;
}
/**
* Allows adding the chip item(s) by passing a single or array of string, number, or ChipModel values.
*
* @param {string[] | number[] | ChipModel[] | string | number | ChipModel} chipsData - We can pass array of string or
* array of number or array of chip model or string data or number data or chip model.
* {% codeBlock src='chips/add/index.md' %}{% endcodeBlock %}
*
* @returns {void}
* @deprecated
*/
public add(chipsData: string[] | number[] | ChipModel[] | string | number | ChipModel): void {
if (this.type !== 'chip') {
const fieldData: string[] | number[] | ChipModel[] = chipsData instanceof Array ?
chipsData : <string[] | number[] | ChipModel[]>[chipsData as string | number | ChipModel];
this.chips = [].slice.call(this.chips).concat(...fieldData as ChipModel[]);
this.chipCreation(fieldData);
}
}
/**
* Allows selecting the chip item(s) by passing a single or array of string, number, or ChipModel values.
*
* @param {number | number[] | HTMLElement | HTMLElement[]} fields - We can pass number or array of number
* or chip element or array of chip element.
* {% codeBlock src='chips/select/index.md' %}{% endcodeBlock %}
*
* @returns {void}
*/
public select(fields: number | number[] | HTMLElement | HTMLElement[] | string[], selectionType?: selectionType): void {
this.onSelect(fields, false, selectionType);
}
private multiSelection(newProp: number[] | string[]): void {
const items: NodeListOf<Element> = this.element.querySelectorAll('.' + 'e-chip');
for (let j: number = 0; j < newProp.length; j++) {
if (typeof newProp[j as number] === 'string') {
for (let k: number = 0; k < items.length; k++) {
if (newProp[j as number] !== k) {
if (newProp[j as number] === items[k as number].attributes[5].value) {
this.multiSelectedChip.push(k);
break;
}
}
}
} else {
this.multiSelectedChip.push(newProp[j as number] as number);
}
}
}
private onSelect(fields: number | number[] | HTMLElement | HTMLElement[] | string[],
callFromProperty: boolean, selectionType?: selectionType): void {
let index: number;
let chipNodes: HTMLElement;
let chipValue: string | number | null = null;
if (this.chipType() && this.selection !== 'None') {
if (callFromProperty) {
const chipElements: NodeListOf<Element> = this.element.querySelectorAll('.' + classNames.chip);
for (let i: number = 0; i < chipElements.length; i++) {
chipElements[i as number].setAttribute('aria-selected', 'false');
chipElements[i as number].classList.remove(classNames.active);
}
}
const fieldData: number[] | HTMLElement[] | string[] = fields instanceof Array ? fields : <number[] | HTMLElement[]>[fields];
for (let i: number = 0; i < fieldData.length; i++) {
let chipElement: HTMLElement = fieldData[i as number] instanceof HTMLElement ? fieldData[i as number] as HTMLElement
: this.element.querySelectorAll('.' + classNames.chip)[fieldData[i as number] as number] as HTMLElement;
if (selectionType !== 'index') {
for (let j: number = 0; j < this.chips.length; j++) {
chipNodes = this.element.querySelectorAll('.' + classNames.chip)[j as number] as HTMLElement;
const fieldsData: ChipFields = this.getFieldValues(this.chips[j as number]);
if (selectionType === 'value') {
if (fieldsData.value !== null) {
chipValue = chipNodes.dataset.value as string | number;
}
} else if (selectionType === 'text') {
chipValue = chipNodes.innerText;
}
if (chipValue === fieldData[i as number].toString()) {
index = j;
chipElement = this.element.querySelectorAll('.' + classNames.chip)[index as number] as HTMLElement;
}
}
}
if (chipElement instanceof HTMLElement) {
this.selectionHandler(chipElement);
}
}
}
}
/**
* Allows removing the chip item(s) by passing a single or array of string, number, or ChipModel values.
*
* @param {number | number[] | HTMLElement | HTMLElement[]} fields - We can pass number or array of number
* or chip element or array of chip element.
* {% codeBlock src='chips/remove/index.md' %}{% endcodeBlock %}
*
* @returns {void}
*/
public remove(fields: number | number[] | HTMLElement | HTMLElement[]): void {
if (this.chipType()) {
const fieldData: number[] | HTMLElement[] = fields instanceof Array ? fields : <number[] | HTMLElement[]>[fields];
const chipElements: HTMLElement[] = [];
const chipCollection: NodeListOf<HTMLElement> = this.element.querySelectorAll('.' + classNames.chip);
(fieldData as HTMLElement[]).forEach((data: HTMLElement | number) => {
const chipElement: HTMLElement = data instanceof HTMLElement ? data as HTMLElement
: chipCollection[data as number] as HTMLElement;
if (chipElement instanceof HTMLElement) {
chipElements.push(chipElement);
}
});
chipElements.forEach((element: HTMLElement) => {
const chips: NodeListOf<HTMLElement> = this.element.querySelectorAll('.' + classNames.chip);
const index: number = Array.prototype.slice.call(chips).indexOf(element);
this.deleteHandler(element, index);
});
}
}
/**
* Returns the selected chip(s) data.
* {% codeBlock src='chips/getSelectedChips/index.md' %}{% endcodeBlock %}
*
* @returns {void}
*/
public getSelectedChips(): SelectedItem | SelectedItems | undefined{
let selectedChips: SelectedItem | SelectedItems | undefined;
if (this.chipType() && this.selection !== 'None') {
const selectedItems: SelectedItems = { texts: [], Indexes: [], data: [], elements: [] };
const items: NodeListOf<Element> = this.element.querySelectorAll('.' + classNames.active);
for (let i: number = 0; i < items.length; i++) {
const chip: HTMLElement = items[i as number] as HTMLElement;
selectedItems.elements.push(chip);
const index: number = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.chip)).indexOf(chip);
selectedItems.Indexes.push(index);
(selectedItems.data as ChipModel[]).push((this.chips as ChipModel[])[index as number]);
const text: string | null | undefined = typeof this.chips[index as number] === 'object' ?
(this.chips[index as number] as ChipModel).text ? (this.chips[index as number] as ChipModel).text
: null : this.chips[index as number].toString();
selectedItems.texts.push(text as string);
}
const selectedItem: SelectedItem = {
text: selectedItems.texts[0], index: selectedItems.Indexes[0],
data: selectedItems.data[0], element: selectedItems.elements[0]
};
selectedChips = !isNullOrUndefined(selectedItem.index) ?
(this.selection === 'Multiple' ? selectedItems : selectedItem) : undefined;
}
return selectedChips;
}
private wireEvent(unWireEvent: boolean): void {
if (!unWireEvent) {
EventHandler.add(this.element, 'click', this.clickHandler, this);
EventHandler.add(this.element, 'focusout', this.focusOutHandler, this);
EventHandler.add(this.element, 'keydown', this.keyHandler, this);
EventHandler.add(this.element, 'keyup', this.keyHandler, this);
} else {
EventHandler.remove(this.element, 'click', this.clickHandler);
EventHandler.remove(this.element, 'focusout', this.focusOutHandler);
EventHandler.remove(this.element, 'keydown', this.keyHandler);
EventHandler.remove(this.element, 'keyup', this.keyHandler);
}
}
private keyHandler(e: KeyboardEventArgs): void {
if ((e.target as HTMLElement).classList.contains(classNames.chip)) {
if (e.type === 'keydown') {
if (e.keyCode === 13 || e.keyCode === 32) {
this.clickHandler(e);
} else if ((e.keyCode === 46 || e.keyCode === 8) && this.enableDelete) {
this.clickHandler(e, true);
}
} else if (e.keyCode === 9) {
this.focusInHandler(e.target as HTMLElement);
}
}
}
private focusInHandler(chipWrapper: HTMLElement): void {
if (!chipWrapper.classList.contains(classNames.focused)) {
chipWrapper.classList.add(classNames.focused);
}
}
private focusOutHandler(e: MouseEventArgs): void {
const chipWrapper: HTMLElement = <HTMLElement>closest((e.target as HTMLElement), '.' + classNames.chip);
const focusedElement: HTMLElement | null = !this.chipType() ? (this.element.classList.contains(classNames.focused) ?
this.element : null) : this.element.querySelector('.' + classNames.focused);
if (chipWrapper && focusedElement) {
focusedElement.classList.remove(classNames.focused);
}
}
private clickHandler(e: MouseEventArgs | KeyboardEventArgs, del: boolean = false): void {
const chipWrapper: HTMLElement = <HTMLElement>closest((e.target as HTMLElement), '.' + classNames.chip);
if (chipWrapper) {
let chipDataArgs: object;
if (this.chipType()) {
chipDataArgs = this.find(chipWrapper);
} else {
const index: number = Array.prototype.slice.call(this.element.querySelectorAll('.' + classNames.chip)).indexOf(chipWrapper);
chipDataArgs = {
text: this.innerText ? this.innerText : this.text,
element: chipWrapper, data: this.text, index: index
};
}
(chipDataArgs as ClickEventArgs).event = e;
(chipDataArgs as ClickEventArgs).cancel = false;
this.trigger('beforeClick', chipDataArgs as ClickEventArgs, (observedArgs: ClickEventArgs) => {
if (!(observedArgs as ClickEventArgs).cancel) {
this.clickEventHandler(observedArgs.element, e, del);
}
});
}
}
private clickEventHandler(chipWrapper: HTMLElement, e: MouseEventArgs | KeyboardEventArgs, del: boolean): void {
if (this.chipType()) {
const chipData: ChipDataArgs = this.find(chipWrapper);
(chipData as ClickEventArgs).event = e;
const deleteElement: HTMLElement | undefined = (e.target as HTMLElement).classList.contains(classNames.deleteIcon) ?
e.target as HTMLElement : (del ? chipWrapper.querySelector('.' + classNames.deleteIcon) as HTMLElement : undefined);
if (deleteElement && this.enableDelete) {
(chipData as DeleteEventArgs).cancel = false;
const deletedItemArgs: DeleteEventArgs = chipData as DeleteEventArgs;
this.trigger('delete', deletedItemArgs, (observedArgs: DeleteEventArgs) => {
if (!observedArgs.cancel) {
this.deleteHandler(observedArgs.element, observedArgs.index);
this.selectionHandler(chipWrapper);
(chipData as ClickEventArgs).selected = observedArgs.element.classList.contains(classNames.active);
const selectedItemArgs: ClickEventArgs = chipData as ClickEventArgs;
this.trigger('click', selectedItemArgs);
const chipElement: HTMLElement = this.element.querySelectorAll('.' + classNames.chip)[observedArgs.index] as HTMLElement;
if (chipElement) {
chipElement.focus();
this.focusInHandler(chipElement);
}
}
});
} else if (this.selection !== 'None') {
this.selectionHandler(chipWrapper);
(chipData as ClickEventArgs).selected = chipWrapper.classList.contains(classNames.active);
const selectedItemArgs: ClickEventArgs = chipData as ClickEventArgs;
this.trigger('click', selectedItemArgs);
} else {
this.focusInHandler(chipWrapper);
const clickedItemArgs: ClickEventArgs = chipData as ClickEventArgs;
this.trigger('click', clickedItemArgs);
}
} else {
this.focusInHandler(chipWrapper);
const clickedItemArgs: ClickEventArgs = {
text: this.innerText ? this.innerText : this.text,
element: chipWrapper, data: this.text, event: e
} as ClickEventArgs;
this.trigger('click', clickedItemArgs);
}
}
private selectionHandler(chipWrapper: HTMLElement): void {
if (this.selection === 'Single') {
const activeElement: HTMLElement = this.element.querySelector('.' + classNames.active) as HTMLElement;
if (activeElement && activeElement !== chipWrapper) {
activeElement.classList.remove(classNames.active);
activeElement.setAttribute('aria-selected', 'false');
}
this.setProperties({ selectedChips: null }, true);
} else {
this.setProperties({ selectedChips: [] }, true);
}
if (chipWrapper.classList.contains(classNames.active)) {
chipWrapper.classList.remove(classNames.active);
chipWrapper.setAttribute('aria-selected', 'false');
} else {
chipWrapper.classList.add(classNames.active);
chipWrapper.setAttribute('aria-selected', 'true');
}
this.updateSelectedChips();
}
private updateSelectedChips(): void {
const chipListEle: NodeListOf<Element> = this.element.querySelectorAll('.e-chip');
const chipCollIndex: number[] = [];
const chipCollValue: string[] = [];
let chip: string | number | null = null;
let value: string | null = null;
for (let i: number = 0; i < chipListEle.length; i++) {
const selectedEle: Element = this.element.querySelectorAll('.e-chip')[i as number];
if (selectedEle.getAttribute('aria-selected') === 'true') {
value = selectedEle.getAttribute('data-value');
if (this.selection === 'Single' && selectedEle.classList.contains('e-active')) {
chip = value ? value : i;
break;
} else {
chip = value ? chipCollValue.push(value) : chipCollIndex.push(i);
}
}
}
this.setProperties({ selectedChips: this.selection === 'Single' ? chip : value ? chipCollValue : chipCollIndex }, true);
}
private deleteHandler(chipWrapper: HTMLElement, index: number): void {
// Used to store the deleted chip item details.
const deletedChipData: ChipDataArgs = this.find(chipWrapper);
this.chips.splice(index, 1);
this.setProperties({ chips: this.chips }, true);
detach(chipWrapper);
this.trigger('deleted', deletedChipData as ChipDeletedEventArgs);
}
/**
* Removes the component from the DOM and detaches all its related event handlers. Also, it removes the attributes and classes.
* {% codeBlock src='chips/destroy/index.md' %}{% endcodeBlock %}
*
* @returns {void}
*/
public destroy(): void {
this.clearTemplate();
removeClass([this.element], [classNames.chipSet, classNames.chip, classNames.rtl,
classNames.multiSelection, classNames.singleSelection, classNames.disabled, classNames.chipWrapper, classNames.iconWrapper,
classNames.active, classNames.focused].concat(this.cssClass ? this.cssClass.toString().split(' ').filter((css: string) => css) : []));