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

    
44
          </div>
45

    
46
      </span>
47

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

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

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

    
99
      this.showInput = true;
100
       if(this.entityType == "project" && this.funderId ){
101
        this.filtered  = this.searchTermStream
102
        .debounceTime(300).distinctUntilChanged()
103
        .switchMap((term: string) =>    {
104
            var results = this._search.searchProjectsByFunder(term, (this.funderId == "0"?"":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)