|
| 1 | +'use client'; |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react'; |
| 4 | + |
| 5 | +interface ReadingProgressBarProps { |
| 6 | + chapterSlug: string; |
| 7 | + isLoading?: boolean; |
| 8 | +} |
| 9 | + |
| 10 | +export default function ReadingProgressBar({ chapterSlug, isLoading = false }: ReadingProgressBarProps) { |
| 11 | + const [progress, setProgress] = useState(0); |
| 12 | + |
| 13 | + useEffect(() => { |
| 14 | + if (typeof window === 'undefined') return; |
| 15 | + |
| 16 | + const storageKey = `reading-progress-${chapterSlug}`; |
| 17 | + |
| 18 | + // Restore scroll position ONLY when content has finished loading |
| 19 | + if (!isLoading) { |
| 20 | + const savedScroll = localStorage.getItem(storageKey); |
| 21 | + if (savedScroll !== null) { |
| 22 | + setTimeout(() => { |
| 23 | + window.scrollTo({ top: Number(savedScroll), behavior: 'smooth' }); |
| 24 | + }, 100); |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + const handleScroll = () => { |
| 29 | + const scrollTop = window.scrollY; |
| 30 | + const docHeight = document.documentElement.scrollHeight - window.innerHeight; |
| 31 | + |
| 32 | + if (docHeight > 0) { |
| 33 | + const currentProgress = (scrollTop / docHeight) * 100; |
| 34 | + setProgress(Math.min(100, Math.max(0, currentProgress))); |
| 35 | + } else { |
| 36 | + setProgress(0); |
| 37 | + } |
| 38 | + }; |
| 39 | + |
| 40 | + // Save scroll position persistently |
| 41 | + const saveScroll = () => { |
| 42 | + if (!isLoading) { |
| 43 | + localStorage.setItem(storageKey, window.scrollY.toString()); |
| 44 | + } |
| 45 | + }; |
| 46 | + |
| 47 | + window.addEventListener('scroll', handleScroll); |
| 48 | + window.addEventListener('beforeunload', saveScroll); |
| 49 | + handleScroll(); |
| 50 | + |
| 51 | + return () => { |
| 52 | + saveScroll(); |
| 53 | + window.removeEventListener('scroll', handleScroll); |
| 54 | + window.removeEventListener('beforeunload', saveScroll); |
| 55 | + }; |
| 56 | + }, [chapterSlug, isLoading]); |
| 57 | + |
| 58 | + return ( |
| 59 | + <div className="fixed top-0 left-0 w-full h-1.5 z-[100]"> |
| 60 | + <div |
| 61 | + className="h-full bg-primary transition-all duration-150 ease-out" |
| 62 | + style={{ width: `${progress}%` }} |
| 63 | + /> |
| 64 | + </div> |
| 65 | + ); |
| 66 | +} |
0 commit comments