Project

General

Profile

1
import {Component, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange} from '@angular/core';
2
import {Observable} from 'rxjs/Observable';
3
import {Subject} from 'rxjs/Subject';
4
import {Value} from '../../searchPages/searchUtils/searchHelperClasses.class';
5
import {EntitiesSearchService} from './entitySearch.service';
6

    
7
//Usage example
8
//<static-autocomplete [(filtered)] =filtered [(selected)] =selected placeHolderMessage = "Search for countries" title = "Countries:" (keywordChange)="keywordChanged($event)"></static-autocomplete>
9

    
10
@Component({
11
    selector: 'entities-autocomplete',
12
    styleUrls:  ['../autoComplete.component.css'],
13
    host: {
14
       '(document:click)': 'handleClick($event)',
15
   },
16
    template: `
17

    
18
        <span class="custom-autocomplete">
19
          <span   *ngIf = "showSelected && selectedValue != ''">
20
            <span  class="uk-alert-default" data-uk-alert=""  *ngFor="let item of selected" [title]="showItem(item)" > <span >{{showItem(item)}} </span>
21
            <span (click)="remove(item)" aria-hidden="true" title="Remove selection" > <i class="uk-icon-remove clickable"></i> </span>
22
          </span>
23
          </span>
24
          <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)=search()   >
25
          <!--span *ngIf="showLoading" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading... </span>
26
          <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-->
27
          <div *ngIf="focus && showInput" class="uk-dropdown" aria-expanded="true" style="display:block" >
28
                <ul class="uk-nav uk-nav-autocomplete uk-autocomplete-results" >
29
                      <li>
30
                          <span *ngIf="!_search.ready" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading..... </span>
31
                          <span *ngIf="warningMessage.length > 0" class="uk-alert uk-alert-warning" data-uk-alert="">{{warningMessage}}</span>
32
                          <span *ngIf="results > 0"  >  {{results}} results found:</span>
33
                          <!--span *ngIf="results == 0 && !showLoading" class="uk-alert uk-alert-info" data-uk-alert=""> No results found</span-->
34
                      </li>
35
                       <li      *ngFor=" let item of filtered | async">
36
                        <a *ngIf= "item.id !=-1 && item.id !=-2" (click)="select(item)" [title]="showItem(item)"  style="text-overflow: ellipsis; ">{{showItem(item)}}</a>
37
                          <span *ngIf= "item.id ==-1"  class="uk-alert uk-alert-info" data-uk-alert=""> No results found</span>
38
                          <span *ngIf= "item.id ==-2"  class="uk-alert uk-alert-warning" data-uk-alert=""> An error occured</span>
39
                     </li>
40
                </ul>
41

    
42
          </div>
43

    
44
      </span>
45

    
46
        `
47
})
48
export class EntitiesAutocompleteComponent {
49
    @Input() placeHolderMessage = "Search for entries";
50
    @Input() title = "Autocomplete";
51
    @Output() addItem = new EventEmitter(); // when selected list  changes update parent component
52
    @Output() selectedValueChanged = new EventEmitter(); // when changed  a method for filtering will be called
53
    @Input() public list = []; // the entries resulted after filtering function
54
    @Input() public selected = []; // the entries selected from user
55
    @Input() public keywordlimit = 3; // the minimum length of keyword
56
    @Input() public showSelected = true; // the minimum length of keyword
57
    @Input() public multipleSelections:boolean = true;
58
    @Input() public allowDuplicates:boolean = false;
59
    @Input() public selectedValue:string = '';
60
    @Input() public keyword = '';
61
    @Input() public fieldId:string ;
62
    public currentFieldId: string ;
63
    public currentFunderId: string ;
64
    public warningMessage = "";
65
    public infoMessage = "";
66
    public tries = 0;
67
    public showInput = true;
68
    public sub;
69
    public done = false;
70
    public showLoading:boolean = false;
71
    public searchTermStream = new Subject<string>();
72
    filtered: Observable<{}> ;
73
    // public numFilteredResults:number = 0;
74

    
75
    @Input() public funderId:string;
76
    @Input() public entityType:string ;
77
    @Input() public depositType:string ;
78
    public results = 0;
79
    public focus:boolean  = false;
80
    constructor (public _search:EntitiesSearchService, private myElement: ElementRef) {
81
      this.currentFieldId=this.fieldId;
82
      this.currentFunderId=this.funderId;
83
      this.initialize();
84
    }
85

    
86
    ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
87
         if(this.currentFieldId!=this.fieldId){ //this is going to be called when
88
          this.currentFieldId=this.fieldId;
89
          this.initialize();
90
        }else if(this.currentFunderId!=this.funderId){
91
          this.currentFunderId=this.funderId;
92
          this.initialize();
93
        }
94
    }
