Project

General

Profile

1
import {Component, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange} from '@angular/core';
2
import {Value} from '../../searchPages/searchUtils/searchHelperClasses.class';
3
import {ISVocabulariesService} from './ISVocabularies.service';
4
import {RefineFieldResultsService} from '../../services/refineFieldResults.service';
5
//Usage example
6
//<static-autocomplete [(filtered)] =filtered [(selected)] =selected placeHolderMessage = "Search for countries" title = "Countries:" (keywordChange)="keywordChanged($event)"></static-autocomplete>
7

    
8
@Component({
9
    selector: 'static-autocomplete',
10
    styleUrls:  ['../autoComplete.component.css'],
11
    host: {
12
       '(document:click)': 'handleClick($event)',
13
   },
14
    template: `
15
        <span class="custom-autocomplete uk-width-1-1">
16
            <span   *ngIf = "showSelected && selectedValue != ''">
17
              <span  class="uk-alert-default" data-uk-alert=""  *ngFor="let item of selected"  [title]="showItem(item)"> <span >{{showItem(item)}} </span>
18
                <span (click)="remove(item)" aria-hidden="true" title="Remove selection" > <i class="uk-icon-remove clickable"></i> </span>
19
              </span>
20
            </span>
21
            <input *ngIf = "showInput " type="text" class="auto-complete-input validate filter-input input-sm form-control  uk-form-width-small " [placeholder]=placeHolderMessage [(ngModel)]=keyword (keyup)=filter()   >
22
            <!--span *ngIf="showLoading" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading... </span>
23
            <span *ngIf="warningMessage.length > 0" class="uk-alert uk-alert-warning" data-uk-alert=""> {{warningMessage}} <a href="" class="uk-alert-close uk-close"></a></span-->
24
            <div  *ngIf="focus && showInput"  class="uk-dropdown" aria-expanded="true" style="display:block" >
25
                  <ul class="uk-nav uk-nav-autocomplete uk-autocomplete-results" >
26
                      <li>
27
                      <span *ngIf="showLoading" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading... </span>
28
                      <span *ngIf="filtered.length > 0"  >  {{results}} results found:</span>
29
                      <span *ngIf="filtered.length == 0" class="uk-alert uk-alert-info" data-uk-alert=""> No results found</span>
30
                      </li>
31
                      <li    *ngFor=" let item of filtered">
32
                          <a (click)="select(item)"  [title]="showItem(item)" style="text-overflow: ellipsis; ">{{showItem(item)}}</a>
33
                      </li>
34
                  </ul>
35
            </div>
36
        </span>
37

    
38
        `
39
})
40
export class StaticAutoCompleteComponent implements OnChanges{
41
    @Input() placeHolderMessage = "Search for entries";
42
    @Input() title = "Autocomplete";
43
    @Output() addItem = new EventEmitter(); // when selected list  changes update parent component
44
    @Output() selectedValueChanged = new EventEmitter(); // when changed  a method for filtering will be called
45
    @Output() listUpdated = new EventEmitter(); // when changed  a method for filtering will be called
46
    @Input() public list = []; // the entries resulted after filtering function
47
    @Input() public filtered = []; // the entries resulted after filtering function
48
    @Input() public selected = []; // the entries selected from user
49
    @Input() public keywordlimit = 3; // the minimum length of keyword
50
    @Input() public showSelected = true; // the minimum length of keyword
51
    @Input() public multipleSelections:boolean = true;
52
    @Input() public allowDuplicates:boolean = false;
53
    @Input() public selectedValue:string = '';
54
    @Input() public vocabularyId:string ;
55
    @Input() public fieldName:string ;
56
    @Input() public entityName:string ;
57
    @Input() public fieldId:string ;
58

    
59
    @Input() public keyword = '';
60
    @Input() public type = 'search' //search, result, context, project
61
    public warningMessage = "";
62
    public infoMessage = "";
63
    public showLoading:boolean = false;
64
    public tries = 0;
65
    public showInput = true;
66
    public sub;
67
    public done = false;
68
    public results = 0;
69
    public focus:boolean  = false;
70
    public currentFieldId: string ;
71
    constructor ( private _vocabulariesService: ISVocabulariesService,private _refineService: RefineFieldResultsService, private myElement: ElementRef) {
72
            this.currentFieldId=this.fieldId;
73

    
74
    }
75
    ngOnDestroy(){
76
      if(this.sub && this.sub != undefined){
77
        this.sub.unsubscribe();
78
      }
79
    }
80

    
81
    ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
82
         if(this.currentFieldId!=this.fieldId){ //this is going to be called when
83
          this.currentFieldId=this.fieldId;
84
          this.initialize();
85
        }
86
    }
87
    private initialize(){
88

    
89
      this.showInput = true;
90
      if(this.list == undefined || this.list.length == 0){
91
        this.showLoading = true;
92

    
93
       if(this.vocabularyId){
94
        // this.list = this._vocabulariesService.getVocabularyByType(this.vocabularyId, this.entityName);
95
        // this.afterListFetchedActions();
96
        this.sub = this._vocabulariesService.getVocabularyByType(this.vocabularyId, this.entityName).subscribe(
97
            data => {
98
                this.list  = data;
99
                this.afterListFetchedActions();
100

    
101
            },
102
            err => {
103
                console.log(err);
104
                this.warningMessage = "An Error occured..."
105
            }
106
        );
107
      }else if(this.fieldName && this.entityName){
108
        // this.list = this._refineService.getRefineFieldResultsByFieldName(this.fieldName,this.entityName);
109
        this.sub = this._refineService.getRefineFieldResultsByFieldName(this.fieldName,this.entityName).subscribe(
110
            data => {
111
                this.list  = data;
112
                this.afterListFetchedActions();
113

    
114
            },
115
            err => {
116
                console.log(err);
117
                this.warningMessage = "An Error occured..."
118
            }
119
        );
120
      }else{
121
        this.showLoading = false;
122

    
123
      }
124
    }else{
125
      this.afterListFetchedActions();
126
    }
127

    
128
    }
