diff options
author | crupest <crupest@outlook.com> | 2023-08-26 23:49:28 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2023-08-26 23:49:28 +0800 |
commit | 256cc9592a3f31fc392e1ccdb699aa206b7b47ce (patch) | |
tree | fdca6f8b1cdbd5ed264a1af9e48496685f4e9a95 /FrontEnd/src/components/hooks/useScrollToBottom.ts | |
parent | f5dfd52f6efece2f4cad227044ecf4dd66301bbc (diff) | |
download | timeline-256cc9592a3f31fc392e1ccdb699aa206b7b47ce.tar.gz timeline-256cc9592a3f31fc392e1ccdb699aa206b7b47ce.tar.bz2 timeline-256cc9592a3f31fc392e1ccdb699aa206b7b47ce.zip |
...
Diffstat (limited to 'FrontEnd/src/components/hooks/useScrollToBottom.ts')
-rw-r--r-- | FrontEnd/src/components/hooks/useScrollToBottom.ts | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/FrontEnd/src/components/hooks/useScrollToBottom.ts b/FrontEnd/src/components/hooks/useScrollToBottom.ts new file mode 100644 index 00000000..79fcda16 --- /dev/null +++ b/FrontEnd/src/components/hooks/useScrollToBottom.ts @@ -0,0 +1,44 @@ +import { useRef, useEffect } from "react"; +import { fromEvent, filter, throttleTime } from "rxjs"; + +function useScrollToBottom( + handler: () => void, + enable = true, + option = { + maxOffset: 5, + throttle: 1000, + }, +): void { + const handlerRef = useRef<(() => void) | null>(null); + + useEffect(() => { + handlerRef.current = handler; + + return () => { + handlerRef.current = null; + }; + }, [handler]); + + useEffect(() => { + const subscription = fromEvent(window, "scroll") + .pipe( + filter( + () => + window.scrollY >= + document.body.scrollHeight - window.innerHeight - option.maxOffset, + ), + throttleTime(option.throttle), + ) + .subscribe(() => { + if (enable) { + handlerRef.current?.(); + } + }); + + return () => { + subscription.unsubscribe(); + }; + }, [enable, option.maxOffset, option.throttle]); +} + +export default useScrollToBottom; |