Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a scroll margin to the top when layout has sections #2574

Merged
merged 6 commits into from
Nov 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 = '';
BrettJephson marked this conversation as resolved.
Show resolved Hide resolved
}
}
};
}, [hash, pathname, props.scrollMarginTop]);
}
Loading