import path from 'path' ; import plugin from '../plugin' ; import { PageContent , Context } from '../types' ; function findDemoOwner ( contents , demoSource ) { const folder = path . basename ( path . dirname ( demoSource ) ) ; let parentName = folder . replace ( /-demo$/ , '' ) ; if ( parentName === 'demo' ) { parentName = path . basename ( path . dirname ( path . dirname ( demoSource ) ) ) ; } return contents . findIndex ( ( item ) : boolean => { const file = path . parse ( path . basename ( item . source ) ) ; return ( file . name === parentName || ( file . name === 'index' && path . basename ( path . dirname ( item . source ) ) === parentName ) ) ; } ) ; } function sortByOrder ( pages ) { return pages . sort ( ( a , b ) => { const aOrder = typeof a . meta . frontmatter . order !== 'undefined' ? Number ( a . meta . frontmatter . order ) : 998 ; const bOrder = typeof b . meta . frontmatter . order !== 'undefined' ? Number ( b . meta . frontmatter . order ) : 999 ; return aOrder - bOrder ; } ) ; } export default plugin ( { runBefore ( context ) { const allDemos = [ ] ; context . pages . forEach ( ( item ) : void => { const folder = path . basename ( path . dirname ( item . source ) ) ; if ( folder . match ( /demo$/ ) ) { const parent = context . pages [ findDemoOwner ( context . pages , item . source ) ] ; if ( parent ) { if ( ! parent . demos ) { parent . demos = [ item ] ; } else { parent . demos . push ( item ) ; } sortByOrder ( parent . demos ) ; allDemos . push ( item ) ; } } } ) ; allDemos . forEach ( ( demo ) => { const index = context . pages . findIndex ( ( i ) => i === demo ) ; if ( index !== - 1 ) { context . pages . splice ( index , 1 ) ; } } ) ; } } ) ;