import BLOG from '@/blog.config' import { useGlobal } from '@/lib/global' import { faArrowDown } from '@fortawesome/free-solid-svg-icons' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { useCallback, useEffect, useState } from 'react' import Typed from 'typed.js' /** * * @returns 头图 */ export default function Header () { const [typed, changeType] = useState() useEffect(() => { if (!typed && window && document.getElementById('typed')) { changeType( new Typed('#typed', { strings: BLOG.headerStrings, typeSpeed: 200, backSpeed: 100, backDelay: 400, showCursor: true, smartBackspace: true }) ) } }) const { theme } = useGlobal() // 监听滚动 let windowTop = 0 let autoScroll = false const autoScrollEnd = () => { windowTop = window.scrollY autoScroll = false } const scrollTrigger = useCallback(() => { if ( (window.scrollY > windowTop) & (window.scrollY < window.innerHeight) & !autoScroll ) { autoScroll = true scrollTo(wrapperTop, autoScrollEnd) } if ( (window.scrollY < windowTop) & (window.scrollY < window.innerHeight) & !autoScroll ) { autoScroll = true scrollTo(0, autoScrollEnd) } windowTop = window.scrollY updateTopNav() }) const updateTopNav = () => { if (theme !== 'dark') { const stickyNavElement = document.getElementById('sticky-nav') if (window.scrollY < window.innerHeight) { stickyNavElement.classList.add('dark') } else { stickyNavElement.classList.remove('dark') } } } let wrapperTop = 0 function updateHeaderHeight () { if (window) { const wrapperElement = document.getElementById('wrapper') wrapperTop = wrapperElement.offsetTop } } useEffect(() => { updateHeaderHeight() updateTopNav() window.addEventListener('scroll', scrollTrigger) window.addEventListener('resize', updateHeaderHeight) return () => { window.removeEventListener('scroll', scrollTrigger) window.removeEventListener('resize', updateHeaderHeight) } }) return ( ) } /** * Native scrollTo with callback * @param offset - offset to scroll to * @param callback - callback function */ function scrollTo (offset, callback) { const fixedOffset = offset.toFixed() const onScroll = function () { if (window.pageYOffset.toFixed() === fixedOffset) { window.removeEventListener('scroll', onScroll) window.onscroll = function () {} callback() } } window.addEventListener('scroll', onScroll) window.onscroll = onScroll() window.scrollTo({ top: offset, behavior: 'smooth' }) }