@primer/components
Version:
Primer react components
30 lines (28 loc) • 1.27 kB
JavaScript
export const scrollIntoViewingArea = (child, container, 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 {
[]: containerStart,
[]: containerEnd
} = container.getBoundingClientRect();
const isChildStartAboveViewingArea = childStart < containerStart + endMargin;
const isChildBottomBelowViewingArea = childEnd > containerEnd - startMargin;
if (isChildStartAboveViewingArea) {
const scrollHeightToChildStart = childStart - containerStart + container[scrollSide];
container.scrollTo({
behavior,
[]: scrollHeightToChildStart - endMargin
});
} else if (isChildBottomBelowViewingArea) {
const scrollHeightToChildBottom = childEnd - containerEnd + container[scrollSide];
container.scrollTo({
behavior,
[]: scrollHeightToChildBottom + startMargin
});
} // either completely in view or outside viewing area on both ends, don't scroll
};