Skip to content

Commit

Permalink
Handle content resizing and hidden scrollbars
Browse files Browse the repository at this point in the history
  • Loading branch information
atomiks committed Sep 30, 2024
1 parent 10427e4 commit c3f12b8
Showing 1 changed file with 32 additions and 3 deletions.
35 changes: 32 additions & 3 deletions packages/mui-base/src/ScrollArea/Viewport/ScrollAreaViewport.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ const ScrollAreaViewport = React.forwardRef(function ScrollAreaViewport(
props: ScrollAreaViewport.Props,
forwardedRef: React.ForwardedRef<HTMLDivElement>,
) {
const { render, className, ...otherProps } = props;
const { render, className, children, ...otherProps } = props;

const { viewportRef, scrollbarYRef, scrollbarXRef, thumbYRef, thumbXRef, setScrolling } =
useScrollAreaRootContext();

const timeoutRef = React.useRef(-1);

const mergedRef = useForkRef(forwardedRef, viewportRef);
const tableWrapperRef = React.useRef<HTMLDivElement | null>(null);

const computeThumb = useEventCallback(() => {
const viewportEl = viewportRef.current;
Expand Down Expand Up @@ -66,9 +67,17 @@ const ScrollAreaViewport = React.forwardRef(function ScrollAreaViewport(

thumbYEl.style.transform = `translate3d(0,${thumbOffsetY}px,0)`;

const scrollbarYHidden = viewportHeight >= scrollableContentHeight;

if (scrollbarYHidden) {
scrollbarYEl.setAttribute('hidden', '');
}

scrollbarYEl.style.setProperty(
'--scroll-area-thumb-height',
`${(viewportHeight / scrollableContentHeight) * viewportHeight}px`,
scrollbarYHidden
? '0px'
: `${(viewportHeight / scrollableContentHeight) * viewportHeight}px`,
);
}

Expand All @@ -85,9 +94,15 @@ const ScrollAreaViewport = React.forwardRef(function ScrollAreaViewport(

thumbXEl.style.transform = `translate3d(${thumbOffsetX}px,0,0)`;

const scrollbarXHidden = viewportWidth >= scrollableContentWidth;

if (scrollbarXHidden) {
scrollbarXEl.setAttribute('hidden', '');
}

scrollbarXEl.style.setProperty(
'--scroll-area-thumb-width',
`${(viewportWidth / scrollableContentWidth) * viewportWidth}px`,
scrollbarXHidden ? '0px' : `${(viewportWidth / scrollableContentWidth) * viewportWidth}px`,
);
}
});
Expand All @@ -97,6 +112,19 @@ const ScrollAreaViewport = React.forwardRef(function ScrollAreaViewport(
queueMicrotask(computeThumb);
}, [computeThumb]);

React.useEffect(() => {
if (!tableWrapperRef.current) {
return undefined;
}

const ro = new ResizeObserver(computeThumb);
ro.observe(tableWrapperRef.current);

return () => {
ro.disconnect();
};
}, [computeThumb]);

const { renderElement } = useComponentRenderer({
render: render ?? 'div',
ref: mergedRef,
Expand All @@ -117,6 +145,7 @@ const ScrollAreaViewport = React.forwardRef(function ScrollAreaViewport(
},
children: (
<div
ref={tableWrapperRef}
style={{
minWidth: '100%',
display: 'table',
Expand Down

0 comments on commit c3f12b8

Please sign in to comment.