Skip to content

Commit

Permalink
add raf
Browse files Browse the repository at this point in the history
  • Loading branch information
linxianxi committed Apr 2, 2024
1 parent 7e5724c commit 1326eaa
Showing 1 changed file with 35 additions and 24 deletions.
59 changes: 35 additions & 24 deletions src/stickyScrollBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import getScrollBarSize from 'rc-util/lib/getScrollBarSize';
import * as React from 'react';
import TableContext from './context/TableContext';
import { useLayoutState } from './hooks/useFrame';
import raf from 'rc-util/lib/raf';

interface StickyScrollBarProps {
scrollBodyRef: React.RefObject<HTMLDivElement>;
Expand Down Expand Up @@ -39,6 +40,14 @@ const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarPr
x: 0,
});
const [isActive, setActive] = React.useState(false);
const rafRef = React.useRef<number | null>(null);

React.useEffect(
() => () => {
raf.cancel(rafRef.current);
},
[],
);

const onMouseUp: React.MouseEventHandler<HTMLDivElement> = () => {
setActive(false);
Expand Down Expand Up @@ -81,30 +90,32 @@ const StickyScrollBar: React.ForwardRefRenderFunction<unknown, StickyScrollBarPr
};

const checkScrollBarVisible = () => {
if (!scrollBodyRef.current) {
return;
}
const tableOffsetTop = getOffset(scrollBodyRef.current).top;
const tableBottomOffset = tableOffsetTop + scrollBodyRef.current.offsetHeight;
const currentClientOffset =
container === window
? document.documentElement.scrollTop + window.innerHeight
: getOffset(container).top + (container as HTMLElement).clientHeight;

if (
tableBottomOffset - getScrollBarSize() <= currentClientOffset ||
tableOffsetTop >= currentClientOffset - offsetScroll
) {
setScrollState(state => ({
...state,
isHiddenScrollBar: true,
}));
} else {
setScrollState(state => ({
...state,
isHiddenScrollBar: false,
}));
}
rafRef.current = raf(() => {
if (!scrollBodyRef.current) {
return;
}

Check warning on line 96 in src/stickyScrollBar.tsx

View check run for this annotation

Codecov / codecov/patch

src/stickyScrollBar.tsx#L95-L96

Added lines #L95 - L96 were not covered by tests
const tableOffsetTop = getOffset(scrollBodyRef.current).top;
const tableBottomOffset = tableOffsetTop + scrollBodyRef.current.offsetHeight;
const currentClientOffset =
container === window
? document.documentElement.scrollTop + window.innerHeight
: getOffset(container).top + (container as HTMLElement).clientHeight;

if (
tableBottomOffset - getScrollBarSize() <= currentClientOffset ||
tableOffsetTop >= currentClientOffset - offsetScroll
) {
setScrollState(state => ({
...state,
isHiddenScrollBar: true,
}));
} else {
setScrollState(state => ({
...state,
isHiddenScrollBar: false,
}));
}
});
};

const setScrollLeft = (left: number) => {
Expand Down

0 comments on commit 1326eaa

Please sign in to comment.