Project

General

Profile

1

    
2
import {switchMap, distinctUntilChanged, debounceTime} from 'rxjs/operators';
3
import {Component, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange} from '@angular/core';
4
import {Observable, Subject} from 'rxjs';
5
import {Value} from '../../searchPages/searchUtils/searchHelperClasses.class';
6
import {EntitiesSearchService} from './entitySearch.service';
7
import{EnvProperties} from '../properties/env-properties';
8

    
9

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

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

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

    
47
          </div>
48

    
49
      </div>
50

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

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

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

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

    
116
        if(this.entityType == "organization" && this.depositType ){
117
         this.filtered  = this.searchTermStream.pipe(
118
        debounceTime(300),distinctUntilChanged(),
119
        switchMap((term: string) => {
120
          var results = this._search.searchByDepositType(term, this.depositType, this.properties);
121
          this.showLoading = false;
122
          this.results = results.length;
123
          return   results;
124
      }),);
125

    
126
      }else{
127

    
128
        this.filtered  = this.searchTermStream.pipe(
129
        debounceTime(300),
130
        distinctUntilChanged(),
131
        switchMap((term: string) => {
132
          var results = this._search.searchByType(term, this.entityType, this.properties);
133
          this.showLoading = false;
134
          this.results = results.length;
135
          return   results;
136
      }),);
137

    
138
        this.getSelectedNameFromGivenId();
139
      }
140

    
141
    }
142
    ngOnDestroy(){
143
      if(this.sub && this.sub != undefined){
144
        this.sub.unsubscribe();
145
      }
146
    }
147

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

    
161
        this.tries = 0;
162
        this.warningMessage = "";
163
        this.searchTermStream.next(this.keyword);
164
        // if(this.numFilteredResults ==0){
165
          this.showLoading = true;
166
          this.focus = true;
167
        // }
168
      }
169

    
170
    }
171

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

    
184

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

    
217
      }
218

    
219
    }
220
    private checkIfExists(item:any,list):number{
221

    
222
       if(item.concept && item.concept.id ){
223

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

    
240
    }
241
    showItem(item:any):string{
242
      //console.log(item);
243
      if (item.projectName || item.projectAcronym || item.code){ //project
244
          return ((item.projectAcronym)?"["+item.projectAcronym+"] ":"")+item.projectName+((item.code)?" ("+item.code+")":"");
245
       }else if (item.name){ //search
246
         return item.name;
247
      }else if( item.concept && item.concept.label){ //context
248
         return item.concept.label;
249
      }else if (item.label){ //simple
250
         return item.label;
251
      }
252

    
253
    }
254
    truncate(str:string, size:number):string{
255
      if(str == null){return "";}
256
      return (str.length > size)?str.substr(0,size)+'...':str;
257
    }
258
    private getSelectedNameFromGivenId(){
259
      this.showInput = true;
260
      if(this.selectedValue && this.selectedValue.length > 0 ){
261

    
262
      console.log(this.selectedValue+" "+this.entityType )
263
      this.sub = this._search.fetchByType(this.selectedValue,this.entityType, this.properties).subscribe(
264
        data => {
265
          this.selected.push( data[0]);
266
          this.showInput = false;
267
         },
268
        err => {
269
          //console.log("An error occured"));
270
          this.handleError("Error getting results of type: "+this.entityType+" with id: "+this.selectedValue, err);
271
        }
272
      );
273
    }
274
  }
275

    
276
    handleClick(event){
277
     var clickedComponent = event.target;
278
     var inside = false;
279
     do {
280
         if (clickedComponent === this.myElement.nativeElement) {
281
             inside = true;
282
         }
283
        clickedComponent = clickedComponent.parentNode;
284
     } while (clickedComponent);
285
      if(!inside){
286
        this.keyword = "";
287
        // this.numFilteredResults = 0;
288
        this.searchTermStream.next(this.keyword);
289
        this.focus=false;
290
      }
291
  }
292

    
293
  private handleError(message: string, error) {
294
      console.error("Autocomplete (component): "+message, error);
295
  }
296
}
(1-1/4)