aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/utilities/hooks/useScrollToTop.ts
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2022-04-24 19:56:15 +0800
committercrupest <crupest@outlook.com>2022-04-24 19:56:15 +0800
commitc81dfffe0076c94dc61397fd17677cb24f67cdf2 (patch)
tree8cf9811371dfb68a487bbde199c67628e12ed020 /FrontEnd/src/utilities/hooks/useScrollToTop.ts
parent4fdf7d1cb50c3dd8ea8e96f7fb4cf8f655152dcc (diff)
downloadtimeline-c81dfffe0076c94dc61397fd17677cb24f67cdf2.tar.gz
timeline-c81dfffe0076c94dc61397fd17677cb24f67cdf2.tar.bz2
timeline-c81dfffe0076c94dc61397fd17677cb24f67cdf2.zip
...
Diffstat (limited to 'FrontEnd/src/utilities/hooks/useScrollToTop.ts')
-rw-r--r--FrontEnd/src/utilities/hooks/useScrollToTop.ts43
1 files changed, 43 insertions, 0 deletions
diff --git a/FrontEnd/src/utilities/hooks/useScrollToTop.ts b/FrontEnd/src/utilities/hooks/useScrollToTop.ts
new file mode 100644
index 00000000..95c8b7b9
--- /dev/null
+++ b/FrontEnd/src/utilities/hooks/useScrollToTop.ts
@@ -0,0 +1,43 @@
+import React from "react";
+import { fromEvent } from "rxjs";
+import { filter, throttleTime } from "rxjs/operators";
+
+function useScrollToTop(
+ handler: () => void,
+ enable = true,
+ option = {
+ maxOffset: 5,
+ throttle: 1000,
+ }
+): void {
+ const handlerRef = React.useRef<(() => void) | null>(null);
+
+ React.useEffect(() => {
+ handlerRef.current = handler;
+
+ return () => {
+ handlerRef.current = null;
+ };
+ }, [handler]);
+
+ React.useEffect(() => {
+ const subscription = fromEvent(window, "scroll")
+ .pipe(
+ filter(() => {
+ return window.scrollY <= option.maxOffset;
+ }),
+ throttleTime(option.throttle)
+ )
+ .subscribe(() => {
+ if (enable) {
+ handlerRef.current?.();
+ }
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ };
+ }, [enable, option.maxOffset, option.throttle]);
+}
+
+export default useScrollToTop;