diff --git a/.changeset/blue-wasps-sparkle.md b/.changeset/blue-wasps-sparkle.md new file mode 100644 index 000000000..aab1bceb7 --- /dev/null +++ b/.changeset/blue-wasps-sparkle.md @@ -0,0 +1,5 @@ +--- +'gitbook': patch +--- + +Fix scroll position when navigating pages on mobile diff --git a/packages/gitbook/src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx b/packages/gitbook/src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx index 2c248bec2..49b29781d 100644 --- a/packages/gitbook/src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx +++ b/packages/gitbook/src/app/(space)/(content)/[[...pathname]]/PageClientLayout.tsx @@ -3,15 +3,15 @@ import { usePathname, useRouter, useSearchParams } from 'next/navigation'; import React from 'react'; -import { useScrollToHash } from '@/components/hooks'; +import { useScrollPage } from '@/components/hooks'; /** * Client component to initialize interactivity for a page. */ export function PageClientLayout(props: {}) { // We use this hook in the page layout to ensure the elements for the blocks - // are rendered before we scroll to the hash. - useScrollToHash(); + // are rendered before we scroll to a hash or to the top of the page + useScrollPage(); useStripFallbackQueryParam(); return null; diff --git a/packages/gitbook/src/components/hooks/index.ts b/packages/gitbook/src/components/hooks/index.ts index 0a0c5c9a0..611c81b4d 100644 --- a/packages/gitbook/src/components/hooks/index.ts +++ b/packages/gitbook/src/components/hooks/index.ts @@ -1,4 +1,4 @@ export * from './useScrollActiveId'; -export * from './useScrollToHash'; +export * from './useScrollPage'; export * from './useHash'; export * from './useIsMounted'; diff --git a/packages/gitbook/src/components/hooks/useScrollToHash.ts b/packages/gitbook/src/components/hooks/useScrollPage.ts similarity index 54% rename from packages/gitbook/src/components/hooks/useScrollToHash.ts rename to packages/gitbook/src/components/hooks/useScrollPage.ts index d384cf698..48a7bf2be 100644 --- a/packages/gitbook/src/components/hooks/useScrollToHash.ts +++ b/packages/gitbook/src/components/hooks/useScrollPage.ts @@ -1,12 +1,16 @@ +import { usePathname } from 'next/navigation'; import React from 'react'; import { useHash } from './useHash'; /** - * Scroll to the current URL hash everytime the URL changes. + * Scroll the page to an anchor point or + * to the top of the page when navigating between pages (pathname) + * or sections of a page (hash). */ -export function useScrollToHash() { +export function useScrollPage() { const hash = useHash(); + const pathname = usePathname(); React.useLayoutEffect(() => { if (hash) { const element = document.getElementById(hash); @@ -16,6 +20,8 @@ export function useScrollToHash() { behavior: 'smooth', }); } + } else { + window.scrollTo(0, 0); } - }, [hash]); + }, [hash, pathname]); }