Matteo Scandolo | 86bc26a | 2017-01-18 11:06:47 -0800 | [diff] [blame] | 1 | import * as _ from 'lodash'; |
| 2 | import {IXosNavigationService} from '../../core/services/navigation'; |
| 3 | import {IXosState} from '../../../index'; |
| 4 | import {IModelStoreService} from '../stores/model.store'; |
| 5 | import {IXosConfigHelpersService} from '../../core/services/helpers/config.helpers'; |
| 6 | |
| 7 | export interface IXosSearchResult { |
| 8 | label: string; |
| 9 | state: string | {name: string, params: any}; |
| 10 | type?: string; |
| 11 | } |
| 12 | |
| 13 | export interface IXosSearchService { |
| 14 | search(query: string): IXosSearchResult[]; |
| 15 | } |
| 16 | |
| 17 | export class SearchService { |
| 18 | static $inject = ['$rootScope', 'NavigationService', 'ModelStore', 'ConfigHelpers']; |
| 19 | private states: IXosState[]; |
| 20 | |
| 21 | constructor ( |
| 22 | private $rootScope: ng.IScope, |
| 23 | private NavigationService: IXosNavigationService, |
| 24 | private ModelStore: IModelStoreService, |
| 25 | private ConfigHelpers: IXosConfigHelpersService |
| 26 | ) { |
| 27 | this.$rootScope.$on('xos.core.modelSetup', () => { |
| 28 | this.states = this.NavigationService.query().reduce((list, state) => { |
| 29 | // if it does not have child (otherwise it is abstract) |
| 30 | if (!state.children || state.children.length === 0) { |
| 31 | list.push(state); |
| 32 | } |
| 33 | // else push child |
| 34 | if (state.children && state.children.length > 0) { |
| 35 | state.children.forEach(c => { |
| 36 | list.push(c); |
| 37 | }); |
| 38 | } |
| 39 | return list; |
| 40 | }, []); |
| 41 | this.states = _.uniqBy(this.states, 'state'); |
| 42 | }); |
| 43 | } |
| 44 | |
| 45 | public search(query: string): IXosSearchResult[] { |
| 46 | const routes: IXosSearchResult[] = _.filter(this.states, s => { |
| 47 | return s.label.toLowerCase().indexOf(query) > -1; |
| 48 | }).map(r => { |
| 49 | r.type = 'View'; |
| 50 | return r; |
| 51 | }); |
| 52 | |
| 53 | const models = _.map(this.ModelStore.search(query), m => { |
| 54 | return { |
| 55 | label: m.humanReadableName ? m.humanReadableName : m.name, |
| 56 | state: this.ConfigHelpers.stateWithParamsForJs(m.modelName, m), |
| 57 | type: m.modelName |
| 58 | }; |
| 59 | }); |
| 60 | return routes.concat(models); |
| 61 | } |
| 62 | } |