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
     host: {
13
       '(document:click)': 'handleClick($event)',
14
   },
15
    template: `
16

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

    
43
          </div>
44

    
45
      </span>
46

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

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

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

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

    
119
      }else{
120

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

    
131
        this.getSelectedNameFromGivenId();
132
      }
133

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

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

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

    
163
    }
164

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

    
177

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

    
210
      }
211

    
212
    }
213
    private checkIfExists(item:any,list):number{
214

    
215
       if(item.concept && item.concept.id ){
216

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

    
233
    }
234
    showItem(item:any):string{
235

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

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

    
253

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

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

    
280
}
(1-1/4)