feat: prevent scroll offset on page navigation (#77)

This commit is contained in:
Valerio Ageno
2024-11-04 19:29:37 +01:00
committed by GitHub
parent edfbd03f13
commit 258b4af0b1
2 changed files with 23 additions and 4 deletions
+9 -2
View File
@@ -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<HTMLAnchorElement> & 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 (
+14 -2
View File
@@ -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 {