import { findHTML } from './utils' ; export class Router { private slotElement : HTMLElement ; private docPath : string ; private links : any [ ] = [ ] ; private lastLink : HTMLElement ; private eventHub : any ; private origin : string ; static removeHashTag ( hash = '' ) { if ( ! hash . startsWith ( '#' ) ) return hash ; return hash . substr ( 1 , hash . length ) ; } static removeSlash ( path ) { return path . replace ( /\/\//g , '/' ) ; } static replaceSuffix ( name ) { name = name . split ( '.md' ) [ 0 ] ; return `${ name }.html` ; } constructor ( slotElement , docPath = '/' ) { this . slotElement = slotElement ; this . docPath = docPath ; this . origin = window . location . origin + window . location . pathname ; this . initList ( ) ; } listen ( eventHub ) { this . eventHub = eventHub ; window . onhashchange = ( ) => this . _parseHash ( ) ; this . _parseHash ( ) ; } private closeMenu ( ) { const sideBar = document . querySelector ( '#side' ) ; const isMobile = sideBar . classList . contains ( 'xs' ) || sideBar . classList . contains ( 'sm' ) ; if ( ! isMobile ) return ; sideBar . classList . remove ( 'active' ) ; } private initList ( ) { const sideList = document . querySelector ( '.side-list' ) ; const links = sideList . querySelectorAll ( 'a' ) ; Array . from ( links ) . forEach ( ( link ) => { this . links . push ( { el : link , href : link . getAttribute ( 'href' ) , } ) ; } ) ; } private toggleList ( hash ) { const link = this . links . find ( link => link . href === `#${ decodeURI ( hash ) }` ) ; if ( ! link ) return ; this . lastLink && this . lastLink . parentElement . classList . remove ( 'active' ) ; link . el . parentElement . classList . add ( 'active' ) ; this . lastLink = link . el ; } private _parseHash ( ) { this . eventHub . dispath ( 'container-will-change' ) ; const hash = Router . removeHashTag ( window . location . hash ) ; this . toggleList ( hash ) ; let path = '/static/' + this . docPath + hash ; if ( path . endsWith ( '/' ) ) { path += window . __paper . router . default ; } const htmlPath = Router . replaceSuffix ( path ) ; this . _loader ( Router . removeSlash ( htmlPath ) ) . then ( ) ; } private async _loader ( path ) { const res = await findHTML ( this . origin + path ) ; const _div = document . createElement ( 'div' ) ; _div . classList . add ( 'container-inner' ) ; _div . innerHTML = await res . text ( ) ; this . slotElement . innerHTML = '' ; this . slotElement . appendChild ( _div ) ; this . slotElement . parentElement . scrollTo ( 0 , 0 ) ; this . eventHub . dispath ( 'container-changed' , path ) ; this . closeMenu ( ) ; } }