redoc/lib/components/Search/redoc-search.ts

89 lines
2.1 KiB
TypeScript
Raw Normal View History

2016-12-29 20:20:29 +03:00
'use strict';
2017-01-28 19:47:12 +03:00
import { Component, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, HostBinding } from '@angular/core';
import { Marker, SearchService, MenuService, MenuItem } from '../../services/';
2017-02-02 23:03:47 +03:00
import { throttle } from '../../utils/';
2016-12-29 20:20:29 +03:00
@Component({
selector: 'redoc-search',
styleUrls: ['./redoc-search.css'],
templateUrl: './redoc-search.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class RedocSearch implements OnInit {
logo:any = {};
2017-01-28 19:47:12 +03:00
items: { menuItem: MenuItem, pointers: string[] }[] = [];
2017-02-02 23:03:47 +03:00
searchTerm = '';
throttledSearch: Function;
2016-12-29 20:20:29 +03:00
2017-01-28 19:47:12 +03:00
_subscription;
constructor(
cdr: ChangeDetectorRef,
private marker: Marker,
public search: SearchService,
public menu: MenuService) {
2017-01-29 21:59:21 +03:00
this._subscription = menu.changed.subscribe(() => {
cdr.markForCheck();
cdr.detectChanges();
});
2017-02-02 23:03:47 +03:00
this.throttledSearch = throttle(() => {
this.updateSearch();
cdr.markForCheck();
cdr.detectChanges();
}, 300, this);
2016-12-29 20:20:29 +03:00
}
init() {
2017-01-24 00:29:52 +03:00
this.search.indexAll();
2016-12-29 20:20:29 +03:00
}
2017-02-02 23:03:47 +03:00
update(event:KeyboardEvent, val) {
if (event && event.keyCode === 27) { // escape
this.searchTerm = '';
} else {
this.searchTerm = val;
}
this.throttledSearch();
}
updateSearch() {
if (!this.searchTerm || this.searchTerm.length < 2) {
this.items = [];
this.marker.unmark();
return;
}
let searchRes = this.search.search(this.searchTerm);
2017-01-24 00:29:52 +03:00
this.items = Object.keys(searchRes).map(id => ({
menuItem: this.menu.getItemById(id),
pointers: searchRes[id].map(el => el.pointer)
})).filter(res => !!res.menuItem);
2017-01-28 19:47:12 +03:00
this.items.sort((a, b) => {
if (a.menuItem.depth > b.menuItem.depth) return 1;
else if (a.menuItem.depth < b.menuItem.depth) return -1;
else return 0;
});
2017-02-02 23:03:47 +03:00
this.marker.mark(this.searchTerm);
2016-12-29 20:20:29 +03:00
}
2017-01-24 00:29:52 +03:00
clickSearch(item) {
this.search.ensureSearchVisible(
item.pointers
);
this.marker.remark();
2017-04-18 16:46:19 +03:00
this.menu.activate(item.menuItem);
2017-01-24 00:29:52 +03:00
this.menu.scrollToActive();
}
2016-12-29 20:20:29 +03:00
ngOnInit() {
2017-01-24 00:29:52 +03:00
this.init();
2016-12-29 20:20:29 +03:00
}
2017-01-28 19:47:12 +03:00
destroy() {
this._subscription.unsubscribe();
}
2016-12-29 20:20:29 +03:00
}