import { EventContract } from '../tsaction/event_contract' ; import { Route } from '../ivy-route-recognizer/route-recognizer/dsl' ; const ROUTER_LOCAL_NAME = 'pages-router' ; function getCurrentLocation ( ) { return window . location . pathname + window . location . search ; } function loadRouterModule ( ) { return import ( '../router-impl/router' ) ; } let routerLoaded = false ; let navigateFn = null ; function lazilyLoadRouter ( loadRouter , routes , contract , onLoad ? ) { if ( ! routerLoaded ) { return loadRouter ( ) . then ( routerModule => { routerModule . registerRouterElement ( document , customElements , '' , routes , contract , router => { if ( router . depth === 1 ) { navigateFn = ( targetUrl ) => { if ( getCurrentLocation ( ) !== targetUrl ) { window . history . pushState ( null , '' , targetUrl ) ; router . navigate ( targetUrl ) ; } return Promise . resolve ( true ) ; } ; } if ( onLoad != null ) { onLoad ( router ) ; } } ) ; routerLoaded = true ; } ) ; } } export function initRouter ( ROUTES , contract ) { if ( document . querySelector ( ROUTER_LOCAL_NAME ) == null ) { return ; } window . addEventListener ( 'popstate' , evt => { lazilyLoadRouter ( loadRouterModule , ROUTES , contract , router => router . navigate ( ) ) ; } ) ; navigateFn = ( targetUrl ) => { if ( getCurrentLocation ( ) !== targetUrl ) { window . history . pushState ( null , '' , targetUrl ) ; return lazilyLoadRouter ( loadRouterModule , ROUTES , contract , router => { if ( router . depth == 1 ) { router . navigate ( targetUrl ) ; } else { router . navigate ( ) ; } } ) ; } } ; contract . setRouterCallback ( navigateFn ) ; } export function navigate ( path ) { if ( navigateFn != null ) { return navigateFn ( path ) ; } return Promise . reject ( 'No router was found in page.' ) ; }