Skip to content

Commit 07cf835

Browse files
authored
Add a scroll margin to the top when layout has sections (#2574)
1 parent 061c0c1 commit 07cf835

File tree

4 files changed

+21
-5
lines changed

4 files changed

+21
-5
lines changed

.changeset/hip-eggs-trade.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'gitbook': patch
3+
---
4+
5+
Add scroll margin to the top when there are sections

packages/gitbook/src/app/(site)/(content)/[[...pathname]]/PageClientLayout.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ import { useScrollPage } from '@/components/hooks';
88
/**
99
* Client component to initialize interactivity for a page.
1010
*/
11-
export function PageClientLayout(props: {}) {
11+
export function PageClientLayout(props: { withSections?: boolean }) {
1212
// We use this hook in the page layout to ensure the elements for the blocks
1313
// are rendered before we scroll to a hash or to the top of the page
14-
useScrollPage();
14+
useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
1515

1616
useStripFallbackQueryParam();
1717
return null;

packages/gitbook/src/app/(site)/(content)/[[...pathname]]/page.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export default async function Page(props: {
111111
/>
112112
</div>
113113
<React.Suspense fallback={null}>
114-
<PageClientLayout />
114+
<PageClientLayout withSections={withSections} />
115115
</React.Suspense>
116116
</>
117117
);

packages/gitbook/src/components/hooks/useScrollPage.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,16 @@ import { useHash } from './useHash';
88
* to the top of the page when navigating between pages (pathname)
99
* or sections of a page (hash).
1010
*/
11-
export function useScrollPage() {
11+
export function useScrollPage(props: { scrollMarginTop?: number }) {
1212
const hash = useHash();
1313
const pathname = usePathname();
1414
React.useLayoutEffect(() => {
1515
if (hash) {
1616
const element = document.getElementById(hash);
1717
if (element) {
18+
if (props.scrollMarginTop) {
19+
element.style.scrollMarginTop = `${props.scrollMarginTop}px`;
20+
}
1821
element.scrollIntoView({
1922
block: 'start',
2023
behavior: 'smooth',
@@ -23,5 +26,13 @@ export function useScrollPage() {
2326
} else {
2427
window.scrollTo(0, 0);
2528
}
26-
}, [hash, pathname]);
29+
return () => {
30+
if (hash) {
31+
const element = document.getElementById(hash);
32+
if (element) {
33+
element.style.scrollMarginTop = '';
34+
}
35+
}
36+
};
37+
}, [hash, pathname, props.scrollMarginTop]);
2738
}

0 commit comments

Comments
 (0)