11'use client' ;
22
33import { useAuthStore } from '@/store/useAuthStore' ;
4- import { useRouter } from 'next/navigation' ;
5- import { useEffect } from 'react' ;
4+ import { useRouter , usePathname } from 'next/navigation' ;
5+ import { useEffect , useRef } from 'react' ;
66import { Sidebar } from '@/components/layout/Sidebar' ;
77import { Header } from '@/components/layout/Header' ;
88import { ErrorBoundary } from '@/components/errors/ErrorBoundary' ;
@@ -14,13 +14,37 @@ export default function DashboardLayout({
1414} ) {
1515 const isAuthenticated = useAuthStore ( ( state ) => state . isAuthenticated ) ;
1616 const router = useRouter ( ) ;
17+ const pathname = usePathname ( ) ;
18+ const mainRef = useRef < HTMLElement > ( null ) ;
19+ const scrollPositions = useRef < Record < string , number > > ( { } ) ;
1720
1821 useEffect ( ( ) => {
1922 if ( ! isAuthenticated ) {
2023 router . push ( '/auth' ) ;
2124 }
2225 } , [ isAuthenticated , router ] ) ;
2326
27+ // Save scroll position when leaving a page
28+ useEffect ( ( ) => {
29+ const main = mainRef . current ;
30+ if ( ! main ) return ;
31+
32+ const handleScroll = ( ) => {
33+ scrollPositions . current [ pathname ] = main . scrollTop ;
34+ } ;
35+
36+ main . addEventListener ( 'scroll' , handleScroll ) ;
37+ return ( ) => main . removeEventListener ( 'scroll' , handleScroll ) ;
38+ } , [ pathname ] ) ;
39+
40+ // Restore scroll position when arriving at a page
41+ useEffect ( ( ) => {
42+ const main = mainRef . current ;
43+ if ( ! main ) return ;
44+ const saved = scrollPositions . current [ pathname ] ;
45+ main . scrollTop = saved ?? 0 ;
46+ } , [ pathname ] ) ;
47+
2448 if ( ! isAuthenticated ) {
2549 return null ;
2650 }
@@ -31,12 +55,11 @@ export default function DashboardLayout({
3155 < Sidebar />
3256 < div className = "flex-1 flex flex-col overflow-hidden lg:ml-64" >
3357 < Header />
34- < main className = "flex-1 overflow-y-auto p-4 sm:p-6" >
58+ < main ref = { mainRef } className = "flex-1 overflow-y-auto p-4 sm:p-6" >
3559 < ErrorBoundary > { children } </ ErrorBoundary >
3660 </ main >
3761 </ div >
3862 </ div >
3963 </ ErrorBoundary >
4064 ) ;
41- }
42-
65+ }
0 commit comments