aboutsummaryrefslogtreecommitdiff
path: root/FrontEnd/src/app/utilities/useScrollToTop.ts
blob: da63cb0a9c76dbcf93796d30b098b1e422f29189 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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;