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

84.61% Statements 77/91
50% Branches 18/36
94.11% Functions 16/17
84.09% Lines 74/88

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 1982x               2x 2x 2x 2x 2x                                 2x   14x 14x 14x           14x                                 3x 3x 3x   3x       1x 1x   1x 1x 1x 1x 1x       1x 1x 1x 1x       1x 1x 1x 1x   1x       1x 1x 1x   1x 1x       1x       1x 1x   1x                                               1x 1x 1x 1x 1x 1x 1x 1x 1x             1x 1x         2x 1x 1x 1x   1x 1x 1x           1x 1x 1x   1x 1x 1x         1x       1x 1x 1x     1x 1x 1x       3x 1x 1x        
import {
  Component,
  ContentChild,
  Input,
  OnInit,
  TemplateRef
} from '@angular/core';
 
import { fireEvent } from '../../ngui-utils/src/fire-event';
import { NguiVirtualListComponent } from './ngui-virtual-list.component';
import { NoMatchFound } from './no-match-found';
import { NoneSelect } from './none-select';
import {fromEvent} from 'rxjs';
 
@Component({
  selector: 'ngui-autocomplete',
  template: `
    <ng-container *ngIf="isReady">
      <div class="ngui-autocomplete">
        <div #pages></div>
      </div>
      <ngui-inview (inview)="addMorePages()"></ngui-inview>
    </ng-container>
  `,
  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;
 
  /**
   * 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); // eslint-disable-line
    this.positionThisUnderInputEl();
 
    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
  }
 
  onEscaped(): void {
    this._escapedFromList = true;
    this.inputEl.focus();
    if (!this._lastSelected) {
      this.inputEl.value = this._orgInputValue;
    }
    this.cdr.detectChanges(); // for ChangeDetectionStrategy.OnPush
  }
 
  onInputElFocused(event): void {
    this.isListLoading = false;
    if (typeof this._orgInputValue === 'undefined') {
      this._orgInputValue = this.inputEl.value;
    }
    this._prevInputValue = this.inputEl.value;
    this.setFocused('input', true);
  }
 
  onInputElBlurred(): void {
    this.setFocused('input', false);
  }
 
  clearList(): void {
    this.inviewPages.forEach(compRef => {
      compRef.destroy();
    });
    this.inviewPages = [];
  }
 
  onInputElKeyup(event: KeyboardEvent): void {
    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 Iif (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 {
    if (this.inviewPages.length) {
      this.addAnInviewPageToPages();
    }
  }
 
  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 thisInputElBCR = this.inputEl.getBoundingClientRect();
    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 {
    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) {
      Iif (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();
  }
 
}