aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/app/utilities/useScrollToTop.ts
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-06-03 18:28:56 +0800
committercrupest <crupest@outlook.com>2021-06-03 18:28:56 +0800
commit44141e188eef44fd4fd1c77aee7df168b68765b1 (patch)
treee8f8c55b578b4676e61511bf65ed4425e4f95d19 /FrontEnd/src/app/utilities/useScrollToTop.ts
parent2cbb0aa75edbaf5269a4a3fdf52452834cf7ed04 (diff)
downloadtimeline-44141e188eef44fd4fd1c77aee7df168b68765b1.tar.gz
timeline-44141e188eef44fd4fd1c77aee7df168b68765b1.tar.bz2
timeline-44141e188eef44fd4fd1c77aee7df168b68765b1.zip
fix: Don't know this is No.which attemp to fix scroll to top bug.
Diffstat (limited to 'FrontEnd/src/app/utilities/useScrollToTop.ts')
-rw-r--r--FrontEnd/src/app/utilities/useScrollToTop.ts49
1 files changed, 49 insertions, 0 deletions
diff --git a/FrontEnd/src/app/utilities/useScrollToTop.ts b/FrontEnd/src/app/utilities/useScrollToTop.ts
new file mode 100644
index 00000000..da63cb0a
--- /dev/null
+++ b/FrontEnd/src/app/utilities/useScrollToTop.ts
@@ -0,0 +1,49 @@
+import React from "react";
+import { fromEvent } from "rxjs";
+import { filter, throttleTime, tap } from "rxjs/operators";
+
+function useScrollToTop(
+ handler: () => void,
+ enable = true,
+ option = {
+ maxOffset: 50,
+ 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(
+ tap(() => {
+ console.log(
+ `Scroll event fired: ${window.scrollY}, time: ${Date.now()}.`
+ );
+ }),
+ filter(() => {
+ return window.scrollY <= option.maxOffset;
+ }),
+ throttleTime(option.throttle)
+ )
+ .subscribe(() => {
+ if (enable) {
+ console.log(`Fire scroll to top event, time: ${Date.now()}.`);
+ handlerRef.current?.();
+ }
+ });
+
+ return () => {
+ subscription.unsubscribe();
+ };
+ }, [enable, option.maxOffset, option.throttle]);
+}
+
+export default useScrollToTop;