-
Notifications
You must be signed in to change notification settings - Fork 185
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Improve snippets scrolling behaviour
- Loading branch information
1 parent
ae7053f
commit e0f0375
Showing
3 changed files
with
41 additions
and
54 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { useEffect } from 'react'; | ||
|
||
export function useScrollIntoView( | ||
element: HTMLElement | null, | ||
scrollContainer: HTMLElement | null | ||
) { | ||
useEffect(() => { | ||
if (!scrollContainer || !element) { | ||
return; | ||
} | ||
|
||
const itemOffsetRelativeToContainer = | ||
element.offsetParent === scrollContainer | ||
? element.offsetTop | ||
: element.offsetTop - scrollContainer.offsetTop; | ||
|
||
let { scrollTop } = scrollContainer; // Top of the visible area | ||
|
||
if (itemOffsetRelativeToContainer < scrollTop) { | ||
// Item is off the top of the visible area | ||
scrollTop = itemOffsetRelativeToContainer; | ||
} else if ( | ||
itemOffsetRelativeToContainer + element.offsetHeight > | ||
scrollTop + scrollContainer.offsetHeight | ||
) { | ||
// Item is off the bottom of the visible area | ||
scrollTop = | ||
itemOffsetRelativeToContainer + | ||
element.offsetHeight - | ||
scrollContainer.offsetHeight; | ||
} | ||
|
||
if (scrollTop !== scrollContainer.scrollTop) { | ||
scrollContainer.scrollTop = scrollTop; | ||
} | ||
}, [scrollContainer, element]); | ||
} |