Project

General

Profile

1
import {Component, ElementRef, Input, Output, EventEmitter, OnChanges, SimpleChange} from '@angular/core';
2
import {Value} from '../../searchPages/searchUtils/searchHelperClasses.class';
3
import {ISVocabulariesService} from './ISVocabularies.service';
4
import {RefineFieldResultsService} from '../../services/refineFieldResults.service';
5
import{EnvProperties} from '../../utils/properties/env-properties';
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: 'static-autocomplete',
12
    host: {
13
       '(document:click)': 'handleClick($event)',
14
   },
15
    template: `
16
        <div class="custom-autocomplete uk-width-1-1">
17
            <div   *ngIf = "showSelected && selectedValue != ''">
18
              <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)"> 
19
                <div class="uk-width-expand uk-padding-remove-left " >{{showItem(item)}} </div>
20
                <div (click)="remove(item)" aria-hidden="true" title="Remove selection" class="uk-padding-remove-left">
21
                  <span class="clickable uk-icon"><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></span>
22
                </div>
23
              </div>
24
            </div>
25
            <input *ngIf = "showInput " type="text" class="auto-complete-input validate filter-input input-sm form-control uk-input" [placeholder]=placeHolderMessage [(ngModel)]=keyword (keyup)=filter() (blur)="keyword = ''"   >
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 [style.display]="showLoading ? 'inline' : 'none'" class="uk-alert uk-alert-primary" data-uk-alert=""> <i class="uk-icon-spinner"></i> Loading... </span>
32
                      <span *ngIf="filtered.length > 0"  >  {{results | number}} results found:</span>
33
                      <span *ngIf="filtered.length == 0" class="uk-alert uk-alert-primary" data-uk-alert=""> No results found</span>
34
                      </li>
35
                      <li    *ngFor=" let item of filtered">
36
                          <a (click)="select(item)"  [title]="showItem(item)" style="text-overflow: ellipsis; ">{{showItem(item)}}</a>
37
                      </li>
38
                  </ul>
39
            </div>
40
        </div>
41

    
42
        `
43
})
44
export class StaticAutoCompleteComponent implements OnChanges{
45
    @Input() placeHolderMessage = "Search for entries";
46
    @Input() title = "Autocomplete";
47
    @Output() addItem = new EventEmitter(); // when selected list  changes update parent component
48
    @Output() selectedValueChanged = new EventEmitter(); // when changed  a method for filtering will be called
49
    @Output() updateValueLabel = new EventEmitter(); //when the value is id sends  an event to update the value (for meta tags)
50
    @Output() listUpdated = new EventEmitter(); // when changed  a method for filtering will be called
51
    @Input() public list = []; // the entries resulted after filtering function
52
    @Input() public filtered = []; // the entries resulted after filtering function
53
    @Input() public selected = []; // the entries selected from user
54
    @Input() public keywordlimit = 3; // the minimum length of keyword
55
    @Input() public showSelected = true; // the minimum length of keyword
56
    @Input() public multipleSelections:boolean = true;
57
    @Input() public allowDuplicates:boolean = false;
58
    @Input() public selectedValue:string = '';
59
    @Input() public vocabularyId:string ;
60
    @Input() public fieldName:string ;
61
    @Input() public entityName:string ;
62
    @Input() public fieldId:string ;
63
    @Input() properties:EnvProperties;
64
    @Input() public keyword = '';
65
    @Input() public type = 'search' //search, result, context, project
66
    public warningMessage = "";
67
    public infoMessage = "";
68
    public showLoading:boolean = false;
69
    public tries = 0;
70
    public showInput = true;
71
    public sub;
72
    public done = false;
73
    public results = 0;
74
    public focus:boolean  = false;
75
    public currentFieldId: string ;
76
    constructor ( private _vocabulariesService: ISVocabulariesService,private _refineService: RefineFieldResultsService, private myElement: ElementRef) {
77
            this.currentFieldId=this.fieldId;
78

    
79
    }
80
    ngOnDestroy(){
81
      if(this.sub){
82
        this.sub.unsubscribe();
83
      }
84
    }
85

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

    
94
      this.showInput = true;
95
      if(this.list == undefined || this.list.length == 0){
96
        this.showLoading = true;
97

    
98
       if(this.vocabularyId){
99
        // this.list = this._vocabulariesService.getVocabularyByType(this.vocabularyId, this.entityName);
100
        // this.afterListFetchedActions();
101
        this.sub = this._vocabulariesService.getVocabularyByType(this.vocabularyId, this.entityName, this.properties).subscribe(
102
            data => {
103
              this.list  = (this.vocabularyId=="type" && this.entityName == "result" && data.length == 2)?data[0].concat(data[1]):data;
104
              this.afterListFetchedActions();
105

    
106
            },
107
            err => {
108
                //console.log(err);
109
                this.handleError("Error getting vocabulary with id: "+this.vocabularyId+" for "+this.entityName, err);
110
                this.warningMessage = "An Error occured..."
111
            }
112
        );
113
      }else if(this.fieldName && this.entityName){
114
        this.sub = this._refineService.getRefineFieldResultsByFieldName(this.fieldName,this.entityName, this.properties).subscribe(
115
            data => {
116
                this.list  = data;
117
                this.afterListFetchedActions();
118

    
119
            },
120
            err => {
121
                //console.log(err);
122
                this.handleError("Error getting results for refine field: "+this.fieldName+" for "+this.entityName, err);
123
                this.warningMessage = "An Error occured..."
124
            }
125
        );
126
      }else{
127
        this.showLoading = false;
128

    
129
      }
130
    }else{
131
      this.afterListFetchedActions();
132
    }
133

    
134
    }
