Project

General

Profile

1

    
2
import {switchMap, distinctUntilChanged, debounceTime} from 'rxjs/operators';
3
import {Component, ElementRef, Input, Output, EventEmitter, SimpleChange} from '@angular/core';
4
import {Observable, Subject} from 'rxjs';
5
import {EntitiesSearchService} from './entitySearch.service';
6
import{EnvProperties} from '../properties/env-properties';
7
import {StringUtils} from "../string-utils.class";
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 uk-margin-remove-left" 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 uk-input " [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
    @Output() updateValueLabel = new EventEmitter(); //when the value is id sends  an event to update the value (for meta tags)
59
    @Input() public list = []; // the entries resulted after filtering function
60
    @Input() public selected = []; // the entries selected from user
61
    @Input() public keywordlimit = 3; // the minimum length of keyword
62
    @Input() public showSelected = true; // the minimum length of keyword
63
    @Input() public multipleSelections:boolean = true;
64
    @Input() public allowDuplicates:boolean = false;
65
    @Input() public selectedValue:string = '';
66
    @Input() public keyword = '';
67
    @Input() public fieldId:string ;
68
    @Input() public properties:EnvProperties ;
69
    public currentFieldId: string ;
70
    public currentFunderId: string ;
71
    public warningMessage = "";
72
    public infoMessage = "";
73
    public tries = 0;
74
    public showInput = true;
75
    public sub;
76
    public done = false;
77
    public showLoading:boolean = false;
78
    public searchTermStream = new Subject<string>();
79
    filtered: Observable<{}> ;
80
    // public numFilteredResults:number = 0;
81

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

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

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

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

    
127
      }else{
128

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

    
139
        this.getSelectedNameFromGivenId();
140
      }
141

    
142
    }
143
    ngOnDestroy(){
144
      if(this.sub){
145
        this.sub.unsubscribe();
146
      }
147
    }
148

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

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

    
171
    }
172

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

    
188

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

    
224
      }
225

    
226
    }
227
    private checkIfExists(item:any,list):number{
228

    
229
       if(item.concept && item.concept.id ){
230

    
231
        for (var _i = 0; _i < list.length; _i++) {
232
            let itemInList = list[_i];
233
            if(item.concept.id == itemInList.concept.id){
234
                 return _i;
235
            }
236
         }
237
      }else if(item.id){
238
        for (var _i = 0; _i < list.length; _i++) {
239
            let itemInList = list[_i];
240
             if(item.id == itemInList.id){
241
                 return _i;
242
            }
243
         }
244
      }
245
      return -1;
246

    
247
    }
248
    showItem(item:any):string{
249
      //console.log(item);
250
      if(!item){
251
        return "[No title available]"
252
      }
253
      else if (item.projectName || item.projectAcronym || item.code){ //project
254
          return ((item.projectAcronym)?"["+item.projectAcronym+"] ":"")+item.projectName+((item.code)?" ("+item.code+")":"");
255
       }else if (item.name){ //search
256
         return item.name;
257
      }else if( item.concept && item.concept.label){ //context
258
         return item.concept.label;
259
      }else if (item.label){ //simple
260
         return item.label;
261
      }
262

    
263
    }
264
    truncate(str:string, size:number):string{
265
      if(str == null){return "";}
266
      return (str.length > size)?str.substr(0,size)+'...':str;
267
    }
268
    private getSelectedNameFromGivenId(){
269
      this.showInput = true;
270
      if(this.selectedValue && this.selectedValue.length > 0 ){
271

    
272
      console.log(this.selectedValue+" "+this.entityType )
273
      this.sub = this._search.fetchByType(this.selectedValue,this.entityType, this.properties).subscribe(
274
        data => {
275
          this.selected.push( data[0]);
276
          this.updateValueLabel.emit({
277
            value:this.showItem(this.selected[0])
278
          });
279
          this.showInput = false;
280
         },
281
        err => {
282
          //console.log("An error occured"));
283
          this.handleError("Error getting results of type: "+this.entityType+" with id: "+this.selectedValue, err);
284
        }
285
      );
286
    }
287
  }
288

    
289
    handleClick(event){
290
     var clickedComponent = event.target;
291
     var inside = false;
292
     do {
293
         if (clickedComponent === this.myElement.nativeElement) {
294
             inside = true;
295
         }
296
        clickedComponent = clickedComponent.parentNode;
297
     } while (clickedComponent);
298
      if(!inside){
299
        this.keyword = "";
300
        // this.numFilteredResults = 0;
301
        this.searchTermStream.next(this.keyword);
302
        this.focus=false;
303
      }
304
  }
305

    
306
  private handleError(message: string, error) {
307
      console.error("Autocomplete (component): "+message, error);
308
  }
309
}
(1-1/4)