129
    public updateList(list){ // used in claim context autocomplete
130
      this.list = list;
131
      this.afterListFetchedActions()
132
    }
133
    private afterListFetchedActions(){
134
      this.showLoading = false;
135
      this.getSelectedNameFromGivenId();
136
      this.listUpdated.emit({
137
          value: this.list
138
      });
139
      if(this.list == null || this.list.length == 0 ){
140
        this.warningMessage = "There are no results";
141
        return;
142
      }
143
      this.done = true;
144
      if(this.keyword != ""){
145
        this.filter();
146
      }
147

    
148
    }
149
    filter() {
150
      this.focus = true;
151
      if(this.done){
152
        this.infoMessage = "";
153
        this.filtered = [];
154
        if(this.keyword == ""){
155
          var cut = 10;
156
          if(this.list.length < 5){
157
            cut = this.list.length;
158
          }
159
          this.results = this.list.length;
160
          this.filtered =this.list.slice(0, cut);
161
          this.tries = 0;
162
          this.warningMessage = "";
163
        // } else if(this.keyword && this.keyword.length < this.keywordlimit){
164
        //   this.tries++;
165
        //   if(this.tries == this.keywordlimit -1 ){
166
        //     this.warningMessage = "Type at least " + this.keywordlimit + " characters";
167
        //     this.tries = 0;
168
        //   }
169
        }else{
170
          this.tries = 0;
171
          this.warningMessage = "";
172
           this.filtered = this.list.filter(function(el){
173
              return el.label.toLowerCase().indexOf(this.keyword.toLowerCase()) > -1;
174
          }.bind(this));
175
          var cut = 10;
176
          if(this.filtered .length < 5){
177
            cut = this.list.length;
178
          }
179
          this.results = this.filtered.length;
180
           this.filtered =this.filtered.slice(0, cut);
181
        }
182
      }
183
    }
184
    remove(item:any){
185
      var index:number =this.checkIfExists(item,this.selected);
186
       if (index > -1) {
187
          this.selected.splice(index, 1);
188
      }
189
      if(!this.multipleSelections && this.selected.length == 0 ){
190
        this.showInput = true;
191
        this.selectedValue = "";
192
        this.selectedValueChanged.emit({
193
            value: this.selectedValue
194
        });
195

    
196

    
197
      }
198
    }
199
    select(item:any){
200
      // console.log("select"+this.selected.length  + item.id + " "+ item.label);
201

    
202
        if(this.multipleSelections){
203
          var index:number =this.checkIfExists(item,this.selected);
204
           if (index > -1 && !this.allowDuplicates) {
205
              this.keyword = "";
206
              this.filtered.splice(0, this.filtered.length);
207
              return;
208
          }
209
          else{
210
              this.selected.push(item);
211
              this.keyword = "";
212
              this.filtered.splice(0, this.filtered.length);
213
              this.addItem.emit({
214
                  value: item
215
              });
216
          }
217
      }else{
218
        this.selected.splice(0, this.selected.length);
219
        this.selected.push(item);
220
        this.filtered.splice(0, this.filtered.length);
221
        this.keyword = "";
222
        this.showInput = false;
223
        this.selectedValue = item.id;
224
        this.selectedValueChanged.emit({
225
            value: this.selectedValue
226
        });
227

    
228
      }
229

    
230
    }
231
    private checkIfExists(item:any,list):number{
232

    
233
       if(item.concept && item.concept.id ){
234

    
235
        for (var _i = 0; _i < list.length; _i++) {
236
            let itemInList = list[_i];
237
            if(item.concept.id == itemInList.concept.id){
238
                 return _i;
239
            }
240
         }
241
      }else if(item.id){
242
        for (var _i = 0; _i < list.length; _i++) {
243
            let itemInList = list[_i];
244
             if(item.id == itemInList.id){
245
                 return _i;
246
            }
247
         }
248
      }
249
      return -1;
250

    
251
    }
252
    showItem(item:any):string{
253

    
254
     if (item.name){ //search
255
         return item.name;
256
      }else if( item.concept && item.concept.label){ //context
257
         return item.concept.label;
258
      }else if (item.label){ //simple
259
         return item.label;
260
      }
261

    
262
    }
263
    truncate(str:string, size:number):string{
264
      if(str == null){return "";}
265
      return (str.length > size)?str.substr(0,size)+'...':str;
266
    }
267
    private getSelectedNameFromGivenId(){
268
      if(this.list == null ){
269
        return;
270
      }
271
      this.showInput = true;
272
      for( var i = 0; i < this.list.length; i++){
273
        if(this.list[i].id == this.selectedValue){
274
          this.selectedValue = this.list[i].label;
275
          this.selected.push(this.list[i]);
276
          this.showInput = false;
277
          return;
278

    
279
        }
280
      }
281
    }
282

    
283
    handleClick(event){
284
     var clickedComponent = event.target;
285
     var inside = false;
286
     do {
287
         if (clickedComponent === this.myElement.nativeElement) {
288
             inside = true;
289
         }
290
        clickedComponent = clickedComponent.parentNode;
291
     } while (clickedComponent);
292
      if(!inside){
293
          this.focus =false;
294
          this.filtered.splice(0, this.filtered.length);
295
      }
296
  }
297

    
298
}
(2-2/3)