Skip to content

Commit

Permalink
Add a scroll margin to the top when layout has sections (#2574)
Browse files Browse the repository at this point in the history
  • Loading branch information
BrettJephson authored Nov 19, 2024
1 parent 061c0c1 commit 07cf835
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/hip-eggs-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gitbook': patch
---

Add scroll margin to the top when there are sections
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ export default async function Page(props: {
/>
</div>
<React.Suspense fallback={null}>
<PageClientLayout />
<PageClientLayout withSections={withSections} />
</React.Suspense>
</>
);
Expand Down
15 changes: 13 additions & 2 deletions packages/gitbook/src/components/hooks/useScrollPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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]);
}

0 comments on commit 07cf835

Please sign in to comment.