forked from Gbuomprisco/ngx-chips
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtag-input.ts
More file actions
1154 lines (962 loc) · 31.2 KB
/
Copy pathtag-input.ts
File metadata and controls
1154 lines (962 loc) · 31.2 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
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
// angular
import {
Component,
forwardRef,
HostBinding,
Input,
Output,
EventEmitter,
Renderer2,
ViewChild,
ViewChildren,
ContentChildren,
ContentChild,
OnInit,
TemplateRef,
QueryList,
AfterViewInit
} from '@angular/core';
import {
AsyncValidatorFn,
FormControl,
NG_VALUE_ACCESSOR,
ValidatorFn
} from '@angular/forms';
// rx
import { Observable } from 'rxjs';
import { debounceTime, filter, map, first } from 'rxjs/operators';
// ng2-tag-input
import { TagInputAccessor } from '../../core/accessor';
import { TagModel } from '../../core/tag-model';
import { listen } from '../../core/helpers/listen';
import * as constants from '../../core/constants';
import { DragProvider, DraggedTag } from '../../core/providers/drag-provider';
import { TagInputForm } from '../tag-input-form/tag-input-form.component';
import { TagComponent } from '../tag/tag.component';
import { animations } from './animations';
import { defaults } from '../../defaults';
import { TagInputDropdown } from '../dropdown/tag-input-dropdown.component';
const CUSTOM_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TagInputComponent),
multi: true
};
@Component({
selector: 'tag-input',
providers: [CUSTOM_ACCESSOR],
styleUrls: ['./tag-input.style.scss'],
templateUrl: './tag-input.template.html',
animations
})
export class TagInputComponent extends TagInputAccessor implements OnInit, AfterViewInit {
/**
* @name separatorKeys
* @desc keyboard keys with which a user can separate items
*/
@Input() public separatorKeys: string[] = defaults.tagInput.separatorKeys;
/**
* @name separatorKeyCodes
* @desc keyboard key codes with which a user can separate items
*/
@Input() public separatorKeyCodes: number[] = defaults.tagInput.separatorKeyCodes;
/**
* @name placeholder
* @desc the placeholder of the input text
*/
@Input() public placeholder: string = defaults.tagInput.placeholder;
/**
* @name secondaryPlaceholder
* @desc placeholder to appear when the input is empty
*/
@Input() public secondaryPlaceholder: string = defaults.tagInput.secondaryPlaceholder;
/**
* @name maxItems
* @desc maximum number of items that can be added
*/
@Input() public maxItems: number = defaults.tagInput.maxItems;
/**
* @name validators
* @desc array of Validators that are used to validate the tag before it gets appended to the list
*/
@Input() public validators: ValidatorFn[] = defaults.tagInput.validators;
/**
* @name asyncValidators
* @desc array of AsyncValidator that are used to validate the tag before it gets appended to the list
*/
@Input() public asyncValidators: AsyncValidatorFn[] = defaults.tagInput.asyncValidators;
/**
* - if set to true, it will only possible to add items from the autocomplete
* @name onlyFromAutocomplete
*/
@Input() public onlyFromAutocomplete = defaults.tagInput.onlyFromAutocomplete;
/**
* @name errorMessages
*/
@Input() public errorMessages: { [key: string]: string } = defaults.tagInput.errorMessages;
/**
* @name theme
*/
@Input() public theme: string = defaults.tagInput.theme;
/**
* @name onTextChangeDebounce
*/
@Input() public onTextChangeDebounce = defaults.tagInput.onTextChangeDebounce;
/**
* - custom id assigned to the input
* @name id
*/
@Input() public inputId = defaults.tagInput.inputId;
/**
* - custom class assigned to the input
*/
@Input() public inputClass: string = defaults.tagInput.inputClass;
/**
* - option to clear text input when the form is blurred
* @name clearOnBlur
*/
@Input() public clearOnBlur: boolean = defaults.tagInput.clearOnBlur;
/**
* - hideForm
* @name clearOnBlur
*/
@Input() public hideForm: boolean = defaults.tagInput.hideForm;
/**
* @name addOnBlur
*/
@Input() public addOnBlur: boolean = defaults.tagInput.addOnBlur;
/**
* @name addOnPaste
*/
@Input() public addOnPaste: boolean = defaults.tagInput.addOnPaste;
/**
* - pattern used with the native method split() to separate patterns in the string pasted
* @name pasteSplitPattern
*/
@Input() public pasteSplitPattern = defaults.tagInput.pasteSplitPattern;
/**
* @name blinkIfDupe
*/
@Input() public blinkIfDupe = defaults.tagInput.blinkIfDupe;
/**
* @name removable
*/
@Input() public removable = defaults.tagInput.removable;
/**
* @name editable
*/
@Input() public editable: boolean = defaults.tagInput.editable;
/**
* @name allowDupes
*/
@Input() public allowDupes = defaults.tagInput.allowDupes;
/**
* @description if set to true, the newly added tags will be added as strings, and not objects
* @name modelAsStrings
*/
@Input() public modelAsStrings = defaults.tagInput.modelAsStrings;
/**
* @name trimTags
*/
@Input() public trimTags = defaults.tagInput.trimTags;
/**
* @name inputText
*/
@Input() public get inputText(): string {
return this.inputTextValue;
}
/**
* @name ripple
*/
@Input() public ripple: boolean = defaults.tagInput.ripple;
/**
* @name tabindex
* @desc pass through the specified tabindex to the input
*/
@Input() public tabindex: string = defaults.tagInput.tabIndex;
/**
* @name disable
*/
@Input() public disable: boolean = defaults.tagInput.disable;
/**
* @name dragZone
*/
@Input() public dragZone: string = defaults.tagInput.dragZone;
/**
* @name onRemoving
*/
@Input() public onRemoving = defaults.tagInput.onRemoving;
/**
* @name onAdding
*/
@Input() public onAdding = defaults.tagInput.onAdding;
/**
* @name animationDuration
*/
@Input() public animationDuration = defaults.tagInput.animationDuration;
/**
* @name onAdd
* @desc event emitted when adding a new item
*/
@Output() public onAdd = new EventEmitter<TagModel>();
/**
* @name onRemove
* @desc event emitted when removing an existing item
*/
@Output() public onRemove = new EventEmitter<TagModel>();
/**
* @name onSelect
* @desc event emitted when selecting an item
*/
@Output() public onSelect = new EventEmitter<TagModel>();
/**
* @name onFocus
* @desc event emitted when the input is focused
*/
@Output() public onFocus = new EventEmitter<string>();
/**
* @name onFocus
* @desc event emitted when the input is blurred
*/
@Output() public onBlur = new EventEmitter<string>();
/**
* @name onTextChange
* @desc event emitted when the input value changes
*/
@Output() public onTextChange = new EventEmitter<TagModel>();
/**
* - output triggered when text is pasted in the form
* @name onPaste
*/
@Output() public onPaste = new EventEmitter<string>();
/**
* - output triggered when tag entered is not valid
* @name onValidationError
*/
@Output() public onValidationError = new EventEmitter<TagModel>();
/**
* - output triggered when tag is edited
* @name onTagEdited
*/
@Output() public onTagEdited = new EventEmitter<TagModel>();
/**
* @name dropdown
*/
// @ContentChild(forwardRef(() => TagInputDropdown), {static: true}) dropdown: TagInputDropdown;
@ContentChild(TagInputDropdown) public dropdown: TagInputDropdown;
/**
* @name template
* @desc reference to the template if provided by the user
*/
@ContentChildren(TemplateRef, { descendants: false }) public templates: QueryList<TemplateRef<any>>;
/**
* @name inputForm
*/
@ViewChild(TagInputForm) public inputForm: TagInputForm;
/**
* @name selectedTag
* @desc reference to the current selected tag
*/
public selectedTag: TagModel | undefined;
/**
* @name isLoading
*/
public isLoading = false;
/**
* @name inputText
* @param text
*/
public set inputText(text: string) {
this.inputTextValue = text;
this.inputTextChange.emit(text);
}
/**
* @name tags
* @desc list of Element items
*/
@ViewChildren(TagComponent) public tags: QueryList<TagComponent>;
/**
* @name listeners
* @desc array of events that get fired using @fireEvents
*/
private listeners = {
[constants.KEYDOWN]: <{ (fun): any }[]>[],
[constants.KEYUP]: <{ (fun): any }[]>[]
};
/**
* @description emitter for the 2-way data binding inputText value
* @name inputTextChange
*/
@Output() public inputTextChange: EventEmitter<string> = new EventEmitter();
/**
* @description private variable to bind get/set
* @name inputTextValue
*/
public inputTextValue = '';
/**
* @desc removes the tab index if it is set - it will be passed through to the input
* @name tabindexAttr
*/
@HostBinding('attr.tabindex')
public get tabindexAttr(): string {
return this.tabindex !== '' ? '-1' : '';
}
/**
* @name animationMetadata
*/
public animationMetadata: { value: string, params: object };
public errors: string[] = [];
public isProgressBarVisible$: Observable<boolean>;
constructor(private readonly renderer: Renderer2,
public readonly dragProvider: DragProvider) {
super();
}
/**
* @name ngAfterViewInit
*/
public ngAfterViewInit(): void {
// set up listeners
this.setUpKeypressListeners();
this.setupSeparatorKeysListener();
this.setUpInputKeydownListeners();
if (this.onTextChange.observers.length) {
this.setUpTextChangeSubscriber();
}
// if clear on blur is set to true, subscribe to the event and clear the text's form
if (this.clearOnBlur || this.addOnBlur) {
this.setUpOnBlurSubscriber();
}
// if addOnPaste is set to true, register the handler and add items
if (this.addOnPaste) {
this.setUpOnPasteListener();
}
const statusChanges$ = this.inputForm.form.statusChanges;
statusChanges$.pipe(
filter((status: string) => status !== 'PENDING')
).subscribe(() => {
this.errors = this.inputForm.getErrorMessages(this.errorMessages);
});
this.isProgressBarVisible$ = statusChanges$.pipe(
map((status: string) => {
return status === 'PENDING' || this.isLoading;
})
);
// if hideForm is set to true, remove the input
if (this.hideForm) {
this.inputForm.destroy();
}
}
/**
* @name ngOnInit
*/
public ngOnInit(): void {
// if the number of items specified in the model is > of the value of maxItems
// degrade gracefully and let the max number of items to be the number of items in the model
// though, warn the user.
const hasReachedMaxItems = this.maxItems !== undefined &&
this.items &&
this.items.length > this.maxItems;
if (hasReachedMaxItems) {
this.maxItems = this.items.length;
console.warn(constants.MAX_ITEMS_WARNING);
}
// Setting editable to false to fix problem with tags in IE still being editable when
// onlyFromAutocomplete is true
this.editable = this.onlyFromAutocomplete ? false : this.editable;
this.setAnimationMetadata();
}
/**
* @name onRemoveRequested
* @param tag
* @param index
*/
public onRemoveRequested(tag: TagModel, index: number): Promise<TagModel> {
return new Promise(resolve => {
const subscribeFn = (model: TagModel) => {
this.removeItem(model, index);
resolve(tag);
};
this.onRemoving ?
this.onRemoving(tag)
.pipe(first())
.subscribe(subscribeFn) : subscribeFn(tag);
});
}
/**
* @name onAddingRequested
* @param fromAutocomplete {boolean}
* @param tag {TagModel}
* @param index? {number}
* @param giveupFocus? {boolean}
*/
public onAddingRequested(fromAutocomplete: boolean, tag: TagModel,
index?: number, giveupFocus?: boolean): Promise<TagModel> {
return new Promise((resolve, reject) => {
const subscribeFn = (model: TagModel) => {
return this
.addItem(fromAutocomplete, model, index, giveupFocus)
.then(resolve)
.catch(reject);
};
return this.onAdding ?
this.onAdding(tag)
.pipe(first())
.subscribe(subscribeFn, reject) : subscribeFn(tag);
});
}
/**
* @name appendTag
* @param tag {TagModel}
*/
public appendTag = (tag: TagModel, index = this.items.length): void => {
const items = this.items;
const model = this.modelAsStrings ? tag[this.identifyBy] : tag;
this.items = [
...items.slice(0, index),
model,
...items.slice(index, items.length)
];
}
/**
* @name createTag
* @param model
*/
public createTag = (model: TagModel): TagModel => {
const trim = (val: TagModel, key: string): TagModel => {
return typeof val === 'string' ? val.trim() : val[key];
};
return {
...typeof model !== 'string' ? model : {},
[this.displayBy]: this.trimTags ? trim(model, this.displayBy) : model,
[this.identifyBy]: this.trimTags ? trim(model, this.identifyBy) : model
};
}
/**
* @name selectItem
* @desc selects item passed as parameter as the selected tag
* @param item
* @param emit
*/
public selectItem(item: TagModel | undefined, emit = true): void {
const isReadonly = item && typeof item !== 'string' && item.readonly;
if (isReadonly || this.selectedTag === item) {
return;
}
this.selectedTag = item;
if (emit) {
this.onSelect.emit(item);
}
}
/**
* @name fireEvents
* @desc goes through the list of the events for a given eventName, and fires each of them
* @param eventName
* @param $event
*/
public fireEvents(eventName: string, $event?): void {
this.listeners[eventName].forEach(listener => listener.call(this, $event));
}
/**
* @name handleKeydown
* @desc handles action when the user hits a keyboard key
* @param data
*/
public handleKeydown(data: any): void {
const event = data.event;
const key = event.keyCode || event.which;
const shiftKey = event.shiftKey || false;
switch (constants.KEY_PRESS_ACTIONS[key]) {
case constants.ACTIONS_KEYS.DELETE:
if (this.selectedTag && this.removable) {
const index = this.items.indexOf(this.selectedTag);
this.onRemoveRequested(this.selectedTag, index);
}
break;
case constants.ACTIONS_KEYS.SWITCH_PREV:
this.moveToTag(data.model, constants.PREV);
break;
case constants.ACTIONS_KEYS.SWITCH_NEXT:
this.moveToTag(data.model, constants.NEXT);
break;
case constants.ACTIONS_KEYS.TAB:
if (shiftKey) {
if (this.isFirstTag(data.model)) {
return;
}
this.moveToTag(data.model, constants.PREV);
} else {
if (this.isLastTag(data.model) && (this.disable || this.maxItemsReached)) {
return;
}
this.moveToTag(data.model, constants.NEXT);
}
break;
default:
return;
}
// prevent default behaviour
event.preventDefault();
}
public async onFormSubmit() {
try {
await this.onAddingRequested(false, this.formValue);
} catch {
return;
}
}
/**
* @name setInputValue
* @param value
*/
public setInputValue(value: string, emitEvent = true): void {
const control = this.getControl();
// update form value with the transformed item
control.setValue(value, { emitEvent });
}
/**
* @name getControl
*/
private getControl(): FormControl {
return this.inputForm.value as FormControl;
}
/**
* @name focus
* @param applyFocus
* @param displayAutocomplete
*/
public focus(applyFocus = false, displayAutocomplete = false): void {
if (this.dragProvider.getState('dragging')) {
return;
}
this.selectItem(undefined, false);
if (applyFocus) {
this.inputForm.focus();
this.onFocus.emit(this.formValue);
}
}
/**
* @name blur
*/
public blur(): void {
this.onTouched();
this.onBlur.emit(this.formValue);
}
/**
* @name hasErrors
*/
public hasErrors(): boolean {
return !!this.inputForm && this.inputForm.hasErrors();
}
/**
* @name isInputFocused
*/
public isInputFocused(): boolean {
return !!this.inputForm && this.inputForm.isInputFocused();
}
/**
* - this is the one way I found to tell if the template has been passed and it is not
* the template for the menu item
* @name hasCustomTemplate
*/
public hasCustomTemplate(): boolean {
const template = this.templates ? this.templates.first : undefined;
const menuTemplate = this.dropdown && this.dropdown.templates ?
this.dropdown.templates.first : undefined;
return Boolean(template && template !== menuTemplate);
}
/**
* @name maxItemsReached
*/
public get maxItemsReached(): boolean {
return this.maxItems !== undefined &&
this.items.length >= this.maxItems;
}
/**
* @name formValue
*/
public get formValue(): string {
const form = this.inputForm.value;
return form ? form.value : '';
}
/**3
* @name onDragStarted
* @param event
* @param index
*/
public onDragStarted(event: DragEvent, tag: TagModel, index: number): void {
event.stopPropagation();
const item = { zone: this.dragZone, tag, index } as DraggedTag;
this.dragProvider.setSender(this);
this.dragProvider.setDraggedItem(event, item);
this.dragProvider.setState({ dragging: true, index });
}
/**
* @name onDragOver
* @param event
*/
public onDragOver(event: DragEvent, index?: number): void {
this.dragProvider.setState({ dropping: true });
this.dragProvider.setReceiver(this);
event.preventDefault();
}
/**
* @name onTagDropped
* @param event
* @param index
*/
public onTagDropped(event: DragEvent, index?: number): void {
const item = this.dragProvider.getDraggedItem(event);
if (!item || item.zone !== this.dragZone) {
return;
}
this.dragProvider.onTagDropped(item.tag, item.index, index);
event.preventDefault();
event.stopPropagation();
}
/**
* @name isDropping
*/
public isDropping(): boolean {
const isReceiver = this.dragProvider.receiver === this;
const isDropping = this.dragProvider.getState('dropping');
return Boolean(isReceiver && isDropping);
}
/**
* @name onTagBlurred
* @param changedElement {TagModel}
* @param index {number}
*/
public onTagBlurred(changedElement: TagModel, index: number): void {
this.items[index] = changedElement;
this.blur();
}
/**
* @name trackBy
* @param items
*/
public trackBy(index: number, item: TagModel): string {
return item[this.identifyBy];
}
/**
* @name updateEditedTag
* @param tag
*/
public updateEditedTag(tag: TagModel): void {
this.onTagEdited.emit(tag);
}
/**
*
* @param tag
* @param isFromAutocomplete
*/
public isTagValid = (tag: TagModel, fromAutocomplete = false): boolean => {
const selectedItem = this.dropdown ? this.dropdown.selectedItem : undefined;
const value = this.getItemDisplay(tag).trim();
if (selectedItem && !fromAutocomplete || !value) {
return false;
}
const dupe = this.findDupe(tag, fromAutocomplete);
// if so, give a visual cue and return false
if (!this.allowDupes && dupe && this.blinkIfDupe) {
const model = this.tags.find(item => {
return this.getItemValue(item.model) === this.getItemValue(dupe);
});
if (model) {
model.blink();
}
}
const isFromAutocomplete = fromAutocomplete && this.onlyFromAutocomplete;
const assertions = [
// 1. there must be no dupe OR dupes are allowed
!dupe || this.allowDupes,
// 2. check max items has not been reached
!this.maxItemsReached,
// 3. check item comes from autocomplete or onlyFromAutocomplete is false
((isFromAutocomplete) || !this.onlyFromAutocomplete)
];
return assertions.filter(Boolean).length === assertions.length;
}
/**
* @name moveToTag
* @param item
* @param direction
*/
private moveToTag(item: TagModel, direction: string): void {
const isLast = this.isLastTag(item);
const isFirst = this.isFirstTag(item);
const stopSwitch = (direction === constants.NEXT && isLast) ||
(direction === constants.PREV && isFirst);
if (stopSwitch) {
this.focus(true);
return;
}
const offset = direction === constants.NEXT ? 1 : -1;
const index = this.getTagIndex(item) + offset;
const tag = this.getTagAtIndex(index);
return tag.select.call(tag);
}
/**
* @name isFirstTag
* @param item {TagModel}
*/
private isFirstTag(item: TagModel): boolean {
return this.tags.first.model === item;
}
/**
* @name isLastTag
* @param item {TagModel}
*/
private isLastTag(item: TagModel): boolean {
return this.tags.last.model === item;
}
/**
* @name getTagIndex
* @param item
*/
private getTagIndex(item: TagModel): number {
const tags = this.tags.toArray();
return tags.findIndex(tag => tag.model === item);
}
/**
* @name getTagAtIndex
* @param index
*/
private getTagAtIndex(index: number) {
const tags = this.tags.toArray();
return tags[index];
}
/**
* @name removeItem
* @desc removes an item from the array of the model
* @param tag {TagModel}
* @param index {number}
*/
public removeItem(tag: TagModel, index: number): void {
this.items = this.getItemsWithout(index);
// if the removed tag was selected, set it as undefined
if (this.selectedTag === tag) {
this.selectItem(undefined, false);
}
// focus input
this.focus(true, false);
// emit remove event
this.onRemove.emit(tag);
}
/**
* @name addItem
* @desc adds the current text model to the items array
* @param fromAutocomplete {boolean}
* @param item {TagModel}
* @param index? {number}
* @param giveupFocus? {boolean}
*/
private addItem(fromAutocomplete = false, item: TagModel, index?: number, giveupFocus?: boolean):
Promise<TagModel> {
const display = this.getItemDisplay(item);
const tag = this.createTag(item);
if (fromAutocomplete) {
this.setInputValue(this.getItemValue(item, true));
}
return new Promise((resolve, reject) => {
/**
* @name reset
*/
const reset = (): void => {
// reset control and focus input
this.setInputValue('');
if (giveupFocus) {
this.focus(false, false);
} else {
// focus input
this.focus(true, false);
}
resolve(display);
};
const appendItem = (): void => {
this.appendTag(tag, index);
// emit event
this.onAdd.emit(tag);
if (!this.dropdown) {
return;
}
this.dropdown.hide();
if (this.dropdown.showDropdownIfEmpty) {
this.dropdown.show();
}
};
const status = this.inputForm.form.status;
const isTagValid = this.isTagValid(tag, fromAutocomplete);
const onValidationError = () => {
this.onValidationError.emit(tag);
return reject();
};
if (status === 'VALID' && isTagValid) {
appendItem();
return reset();
}
if (status === 'INVALID' || !isTagValid) {
reset();
return onValidationError();
}
if (status === 'PENDING') {
const statusUpdate$ = this.inputForm.form.statusChanges;
return statusUpdate$
.pipe(
filter(statusUpdate => statusUpdate !== 'PENDING'),
first()
)
.subscribe((statusUpdate) => {
if (statusUpdate === 'VALID' && isTagValid) {
appendItem();
return reset();
} else {
reset();
return onValidationError();
}
});
}
});
}
/**
* @name setupSeparatorKeysListener
*/
private setupSeparatorKeysListener(): void {
const useSeparatorKeys = this.separatorKeyCodes.length > 0 || this.separatorKeys.length > 0;
const listener = ($event) => {
const hasKeyCode = this.separatorKeyCodes.indexOf($event.keyCode) >= 0;
const hasKey = this.separatorKeys.indexOf($event.key) >= 0;
// the keyCode of keydown event is 229 when IME is processing the key event.
const isIMEProcessing = $event.keyCode === 229;
if (hasKeyCode || (hasKey && !isIMEProcessing)) {
$event.preventDefault();