/**
 * Copyright © 2019 Johnson & Johnson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ import path from 'path' ; import fs from 'fs-extra' ; import { Tree } from './type' ; const niceName = ( s ) => s . replace ( /[a-z0-9]([A-Z])/g , m => `${ m [ 0 ] }_${ m [ 1 ] }` ) . replace ( /_/g , ' ' ) . split ( ' ' ) . map ( word => `${ word . slice ( 0 , 1 ) . toUpperCase ( ) }${ word . slice ( 1 ) }` ) . join ( ' ' ) ; param paths param parent param depth const createBar = ( paths , parent , depth , writeHeader = true , indent = 1 ) => { const pathPrefix = `/${ parent . map ( ( item ) => `${ item }/` ) . join ( '' ) }` ; const linePrefix = ' ' . repeat ( indent * 2 ) ; const markdownPrefix = '-' ; const header = writeHeader && parent . length > 0 && parent . slice ( - 1 ) [ 0 ] ; let navbar = header ? `${ markdownPrefix } ${ niceName ( header . replace ( /.md$/ , '' ) ) }\n` : '' ; Object . keys ( paths ) . forEach ( ( key ) => { let line = '' ; const link = key . replace ( /.md$/ , '' ) ; const name = niceName ( link ) ; if ( typeof paths [ key ] === 'object' ) { const branch = paths [ key ] as Tree ; const subLines = depth > 0 || ! branch [ 'README.md' ] ? createBar ( paths [ key ] as Tree , [ ... parent , key ] , depth - 1 , false , indent + 1 ) : '' ; if ( branch [ 'README.md' ] ) { line = `${ linePrefix }${ markdownPrefix } [${ name }](${ pathPrefix }${ link }/)\n` ; } else if ( subLines ) { line = `${ linePrefix }${ markdownPrefix } ${ name }\n` ; } line += subLines ; } else if ( key !== 'README.md' && path . extname ( paths [ key ] as string ) === '.md' ) { line = `${ linePrefix }${ markdownPrefix } [${ name }](${ pathPrefix }${ link })\n` ; } navbar += line ; } ) ; return navbar ; } ; param loc param tree param parents export const writeSideBar = ( loc , tree , parents ) => ( fs . writeFile ( path . join ( loc , '_sidebar.md' ) , createBar ( tree , parents , 100 , true ) ) ) ; param loc param tree export const writeSideBars = ( loc , tree ) => ( writeSideBar ( loc , tree , [ ] ) ) ; export default createBar ;