Skip to content

Commit ce33787

Browse files
committed
feat(experimental): export default scroll capture listener setup
1 parent e9f34f6 commit ce33787

4 files changed

Lines changed: 98 additions & 85 deletions

File tree

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

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,9 +97,9 @@ The router _captures_ the position **when you leave the page**, and when the bro
9797

9898
## Capture events
9999

100-
The plugin captures positions after each successful navigation and when the document becomes hidden. It does not listen to `pagehide`.
100+
The plugin captures positions after each successful navigation, on `pagehide`, and when the document becomes hidden.
101101

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.
102+
Use `setupListeners(capture, signal)` to replace the default event listeners. The supplied `capture()` saves all active scroll registrations for the current route. Navigation capture remains enabled.
103103

104104
For example, capture on scroll:
105105

@@ -116,6 +116,22 @@ app.use(ScrollRestoration, {
116116

117117
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: () => {}`.
118118

119+
To keep the default events and add your own, call `SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT`:
120+
121+
```ts
122+
import { SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT } from 'vue-router/experimental'
123+
124+
app.use(ScrollRestoration, {
125+
router,
126+
capture: SCROLL_RESTORATION_CAPTURE_DEFAULT,
127+
restore: SCROLL_RESTORATION_RESTORE_DEFAULT,
128+
setupListeners(capture, signal) {
129+
SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT(capture, signal)
130+
window.addEventListener('save-scroll', capture, { signal })
131+
},
132+
})
133+
```
134+
119135
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.
120136

121137
## Multiple positions

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export {
2222
type UseScrollRestorationOptions,
2323
SCROLL_RESTORATION_CAPTURE_DEFAULT,
2424
SCROLL_RESTORATION_RESTORE_DEFAULT,
25+
SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT,
2526
} from './scroll-restoration'
2627

2728
export { onRouteRendered } from './on-route-rendered'

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

Lines changed: 55 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,13 @@ const Root = defineComponent({
2929
template: '<RouterView />',
3030
})
3131

32+
const ScrollPage = defineComponent({
33+
setup() {
34+
useScrollRestoration()
35+
},
36+
template: '<main>Page</main>',
37+
})
38+
3239
const EmptyPage = defineComponent({ template: '<main />' })
3340
const NeutralPage = defineComponent({ template: '<main>Neutral page</main>' })
3441

@@ -128,49 +135,43 @@ enableAutoUnmount(afterEach)
128135
describe('useScrollRestoration', () => {
129136
mockWarn()
130137

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+
it('captures on pagehide and hidden visibility and stops on unmount', async () => {
138139
const { navigate, setScroll, wrapper } = await mountRouter([
139-
{ path: '/events', component: Page },
140+
{ path: '/events', component: ScrollPage },
140141
])
141142
await navigate('/events')
142143
setScroll(0, 75)
143144

144145
window.dispatchEvent(new Event('pagehide'))
145-
expect(sessionStorage.getItem('vue:scroll:/events')).toBeNull()
146+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
147+
default: { left: 0, top: 75 },
148+
})
149+
setScroll(0, 100)
146150
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible')
147151
document.dispatchEvent(new Event('visibilitychange'))
148-
expect(sessionStorage.getItem('vue:scroll:/events')).toBeNull()
152+
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
153+
default: { left: 0, top: 75 },
154+
})
149155

150156
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
151157
document.dispatchEvent(new Event('visibilitychange'))
152158
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
153-
default: { left: 0, top: 75 },
159+
default: { left: 0, top: 100 },
154160
})
155161

156162
wrapper.unmount()
157-
setScroll(0, 100)
163+
setScroll(0, 150)
158164
document.dispatchEvent(new Event('visibilitychange'))
165+
window.dispatchEvent(new Event('pagehide'))
159166
await navigate('/neutral')
160167
expect(JSON.parse(sessionStorage.getItem('vue:scroll:/events')!)).toEqual({
161-
default: { left: 0, top: 75 },
168+
default: { left: 0, top: 100 },
162169
})
163170
})
164171

165172
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-
})
172173
const { navigate, setScroll, wrapper } = await mountRouter(
173-
[{ path: '/custom', component: Page }],
174+
[{ path: '/custom', component: ScrollPage }],
174175
{
175176
setupListeners(capture, signal) {
176177
window.addEventListener('scroll', capture, { passive: true, signal })
@@ -181,6 +182,7 @@ describe('useScrollRestoration', () => {
181182
setScroll(0, 45)
182183
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
183184
document.dispatchEvent(new Event('visibilitychange'))
185+
window.dispatchEvent(new Event('pagehide'))
184186
expect(sessionStorage.getItem('vue:scroll:/custom')).toBeNull()
185187

186188
window.dispatchEvent(new Event('scroll'))
@@ -198,16 +200,10 @@ describe('useScrollRestoration', () => {
198200

199201
it('allows manual capture of the current route without event listeners', async () => {
200202
let captureNow!: () => void
201-
const Page = defineComponent({
202-
setup() {
203-
useScrollRestoration()
204-
},
205-
template: '<main>Page</main>',
206-
})
207203
const { navigate, setScroll } = await mountRouter(
208204
[
209-
{ path: '/first', component: Page },
210-
{ path: '/second', component: Page },
205+
{ path: '/first', component: ScrollPage },
206+
{ path: '/second', component: ScrollPage },
211207
],
212208
{
213209
setupListeners: capture => {
@@ -964,53 +960,39 @@ describe('useScrollRestoration', () => {
964960
expect(window.scrollY).toBe(10)
965961
})
966962

967-
it('restores the initial navigation when mounted after it', async () => {
968-
const Page = defineComponent({
969-
setup() {
970-
useScrollRestoration({ key: 'initial' })
971-
},
972-
template: '<main>Page</main>',
973-
})
974-
const routes = [{ path: '/initial', component: Page }]
975-
const first = await mountRouter(routes)
976-
await first.navigate('/initial')
977-
first.setScroll(0, 70)
978-
// reload
979-
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
980-
document.dispatchEvent(new Event('visibilitychange'))
981-
first.wrapper.unmount()
982-
vi.restoreAllMocks()
983-
984-
const { wrapper } = await mountRouter(routes, { initialPath: '/initial' })
985-
await flushPromises()
986-
987-
expect(wrapper.text()).toBe('Page')
988-
expect(window.scrollY).toBe(70)
989-
})
990-
991-
it('restores the initial navigation at the root when mounted after it', async () => {
992-
const ScrollRoot = defineComponent({
993-
components: { RouterView },
994-
setup() {
995-
useScrollRestoration()
996-
},
997-
template: '<RouterView />',
998-
})
999-
const routes = [{ path: '/initial', component: EmptyPage }]
1000-
const first = await mountRouter(routes, { root: ScrollRoot })
1001-
await first.navigate('/initial')
1002-
first.setScroll(0, 85)
1003-
// reload
1004-
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
1005-
document.dispatchEvent(new Event('visibilitychange'))
1006-
first.wrapper.unmount()
1007-
vi.restoreAllMocks()
963+
it.each(['page', 'root'] as const)(
964+
'restores the initial navigation with a %s registration',
965+
async registration => {
966+
const ScrollRoot = defineComponent({
967+
components: { RouterView },
968+
setup() {
969+
useScrollRestoration()
970+
},
971+
template: '<RouterView />',
972+
})
973+
const root = registration === 'root' ? ScrollRoot : Root
974+
const component = registration === 'page' ? ScrollPage : NeutralPage
975+
const routes = [{ path: '/initial', component }]
976+
const first = await mountRouter(routes, { root })
977+
await first.navigate('/initial')
978+
first.setScroll(0, 70)
979+
vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('hidden')
980+
document.dispatchEvent(new Event('visibilitychange'))
981+
first.wrapper.unmount()
982+
vi.restoreAllMocks()
1008983

1009-
await mountRouter(routes, { root: ScrollRoot, initialPath: '/initial' })
1010-
await flushPromises()
984+
const { wrapper } = await mountRouter(routes, {
985+
root,
986+
initialPath: '/initial',
987+
})
988+
await flushPromises()
1011989

1012-
expect(window.scrollY).toBe(85)
1013-
})
990+
expect(wrapper.text()).toBe(
991+
registration === 'page' ? 'Page' : 'Neutral page'
992+
)
993+
expect(window.scrollY).toBe(70)
994+
}
995+
)
1014996

1015997
it('removes the saved entry when capture returns null', async () => {
1016998
let shouldCapture = true

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

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,14 @@ export interface ScrollRestorationPluginOptions extends UseScrollRestorationOpti
100100

101101
/**
102102
* Registers additional capture triggers when the plugin is installed.
103-
* Replaces the default listener, which captures when the document is hidden.
103+
* Replaces the default pagehide and hidden visibilitychange listeners.
104104
* Capture after successful navigation is always enabled.
105105
*
106106
* `capture` saves all active registrations for the current route. Use `signal`
107107
* to remove listeners or cancel pending work when the app is unmounted.
108108
* A function that registers no listeners allows manual capture.
109+
*
110+
* @defaultValue {@link SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT}
109111
*/
110112
setupListeners?: (capture: () => void, signal: AbortSignal) => void
111113

@@ -259,6 +261,26 @@ export function SCROLL_RESTORATION_RESTORE_DEFAULT(
259261
window.scrollTo(options)
260262
}
261263

264+
/**
265+
* Captures on pagehide and when the document becomes hidden.
266+
* The signal removes both listeners when the app is unmounted.
267+
*
268+
* @see {@link ScrollRestorationPluginOptions.setupListeners}
269+
*/
270+
export function SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT(
271+
capture: () => void,
272+
signal: AbortSignal
273+
): void {
274+
window.addEventListener('pagehide', capture, { signal })
275+
document.addEventListener(
276+
'visibilitychange',
277+
() => {
278+
if (document.visibilityState === 'hidden') capture()
279+
},
280+
{ signal }
281+
)
282+
}
283+
262284
/**
263285
* @internal
264286
*/
@@ -296,15 +318,7 @@ const SCROLL_RESTORATION_PLUGIN_OPTIONS_DEFAULTS: Required<
296318
// restore: SCROLL_RESTORATION_RESTORE_DEFAULT,
297319
key: to => to.path + to.hash,
298320
manual: false,
299-
setupListeners(capture, signal) {
300-
document.addEventListener(
301-
'visibilitychange',
302-
() => {
303-
if (document.visibilityState === 'hidden') capture()
304-
},
305-
{ signal }
306-
)
307-
},
321+
setupListeners: SCROLL_RESTORATION_SETUP_LISTENERS_DEFAULT,
308322
}
309323

310324
const SCROLL_RESTORATION_OPTIONS_KEY: InjectionKey<

0 commit comments

Comments
 (0)