135
    public updateList(list){ // used in claim context autocomplete
136
      this.list = list;
137
      this.afterListFetchedActions()
138
    }
139
    private afterListFetchedActions(){
140
      this.showLoading = false;
141
      this.getSelectedNameFromGivenId();
142
      this.listUpdated.emit({
143
          value: this.list
144
      });
145
      if(this.list == null || this.list.length == 0 ){
146
        this.warningMessage = "No results available";
147
        return;
148
      }
149
      this.done = true;
150
      if(this.keyword != ""){
151
        this.filter();
152
      }
153

    
154
    }
155
    filter() {
156
      this.focus = true;
157
      if(this.done){
158
        this.infoMessage = "";
159
        this.filtered = [];
160
        if(this.keyword == ""){
161
          var cut = 10;
162
          if(this.list.length < 5){
163
            cut = this.list.length;
164
          }
165
          this.results = this.list.length;
166
          this.filtered =this.list.slice(0, cut);
167
          this.tries = 0;
168
          this.warningMessage = "";
169
        // } else if(this.keyword && this.keyword.length < this.keywordlimit){
170
        //   this.tries++;
171
        //   if(this.tries == this.keywordlimit -1 ){
172
        //     this.warningMessage = "Type at least " + this.keywordlimit + " characters";
173
        //     this.tries = 0;
174
        //   }
175
        }else{
176
          this.tries = 0;
177
          this.warningMessage = "";
178
           this.filtered = this.list.filter(function(el){
179
              return el.label.toLowerCase().indexOf(this.keyword.toLowerCase()) > -1;
180
          }.bind(this));
181
          var cut = 10;
182
          if(this.filtered .length < 5){
183
            cut = this.list.length;
184
          }
185
          this.results = this.filtered.length;
186
           this.filtered =this.filtered.slice(0, cut);
187
        }
188
      }
189
    }
190
    remove(item:any){
191
      var index:number =this.checkIfExists(item,this.selected);
192
       if (index > -1) {
193
          this.selected.splice(index, 1);
194
      }
195
      if(!this.multipleSelections && this.selected.length == 0 ){
196
        this.showInput = true;
197
        this.selectedValue = "";
198
        this.selectedValueChanged.emit({
199
            value: this.selectedValue
200
        });
201
        this.updateValueLabel.emit({
202
          value:""
203
        });
204

    
205
      }
206
    }
207
    select(item:any){
208
      // console.log("select"+this.selected.length  + item.id + " "+ item.label);
209

    
210
        if(this.multipleSelections){
211
          var index:number =this.checkIfExists(item,this.selected);
212
           if (index > -1 && !this.allowDuplicates) {
213
              this.keyword = "";
214
              this.filtered.splice(0, this.filtered.length);
215
              return;
216
          }
217
          else{
218
              this.selected.push(item);
219
              this.keyword = "";
220
              this.filtered.splice(0, this.filtered.length);
221
              this.addItem.emit({
222
                  value: item
223
              });
224
          }
225
      }else{
226
        this.selected.splice(0, this.selected.length);
227
        this.selected.push(item);
228
        this.filtered.splice(0, this.filtered.length);
229
        this.keyword = "";
230
        this.showInput = false;
231
        this.selectedValue = item.id;
232
        this.selectedValueChanged.emit({
233
            value: this.selectedValue
234
        });
235
          this.updateValueLabel.emit({
236
            value:this.showItem(item)
237
          });
238
      }
239

    
240
    }
241
    private checkIfExists(item:any,list):number{
242

    
243
       if(item.concept && item.concept.id ){
244

    
245
        for (var _i = 0; _i < list.length; _i++) {
246
            let itemInList = list[_i];
247
            if(item.concept.id == itemInList.concept.id){
248
                 return _i;
249
            }
250
         }
251
      }else if(item.id){
252
        for (var _i = 0; _i < list.length; _i++) {
253
            let itemInList = list[_i];
254
             if(item.id == itemInList.id){
255
                 return _i;
256
            }
257
         }
258
      }
259
      return -1;
260

    
261
    }
262
    showItem(item:any):string{
263

    
264
     if (item.name){ //search
265
         return item.name;
266
      }else if( item.concept && item.concept.label){ //context
267
         return item.concept.label;
268
      }else if (item.label){ //simple
269
         return item.label;
270
      }
271

    
272
    }
273
    truncate(str:string, size:number):string{
274
      if(str == null){return "";}
275
      return (str.length > size)?str.substr(0,size)+'...':str;
276
    }
277
    private getSelectedNameFromGivenId(){
278
      if(this.list == null ){
279
        return;
280
      }
281
      this.showInput = true;
282
      for( var i = 0; i < this.list.length; i++){
283
        if(this.list[i].id == this.selectedValue){
284
          this.selectedValue = this.list[i].label;
285
          this.selected.push(this.list[i]);
286
          this.showInput = false;
287
          this.updateValueLabel.emit({
288
            value:this.showItem(this.list[i])
289
          });
290
          return;
291

    
292
        }
293
      }
294
    }
295

    
296
    handleClick(event){
297
     var clickedComponent = event.target;
298
     var inside = false;
299
     do {
300
         if (clickedComponent === this.myElement.nativeElement) {
301
             inside = true;
302
         }
303
        clickedComponent = clickedComponent.parentNode;
304
     } while (clickedComponent);
305
      if(!inside){
306
          this.focus =false;
307
          this.filtered.splice(0, this.filtered.length);
308
      }
309
  }
310

    
311
  private handleError(message: string, error) {
312
      console.error("Static Autocomplete (component): "+message, error);
313
  }
314
}
(2-2/3)