import { useCallback, useEffect, useRef, useState } from 'react' import Logo from './Logo' import throttle from 'lodash.throttle' import RandomPostButton from './RandomPostButton' import SearchButton from './SearchButton' import DarkModeButton from './DarkModeButton' import SlideOver from './SlideOver' import ReadingProgress from './ReadingProgress' import { MenuListTop } from './MenuListTop' import { isBrowser } from '@/lib/utils' import { siteConfig } from '@/lib/config' /** * 顶部导航 * @param {*} param0 * @returns */ const NavBar = props => { const [fixedNav, setFixedNav] = useState(false) const [textWhite, setTextWhite] = useState(false) const [navBgWhite, setBgWhite] = useState(false) const [activeIndex, setActiveIndex] = useState(0) const slideOverRef = useRef() const toggleMenuOpen = () => { slideOverRef?.current?.toggleSlideOvers() } /** * 根据滚动条,切换导航栏样式 */ const scrollTrigger = useCallback(throttle(() => { const scrollS = window.scrollY // 导航栏设置 白色背景 if (scrollS <= 0) { setFixedNav(false) setBgWhite(false) // 文章详情页特殊处理 if (document.querySelector('#post-bg')) { setFixedNav(true) setTextWhite(true) setBgWhite(false) } } else { // 向下滚动后的导航样式 setFixedNav(true) setTextWhite(false) setBgWhite(true) } }, 200)) // 监听滚动 useEffect(() => { scrollTrigger() window.addEventListener('scroll', scrollTrigger) return () => { window.removeEventListener('scroll', scrollTrigger) } }, []) // 监听导航栏显示文字 useEffect(() => { let prevScrollY = 0 let ticking = false const handleScroll = () => { if (!ticking) { window.requestAnimationFrame(() => { const currentScrollY = window.scrollY if (currentScrollY > prevScrollY) { setActiveIndex(1) // 向下滚动时设置activeIndex为1 } else { setActiveIndex(0) // 向上滚动时设置activeIndex为0 } prevScrollY = currentScrollY ticking = false }) ticking = true } } if (isBrowser) { window.addEventListener('scroll', handleScroll) } return () => { if (isBrowser) { window.removeEventListener('scroll', handleScroll) } } }, []) return (<> {/* 顶部导航菜单栏 */} ) } export default NavBar