diff --git a/docs/reference/runtime-api.md b/docs/reference/runtime-api.md index 416a8217..e4839d0c 100644 --- a/docs/reference/runtime-api.md +++ b/docs/reference/runtime-api.md @@ -86,8 +86,27 @@ Returns the VitePress router instance so you can programmatically navigate to an ```ts interface Router { + /** + * Current route. + */ route: Route - go: (href?: string) => Promise + /** + * Navigate to a new URL. + */ + go: (to?: string) => Promise + /** + * Called before the route changes. Return `false` to cancel the navigation. + */ + onBeforeRouteChange?: (to: string) => Awaitable + /** + * Called before the page component is loaded (after the history state is + * updated). Return `false` to cancel the navigation. + */ + onBeforePageLoad?: (to: string) => Awaitable + /** + * Called after the route changes. + */ + onAfterRouteChanged?: (to: string) => Awaitable } ``` diff --git a/src/client/app/router.ts b/src/client/app/router.ts index d1c82843..084d4e78 100644 --- a/src/client/app/router.ts +++ b/src/client/app/router.ts @@ -12,9 +12,26 @@ export interface Route { } export interface Router { + /** + * Current route. + */ route: Route - go: (href?: string) => Promise - onBeforeRouteChange?: (to: string) => Awaitable + /** + * Navigate to a new URL. + */ + go: (to?: string) => Promise + /** + * Called before the route changes. Return `false` to cancel the navigation. + */ + onBeforeRouteChange?: (to: string) => Awaitable + /** + * Called before the page component is loaded (after the history state is + * updated). Return `false` to cancel the navigation. + */ + onBeforePageLoad?: (to: string) => Awaitable + /** + * Called after the route changes. + */ onAfterRouteChanged?: (to: string) => Awaitable } @@ -47,7 +64,7 @@ export function createRouter( } async function go(href: string = inBrowser ? location.href : '/') { - await router.onBeforeRouteChange?.(href) + if ((await router.onBeforeRouteChange?.(href)) === false) return const url = new URL(href, fakeHost) if (!siteDataRef.value.cleanUrls) { // ensure correct deep link so page refresh lands on correct files. @@ -62,6 +79,7 @@ export function createRouter( history.replaceState({ scrollPosition: window.scrollY }, document.title) history.pushState(null, '', href) } + if ((await router.onBeforePageLoad?.(href)) === false) return await loadPage(href) await router.onAfterRouteChanged?.(href) }