mirror of
https://github.com/tuono-labs/tuono
synced 2026-07-25 12:52:47 -07:00
feat: prevent scroll offset on page navigation (#77)
This commit is contained in:
@@ -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 (
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user