@@ -74,11 +74,7 @@ export function createRouter(
74
74
href = url . pathname + url . search + url . hash
75
75
}
76
76
}
77
- if ( inBrowser && href !== location . href ) {
78
- // save scroll position before changing url
79
- history . replaceState ( { scrollPosition : window . scrollY } , document . title )
80
- history . pushState ( null , '' , href )
81
- }
77
+ updateHistory ( href )
82
78
await loadPage ( href )
83
79
await router . onAfterRouteChanged ?.( href )
84
80
}
@@ -211,15 +207,18 @@ export function createRouter(
211
207
search === currentUrl . search
212
208
) {
213
209
// scroll between hash anchors in the same page
210
+ // avoid duplicate history entries when the hash is same
211
+ if ( hash !== currentUrl . hash ) {
212
+ history . pushState ( null , '' , hash )
213
+ // still emit the event so we can listen to it in themes
214
+ window . dispatchEvent ( new Event ( 'hashchange' ) )
215
+ }
214
216
if ( hash ) {
215
- // avoid duplicate history entries when the hash is same
216
- if ( hash !== currentUrl . hash ) {
217
- history . pushState ( null , '' , hash )
218
- // still emit the event so we can listen to it in themes
219
- window . dispatchEvent ( new Event ( 'hashchange' ) )
220
- }
221
217
// use smooth scroll when clicking on header anchor links
222
218
scrollTo ( link , hash , link . classList . contains ( 'header-anchor' ) )
219
+ } else {
220
+ updateHistory ( href )
221
+ window . scrollTo ( 0 , 0 )
223
222
}
224
223
} else {
225
224
go ( href )
@@ -292,20 +291,11 @@ export function scrollTo(el: Element, hash: string, smooth = false) {
292
291
target . getBoundingClientRect ( ) . top -
293
292
offset +
294
293
targetPadding
295
- // only smooth scroll if distance is smaller than screen height.
296
294
function scrollToTarget ( ) {
297
- if (
298
- ! smooth ||
299
- Math . abs ( targetTop - window . scrollY ) > window . innerHeight
300
- ) {
295
+ // only smooth scroll if distance is smaller than screen height.
296
+ if ( ! smooth || Math . abs ( targetTop - window . scrollY ) > window . innerHeight )
301
297
window . scrollTo ( 0 , targetTop )
302
- } else {
303
- window . scrollTo ( {
304
- left : 0 ,
305
- top : targetTop ,
306
- behavior : 'smooth'
307
- } )
308
- }
298
+ else window . scrollTo ( { left : 0 , top : targetTop , behavior : 'smooth' } )
309
299
}
310
300
requestAnimationFrame ( scrollToTarget )
311
301
}
@@ -338,3 +328,11 @@ function shouldHotReload(payload: PageDataPayload): boolean {
338
328
. slice ( siteDataRef . value . base . length - 1 )
339
329
return payloadPath === locationPath
340
330
}
331
+
332
+ function updateHistory ( href : string ) {
333
+ if ( inBrowser && href !== location . href ) {
334
+ // save scroll position before changing url
335
+ history . replaceState ( { scrollPosition : window . scrollY } , document . title )
336
+ history . pushState ( null , '' , href )
337
+ }
338
+ }
0 commit comments