mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-22 18:43:29 +00:00
Add a scroll margin to the top when layout has sections (#2574)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Add scroll margin to the top when there are sections
|
||||
@@ -8,10 +8,10 @@ import { useScrollPage } from '@/components/hooks';
|
||||
/**
|
||||
* Client component to initialize interactivity for a page.
|
||||
*/
|
||||
export function PageClientLayout(props: {}) {
|
||||
export function PageClientLayout(props: { withSections?: boolean }) {
|
||||
// We use this hook in the page layout to ensure the elements for the blocks
|
||||
// are rendered before we scroll to a hash or to the top of the page
|
||||
useScrollPage();
|
||||
useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
|
||||
|
||||
useStripFallbackQueryParam();
|
||||
return null;
|
||||
|
||||
@@ -111,7 +111,7 @@ export default async function Page(props: {
|
||||
/>
|
||||
</div>
|
||||
<React.Suspense fallback={null}>
|
||||
<PageClientLayout />
|
||||
<PageClientLayout withSections={withSections} />
|
||||
</React.Suspense>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -8,13 +8,16 @@ import { useHash } from './useHash';
|
||||
* to the top of the page when navigating between pages (pathname)
|
||||
* or sections of a page (hash).
|
||||
*/
|
||||
export function useScrollPage() {
|
||||
export function useScrollPage(props: { scrollMarginTop?: number }) {
|
||||
const hash = useHash();
|
||||
const pathname = usePathname();
|
||||
React.useLayoutEffect(() => {
|
||||
if (hash) {
|
||||
const element = document.getElementById(hash);
|
||||
if (element) {
|
||||
if (props.scrollMarginTop) {
|
||||
element.style.scrollMarginTop = `${props.scrollMarginTop}px`;
|
||||
}
|
||||
element.scrollIntoView({
|
||||
block: 'start',
|
||||
behavior: 'smooth',
|
||||
@@ -23,5 +26,13 @@ export function useScrollPage() {
|
||||
} else {
|
||||
window.scrollTo(0, 0);
|
||||
}
|
||||
}, [hash, pathname]);
|
||||
return () => {
|
||||
if (hash) {
|
||||
const element = document.getElementById(hash);
|
||||
if (element) {
|
||||
element.style.scrollMarginTop = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
}, [hash, pathname, props.scrollMarginTop]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user