@primer/components
Version:
Primer react components
30 lines (28 loc) • 1.3 kB
JavaScript
export const scrollIntoViewingArea = (child, viewingArea, direction = 'vertical', startMargin = 8, endMargin = 0, behavior = 'smooth') => {
const startSide = direction === 'vertical' ? 'top' : 'left';
const endSide = direction === 'vertical' ? 'bottom' : 'right';
const scrollSide = direction === 'vertical' ? 'scrollTop' : 'scrollLeft';
const {
[]: childStart,
[]: childEnd
} = child.getBoundingClientRect();
const {
[]: viewingAreaStart,
[]: viewingAreaEnd
} = viewingArea.getBoundingClientRect();
const isChildStartAboveViewingArea = childStart < viewingAreaStart + endMargin;
const isChildBottomBelowViewingArea = childEnd > viewingAreaEnd - startMargin;
if (isChildStartAboveViewingArea) {
const scrollHeightToChildStart = childStart - viewingAreaStart + viewingArea[scrollSide];
viewingArea.scrollTo({
behavior,
[]: scrollHeightToChildStart - endMargin
});
} else if (isChildBottomBelowViewingArea) {
const scrollHeightToChildBottom = childEnd - viewingAreaEnd + viewingArea[scrollSide];
viewingArea.scrollTo({
behavior,
[]: scrollHeightToChildBottom + startMargin
});
} // either completely in view or outside viewing area on both ends, don't scroll
};