import { urlGenerator } from './urlGenerator' ; import { ArticleFields , ArticleFrontmatter } from '../interfaces/Article.interface' ; interface TreeNode { node : { fields : ArticleFields ; frontmatter : ArticleFrontmatter ; } ; } const getCollpaseState = ( part , location ) => { const mainpath = location . pathname . replace ( /^\/|\/$/g , '' ) . split ( '/' ) ; const subpath = urlGenerator ( part ) . replace ( /^\/|\/$/g , '' ) . split ( '/' ) ; const state = subpath . every ( ( val ) => mainpath . includes ( val ) ) ; return ! state ; } ; export const calculateTreeData = ( edges , defaultCollapsed , location ) => { const tree = edges . reduce ( ( accu , { node : { fields : { slug , modSlug } , frontmatter : { title , navTitle , staticLink , duration , experimental , preview , earlyaccess , dbSwitcher , langSwitcher , hidePage , codeStyle , } , } , } ) => { const parts = slug . split ( '/' ) ; const topLevel = parts . length == 3 && parts [ parts . length - 1 ] === 'index' ? true : false ; let { items : prevItems } = accu ; const slicedParts = parts . slice ( 1 , - 1 ) ; const newParams = `${ langSwitcher ? `${ langSwitcher [ 0 ] }${ dbSwitcher ? '-' : '' }` : '' }${ dbSwitcher ? `${ dbSwitcher [ 0 ] }` : '' }` ; for ( const part of slicedParts ) { let tmp = prevItems && prevItems . find ( ( { label } ) => label == part ) ; if ( tmp ) { if ( ! tmp . items ) { tmp . items = [ ] ; } } else { tmp = { label : part , items : [ ] , topLevel , experimental , preview , earlyaccess , staticLink , } ; prevItems . push ( tmp ) ; } if ( parts [ parts . length - 1 ] === 'index' && parts [ parts . length - 2 ] === part ) { tmp . url = `${ urlGenerator ( modSlug ) }${ newParams ? '-' + newParams : '' }` ; tmp . slug = slug ; tmp . title = title ; tmp . navTitle = navTitle ; tmp . staticLink = staticLink ; tmp . duration = duration ; tmp . experimental = experimental ; tmp . preview = preview ; tmp . earlyaccess = earlyaccess ; tmp . topLevel = topLevel ; tmp . hidePage = hidePage ; tmp . codeStyle = codeStyle ; tmp . parentLabel = parts [ parts . length - 3 ] ; tmp . parents = parts . filter ( ( part ) => part !== 'index' ) ; if ( defaultCollapsed && location ) { defaultCollapsed [ part . toLowerCase ( ) ] = tmp . topLevel || tmp . staticLink ? null : getCollpaseState ( modSlug , location ) ; } } prevItems = tmp . items ; } const slicedLength = parts . length - 1 ; const existingItem = prevItems . find ( ( { label } ) => label === parts [ slicedLength ] ) ; if ( ! existingItem ) { prevItems . push ( { label : parts [ slicedLength ] , url : `${ urlGenerator ( modSlug ) }${ newParams ? '-' + newParams : '' }` , slug : slug , items : [ ] , title , navTitle , staticLink , duration , experimental , preview , earlyaccess , topLevel , hidePage , codeStyle , parentLabel : parts [ parts . length - 3 ] , parents : parts . filter ( ( part ) => part !== 'index' ) , } ) ; } return accu ; } , { items : [ ] } ) ; return tree ; } ;