Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame^] | 1 | /// <reference path="../../../../typings/index.d.ts" /> |
| 2 | |
| 3 | import * as _ from 'lodash'; |
| 4 | import {StyleConfig} from '../../config/style.config'; |
| 5 | |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 6 | export interface IXosNavigationRoute { |
| 7 | label: string; |
| 8 | state?: string; |
| 9 | url?: string; |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame^] | 10 | parent?: string; |
| 11 | children?: [IXosNavigationRoute]; |
| 12 | opened?: boolean; |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 13 | } |
| 14 | |
| 15 | export interface IXosNavigationService { |
| 16 | query(): IXosNavigationRoute[]; |
| 17 | add(route: IXosNavigationRoute): void; |
| 18 | } |
| 19 | |
| 20 | export class NavigationService { |
| 21 | private routes: IXosNavigationRoute[]; |
| 22 | |
| 23 | constructor() { |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame^] | 24 | const defaultRoutes = [ |
| 25 | { |
| 26 | label: 'Core', |
| 27 | state: 'xos.core' |
| 28 | }, |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 29 | { |
| 30 | label: 'Home', |
| 31 | state: 'xos.dashboard' |
| 32 | } |
| 33 | ]; |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame^] | 34 | // adding configuration defined routes |
| 35 | this.routes = StyleConfig.routes.concat(defaultRoutes).reverse(); |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 36 | } |
| 37 | |
| 38 | query() { |
| 39 | return this.routes; |
| 40 | } |
| 41 | |
| 42 | add(route: IXosNavigationRoute) { |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame] | 43 | if (angular.isDefined(route.state) && angular.isDefined(route.url)) { |
| 44 | throw new Error('[XosNavigation] You can\'t provide both state and url'); |
| 45 | } |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame^] | 46 | |
| 47 | |
| 48 | if (angular.isDefined(route.parent)) { |
| 49 | // route parent should be a state for now |
| 50 | const parentRoute = _.find(this.routes, {state: route.parent}); |
| 51 | |
| 52 | if (angular.isArray(parentRoute.children)) { |
| 53 | parentRoute.children.push(route); |
| 54 | } |
| 55 | else { |
| 56 | parentRoute.children = [route]; |
| 57 | } |
| 58 | } |
| 59 | else { |
| 60 | this.routes.push(route); |
| 61 | } |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 62 | } |
| 63 | } |