saleor-dashboard/src/hooks/useElementScroll.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

2019-08-09 10:17:04 +00:00
import throttle from "lodash-es/throttle";
import { MutableRefObject, useEffect, useState } from "react";
2019-10-15 10:33:14 +00:00
export type Position = Record<"x" | "y", number>;
function getPosition(anchor?: HTMLElement): Position {
2019-08-09 10:17:04 +00:00
if (!!anchor) {
return {
x: anchor.scrollLeft,
y: anchor.scrollTop
};
}
2019-10-15 10:33:14 +00:00
return undefined;
}
export function isScrolledToBottom(
anchor: MutableRefObject<HTMLElement>,
position: Position,
offset: number = 0
) {
return !!anchor.current && position
? position.y + anchor.current.clientHeight + offset >=
anchor.current.scrollHeight
2019-10-15 12:33:35 +00:00
: undefined;
2019-08-09 10:17:04 +00:00
}
2019-10-15 10:33:14 +00:00
function useElementScroll(anchor: MutableRefObject<HTMLElement>): Position {
2019-08-09 10:17:04 +00:00
const [scroll, setScroll] = useState(getPosition(anchor.current));
useEffect(() => {
if (!!anchor.current) {
const handleScroll = throttle(
() => setScroll(getPosition(anchor.current)),
100
);
anchor.current.addEventListener("scroll", handleScroll);
2019-11-06 15:51:02 +00:00
return () => {
if (!!anchor.current) {
anchor.current.removeEventListener("scroll", handleScroll);
}
};
2019-08-09 10:17:04 +00:00
}
}, [anchor.current]);
2019-10-15 12:33:35 +00:00
useEffect(() => {
setTimeout(() => setScroll(getPosition(anchor.current)), 100);
}, []);
2019-08-09 10:17:04 +00:00
return scroll;
}
export default useElementScroll;