import { Service } from "@bluelibs/core" ; import { IMenuItemConfig } from "../defs" ; import * as startCase from "lodash.startcase" ; @ Service ( ) export class MenuService { public readonly items : IMenuItemConfig [ ] = [ ] ; /**
     * All items stored in a flat structure.
     */ public readonly allItems : IMenuItemConfig [ ] = [ ] ; param item add ( item ) { this . prepareItem ( item ) ; if ( item . inject ) { const parts = item . inject . split ( "." ) ; this . injectItem ( null , parts , item ) ; } else { this . addSubitem ( this . items , item ) ; } } protected addSubitem ( parent , item ) { if ( Array . isArray ( parent ) ) { parent . push ( item ) ; this . sort ( parent ) ; } else { parent . subitems . push ( item ) ; this . sort ( parent . subitems ) ; } this . allItems . push ( item ) ; } param item protected prepareItem ( item ) { if ( item . route ) { if ( ! item . path ) { item . path = item . route . path ; } if ( ! item . roles && item . route . roles ) { item . roles = item . route . roles ; } } if ( ! item . label ) { item . label = this . labelify ( item . key ) ; } if ( ! item . isSelected ) { item . isSelected = this . createIsSelected ( item ) ; } if ( item . order === undefined || item . order === null ) { item . order = 1000 ; } if ( ! item . subitems ) { item . subitems = [ ] ; } } param parent param parts injectItem ( parent , parts , item ) { if ( parts . length === 0 ) { if ( parent === null ) { this . addSubitem ( this . items , item ) ; } else { this . addSubitem ( parent , item ) ; } } else { let foundItem ; const [ currentPart , ... restParts ] = parts ; const itemsList = parent === null ? this . items : parent . subitems ; foundItem = this . items . find ( ( item ) => item . key === currentPart ) ; if ( ! foundItem ) { foundItem = { key : currentPart , label : this . labelify ( currentPart ) , subitems : [ ] , } ; this . addSubitem ( itemsList , foundItem ) ; } this . injectItem ( foundItem , restParts , item ) ; } } sort ( items ) { items . sort ( function ( a , b ) { if ( a . order < b . order ) { return - 1 ; } if ( a . order > b . order ) { return 1 ; } return 0 ; } ) ; } createIsSelected ( item ) { return ( pathname ) => { if ( item . path === pathname ) { return true ; } if ( pathname . indexOf ( item . path ) >= 0 ) { return true ; } return false ; } ; } param key getItem ( key ) { return this . allItems . find ( ( item ) => item . key === key ) ; } param strings getPath ( strings ) { return strings . join ( "." ) ; } param label labelify ( label ) { return startCase ( label ) ; } }