import HistoryManager from './HistoryManager' ; class HTML5HistoryManager implements HistoryManager { private navigateHistory : ( e : PopStateEvent ) => void = null ; private applicationPath : string = '' ; disabled : boolean = ( typeof window === 'undefined' ) || ! ( window . history && window . history . pushState ) ; constructor ( applicationPath = '' ) { this . applicationPath = HTML5HistoryManager . prependSlash ( applicationPath ) ; } init ( navigateHistory ) { if ( ! this . disabled && ! this . navigateHistory ) { this . navigateHistory = e => navigateHistory ( ( e . state && e . state . navigationLink ) || undefined ) ; window . addEventListener ( 'popstate' , this . navigateHistory ) ; } } addHistory ( url , replace ) { if ( ! this . disabled && ( window . history . state ?. navigationLink || this . getUrl ( window . location ) ) !== url ) { if ( ! replace ) window . history . pushState ( { navigationLink : url } , null , this . getHref ( url ) ) ; else window . history . replaceState ( { navigationLink : url } , null , this . getHref ( url ) ) ; } } getCurrentUrl ( ) { return this . getUrl ( window . location ) ; } getHref ( url ) { if ( url == null ) throw new Error ( 'The Url is invalid' ) ; return this . applicationPath + HTML5HistoryManager . prependSlash ( url ) ; } getUrl ( hrefElement ) { return hrefElement . pathname . substring ( this . applicationPath . length ) + hrefElement . search + hrefElement . hash ; } stop ( ) { if ( this . navigateHistory ) window . removeEventListener ( 'popstate' , this . navigateHistory ) ; this . navigateHistory = null ; } private static prependSlash ( url ) { return ( url && url . substring ( 0 , 1 ) !== '/' ) ? '/' + url : url ; } } export default HTML5HistoryManager ;