import React, { useState } from 'react'; import { motion, useScroll, useMotionValueEvent, AnimatePresence, LayoutGroup } from 'framer-motion'; import { NAV_ITEMS } from '../../data/mockData'; import { NavItem } from '../../types'; interface FloatingNavProps { activeTab: string; onTabChange: (id: string) => void; } const FloatingNav: React.FC = ({ activeTab, onTabChange }) => { const { scrollY } = useScroll(); const [isScrollingDown, setIsScrollingDown] = useState(false); const [hasScrolled, setHasScrolled] = useState(false); useMotionValueEvent(scrollY, "change", (latest) => { const previous = scrollY.getPrevious() || 0; const isDown = latest > previous; // Add a threshold to prevent jitter if (Math.abs(latest - previous) > 5) { setIsScrollingDown(isDown); } setHasScrolled(latest > 100); }); const heavyEase: [number, number, number, number] = [0.22, 1, 0.36, 1]; // Find active label for the dynamic indicator const activeLabel = NAV_ITEMS.find(n => n.id === activeTab)?.label || ""; // --- Sliding Window Logic --- // We want to show 4 items. // We try to keep the active item at index 1 (2nd position) of the window if possible, // to allow seeing one previous item and two future items. const WINDOW_SIZE = 4; const activeIndex = NAV_ITEMS.findIndex(n => n.id === activeTab); let startIndex = activeIndex - 1; // Clamp start index if (startIndex < 0) startIndex = 0; // Ensure we don't go out of bounds at the end if (startIndex + WINDOW_SIZE > NAV_ITEMS.length) { startIndex = NAV_ITEMS.length - WINDOW_SIZE; } // Safety check if total items < WINDOW_SIZE if (startIndex < 0) startIndex = 0; const visibleItems = NAV_ITEMS.slice(startIndex, startIndex + WINDOW_SIZE); return (
{/* Dynamic Current Section Indicator (Appears when scrolling) */} {hasScrolled && !isScrollingDown && ( Viewing: {activeLabel} )} {/* Main Nav Container */} {/* Using LayoutGroup to automatically animate the "slide" effect when items are removed/added from the DOM */}
{visibleItems.map((item: NavItem) => { const isActive = activeTab === item.id; return ( onTabChange(item.id)} initial={{ opacity: 0, scale: 0.8, filter: "blur(4px)" }} animate={{ opacity: 1, scale: 1, filter: "blur(0px)" }} exit={{ opacity: 0, scale: 0.8, filter: "blur(4px)" }} transition={{ duration: 0.4, ease: "easeOut" }} className="relative flex-shrink-0 px-5 py-2.5 rounded-full text-sm font-medium outline-none group overflow-hidden whitespace-nowrap focus-visible:ring-2 focus-visible:ring-brand-gold/40" > {/* Active Pill Background */} {isActive && (
)} {/* Text Label */} {item.label} ); })}
); }; export default FloatingNav;