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
import{EnvProperties} from '../properties/env-properties';
7
import 'rxjs/add/operator/debounceTime';
8
import 'rxjs/add/operator/distinctUntilChanged';
9
//Usage example
10
//<static-autocomplete [(filtered)] =filtered [(selected)] =selected placeHolderMessage = "Search for countries" title = "Countries:" (keywordChange)="keywordChanged($event)"></static-autocomplete>
11

    
12
@Component({
13
    selector: 'entities-autocomplete',
14
     host: {
15
       '(document:click)': 'handleClick($event)',
16
   },
17
    template: `
18

    
19
        <span class="custom-autocomplete">
20
          <span   *ngIf = "showSelected && selectedValue != ''">
21
            <span  class="uk-alert-default" data-uk-alert=""  *ngFor="let item of selected" [title]="showItem(item)" > <span >{{showItem(item)}} </span>
22
            <span (click)="remove(item)" aria-hidden="true" title="Remove selection" > <span class="clickable uk-icon">
23
<svg width="20" height="20" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" icon="close" ratio="1"><path fill="none" stroke="#000" stroke-width="1.06" d="M16,16 L4,4"></path><path fill="none" stroke="#000" stroke-width="1.06" d="M16,4 L4,16"></path></svg>
24
</span> </span>
25
          </span>
26
          </span>
27
          <input *ngIf = "showInput" type="text" class="auto-complete-input validate filter-input input-sm form-control -width-small " [placeholder]=placeHolderMessage [(ngModel)]=keyword (keyup)=search()   >
28
          <!--span [style.display]="showLoading ? 'inline' : 'none'" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading... </span>
29
          <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-->
30
          <div *ngIf="focus && showInput" class="uk-dropdown" aria-expanded="true" style="display:block" >
31
                <ul class="uk-nav uk-nav-autocomplete uk-autocomplete-results" >
32
                      <li>
33
                          <span *ngIf="!_search.ready" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading..... </span>
34
                          <span *ngIf="warningMessage.length > 0" class="uk-alert uk-alert-warning" data-uk-alert="">{{warningMessage}}</span>
35
                          <span *ngIf="results > 0"  >  {{results}} results found:</span>
36
                          <!--span *ngIf="results == 0 && !showLoading" class="uk-alert uk-alert-primary" data-uk-alert=""> No results found</span-->
37
                      </li>
38
                       <li      *ngFor=" let item of filtered | async">
39
                        <a *ngIf= "item.id !=-1 && item.id !=-2" (click)="select(item)" [title]="showItem(item)"  style="text-overflow: ellipsis; ">{{showItem(item)}}</a>
40
                          <span *ngIf= "item.id ==-1"  class="uk-alert uk-alert-primary" data-uk-alert=""> No results found</span>
41
                          <span *ngIf= "item.id ==-2"  class="uk-alert uk-alert-warning" data-uk-alert=""> An error occured</span>
42
                     </li>
43
                </ul>
44

    
45
          </div>
46

    
47
      </span>
48

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

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

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

    
101
      this.showInput = true;
102
       if(this.entityType == "project" && this.funderId ){
103
        this.filtered  = this.searchTermStream
104
        .debounceTime(300).distinctUntilChanged()
105
        .switchMap((term: string) =>    {
106
          console.log("funder"+this.funderId);
107
            var results = this._search.searchProjectsByFunder(term, (this.funderId == "0"?"":encodeURIComponent(this.funderId)), this.properties);
108
            this.showLoading = false;
109
             this.results = results.length;
110
            return   results;
111
        });
112
      }else if(this.entityType == "organization" && this.depositType ){
113
         this.filtered  = this.searchTermStream
114
        .debounceTime(300).distinctUntilChanged()
115
        .switchMap((term: string) => {
116
          var results = this._search.searchByDepositType(term, this.depositType, this.properties);
117
          this.showLoading = false;
118
          this.results = results.length;
119
          return   results;
120
      });
121

    
122
      }else{
123

    
124
        this.filtered  = this.searchTermStream
125
        .debounceTime(300)
126
        .distinctUntilChanged()
127
        .switchMap((term: string) => {
128
          var results = this._search.searchByType(term, this.entityType, this.properties);
129
          this.showLoading = false;
130
          this.results = results.length;
131
          return   results;
132
      });
133

    
134
        this.getSelectedNameFromGivenId();
135
      }
136

    
137
    }
138
    ngOnDestroy(){
139
      if(this.sub && this.sub != undefined){
140
        this.sub.unsubscribe();
141
      }
142
    }
143

    
144
    search() {
145
      this.infoMessage = "";
146
      if(this.keyword == ""){
147
        this.tries = 0;
148
        this.warningMessage = "";
149
      } else if(this.keyword && this.keyword.length < this.keywordlimit){
150
        this.tries++;
151
        if(this.tries == this.keywordlimit -1 ){
152
          this.warningMessage = "Type at least " + this.keywordlimit + " characters";
153
          this.tries = 0;
154
        }
155
      }else{
156

    
157
        this.tries = 0;
158
        this.warningMessage = "";
159
        this.searchTermStream.next(this.keyword);
160
        // if(this.numFilteredResults ==0){
161
          this.showLoading = true;
162
          this.focus = true;
163
        // }
164
      }
165

    
166
    }
167

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

    
180

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

    
213
      }
214

    
215
    }
216
    private checkIfExists(item:any,list):number{
217

    
218
       if(item.concept && item.concept.id ){
219

    
220
        for (var _i = 0; _i < list.length; _i++) {
221
            let itemInList = list[_i];
222
            if(item.concept.id == itemInList.concept.id){
223
                 return _i;
224
            }
225
         }
226
      }else if(item.id){
227
        for (var _i = 0; _i < list.length; _i++) {
228
            let itemInList = list[_i];
229
             if(item.id == itemInList.id){
230
                 return _i;
231
            }
232
         }
233
      }
234
      return -1;
235

    
236
    }
237
    showItem(item:any):string{
238

    
239
     if (item.name){ //search
240
         return item.name;
241
      }else if( item.concept && item.concept.label){ //context
242
         return item.concept.label;
243
      }else if (item.label){ //simple
244
         return item.label;
245
      }
246

    
247
    }
248
    truncate(str:string, size:number):string{
249
      if(str == null){return "";}
250
      return (str.length > size)?str.substr(0,size)+'...':str;
251
    }
252
    private getSelectedNameFromGivenId(){
253
      this.showInput = true;
254
      if(this.selectedValue && this.selectedValue.length > 0 ){
255

    
256

    
257
      this.sub = this._search.fetchByType(this.selectedValue,this.entityType, this.properties).subscribe(
258
        data => {
259
          this.selected.push( data[0]);
260
          this.showInput = false;
261
         },
262
        err => console.log("An error occured"));
263
    }
264
  }
265

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

    
283
}
(1-1/4)