95
    private initialize(){
96

    
97
      this.showInput = true;
98
       if(this.entityType == "project" && this.funderId ){
99
        this.filtered  = this.searchTermStream
100
        .debounceTime(300).distinctUntilChanged()
101
        .switchMap((term: string) =>    {
102
            var results = this._search.searchProjectsByFunder(term, (this.funderId == "0"?"":this.funderId));
103
            this.showLoading = false;
104
             this.results = results.length;
105
            return   results;
106
        });
107
      }else if(this.entityType == "organization" && this.depositType ){
108
         this.filtered  = this.searchTermStream
109
        .debounceTime(300).distinctUntilChanged()
110
        .switchMap((term: string) => {
111
          var results = this._search.searchByDepositType(term, this.depositType);
112
          this.showLoading = false;
113
          this.results = results.length;
114
          return   results;
115
      });
116

    
117
      }else{
118

    
119
        this.filtered  = this.searchTermStream
120
        .debounceTime(300)
121
        .distinctUntilChanged()
122
        .switchMap((term: string) => {
123
          var results = this._search.searchByType(term, this.entityType);
124
          this.showLoading = false;
125
          this.results = results.length;
126
          return   results;
127
      });
128

    
129
        this.getSelectedNameFromGivenId();
130
      }
131

    
132
    }
133
    ngOnDestroy(){
134
      if(this.sub && this.sub != undefined){
135
        this.sub.unsubscribe();
136
      }
137
    }
138

    
139
    search() {
140
      this.infoMessage = "";
141
      if(this.keyword == ""){
142
        this.tries = 0;
143
        this.warningMessage = "";
144
      } else if(this.keyword && this.keyword.length < this.keywordlimit){
145
        this.tries++;
146
        if(this.tries == this.keywordlimit -1 ){
147
          this.warningMessage = "Type at least " + this.keywordlimit + " characters";
148
          this.tries = 0;
149
        }
150
      }else{
151

    
152
        this.tries = 0;
153
        this.warningMessage = "";
154
        this.searchTermStream.next(this.keyword);
155
        // if(this.numFilteredResults ==0){
156
          this.showLoading = true;
157
          this.focus = true;
158
        // }
159
      }
160

    
161
    }
162

    
163
    remove(item:any){
164
      var index:number =this.checkIfExists(item,this.selected);
165
       if (index > -1) {
166
          this.selected.splice(index, 1);
167
      }
168
      if(!this.multipleSelections && this.selected.length == 0 ){
169
        this.showInput = true;
170
        this.selectedValue = "";
171
        this.selectedValueChanged.emit({
172
            value: this.selectedValue
173
        });
174

    
175

    
176
      }
177
    }
178
    select(item:any){
179
        if(this.multipleSelections){
180
          var index:number =this.checkIfExists(item,this.selected);
181
           if (index > -1 && !this.allowDuplicates) {
182
              // this.keyword = "";
183
              // this.filtered.splice(0, this.filtered.length);
184
              this.focus=false;
185
              return;
186
          }
187
          else{
188
              this.selected.push(item);
189
              // this.keyword = "";
190
              // this.filtered.splice(0, this.filtered.length);
191
              this.addItem.emit({
192
                  value: item
193
              });
194
              this.focus=false;
195
          }
196
      }else{
197
        this.selected.splice(0, this.selected.length);
198
        this.selected.push(item);
199
        // this.filtered.splice(0, this.filtered.length);
200
        this.keyword = "";
201
        this.showInput = false;
202
        this.selectedValue = item.id;
203
        this.selectedValueChanged.emit({
204
            value: this.selectedValue
205
        });
206
        this.focus=false;
207

    
208
      }
209

    
210
    }
211
    private checkIfExists(item:any,list):number{
212

    
213
       if(item.concept && item.concept.id ){
214

    
215
        for (var _i = 0; _i < list.length; _i++) {
216
            let itemInList = list[_i];
217
            if(item.concept.id == itemInList.concept.id){
218
                 return _i;
219
            }
220
         }
221
      }else if(item.id){
222
        for (var _i = 0; _i < list.length; _i++) {
223
            let itemInList = list[_i];
224
             if(item.id == itemInList.id){
225
                 return _i;
226
            }
227
         }
228
      }
229
      return -1;
230

    
231
    }
232
    showItem(item:any):string{
233

    
234
     if (item.name){ //search
235
         return item.name;
236
      }else if( item.concept && item.concept.label){ //context
237
         return item.concept.label;
238
      }else if (item.label){ //simple
239
         return item.label;
240
      }
241

    
242
    }
243
    truncate(str:string, size:number):string{
244
      if(str == null){return "";}
245
      return (str.length > size)?str.substr(0,size)+'...':str;
246
    }
247
    private getSelectedNameFromGivenId(){
248
      this.showInput = true;
249
      if(this.selectedValue && this.selectedValue.length > 0 ){
250

    
251

    
252
      this.sub = this._search.fetchByType(this.selectedValue,this.entityType).subscribe(
253
        data => {
254
          this.selected.push( data[0]);
255
          this.showInput = false;
256
         },
257
        err => console.log("An error occured"));
258
    }
259
  }
260

    
261
    handleClick(event){
262
     var clickedComponent = event.target;
263
     var inside = false;
264
     do {
265
         if (clickedComponent === this.myElement.nativeElement) {
266
             inside = true;
267
         }
268
        clickedComponent = clickedComponent.parentNode;
269
     } while (clickedComponent);
270
      if(!inside){
271
        this.keyword = "";
272
        // this.numFilteredResults = 0;
273
        this.searchTermStream.next(this.keyword);
274
        this.focus=false;
275
      }
276
  }
277

    
278
}
(1-1/4)