|
| 1 | +import {Component, HostBinding} from '@angular/core'; |
| 2 | +import {Router} from '@angular/router'; |
| 3 | +import {FormControl} from '@angular/forms'; |
| 4 | +import {MdSnackBar} from '@angular/material'; |
| 5 | +import {Observable} from 'rxjs'; |
| 6 | + |
| 7 | +import {DocumentationItems, DocItem} from '../../documentation-items/documentation-items'; |
| 8 | + |
| 9 | + |
| 10 | +@Component({ |
| 11 | + selector: 'search-bar-component', |
| 12 | + templateUrl: './searchbar.html', |
| 13 | + styleUrls: ['./searchbar.scss'] |
| 14 | +}) |
| 15 | + |
| 16 | +export class SearchBar { |
| 17 | + @HostBinding('class.expanded') _isExpanded = false; |
| 18 | + public allDocItems: DocItem[]; |
| 19 | + public filteredSuggestions: Observable<DocItem[]>; |
| 20 | + public searchControl: FormControl = new FormControl(''); |
| 21 | + |
| 22 | + constructor( |
| 23 | + private _docItems: DocumentationItems, |
| 24 | + private _router: Router, |
| 25 | + private _snackBar: MdSnackBar |
| 26 | + ) { |
| 27 | + this.allDocItems = _docItems.getAllItems(); |
| 28 | + this.filteredSuggestions = this.searchControl.valueChanges |
| 29 | + .startWith(null) |
| 30 | + .map(item => this.filterSearchSuggestions(item)); |
| 31 | + } |
| 32 | + |
| 33 | + public toggleIsExpanded() { |
| 34 | + this._isExpanded = !this._isExpanded; |
| 35 | + } |
| 36 | + |
| 37 | + public filterSearchSuggestions(searchTerm): DocItem[] { |
| 38 | + return this.allDocItems.filter(item => new RegExp(`^${searchTerm}`, 'gi').test(item.name)); |
| 39 | + } |
| 40 | + |
| 41 | + public navigate(searchValue) { |
| 42 | + const category = this.allDocItems.find(item => item.name.toLowerCase() === searchValue); |
| 43 | + category ? |
| 44 | + this._router.navigateByUrl(`/components/component/${category.id}`) : |
| 45 | + this._showError(); |
| 46 | + } |
| 47 | + |
| 48 | + private _showError() { |
| 49 | + this._snackBar.open('No search results found.', null, {duration: 3000}); |
| 50 | + } |
| 51 | +} |
0 commit comments