Created
May 6, 2021 15:19
-
-
Save charlintosh/37f5a3d9b2b820d7cde34edf729d2c2a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Observable, animationFrameScheduler, fromEvent, of } from "rxjs"; | |
import { distinctUntilChanged, filter, map, pairwise, switchMap, throttleTime } from "rxjs/operators"; | |
import { ScrollType, ScrollMovement } from "./types"; | |
export const watchScroll$ = (): Observable<ScrollType> => | |
of(typeof window === "undefined") | |
.pipe( | |
filter((undefinedWindow) => (!undefinedWindow)), | |
switchMap(() => fromEvent(window, "scroll", {passive: true})), | |
throttleTime(0, animationFrameScheduler), | |
map(() => (window.pageYOffset)), | |
pairwise(), | |
map(([previous, current]) => | |
( | |
current < previous || current === 0 | |
? ScrollMovement.UP | |
: ScrollMovement.DOWN | |
) | |
), | |
distinctUntilChanged() | |
); | |
distinctUntilChanged() | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment