@kadoui/react
Version:
Kadoui primitive components for React
36 lines (35 loc) • 1.29 kB
JavaScript
"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import { useState, useEffect } from "react";
export const Affix = ({ onClick, ...p }) => {
const [isVisible, setIsVisible] = useState(false);
const [lastScrollY, setLastScrollY] = useState(0);
useEffect(() => {
const handleScroll = () => {
const currentScrollY = window.scrollY;
const viewportHeight = window.innerHeight;
const scrollThreshold = viewportHeight * 0.5;
if (currentScrollY > scrollThreshold && currentScrollY > lastScrollY) {
setIsVisible(true);
}
else if (currentScrollY < lastScrollY && currentScrollY < scrollThreshold) {
setIsVisible(false);
}
setLastScrollY(currentScrollY);
};
window.addEventListener("scroll", handleScroll, {
passive: true,
});
return () => window.removeEventListener("scroll", handleScroll);
}, [lastScrollY]);
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: "smooth",
});
};
return (_jsx("button", { "data-state": isVisible, onClick: (ev) => {
onClick?.(ev);
scrollToTop();
}, ...p }));
};