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 | { |
Matteo Scandolo | a8a6fbb | 2016-12-21 16:59:08 -0800 | [diff] [blame] | 26 | label: 'Home', |
| 27 | state: 'xos.dashboard' |
| 28 | }, |
| 29 | { |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame] | 30 | label: 'Core', |
| 31 | state: 'xos.core' |
| 32 | }, |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 33 | ]; |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame] | 34 | // adding configuration defined routes |
Matteo Scandolo | a8a6fbb | 2016-12-21 16:59:08 -0800 | [diff] [blame] | 35 | // this.routes = StyleConfig.routes.concat(defaultRoutes).reverse(); |
| 36 | this.routes = defaultRoutes; |
| 37 | StyleConfig.routes.forEach(r => { |
| 38 | this.add(r); |
| 39 | }); |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 40 | } |
| 41 | |
| 42 | query() { |
| 43 | return this.routes; |
| 44 | } |
| 45 | |
| 46 | add(route: IXosNavigationRoute) { |
Matteo Scandolo | a4a4711 | 2016-12-16 10:06:13 -0800 | [diff] [blame] | 47 | if (angular.isDefined(route.state) && angular.isDefined(route.url)) { |
| 48 | throw new Error('[XosNavigation] You can\'t provide both state and url'); |
| 49 | } |
Matteo Scandolo | e0d71ea | 2016-12-19 11:56:12 -0800 | [diff] [blame] | 50 | |
| 51 | |
| 52 | if (angular.isDefined(route.parent)) { |
| 53 | // route parent should be a state for now |
| 54 | const parentRoute = _.find(this.routes, {state: route.parent}); |
| 55 | |
| 56 | if (angular.isArray(parentRoute.children)) { |
| 57 | parentRoute.children.push(route); |
| 58 | } |
| 59 | else { |
| 60 | parentRoute.children = [route]; |
| 61 | } |
| 62 | } |
| 63 | else { |
| 64 | this.routes.push(route); |
| 65 | } |
Matteo Scandolo | f2c3ed6 | 2016-12-15 14:32:50 -0800 | [diff] [blame] | 66 | } |
| 67 | } |