Skip to content

Commit 062fa6d

Browse files
committed
feat(experimental): customize scroll restoration capture listeners
1 parent 35cf5e3 commit 062fa6d

4 files changed

Lines changed: 159 additions & 17 deletions

File tree

‎packages/docs/experimental/scroll-restoration.md‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,30 @@ useScrollRestoration()
9393
</script>
9494
```
9595

96-
The router _captures_ the position **when you leave the page**, and when the browser tab is hidden or closed. It _restores_ the position after a navigation, when the page is rendered. It uses `onRouteRendered()` under the hood.
96+
The router _captures_ the position **when you leave the page**, and when the browser tab becomes hidden. It _restores_ the position after a navigation, when the page is rendered. It uses `onRouteRendered()` under the hood.
97+
98+
## Capture events
99+
100+
The plugin captures positions after each successful navigation and when the document becomes hidden. It does not listen to `pagehide`.
101+
102+
Use `setupListeners(capture, signal)` to replace the default `visibilitychange` listener. The supplied `capture()` saves all active scroll registrations for the current route. Navigation capture remains enabled.
103+
104+
For example, capture on scroll:
105+
106+
```ts
107+
app.use(ScrollRestoration, {
108+
router,
109+
capture: SCROLL_RESTORATION_CAPTURE_DEFAULT,
110+
restore: SCROLL_RESTORATION_RESTORE_DEFAULT,
111+
setupListeners(capture, signal) {
112+
window.addEventListener('scroll', capture, { passive: true, signal })
113+
},
114+
})
115+
```
116+
117+
Pass `signal` to your listeners so they are removed when the app is unmounted. You can listen to your own event instead, or save the supplied `capture` function and call it manually. To disable additional capture events, use `setupListeners: () => {}`.
118+
119+
A [`scroll` event cannot be canceled](https://developer.chrome.com/blog/passive-event-listeners), so `passive: true` does not improve scroll performance. Each capture calls all active capture functions and writes to `sessionStorage` synchronously. For frequent events, throttle captures and use the signal to cancel pending work on unmount.
97120

98121
## Multiple positions
99122

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ test.describe('scroll-restoration', () => {
5555
await expect.poll(() => scrollY(page)).toBe(600)
5656
})
5757

58-
test('captures on pagehide and restores after reload', async ({ page }) => {
58+
test('captures when hidden and restores after reload', async ({ page }) => {
5959
await page.goto('/scroll-restoration/automatic-a')
6060
await expect(page.locator('.automatic-a')).toBeVisible()
6161
await page.evaluate(() => window.scrollTo(0, 720))

‎packages/router/src/experimental/scroll-restoration.spec.ts‎

Lines changed: 111 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ async function mountRouter(
7171
attachTo,
7272
storageKeyPrefix,
7373
initialPath,
74+
setupListeners,
7475
capture = SCROLL_RESTORATION_CAPTURE_DEFAULT,
7576
restore = SCROLL_RESTORATION_RESTORE_DEFAULT,
7677
}: MountRouterOptions = {}
@@ -101,6 +102,7 @@ async function mountRouter(
101102
...(storageKeyPrefix && { storageKeyPrefix }),
102103
capture,
103104
restore,
105+
...(setupListeners && { setupListeners }),
104106
},
105107
],
106108
router,
@@ -126,6 +128,111 @@ enableAutoUnmount(afterEach)
126128
describe('useScrollRestoration', () => {
127129
mockWarn()
128130

131+
it('captures only when the document becomes hidden by default', async () => {
132+
const Page = defineComponent({
133+
setup() {
134+
useScrollRestoration()
135+
},
136+
template: '<main>Page</main>',
137+
})
138+
const { navigate, setScroll, wrapper } = await mountRouter([
139+
{ path: '/events', component: Page },
140+
])
141+
await navigate('/events')
142+
setScroll(0, 75)
143+
144+
window.dispatchEvent(new Event('pagehide'))
145+
expect(sessionStorage.getItem('vue:scroll:/events')).toBeNull()
146+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
147+
document.dispatchEvent(new Event('visibilitychange'))
148+
expect(sessionStorage.getItem('vue:scroll:/events')).toBeNull()
149+
150+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
151+
document.dispatchEvent(new Event('visibilitychange'))
152+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
153+
default: { left: 0, top: 75 },
154+
})
155+
156+
wrapper.unmount()
157+
setScroll(0, 100)
158+
document.dispatchEvent(new Event('visibilitychange'))
159+
await navigate('/neutral')
160+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
161+
default: { left: 0, top: 75 },
162+
})
163+
})
164+
165+
it('replaces default listeners and stops custom listeners on unmount', async () => {
166+
const Page = defineComponent({
167+
setup() {
168+
useScrollRestoration()
169+
},
170+
template: '<main>Page</main>',
171+
})
172+
const { navigate, setScroll, wrapper } = await mountRouter(
173+
[{ path: '/custom', component: Page }],
174+
{
175+
setupListeners(capture, signal) {
176+
window.addEventListener('scroll', capture, { passive: true, signal })
177+
},
178+
}
179+
)
180+
await navigate('/custom')
181+
setScroll(0, 45)
182+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
183+
document.dispatchEvent(new Event('visibilitychange'))
184+
expect(sessionStorage.getItem('vue:scroll:/custom')).toBeNull()
185+
186+
window.dispatchEvent(new Event('scroll'))
187+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/custom')!)).toEqual({
188+
default: { left: 0, top: 45 },
189+
})
190+
191+
wrapper.unmount()
192+
setScroll(0, 90)
193+
window.dispatchEvent(new Event('scroll'))
194+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/custom')!)).toEqual({
195+
default: { left: 0, top: 45 },
196+
})
197+
})
198+
199+
it('allows manual capture of the current route without event listeners', async () => {
200+
let captureNow!: () => void
201+
const Page = defineComponent({
202+
setup() {
203+
useScrollRestoration()
204+
},
205+
template: '<main>Page</main>',
206+
})
207+
const { navigate, setScroll } = await mountRouter(
208+
[
209+
{ path: '/first', component: Page },
210+
{ path: '/second', component: Page },
211+
],
212+
{
213+
setupListeners: capture => {
214+
captureNow = capture
215+
},
216+
}
217+
)
218+
await navigate('/first')
219+
setScroll(0, 30)
220+
captureNow()
221+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/first')!)).toEqual({
222+
default: { left: 0, top: 30 },
223+
})
224+
setScroll(0, 60)
225+
await navigate('/second')
226+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/first')!)).toEqual({
227+
default: { left: 0, top: 60 },
228+
})
229+
setScroll(0, 90)
230+
captureNow()
231+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/second')!)).toEqual({
232+
default: { left: 0, top: 90 },
233+
})
234+
})
235+
129236
it('preserves the saved root position on initial navigation', async () => {
130237
const savedPosition = JSON.stringify({ default: { left: 0, top: 123 } })
131238
sessionStorage.setItem('vue:scroll:/', savedPosition)
@@ -869,7 +976,8 @@ describe('useScrollRestoration', () => {
869976
await first.navigate('/initial')
870977
first.setScroll(0, 70)
871978
// reload
872-
window.dispatchEvent(new Event('pagehide'))
979+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
980+
document.dispatchEvent(new Event('visibilitychange'))
873981
first.wrapper.unmount()
874982
vi.restoreAllMocks()
875983

@@ -893,7 +1001,8 @@ describe('useScrollRestoration', () => {
8931001
await first.navigate('/initial')
8941002
first.setScroll(0, 85)
8951003
// reload
896-
window.dispatchEvent(new Event('pagehide'))
1004+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
1005+
document.dispatchEvent(new Event('visibilitychange'))
8971006
first.wrapper.unmount()
8981007
vi.restoreAllMocks()
8991008

‎packages/router/src/experimental/scroll-restoration.ts‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,17 @@ export interface ScrollRestorationPluginOptions extends UseScrollRestorationOpti
9898
*/
9999
storageKeyPrefix?: string
100100

101+
/**
102+
* Registers additional capture triggers when the plugin is installed.
103+
* Replaces the default listener, which captures when the document is hidden.
104+
* Capture after successful navigation is always enabled.
105+
*
106+
* `capture` saves all active registrations for the current route. Use `signal`
107+
* to remove listeners or cancel pending work when the app is unmounted.
108+
* A function that registers no listeners allows manual capture.
109+
*/
110+
setupListeners?: (capture: () => void, signal: AbortSignal) => void
111+
101112
capture: NonNullable<UseScrollRestorationOptions['capture']>
102113
restore: NonNullable<UseScrollRestorationOptions['restore']>
103114
}
@@ -285,6 +296,15 @@ const SCROLL_RESTORATION_PLUGIN_OPTIONS_DEFAULTS: Required<
285296
// restore: SCROLL_RESTORATION_RESTORE_DEFAULT,
286297
key: to => to.path + to.hash,
287298
manual: false,
299+
setupListeners(capture, signal) {
300+
document.addEventListener(
301+
'visibilitychange',
302+
() => {
303+
if (document.visibilityState === 'hidden') capture()
304+
},
305+
{ signal }
306+
)
307+
},
288308
}
289309

290310
const SCROLL_RESTORATION_OPTIONS_KEY: InjectionKey<
@@ -413,19 +433,9 @@ function ScrollRestorationClient(
413433
if (!failure && from !== START_LOCATION_NORMALIZED) capture(from)
414434
})
415435
const listenersController = new AbortController()
416-
const captureOnPageHide = () => capture(router.currentRoute.value)
417-
// a hidden page can be killed without pagehide
418-
window.addEventListener('pagehide', captureOnPageHide, {
419-
signal: listenersController.signal,
420-
})
421-
document.addEventListener(
422-
'visibilitychange',
423-
() => {
424-
if (document.visibilityState === 'hidden') captureOnPageHide()
425-
},
426-
{
427-
signal: listenersController.signal,
428-
}
436+
optionsWithDefaults.setupListeners(
437+
() => capture(router.currentRoute.value),
438+
listenersController.signal
429439
)
430440

431441
app.onUnmount(() => {

0 commit comments

Comments
 (0)