From 944fa647ad044d35e2cae30bf29eb5ce989f757d Mon Sep 17 00:00:00 2001 From: Dionysos Dajka Date: Wed, 5 May 2021 17:33:12 +0200 Subject: [PATCH] fix(utils): Improve getScrollParent --- src/utils/getScrollParent.js | 21 +++++++++++++++++++++ src/utils/index.js | 6 ++---- src/utils/scrollIntoViewIfNeeded.js | 13 +------------ 3 files changed, 24 insertions(+), 16 deletions(-) create mode 100644 src/utils/getScrollParent.js diff --git a/src/utils/getScrollParent.js b/src/utils/getScrollParent.js new file mode 100644 index 000000000..d339da7cf --- /dev/null +++ b/src/utils/getScrollParent.js @@ -0,0 +1,21 @@ +function getScrollParent(node) { + const isElement = node instanceof HTMLElement; + const overflowY = isElement && window.getComputedStyle(node).overflowY; + const isScrollable = !( + overflowY.includes('hidden') || overflowY.includes('visible') + ); + + if (!node) { + return null; + } else if (isScrollable && node.scrollHeight >= node.clientHeight) { + return node; + } + + return ( + getScrollParent(node.parentNode) || + document.scrollingElement || + document.body + ); +} + +export default getScrollParent; diff --git a/src/utils/index.js b/src/utils/index.js index 534d21be6..bce15cbfd 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -2,11 +2,9 @@ export * from './colors'; export {default as mergeRefs} from './mergeRefs'; export {default as mergeCallbacks} from './mergeCallbacks'; export {default as getLength} from './getLength'; +export {default as getScrollParent} from './getScrollParent'; export {default as getSpacing} from './getSpacing'; -export { - default as scrollIntoViewIfNeeded, - getScrollParent, -} from './scrollIntoViewIfNeeded'; +export {default as scrollIntoViewIfNeeded} from './scrollIntoViewIfNeeded'; export * from './spacing'; export {default as truncateText} from './truncateText'; export * from './units'; diff --git a/src/utils/scrollIntoViewIfNeeded.js b/src/utils/scrollIntoViewIfNeeded.js index dd0dbddcf..3bdb9610b 100644 --- a/src/utils/scrollIntoViewIfNeeded.js +++ b/src/utils/scrollIntoViewIfNeeded.js @@ -1,13 +1,4 @@ -function getScrollParent(element) { - if (!element) { - return null; - } - if (element.scrollHeight > element.clientHeight) { - return element; - } else { - return getScrollParent(element.parentNode); - } -} +import getScrollParent from './getScrollParent'; /** * Vertically Scrolls an element into view if it's not visible yet. @@ -32,6 +23,4 @@ function scrollIntoViewIfNeeded(element) { } } -export {getScrollParent}; - export default scrollIntoViewIfNeeded;