const interceptors = new Set < ( ) => string | void > ( ) ; export const defaultPrompt = 'Are you sure you want to leave this page?' ; let hasIntercepted = false ; let hasUserCancelled = false ; let lastScroll = [ 0 , 0 ] as [ number , number ] ; export function shouldCancelNavigation ( ) { lastScroll = [ window . scrollX , window . scrollY ] ; if ( hasIntercepted ) return hasUserCancelled ; return Array . from ( interceptors ) . some ( ( interceptor ) => { const prompt = interceptor ( ) ; if ( ! prompt ) return false ; hasUserCancelled = ! window . confirm ( prompt ) ; hasIntercepted = true ; setTimeout ( ( ) => { hasIntercepted = false ; hasUserCancelled = false ; } , 0 ) ; return hasUserCancelled ; } ) ; } export function addInterceptor ( handler ) { window . addEventListener ( 'beforeunload' , handler ) ; interceptors . add ( handler ) ; } export function removeInterceptor ( handler ) { window . removeEventListener ( 'beforeunload' , handler ) ; interceptors . delete ( handler ) ; } export function undoNavigation ( lastPath ) { window . history . pushState ( null , null as unknown as string , lastPath ) ; setTimeout ( ( ) => { window . scrollTo ( ... lastScroll ) ; } , 0 ) ; }