Skip to content

Commit

Permalink
[Tabs] Refactor IntersectionObserver logic (#38133)
Browse files Browse the repository at this point in the history
Co-authored-by: Olivier Tassinari <[email protected]>
  • Loading branch information
ZeeshanTamboli and oliviertassinari committed Jul 25, 2023
1 parent 1140095 commit 2e56fbd
Showing 1 changed file with 22 additions and 34 deletions.
56 changes: 22 additions & 34 deletions packages/mui-material/src/Tabs/Tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -604,53 +604,41 @@ const Tabs = React.forwardRef(function Tabs(inProps, ref) {
* Using IntersectionObserver on first and last Tabs.
*/
React.useEffect(() => {
let firstObserver;
let lastObserver;
const tabListChildren = Array.from(tabListRef.current.children);
const length = tabListChildren.length;
const firstTab = tabListChildren[0];
const lastTab = tabListChildren[length - 1];
const threshold = 0.99;
const observerOptions = {
root: tabsRef.current,
threshold,
};

const handleScrollButtonStart = (entries) => {
let display = false;
entries.forEach(({ isIntersecting }) => {
display = !isIntersecting;
});
setDisplayStartScroll(display);
};

const handleScrollButtonEnd = (entries) => {
let display = false;
entries.forEach(({ isIntersecting }) => {
display = !isIntersecting;
});
setDisplayEndScroll(display);
};

if (
typeof IntersectionObserver !== 'undefined' &&
length > 0 &&
scrollable &&
scrollButtons !== false
) {
firstObserver = new IntersectionObserver(handleScrollButtonStart, observerOptions);
const firstTab = tabListChildren[0];
const lastTab = tabListChildren[length - 1];
const observerOptions = {
root: tabsRef.current,
threshold: 0.99,
};

const handleScrollButtonStart = (entries) => {
setDisplayStartScroll(!entries[0].isIntersecting);
};
const firstObserver = new IntersectionObserver(handleScrollButtonStart, observerOptions);
firstObserver.observe(firstTab);

if (length > 1) {
lastObserver = new IntersectionObserver(handleScrollButtonEnd, observerOptions);
lastObserver.observe(lastTab);
}
const handleScrollButtonEnd = (entries) => {
setDisplayEndScroll(!entries[0].isIntersecting);
};
const lastObserver = new IntersectionObserver(handleScrollButtonEnd, observerOptions);
lastObserver.observe(lastTab);

return () => {
firstObserver.disconnect();
lastObserver.disconnect();
};
}

return () => {
firstObserver?.disconnect();
lastObserver?.disconnect();
};
return undefined;
}, [scrollable, scrollButtons, updateScrollObserver, childrenProp?.length]);

React.useEffect(() => {
Expand Down

0 comments on commit 2e56fbd

Please sign in to comment.