Skip to content

Commit 2b1be28

Browse files
refactor: simplify scroll detection code
1 parent 17a21a2 commit 2b1be28

1 file changed

Lines changed: 8 additions & 20 deletions

File tree

packages/raystack/components/navbar/navbar-root.tsx

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,8 @@ export const NavbarRoot = forwardRef<ComponentRef<'nav'>, NavbarRootProps>(
6262
) => {
6363
// hideOnScroll: whether navbar is currently hidden (driven by scroll position/direction)
6464
const [hidden, setHidden] = useState(false);
65-
// Last scroll position; used to compute delta and drive hide/show
65+
// Last scroll position at which we updated hidden; only updated when we show/hide or are at top
6666
const lastScrollY = useRef(0);
67-
// Accumulated scroll delta in current direction; makes slow scrolls still trigger hide/show
68-
const accum = useRef(0);
6967
// Nav DOM node; used to find scroll container and attach listeners
7068
const navRef = useRef<HTMLElement>(null);
7169

@@ -87,26 +85,16 @@ export const NavbarRoot = forwardRef<ComponentRef<'nav'>, NavbarRootProps>(
8785
const scrollY = isWindow
8886
? (window.scrollY ?? document.documentElement.scrollTop)
8987
: scrollContainer!.scrollTop;
90-
const delta = scrollY - lastScrollY.current;
91-
lastScrollY.current = scrollY;
9288

9389
if (scrollY <= SHOW_AT_TOP_THRESHOLD) {
9490
setHidden(false);
95-
accum.current = 0;
96-
} else if (delta > 0) {
97-
// Scrolling down: add to accum, reset if we were scrolling up
98-
accum.current = accum.current > 0 ? accum.current + delta : delta;
99-
if (accum.current >= SCROLL_THRESHOLD) {
100-
setHidden(true);
101-
accum.current = 0;
102-
}
103-
} else if (delta < 0) {
104-
// Scrolling up: add to accum (delta is negative), reset if we were scrolling down
105-
accum.current = accum.current < 0 ? accum.current + delta : delta;
106-
if (accum.current <= -SCROLL_THRESHOLD) {
107-
setHidden(false);
108-
accum.current = 0;
109-
}
91+
lastScrollY.current = scrollY;
92+
} else if (scrollY > lastScrollY.current + SCROLL_THRESHOLD) {
93+
setHidden(true);
94+
lastScrollY.current = scrollY;
95+
} else if (scrollY < lastScrollY.current - SCROLL_THRESHOLD) {
96+
setHidden(false);
97+
lastScrollY.current = scrollY;
11098
}
11199
ticking = false;
112100
});

0 commit comments

Comments
 (0)