1- import React , { useState , useEffect } from 'react' ;
1+ import React , { useState , useEffect , useRef } from 'react' ;
22import { useParams , Link } from 'react-router-dom' ;
33import ReactMarkdown from 'react-markdown' ;
44import fm from 'front-matter' ;
@@ -8,6 +8,9 @@ const BlogPostPage = () => {
88 const { slug } = useParams ( ) ;
99 const [ post , setPost ] = useState ( null ) ;
1010 const [ loading , setLoading ] = useState ( true ) ;
11+ const [ readingProgress , setReadingProgress ] = useState ( 0 ) ;
12+ const [ isAtTop , setIsAtTop ] = useState ( true ) ; // New state for tracking if at top
13+ const contentRef = useRef ( null ) ;
1114
1215 useEffect ( ( ) => {
1316 const fetchPost = async ( ) => {
@@ -31,6 +34,21 @@ const BlogPostPage = () => {
3134 fetchPost ( ) ;
3235 } , [ slug ] ) ;
3336
37+ useEffect ( ( ) => {
38+ const handleScroll = ( ) => {
39+ if ( contentRef . current ) {
40+ const { scrollTop, scrollHeight, clientHeight } = document . documentElement ;
41+ const totalHeight = scrollHeight - clientHeight ;
42+ const currentProgress = ( scrollTop / totalHeight ) * 100 ;
43+ setReadingProgress ( currentProgress ) ;
44+ setIsAtTop ( scrollTop === 0 ) ; // Update isAtTop based on scroll position
45+ }
46+ } ;
47+
48+ window . addEventListener ( 'scroll' , handleScroll ) ;
49+ return ( ) => window . removeEventListener ( 'scroll' , handleScroll ) ;
50+ } , [ post ] ) ; // Re-attach scroll listener if post changes
51+
3452 if ( loading ) {
3553 return < div className = "text-center py-16" > Loading...</ div > ;
3654 }
@@ -47,12 +65,12 @@ const BlogPostPage = () => {
4765 < Link to = "/blog" className = "text-primary-400 hover:text-primary-500 transition-colors mb-8 block" >
4866 ← Back to Blog
4967 </ Link >
50- < div className = "prose prose-xl prose-dark max-w-none" >
68+ < div ref = { contentRef } className = "prose prose-xl prose-dark max-w-none" >
5169 < ReactMarkdown > { post . body } </ ReactMarkdown >
5270 </ div >
5371 </ div >
5472 < div className = "hidden lg:block" >
55- < PostMetadata metadata = { post . attributes } />
73+ < PostMetadata metadata = { post . attributes } readingProgress = { readingProgress } isAtTop = { isAtTop } />
5674 </ div >
5775 </ div >
5876 </ div >
0 commit comments