From 258b4af0b19247f3541a65641c1bc87e4ecea16f Mon Sep 17 00:00:00 2001 From: Valerio Ageno <51341197+Valerioageno@users.noreply.github.com> Date: Mon, 4 Nov 2024 19:29:37 +0100 Subject: [PATCH] feat: prevent scroll offset on page navigation (#77) --- packages/router/src/components/Link.tsx | 11 +++++++++-- packages/router/src/hooks/useRouter.tsx | 16 ++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/packages/router/src/components/Link.tsx b/packages/router/src/components/Link.tsx index a5a6b6e1..235b6144 100644 --- a/packages/router/src/components/Link.tsx +++ b/packages/router/src/components/Link.tsx @@ -5,13 +5,20 @@ import useRoute from '../hooks/useRoute' import { useInView } from 'react-intersection-observer' interface TuonoLinkProps { + /** + * If "true" the route gets loaded when the link enters the viewport. Default "true" + */ preload?: boolean + /** + * If "false" the scroll offset will be kept across page navigation. Default "true" + */ + scroll?: boolean } export default function Link( componentProps: AnchorHTMLAttributes & TuonoLinkProps, ): JSX.Element { - const { preload = true, ...props } = componentProps + const { preload = true, scroll = true, ...props } = componentProps const router = useRouter() const route = useRoute(props.href) const { ref } = useInView({ @@ -30,7 +37,7 @@ export default function Link( return } - router.push(props.href || '') + router.push(props.href || '', { scroll }) } return ( diff --git a/packages/router/src/hooks/useRouter.tsx b/packages/router/src/hooks/useRouter.tsx index 24a6ba60..68a1fff2 100644 --- a/packages/router/src/hooks/useRouter.tsx +++ b/packages/router/src/hooks/useRouter.tsx @@ -1,10 +1,17 @@ import { useRouterStore } from './useRouterStore' +interface PushOptions { + /** + * If "false" the scroll offset will be kept across page navigation. Default "true" + */ + scroll?: boolean +} + interface UseRouterHook { /** * Redirects to the path passed as argument updating the browser history. */ - push: (path: string) => void + push: (path: string, opt?: PushOptions) => void /** * This object contains all the query params of the current route @@ -23,7 +30,8 @@ export const useRouter = (): UseRouterHook => { st.updateLocation, ]) - const push = (path: string): void => { + const push = (path: string, opt?: PushOptions): void => { + const { scroll = true } = opt || {} const url = new URL(path, window.location.origin) updateLocation({ @@ -34,6 +42,10 @@ export const useRouter = (): UseRouterHook => { hash: url.hash, }) history.pushState(path, '', path) + + if (scroll) { + window.scroll(0, 0) + } } return {