Skip to content

Commit baa5f6f

Browse files
committed
fix(scroll): save scroll positions in sessionStorage instead of history.state
1 parent e407f0d commit baa5f6f

8 files changed

Lines changed: 130 additions & 142 deletions

File tree

‎packages/router/__tests__/router.spec.ts‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ describe('Router', () => {
153153
vi.spyOn(history, 'replace')
154154
await router.replace('/foo')
155155
expect(history.replace).toHaveBeenCalledTimes(1)
156-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
156+
expect(history.location).toBe('/foo')
157157
})
158158

159159
it('parses query and hash with router.replace', async () => {
@@ -162,10 +162,7 @@ describe('Router', () => {
162162
vi.spyOn(history, 'replace')
163163
await router.replace('/foo?q=2#a')
164164
expect(history.replace).toHaveBeenCalledTimes(1)
165-
expect(history.replace).toHaveBeenCalledWith(
166-
'/foo?q=2#a',
167-
expect.anything()
168-
)
165+
expect(history.location).toBe('/foo?q=2#a')
169166
})
170167

171168
it('replaces if a guard redirects', async () => {
@@ -182,7 +179,7 @@ describe('Router', () => {
182179
await router.replace('/home-before')
183180
expect(history.push).toHaveBeenCalledTimes(0)
184181
expect(history.replace).toHaveBeenCalledTimes(1)
185-
expect(history.replace).toHaveBeenCalledWith('/', expect.anything())
182+
expect(history.location).toBe('/')
186183
})
187184

188185
it('replaces if a guard redirect replaces', async () => {
@@ -201,7 +198,6 @@ describe('Router', () => {
201198
expect(history.location).toBe('/foo')
202199
expect(history.push).toHaveBeenCalledTimes(0)
203200
expect(history.replace).toHaveBeenCalledTimes(1)
204-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
205201
})
206202

207203
it('allows to customize parseQuery', async () => {
@@ -293,23 +289,23 @@ describe('Router', () => {
293289
vi.spyOn(history, 'replace')
294290
await router.push({ path: '/foo', replace: true })
295291
expect(history.replace).toHaveBeenCalledTimes(1)
296-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
292+
expect(history.location).toBe('/foo')
297293
})
298294

299295
it('can replaces current location with a string location', async () => {
300296
const { router, history } = await newRouter()
301297
vi.spyOn(history, 'replace')
302298
await router.replace('/foo')
303299
expect(history.replace).toHaveBeenCalledTimes(1)
304-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
300+
expect(history.location).toBe('/foo')
305301
})
306302

307303
it('can replaces current location with an object location', async () => {
308304
const { router, history } = await newRouter()
309305
vi.spyOn(history, 'replace')
310306
await router.replace({ path: '/foo' })
311307
expect(history.replace).toHaveBeenCalledTimes(1)
312-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
308+
expect(history.location).toBe('/foo')
313309
})
314310

315311
it('navigates if the location does not exist', async () => {

‎packages/router/__tests__/scroll-history.spec.ts‎

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import {
1212
normalizeRouteRecord,
1313
} from '../src/experimental'
1414
import { nextNavigation } from './utils'
15-
import { scrollPositions } from '../src/scrollBehavior'
1615

1716
const routes = ['/', '/b', '/c'].map(path => ({ path, component: {} }))
1817
const resolver = createFixedResolver(
@@ -45,7 +44,7 @@ describe.each([
4544
let top = 0
4645

4746
beforeEach(() => {
48-
scrollPositions.clear()
47+
sessionStorage.clear()
4948
window.history.replaceState(null, '', '/')
5049
top = 0
5150
vi.spyOn(window, 'scrollX', 'get').mockReturnValue(0)
@@ -59,7 +58,7 @@ describe.each([
5958

6059
afterEach(() => {
6160
history?.destroy()
62-
scrollPositions.clear()
61+
sessionStorage.clear()
6362
vi.restoreAllMocks()
6463
})
6564

@@ -69,7 +68,8 @@ describe.each([
6968
(_to, _from, saved) => saved || { left: 0, top: 0 }
7069
)
7170
const router = create(history, scrollBehavior)
72-
await router.push('/')
71+
// the current url, to support reloads
72+
await router.push(history.location)
7373
await nextTick()
7474

7575
async function push(path: string) {
@@ -87,6 +87,47 @@ describe.each([
8787
return { router, scrollBehavior, push, go }
8888
}
8989

90+
it('restores the position saved on pagehide after a reload', async () => {
91+
const { push } = await setup()
92+
await push('/b')
93+
top = 1000
94+
const stateBefore = window.history.state
95+
const replaceState = vi.spyOn(window.history, 'replaceState')
96+
window.dispatchEvent(new Event('pagehide'))
97+
// replaceState() during pagehide can break the bfcache
98+
expect(replaceState).not.toHaveBeenCalled()
99+
expect(window.history.state).toEqual(stateBefore)
100+
replaceState.mockRestore()
101+
102+
// reload: a new document keeps history.state and sessionStorage
103+
history.destroy()
104+
top = 0
105+
const { scrollBehavior } = await setup()
106+
107+
expect(scrollBehavior.mock.lastCall?.[2]).toEqual({ left: 0, top: 1000 })
108+
expect(top).toBe(1000)
109+
})
110+
111+
it('restores the position saved on push in a new document', async () => {
112+
const { push } = await setup()
113+
await push('/b')
114+
top = 1000
115+
await push('/c')
116+
117+
// a new document at the /b entry, e.g. after leaving the app
118+
history.destroy()
119+
const popped = new Promise(resolve =>
120+
window.addEventListener('popstate', resolve, { once: true })
121+
)
122+
window.history.back()
123+
await popped
124+
top = 0
125+
const { scrollBehavior } = await setup()
126+
127+
expect(scrollBehavior.mock.lastCall?.[2]).toEqual({ left: 0, top: 1000 })
128+
expect(top).toBe(1000)
129+
})
130+
90131
it('restores the new entry after replacing the forward branch', async () => {
91132
const { scrollBehavior, push, go } = await setup()
92133
await push('/b')
@@ -97,7 +138,6 @@ describe.each([
97138
await push('/')
98139
await go(-1)
99140

100-
expect(window.history.state.scroll.top).toBe(2000)
101141
expect(scrollBehavior.mock.lastCall?.[2]).toEqual({ left: 0, top: 2000 })
102142
expect(top).toBe(2000)
103143
})
@@ -138,7 +178,6 @@ describe.each([
138178
if (operation === 'push') await go(-1)
139179
await go(-1)
140180

141-
expect(window.history.state.scroll.top).toBe(1000)
142181
expect(scrollBehavior.mock.lastCall?.[2]).toEqual({
143182
left: 0,
144183
top: 2000,
@@ -179,7 +218,6 @@ describe.each([
179218
await push('/c')
180219
await go(-1)
181220

182-
expect(window.history.state.scroll.top).toBe(2000)
183221
expect(scrollBehavior.mock.lastCall?.[2]).toEqual({ left: 0, top: 2000 })
184222
expect(top).toBe(2000)
185223
})

‎packages/router/e2e/specs/scroll-behavior.spec.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,6 @@ test.describe('scroll-behavior', () => {
6060
await navigate(page, -1)
6161

6262
await expect.poll(() => scrollY(page)).toBe(2000)
63-
expect(await page.evaluate(() => window.history.state.scroll.top)).toBe(
64-
2000
65-
)
6663
})
6764

6865
test('discards other URLs from a removed forward branch', async ({

‎packages/router/src/experimental/router.spec.ts‎

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -356,7 +356,7 @@ describe('Experimental Router', () => {
356356
vi.spyOn(history, 'replace')
357357
await router.replace('/foo')
358358
expect(history.replace).toHaveBeenCalledTimes(1)
359-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
359+
expect(history.location).toBe('/foo')
360360
})
361361

362362
it('parses query and hash with router.replace', async () => {
@@ -365,10 +365,7 @@ describe('Experimental Router', () => {
365365
vi.spyOn(history, 'replace')
366366
await router.replace('/foo?q=2#a')
367367
expect(history.replace).toHaveBeenCalledTimes(1)
368-
expect(history.replace).toHaveBeenCalledWith(
369-
'/foo?q=2#a',
370-
expect.anything()
371-
)
368+
expect(history.location).toBe('/foo?q=2#a')
372369
})
373370

374371
it('replaces if a guard redirects', async () => {
@@ -385,7 +382,7 @@ describe('Experimental Router', () => {
385382
await router.replace('/home-before')
386383
expect(history.push).toHaveBeenCalledTimes(0)
387384
expect(history.replace).toHaveBeenCalledTimes(1)
388-
expect(history.replace).toHaveBeenCalledWith('/', expect.anything())
385+
expect(history.location).toBe('/')
389386
})
390387

391388
it('replaces if a guard redirect replaces', async () => {
@@ -404,7 +401,6 @@ describe('Experimental Router', () => {
404401
expect(history.location).toBe('/foo')
405402
expect(history.push).toHaveBeenCalledTimes(0)
406403
expect(history.replace).toHaveBeenCalledTimes(1)
407-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
408404
})
409405

410406
it.skip('allows to customize parseQuery', async () => {})
@@ -496,23 +492,23 @@ describe('Experimental Router', () => {
496492
vi.spyOn(history, 'replace')
497493
await router.push({ path: '/foo', replace: true })
498494
expect(history.replace).toHaveBeenCalledTimes(1)
499-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
495+
expect(history.location).toBe('/foo')
500496
})
501497

502498
it('can replaces current location with a string location', async () => {
503499
const { router, history } = await newRouter()
504500
vi.spyOn(history, 'replace')
505501
await router.replace('/foo')
506502
expect(history.replace).toHaveBeenCalledTimes(1)
507-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
503+
expect(history.location).toBe('/foo')
508504
})
509505

510506
it('can replaces current location with an object location', async () => {
511507
const { router, history } = await newRouter()
512508
vi.spyOn(history, 'replace')
513509
await router.replace({ path: '/foo' })
514510
expect(history.replace).toHaveBeenCalledTimes(1)
515-
expect(history.replace).toHaveBeenCalledWith('/foo', expect.anything())
511+
expect(history.location).toBe('/foo')
516512
})
517513

518514
it('navigates if the location does not exist', async () => {

‎packages/router/src/experimental/router.ts‎

Lines changed: 12 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -854,17 +854,9 @@ export function experimental_createRouter(
854854
from,
855855
}
856856
)
857-
// trigger scroll to allow scrolling to the same anchor
858-
handleScroll(
859-
from,
860-
from,
861-
// this is a push, the only way for it to be triggered from a
862-
// history.listen is with a redirect, which makes it become a push
863-
true,
864-
// This cannot be the first navigation because the initial location
865-
// cannot be manually navigated to
866-
false
867-
)
857+
// trigger scroll to allow scrolling to the same anchor, without a
858+
// saved position since it's a push
859+
handleScroll(from, from)
868860
}
869861

870862
return (failure ? Promise.resolve(failure) : navigate(toLocation, from))
@@ -1119,29 +1111,23 @@ export function experimental_createRouter(
11191111

11201112
// only consider as push if it's not the first navigation
11211113
const isFirstNavigation = from === START_LOCATION_NORMALIZED
1122-
const state: Partial<HistoryState> | null = !isBrowser ? {} : history.state
1114+
1115+
// read before the url change invalidates it
1116+
const savedPosition =
1117+
(isFirstNavigation || !isPush) &&
1118+
getSavedScrollPosition(toLocation.fullPath)
11231119

11241120
// change URL only if the user did a push/replace and if it's not the initial navigation because
11251121
// it's just reflecting the url
11261122
if (isPush) {
1127-
// on the initial navigation, we want to reuse the scroll position from
1128-
// history state if it exists
11291123
if (replace || isFirstNavigation)
1130-
routerHistory.replace(
1131-
toLocation.fullPath,
1132-
assign(
1133-
{
1134-
scroll: isFirstNavigation && state && state.scroll,
1135-
},
1136-
data
1137-
)
1138-
)
1124+
routerHistory.replace(toLocation.fullPath, data)
11391125
else routerHistory.push(toLocation.fullPath, data)
11401126
}
11411127

11421128
// accept current navigation
11431129
currentRoute.value = toLocation
1144-
handleScroll(toLocation, from, isPush, isFirstNavigation)
1130+
handleScroll(toLocation, from, savedPosition)
11451131

11461132
markAsReady()
11471133
}
@@ -1362,23 +1348,15 @@ export function experimental_createRouter(
13621348
function handleScroll(
13631349
to: RouteLocationNormalizedLoaded,
13641350
from: RouteLocationNormalizedLoaded,
1365-
isPush: boolean,
1366-
isFirstNavigation: boolean
1351+
savedPosition?: _ScrollPositionNormalized | null | false
13671352
): // the return is not meant to be used
13681353
Promise<unknown> {
13691354
const { scrollBehavior } = options
13701355
if (!isBrowser || !scrollBehavior) return Promise.resolve()
13711356

1372-
const scrollPosition: _ScrollPositionNormalized | null =
1373-
(!isPush && getSavedScrollPosition(getScrollKey(to.fullPath, 0))) ||
1374-
((isFirstNavigation || !isPush) &&
1375-
(history.state as HistoryState) &&
1376-
history.state.scroll) ||
1377-
null
1378-
13791357
return (
13801358
nextTick()
1381-
.then(() => scrollBehavior(to, from, scrollPosition))
1359+
.then(() => scrollBehavior(to, from, savedPosition || null))
13821360
// avoid scrollBehavior on old navigations
13831361
.then(
13841362
position =>

0 commit comments

Comments
 (0)