Skip to content

Commit

Permalink
Optimize and refactor getScrollElement
Browse files Browse the repository at this point in the history
  • Loading branch information
Aljullu committed Mar 28, 2022
1 parent 7559469 commit b02d1e1
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 43 deletions.
6 changes: 3 additions & 3 deletions src/hoc/trackWindowScroll.js
Expand Up @@ -4,7 +4,7 @@ import { PropTypes } from 'prop-types';
import debounce from 'lodash.debounce';
import throttle from 'lodash.throttle';
import isIntersectionObserverAvailable from '../utils/intersection-observer';
import getScrollElement from '../utils/get-scroll-element';
import getScrollAncestor from '../utils/get-scroll-ancestor';

const getScrollX = () =>
typeof window === 'undefined' ? 0 : window.scrollX || window.pageXOffset;
Expand Down Expand Up @@ -54,7 +54,7 @@ const trackWindowScroll = BaseComponent => {
return;
}

const scrollElement = getScrollElement(
const scrollElement = getScrollAncestor(
ReactDom.findDOMNode(this.baseComponentRef.current)
);

Expand All @@ -69,7 +69,7 @@ const trackWindowScroll = BaseComponent => {
return;
}

this.scrollElement = getScrollElement(
this.scrollElement = getScrollAncestor(
ReactDom.findDOMNode(this.baseComponentRef.current)
);

Expand Down
35 changes: 35 additions & 0 deletions src/utils/get-scroll-ancestor.ts
@@ -0,0 +1,35 @@
// Adapted from https://github.com/loktar00/react-lazy-load/blob/master/src/utils/parentScroll.js

const getElementOverflowValues = (element: HTMLElement) : string => {
const computedStyle = getComputedStyle(element, null);

return (
computedStyle.getPropertyValue('overflow') +
computedStyle.getPropertyValue('overflow-y') +
computedStyle.getPropertyValue('overflow-x')
);
};

const getScrollAncestor = (element: Node) : HTMLElement | Window => {
if (!(element instanceof HTMLElement)) {
return window;
}

let parent : Node = element;

while (parent) {
if (!(parent instanceof HTMLElement)) {
break;
}

if (/(scroll|auto)/.test(getElementOverflowValues(parent))) {
return parent;
}

parent = parent.parentNode;
}

return window;
};

export default getScrollAncestor;
39 changes: 0 additions & 39 deletions src/utils/get-scroll-element.js

This file was deleted.

5 changes: 4 additions & 1 deletion webpack.config.js
Expand Up @@ -12,7 +12,7 @@ module.exports = {
module: {
rules: [
{
test: /\.jsx?$/,
test: /\.(j|t)sx?$/,
include: path.resolve(__dirname, 'src'),
exclude: /(node_modules|bower_components|build)/,
use: {
Expand Down Expand Up @@ -46,4 +46,7 @@ module.exports = {
extensions: ['js', 'jsx', 'ts', 'tsx'],
}),
],
resolve: {
extensions: ['.ts', '.tsx', '.js', '.jsx'],
},
};

0 comments on commit b02d1e1

Please sign in to comment.