|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | + |
| 5 | +import { MaterialSymbolsProgressActivity } from '@/components/icons/Progress'; |
| 6 | +import { MotionButtonBase } from '@/components/ui/button'; |
| 7 | +import { cn } from '@/lib/helper'; |
| 8 | +import { springScrollToTop } from '@/lib/scroller'; |
| 9 | +import { useMainArticleStore } from '@/store/mainArticleStore'; |
| 10 | + |
| 11 | +export const ReadIndicator = () => { |
| 12 | + const { Element } = useMainArticleStore(); |
| 13 | + const [readPercent, setReadPercent] = useState(0); |
| 14 | + |
| 15 | + useEffect(() => { |
| 16 | + const handleScroll = () => { |
| 17 | + if (!Element) return; |
| 18 | + |
| 19 | + const elementTop = Element.getBoundingClientRect().top + window.scrollY; |
| 20 | + const scrollTop = window.scrollY; |
| 21 | + const winHeight = window.innerHeight; |
| 22 | + const elementHeight = Element.offsetHeight; |
| 23 | + // 为了解决一开始进度不为0的问题 |
| 24 | + const readHeight = scrollTop > winHeight ? scrollTop + winHeight - elementTop : scrollTop; |
| 25 | + const scrollPosition = (readHeight / elementHeight) * 100; |
| 26 | + setReadPercent(Math.floor(Math.min(Math.max(0, scrollPosition), 100))); |
| 27 | + }; |
| 28 | + |
| 29 | + window.addEventListener('scroll', handleScroll); |
| 30 | + handleScroll(); |
| 31 | + |
| 32 | + return () => { |
| 33 | + window.removeEventListener('scroll', handleScroll); |
| 34 | + }; |
| 35 | + }, [Element]); |
| 36 | + |
| 37 | + return ( |
| 38 | + <div className="text-gray-800 dark:text-neutral-300"> |
| 39 | + <div className="flex items-center gap-2"> |
| 40 | + <MaterialSymbolsProgressActivity progress={readPercent} /> |
| 41 | + {readPercent}%<br /> |
| 42 | + </div> |
| 43 | + <MotionButtonBase |
| 44 | + onClick={springScrollToTop} |
| 45 | + className={cn( |
| 46 | + 'mt-1 flex flex-nowrap items-center gap-2 opacity-50 transition-all duration-500 hover:opacity-100', |
| 47 | + readPercent > 10 ? '' : 'pointer-events-none opacity-0', |
| 48 | + )} |
| 49 | + > |
| 50 | + <i className="i-mingcute-arrow-up-circle-line" /> |
| 51 | + <span className="whitespace-nowrap">回到顶部</span> |
| 52 | + </MotionButtonBase> |
| 53 | + </div> |
| 54 | + ); |
| 55 | +}; |
0 commit comments