saleor-dashboard/src/hooks/useElementScroll.ts
Dawid 158188002a
Update React to 17 and related packages (#2370)
* Update React to 17

* Update types for React 17

* Update references in useEffect cleanup functions

* Update react-error-boundary

* Update react-inlinesvg

* Update Apollo Client and Upload Link

* Update apollo-upload-client types

* Fix comment about csstypes

* Downgrade apollo-client version due to log-in bug

* Add missing apollo link

* Update package-lock version

* Fix button type

* Fix datagrid test after react update

* Fix polish language letter bug
2022-10-24 11:49:11 +02:00

54 lines
1.3 KiB
TypeScript

import throttle from "lodash/throttle";
import { MutableRefObject, useEffect, useState } from "react";
export type Position = Record<"x" | "y", number>;
function getPosition(anchor?: HTMLElement): Position {
if (!!anchor) {
return {
x: anchor.scrollLeft,
y: anchor.scrollTop,
};
}
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
: undefined;
}
function useElementScroll(anchor: MutableRefObject<HTMLElement>): Position {
const [scroll, setScroll] = useState(getPosition(anchor.current));
useEffect(() => {
const anchorInstance = anchor.current;
if (!!anchorInstance) {
const handleScroll = throttle(
() => setScroll(getPosition(anchorInstance)),
100,
);
anchorInstance.addEventListener("scroll", handleScroll);
return () => {
if (!!anchorInstance) {
anchorInstance.removeEventListener("scroll", handleScroll);
}
};
}
}, [anchor.current]);
useEffect(() => {
setTimeout(() => setScroll(getPosition(anchor.current)), 100);
}, []);
return scroll;
}
export default useElementScroll;