2024-03-16 04:45:46 +08:00
|
|
|
import {
|
2024-10-18 09:11:47 +08:00
|
|
|
useCallback, useEffect, useRef,
|
2024-03-16 04:45:46 +08:00
|
|
|
} from 'react';
|
|
|
|
|
|
|
|
interface Handlers {
|
|
|
|
startObserving(): void;
|
|
|
|
stopObserving(): void;
|
|
|
|
}
|
|
|
|
|
2024-10-03 06:28:02 +08:00
|
|
|
const useStickyScroll = (stickyElement: HTMLElement | null, onResizeOf: HTMLElement | null) => {
|
2024-03-16 04:45:46 +08:00
|
|
|
const elHeight = useRef(0);
|
2024-08-10 01:58:44 +08:00
|
|
|
const timeout = useRef<ReturnType<typeof setTimeout>>();
|
2024-10-18 09:11:47 +08:00
|
|
|
const observer = useRef<ResizeObserver | null>(null);
|
2024-03-16 04:45:46 +08:00
|
|
|
const handlers = useRef<Handlers>({
|
|
|
|
startObserving: () => {},
|
|
|
|
stopObserving: () => {},
|
|
|
|
});
|
|
|
|
|
2024-10-18 09:11:47 +08:00
|
|
|
useEffect(() => {
|
|
|
|
if (observer.current) {
|
|
|
|
observer.current.disconnect();
|
|
|
|
}
|
|
|
|
|
|
|
|
observer.current = new ResizeObserver((entries) => {
|
2024-03-16 04:45:46 +08:00
|
|
|
entries.forEach((entry) => {
|
|
|
|
const { target } = entry;
|
|
|
|
if (target instanceof HTMLElement) {
|
2024-10-18 09:11:47 +08:00
|
|
|
if (target.offsetHeight !== elHeight.current) {
|
2024-03-16 04:45:46 +08:00
|
|
|
elHeight.current = target.offsetHeight;
|
2024-10-03 06:28:02 +08:00
|
|
|
if (stickyElement) {
|
|
|
|
// eslint-disable-next-line no-param-reassign
|
|
|
|
stickyElement.scrollTop = stickyElement.scrollHeight + stickyElement.clientHeight;
|
|
|
|
}
|
2024-03-16 04:45:46 +08:00
|
|
|
} else {
|
|
|
|
elHeight.current = 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2024-10-18 09:11:47 +08:00
|
|
|
});
|
|
|
|
}, [stickyElement]);
|
2024-03-16 04:45:46 +08:00
|
|
|
|
|
|
|
handlers.current.startObserving = useCallback(() => {
|
2024-10-03 06:28:02 +08:00
|
|
|
if (!onResizeOf) return;
|
2024-03-16 04:45:46 +08:00
|
|
|
clearTimeout(timeout.current);
|
2024-10-18 09:11:47 +08:00
|
|
|
observer.current?.observe(onResizeOf);
|
|
|
|
}, [onResizeOf, observer.current]);
|
2024-03-16 04:45:46 +08:00
|
|
|
|
|
|
|
handlers.current.stopObserving = useCallback(() => {
|
2024-10-03 06:28:02 +08:00
|
|
|
if (!onResizeOf) return;
|
2024-03-16 04:45:46 +08:00
|
|
|
timeout.current = setTimeout(() => {
|
2024-10-18 09:11:47 +08:00
|
|
|
observer.current?.unobserve(onResizeOf);
|
2024-03-16 04:45:46 +08:00
|
|
|
}, 500);
|
2024-10-18 09:11:47 +08:00
|
|
|
}, [onResizeOf, observer.current]);
|
2024-03-16 04:45:46 +08:00
|
|
|
|
|
|
|
useEffect(
|
|
|
|
() => () => {
|
2024-10-18 09:11:47 +08:00
|
|
|
observer.current?.disconnect();
|
2024-03-16 04:45:46 +08:00
|
|
|
},
|
|
|
|
[],
|
|
|
|
);
|
|
|
|
|
|
|
|
return handlers.current;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default useStickyScroll;
|