@@ -20,26 +20,34 @@ function getRootDepth({ pathname, search }: { pathname: string; search: string }
2020 return null ;
2121}
2222
23+ function getHistoryIndex ( ) : number {
24+ return window . history . state ?. idx ?? 0 ;
25+ }
26+
2327export function NavigationStackProvider ( { children } : { children : ReactNode } ) {
2428 const location = useLocation ( ) ;
2529 const navigationType = useNavigationType ( ) ;
26- const [ depth , setDepth ] = useState ( ( ) => getRootDepth ( location ) ?? 2 ) ;
30+ const initialRootDepth = getRootDepth ( location ) ;
31+ const [ depth , setDepth ] = useState ( ( ) => initialRootDepth ?? Math . min ( 2 , getHistoryIndex ( ) ) ) ;
2732 const lastLocationKey = useRef ( location . key ) ;
28- const isDepthUnknown = useRef ( getRootDepth ( location ) === null ) ;
33+ const minPopDepth = useRef ( initialRootDepth === null ? 2 : 1 ) ;
2934
3035 useEffect ( ( ) => {
3136 if ( lastLocationKey . current === location . key ) return ;
3237 lastLocationKey . current = location . key ;
3338
3439 const rootDepth = getRootDepth ( location ) ;
3540 if ( rootDepth !== null ) {
36- isDepthUnknown . current = false ;
41+ minPopDepth . current = 1 ;
3742 setDepth ( rootDepth ) ;
38- } else if ( navigationType === 'PUSH' ) {
39- setDepth ( ( prev ) => prev + 1 ) ;
43+ return ;
44+ }
45+
46+ const maxDepth = getHistoryIndex ( ) ;
47+ if ( navigationType === 'PUSH' ) {
48+ setDepth ( ( prev ) => Math . min ( maxDepth , prev + 1 ) ) ;
4049 } else if ( navigationType === 'POP' ) {
41- const minDepth = isDepthUnknown . current ? 2 : 1 ;
42- setDepth ( ( prev ) => Math . max ( minDepth , prev - 1 ) ) ;
50+ setDepth ( ( prev ) => Math . min ( maxDepth , Math . max ( minPopDepth . current , prev - 1 ) ) ) ;
4351 }
4452 // oxlint-disable-next-line react-hooks/exhaustive-deps
4553 } , [ location . key , navigationType ] ) ;
0 commit comments