@@ -182,6 +182,31 @@ export function useActive(
182182 setTargets ( ) ;
183183 }
184184
185+ function getHashId ( ) {
186+ return targets . elements . find ( ( { id } ) => id === location . hash . slice ( 1 ) ) ?. id ;
187+ }
188+
189+ function onHashChange ( event : HashChangeEvent ) {
190+ if ( matchMedia . value ) {
191+ if ( ! event . newURL . includes ( '#' ) && activeId . value ) {
192+ const prevY = getSentinel ( ) ;
193+
194+ requestAnimationFrame ( ( ) => {
195+ // If scrolled on its own reset activeId, if not keep current
196+ const newY = getSentinel ( ) ;
197+ if ( prevY !== newY ) {
198+ return ( activeId . value = jumpToFirst ? ids . value [ 0 ] : '' ) ;
199+ }
200+ } ) ;
201+ }
202+
203+ const hashId = getHashId ( ) ;
204+ if ( hashId ) {
205+ activeId . value = hashId ;
206+ }
207+ }
208+ }
209+
185210 // Lifecycle
186211
187212 onMounted ( async ( ) => {
@@ -195,9 +220,10 @@ export function useActive(
195220 setTargets ( ) ;
196221
197222 window . addEventListener ( 'resize' , onResize , { passive : true } ) ;
223+ window . addEventListener ( 'hashchange' , onHashChange ) ;
198224
199225 if ( matchMedia . value ) {
200- const hashId = targets . elements . find ( ( { id } ) => id === location . hash . slice ( 1 ) ) ?. id ;
226+ const hashId = getHashId ( ) ;
201227 if ( hashId ) {
202228 return ( activeId . value = hashId ) ;
203229 }
@@ -210,6 +236,7 @@ export function useActive(
210236
211237 onBeforeUnmount ( ( ) => {
212238 window . removeEventListener ( 'resize' , onResize ) ;
239+ window . removeEventListener ( 'hashchange' , onHashChange ) ;
213240 } ) ;
214241
215242 // Watchers
@@ -219,7 +246,7 @@ export function useActive(
219246 } ) ;
220247
221248 watch ( activeId , ( newId ) => {
222- if ( replaceHash ) {
249+ if ( ! replaceHash ) {
223250 const start = jumpToFirst ? 0 : - 1 ;
224251 const newHash = `${ location . pathname } ${ activeIndex . value > start ? `#${ newId } ` : '' } ` ;
225252 history . replaceState ( history . state , '' , newHash ) ;
0 commit comments