Skip to content

Commit 78d8cce

Browse files
committed
added scroll preservation opt in to the compare page to avoid input updates resetting it
1 parent 6321dae commit 78d8cce

3 files changed

Lines changed: 66 additions & 0 deletions

File tree

app/pages/compare.vue

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import FacetBarChart from '~/components/Compare/FacetBarChart.vue'
55
66
definePageMeta({
77
name: 'compare',
8+
preserveScrollOnQuery: true,
89
})
910
1011
const { locale } = useI18n()

app/router.options.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,17 @@ export default {
77
if (savedPosition) {
88
return savedPosition
99
}
10+
11+
// Preserve the current viewport for query-only updates on pages that opt in,
12+
// such as compare where controls sync state to the URL in-place.
13+
if (
14+
to.path === _from.path &&
15+
to.hash === _from.hash &&
16+
to.meta.preserveScrollOnQuery === true
17+
) {
18+
return false
19+
}
20+
1021
// If navigating to a hash anchor, scroll to it
1122
if (to.hash) {
1223
const { scrollMargin } = to.meta
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { describe, expect, it } from 'vitest'
2+
import routerOptions from '../../../app/router.options'
3+
4+
function createRoute(overrides: Record<string, unknown> = {}) {
5+
return {
6+
path: '/',
7+
hash: '',
8+
meta: {},
9+
...overrides,
10+
} as any
11+
}
12+
13+
describe('router scrollBehavior', () => {
14+
it('restores saved position when available', () => {
15+
const savedPosition = { left: 12, top: 345 }
16+
17+
expect(routerOptions.scrollBehavior(createRoute(), createRoute(), savedPosition)).toEqual(
18+
savedPosition,
19+
)
20+
})
21+
22+
it('preserves scroll on query-only updates for pages that opt in', () => {
23+
const to = createRoute({
24+
path: '/compare',
25+
meta: { preserveScrollOnQuery: true },
26+
})
27+
const from = createRoute({
28+
path: '/compare',
29+
meta: { preserveScrollOnQuery: true },
30+
})
31+
32+
expect(routerOptions.scrollBehavior(to, from, null)).toBe(false)
33+
})
34+
35+
it('scrolls to hash anchors', () => {
36+
const to = createRoute({
37+
hash: '#section-function',
38+
meta: { scrollMargin: 96 },
39+
})
40+
41+
expect(routerOptions.scrollBehavior(to, createRoute(), null)).toEqual({
42+
el: '#section-function',
43+
behavior: 'smooth',
44+
top: 96,
45+
})
46+
})
47+
48+
it('scrolls to top for regular navigations', () => {
49+
const to = createRoute({ path: '/compare', meta: { preserveScrollOnQuery: true } })
50+
const from = createRoute({ path: '/search' })
51+
52+
expect(routerOptions.scrollBehavior(to, from, null)).toEqual({ left: 0, top: 0 })
53+
})
54+
})

0 commit comments

Comments
 (0)