# All files / modules/list/src ngui-autocomplete.component.ts

0% Statements 0/126
0% Branches 0/50
0% Functions 0/20
0% Lines 0/119

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211

     import {
      Component,
      ContentChild,
      Input,
      OnInit,
      TemplateRef
    } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/add/observable/fromEvent';
    import 'rxjs/add/operator/map';

    import { fireEvent } from '../../utils';
    import { NguiVirtualListComponent } from './ngui-virtual-list.component';
    import { NoMatchFound } from './no-match-found';
    import { NoneSelect } from './none-select';

    @Component({
      selector: 'ngui-autocomplete',
      template: `
        <div *ngIf="isReady" class="ngui-autocomplete">
          <div #pages></div>
          <ngui-inview (inview)="addMorePages()"></ngui-inview>
        </div>
      `,
      styles: [`
        :host {position: absolute; background-color: #fff; max-height: 300px; overflow: auto}
        .ngui-autocomplete { border: 1px solid #ccc; padding: 4px }
      `]
    })
    export class NguiAutocompleteComponent extends NguiVirtualListComponent implements OnInit {
      @Input() for: string; // input tag id
      @Input() minInputChars = 1;
      @Input() blankOption = 'Select One';
      @Input() noMatchItem = 'No Match Found';

      /** Template of NguiInviewPage. Allow users to define their own template  */
      @ContentChild(TemplateRef) template: TemplateRef<any>;

      inputEl: HTMLInputElement;
      _focused: any = {input: false, listItem: false};
      _focusTimer;
      _acTimer;
      _selectedFromList: boolean;
      _escapedFromList: boolean;
      _orgInputValue: string;
      _prevInputValue: string;
      _lastSelected: any;

      wow(): void {
        alert('wow');
      }
      /**
       * returns autocomplete display condition
       * autocompolete list is only visible
       *   - when input element is focused or list element is focused
       *   - when input value has enought characters
       *   - and user just did not selected or escaped
       */
      get isReady(): boolean {
        const selectedOrEscaped = this._selectedFromList || this._escapedFromList;
        const focused = this._focused.input || this._focused.listItem;
        const minChars = this.inputEl.value.length >= this.minInputChars;

        return (!selectedOrEscaped && focused && minChars);
      }

      ngOnInit(): void {
        this.inputEl = <HTMLInputElement> document.querySelector('#' + this.for); // tslint:disable-line
        this.positionThisUnderInputEl();

        Observable.fromEvent(this.inputEl, 'keyup').subscribe(this.onInputElKeyup.bind(this));
        this.inputEl.addEventListener('focus', this.onInputElFocused.bind(this));
        this.inputEl.addEventListener('blur', this.onInputElBlurred.bind(this));
        this.selected.subscribe(this.onSelected.bind(this));
        this.escaped.subscribe(this.onEscaped.bind(this));
      }

      onSelected(value): void {
        this._selectedFromList = true;
        this.inputEl.focus();
        this._lastSelected = value;
        this.cdr.detectChanges();    // for ChangeDetectionStrategy.OnPush
        console.log('NguiAutoCompleteComponent.onSelected() is called', value);
      }

      onEscaped(): void {
        this._escapedFromList = true;
        this.inputEl.focus();
        if (!this._lastSelected) {
          this.inputEl.value = this._orgInputValue;
        }
        this.cdr.detectChanges(); // for ChangeDetectionStrategy.OnPush
        console.log('NguiAutoCompleteComponent.onEscaped() is called');
      }

      onInputElFocused(event): void {
        console.log('NguiAutoCompleteComponent.onInputElFocused() is called', event);
        this.isListLoading = false;
        if (typeof this._orgInputValue === 'undefined') {
          this._orgInputValue = this.inputEl.value;
        }
        this._prevInputValue = this.inputEl.value;
        this.setFocused('input', true);
      }

      onInputElBlurred(event): void {
        this.setFocused('input', false);
      }

      clearList(): void {
        this.inviewPages.forEach(compRef => {
          compRef.destroy();
        });
        this.inviewPages = [];
      }

      onInputElKeyup(event: KeyboardEvent): void {
        console.log('NguiAutoCompleteComponent.onInputKeyup() is called', event.key);
        const firstList = this.element.nativeElement.querySelector('ngui-list-item');
        if (event.key === 'Enter' || event.key === 'Escape') {
          if (firstList) {
            fireEvent(firstList, 'keyup', {key: event.key});
          } else {
            this.onEscaped();
          }
        } else if (event.key === 'ArrowDown' || event.key === 'ArrowRight') {
          firstList && firstList.focus();
        } else if (event.key === 'ArrowUp' || event.key === 'ArrowLeft') {
          //
        } else if (this.inputEl.value.length >= this.minInputChars) {
          this._selectedFromList = false;
          this._escapedFromList = false;
          this.addAutocompleteList();
        }
      }

      /** Complete the first page of autocomplete */
      addAutocompleteList(): void {
        if (this.isReady) {
          clearTimeout(this._acTimer);
          this._acTimer = setTimeout(_ => {
            this.isListLoading = false; // ???????/
            this._prevInputValue = this.inputEl.value;
            this._escapedFromList = false;
            this._selectedFromList = false;
            this.clearList();
            this.addAnInviewPageToPages();
          }, 200);
        }
      }

      /** Complete after the first page of autocomplete when it scrolls to the bottom */
      addMorePages(): void {
        console.debug('NguiAutocompleteComponent.addMorePages() is called.');
        if (this.inviewPages.length) {
          this.addAnInviewPageToPages();
        } else {
          console.debug('skipping addMorePages');
        }
      }

      setFocused(elType: 'input' | 'listItem', val: boolean): void {
        if (val) {
          clearTimeout(this._focusTimer);
          this._focused = {input: false, listItem: false};
          this._focused[elType] = true;
        } else {
          this._focusTimer = setTimeout(_ => {
            this._focused[elType] = false;
            this.cdr.detectChanges(); // for ChangeDetectionStrategy.OnPush
          }, 100);
        }
      }

      positionThisUnderInputEl(): void {
        const thisEl = this.element.nativeElement;
        const thisElBCR = thisEl.getBoundingClientRect();
        const thisInputElBCR = this.inputEl.getBoundingClientRect();
        const closeToBottom = thisInputElBCR.bottom + 100 > window.innerHeight;
        const top = thisInputElBCR.top + thisInputElBCR.height + window.scrollY;

        this.renderer.setStyle(thisEl, 'left', `${thisInputElBCR.left}px`);
        this.renderer.setStyle(thisEl, 'top', `${top}px`);
        this.renderer.setStyle(thisEl, 'minWidth', `${thisInputElBCR.width}px`);
      }

      // set items of NguiInviewPageComponent
      addList(items: Array<any>): void {
        console.log('>>>>>> NguiAutocompleteComponent.addList() is called()');
        this.isListLoading = false;

        // TODO: ........ for 1st page only, show no match found or blank option
        let noMatchItem: any;
        let blankItem: any;
        if (this.inviewPages.length === 1) {
          if (this.noMatchItem && (!items || items.length === 0)) { // add no match item
            noMatchItem = new NoMatchFound();
            blankItem.html = this.noMatchItem;
          } else if (this.blankOption) {
            blankItem = new NoneSelect();
            blankItem.html = this.blankOption;
          }
        }

        const allItems = [].concat(noMatchItem, blankItem, items).filter(x => x);
        this.inviewPage.instance.setItems(allItems);
        this.cdr.detectChanges();
      }

    }