Skip to content

Commit efcc684

Browse files
fix: Fix hash scrolling with resetScroll={false}
1 parent e2896b5 commit efcc684

12 files changed

Lines changed: 348 additions & 95 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/router-core': patch
3+
---
4+
5+
Fix hash scrolling with `resetScroll={false}`

‎e2e/react-start/scroll-restoration/src/routeTree.gen.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
1212
import { Route as IndexRouteImport } from './routes/index'
1313
import { Route as testsWithSearchRouteImport } from './routes/(tests)/with-search'
1414
import { Route as testsWithLoaderRouteImport } from './routes/(tests)/with-loader'
15+
import { Route as testsSsrScrollKeyRouteImport } from './routes/(tests)/ssr-scroll-key'
1516
import { Route as testsResetScrollFalseCRouteImport } from './routes/(tests)/reset-scroll-false-c'
1617
import { Route as testsResetScrollFalseBRouteImport } from './routes/(tests)/reset-scroll-false-b'
1718
import { Route as testsResetScrollFalseARouteImport } from './routes/(tests)/reset-scroll-false-a'
@@ -38,6 +39,11 @@ const testsWithLoaderRoute = testsWithLoaderRouteImport.update({
3839
path: '/with-loader',
3940
getParentRoute: () => rootRouteImport,
4041
} as any)
42+
const testsSsrScrollKeyRoute = testsSsrScrollKeyRouteImport.update({
43+
id: '/(tests)/ssr-scroll-key',
44+
path: '/ssr-scroll-key',
45+
getParentRoute: () => rootRouteImport,
46+
} as any)
4147
const testsResetScrollFalseCRoute = testsResetScrollFalseCRouteImport.update({
4248
id: '/(tests)/reset-scroll-false-c',
4349
path: '/reset-scroll-false-c',
@@ -103,6 +109,7 @@ export interface FileRoutesByFullPath {
103109
'/reset-scroll-false-a': typeof testsResetScrollFalseARoute
104110
'/reset-scroll-false-b': typeof testsResetScrollFalseBRoute
105111
'/reset-scroll-false-c': typeof testsResetScrollFalseCRoute
112+
'/ssr-scroll-key': typeof testsSsrScrollKeyRoute
106113
'/with-loader': typeof testsWithLoaderRoute
107114
'/with-search': typeof testsWithSearchRoute
108115
}
@@ -118,6 +125,7 @@ export interface FileRoutesByTo {
118125
'/reset-scroll-false-a': typeof testsResetScrollFalseARoute
119126
'/reset-scroll-false-b': typeof testsResetScrollFalseBRoute
120127
'/reset-scroll-false-c': typeof testsResetScrollFalseCRoute
128+
'/ssr-scroll-key': typeof testsSsrScrollKeyRoute
121129
'/with-loader': typeof testsWithLoaderRoute
122130
'/with-search': typeof testsWithSearchRoute
123131
}
@@ -134,6 +142,7 @@ export interface FileRoutesById {
134142
'/(tests)/reset-scroll-false-a': typeof testsResetScrollFalseARoute
135143
'/(tests)/reset-scroll-false-b': typeof testsResetScrollFalseBRoute
136144
'/(tests)/reset-scroll-false-c': typeof testsResetScrollFalseCRoute
145+
'/(tests)/ssr-scroll-key': typeof testsSsrScrollKeyRoute
137146
'/(tests)/with-loader': typeof testsWithLoaderRoute
138147
'/(tests)/with-search': typeof testsWithSearchRoute
139148
}
@@ -151,6 +160,7 @@ export interface FileRouteTypes {
151160
| '/reset-scroll-false-a'
152161
| '/reset-scroll-false-b'
153162
| '/reset-scroll-false-c'
163+
| '/ssr-scroll-key'
154164
| '/with-loader'
155165
| '/with-search'
156166
fileRoutesByTo: FileRoutesByTo
@@ -166,6 +176,7 @@ export interface FileRouteTypes {
166176
| '/reset-scroll-false-a'
167177
| '/reset-scroll-false-b'
168178
| '/reset-scroll-false-c'
179+
| '/ssr-scroll-key'
169180
| '/with-loader'
170181
| '/with-search'
171182
id:
@@ -181,6 +192,7 @@ export interface FileRouteTypes {
181192
| '/(tests)/reset-scroll-false-a'
182193
| '/(tests)/reset-scroll-false-b'
183194
| '/(tests)/reset-scroll-false-c'
195+
| '/(tests)/ssr-scroll-key'
184196
| '/(tests)/with-loader'
185197
| '/(tests)/with-search'
186198
fileRoutesById: FileRoutesById
@@ -197,6 +209,7 @@ export interface RootRouteChildren {
197209
testsResetScrollFalseARoute: typeof testsResetScrollFalseARoute
198210
testsResetScrollFalseBRoute: typeof testsResetScrollFalseBRoute
199211
testsResetScrollFalseCRoute: typeof testsResetScrollFalseCRoute
212+
testsSsrScrollKeyRoute: typeof testsSsrScrollKeyRoute
200213
testsWithLoaderRoute: typeof testsWithLoaderRoute
201214
testsWithSearchRoute: typeof testsWithSearchRoute
202215
}
@@ -224,6 +237,13 @@ declare module '@tanstack/react-router' {
224237
preLoaderRoute: typeof testsWithLoaderRouteImport
225238
parentRoute: typeof rootRouteImport
226239
}
240+
'/(tests)/ssr-scroll-key': {
241+
id: '/(tests)/ssr-scroll-key'
242+
path: '/ssr-scroll-key'
243+
fullPath: '/ssr-scroll-key'
244+
preLoaderRoute: typeof testsSsrScrollKeyRouteImport
245+
parentRoute: typeof rootRouteImport
246+
}
227247
'/(tests)/reset-scroll-false-c': {
228248
id: '/(tests)/reset-scroll-false-c'
229249
path: '/reset-scroll-false-c'
@@ -309,6 +329,7 @@ const rootRouteChildren: RootRouteChildren = {
309329
testsResetScrollFalseARoute: testsResetScrollFalseARoute,
310330
testsResetScrollFalseBRoute: testsResetScrollFalseBRoute,
311331
testsResetScrollFalseCRoute: testsResetScrollFalseCRoute,
332+
testsSsrScrollKeyRoute: testsSsrScrollKeyRoute,
312333
testsWithLoaderRoute: testsWithLoaderRoute,
313334
testsWithSearchRoute: testsWithSearchRoute,
314335
}

‎e2e/react-start/scroll-restoration/src/router.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ export function getRouter() {
99
scrollRestoration: true,
1010
scrollToTopSelectors: ['[data-scroll-restoration-id="carry-over-reset"]'],
1111
getScrollRestorationKey: (location) => {
12+
if (location.pathname === '/ssr-scroll-key') {
13+
return 'ssr-scroll-key'
14+
}
15+
1216
if (location.pathname === '/hash-scroll-repro') {
1317
return location.pathname
1418
}

‎e2e/react-start/scroll-restoration/src/routes/(tests)/hash-scroll-repro.tsx‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,15 @@ function Component() {
5252
>
5353
#one
5454
</Link>
55+
<Link
56+
to="/hash-scroll-repro"
57+
hash="four"
58+
className="rounded border px-3 py-2"
59+
data-testid="hash-scroll-section-four-no-reset-link"
60+
resetScroll={false}
61+
>
62+
#four no reset
63+
</Link>
5564
</div>
5665
</div>
5766

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { createFileRoute } from '@tanstack/react-router'
2+
import * as React from 'react'
3+
import { ScrollBlock } from '../-components/scroll-block'
4+
5+
export const Route = createFileRoute('/(tests)/ssr-scroll-key')({
6+
component: Component,
7+
})
8+
9+
function Component() {
10+
return (
11+
<div className="p-2">
12+
<h3>ssr-scroll-key</h3>
13+
<ScrollBlock />
14+
</div>
15+
)
16+
}

‎e2e/react-start/scroll-restoration/tests/app.spec.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,46 @@ test('Smoke - Renders home', async ({ page }) => {
88
).toBeVisible()
99
})
1010

11+
test('restores window scroll after force reload of a navigated route', async ({
12+
page,
13+
}) => {
14+
await page.goto('/')
15+
await page.getByRole('link', { name: '/reset-scroll-false-a' }).click()
16+
await expect(
17+
page.getByRole('heading', { name: 'reset-scroll-false-a' }),
18+
).toBeVisible()
19+
await expect
20+
.poll(async () =>
21+
page.evaluate(() => document.documentElement.scrollHeight > innerHeight),
22+
)
23+
.toBe(true)
24+
25+
const scrollY = await page.evaluate(async () => {
26+
window.scrollTo(0, 500)
27+
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)))
28+
return window.scrollY
29+
})
30+
31+
expect(scrollY).toBeGreaterThan(0)
32+
33+
await page.reload()
34+
await expect(
35+
page.getByRole('heading', { name: 'reset-scroll-false-a' }),
36+
).toBeVisible()
37+
await expect
38+
.poll(async () => page.evaluate(() => window.scrollY))
39+
.toBe(scrollY)
40+
})
41+
42+
test('initial hard navigation to a hash scrolls to the hash target', async ({
43+
page,
44+
}) => {
45+
await page.goto('/hash-scroll-repro#four')
46+
await page.waitForLoadState('networkidle')
47+
await expect(page.getByTestId('hash-scroll-section-four')).toBeInViewport()
48+
await expect(page.getByTestId('hash-scroll-section-one')).not.toBeInViewport()
49+
})
50+
1151
// Test for scroll related stuff
1252
;[
1353
linkOptions({ to: '/normal-page' }),

‎e2e/react-start/scroll-restoration/tests/hash-scroll-repro.spec.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,3 +141,19 @@ test('hash navigation still runs when only nested scroll entries restore', async
141141
})
142142
.toBe(nestedScrollTop)
143143
})
144+
145+
test('hash navigation scrolls when resetScroll is false', async ({ page }) => {
146+
await page.goto('/hash-scroll-repro#one')
147+
await page.waitForLoadState('networkidle')
148+
await expect(page.getByTestId('hash-scroll-section-one')).toBeInViewport()
149+
150+
const scrollYBeforeHashNavigation = await page.evaluate(() => window.scrollY)
151+
152+
await page.getByTestId('hash-scroll-section-four-no-reset-link').click()
153+
154+
await expect(page).toHaveURL(/#four$/)
155+
await expect(page.getByTestId('hash-scroll-section-four')).toBeInViewport()
156+
await expect
157+
.poll(async () => page.evaluate(() => window.scrollY))
158+
.toBeGreaterThan(scrollYBeforeHashNavigation)
159+
})
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { expect, test } from '@playwright/test'
2+
3+
const storageKey = 'tsr-scroll-restoration-v1_3'
4+
5+
test('SSR scroll restoration uses a custom restoration key', async ({
6+
page,
7+
}) => {
8+
const customKeyScrollY = 650
9+
const historyKeyScrollY = 80
10+
11+
await page.goto('/')
12+
await page.evaluate(
13+
({ customKeyScrollY, historyKeyScrollY, storageKey }) => {
14+
window.sessionStorage.setItem(
15+
storageKey,
16+
JSON.stringify({
17+
'ssr-scroll-key': {
18+
window: { scrollX: 0, scrollY: customKeyScrollY },
19+
},
20+
'history-key': {
21+
window: { scrollX: 0, scrollY: historyKeyScrollY },
22+
},
23+
}),
24+
)
25+
},
26+
{ customKeyScrollY, historyKeyScrollY, storageKey },
27+
)
28+
29+
await page.addInitScript(() => {
30+
window.history.replaceState({ __TSR_key: 'history-key' }, '')
31+
})
32+
await page.route(/\/assets\/.*\.js$/, (route) => route.abort())
33+
34+
await page.goto('/ssr-scroll-key', { waitUntil: 'domcontentloaded' })
35+
await expect(
36+
page.getByRole('heading', { name: 'ssr-scroll-key' }),
37+
).toBeVisible()
38+
await expect
39+
.poll(async () => page.evaluate(() => window.scrollY))
40+
.toBe(customKeyScrollY)
41+
})
Lines changed: 19 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,62 +1,43 @@
1-
export default function (options: { storageKey: string; key?: string }) {
1+
export default function (storageKey: string, key?: string) {
22
let byKey
33

44
try {
5-
byKey = JSON.parse(sessionStorage.getItem(options.storageKey) || '{}')
6-
} catch (error) {
7-
console.error(error)
5+
byKey = JSON.parse(sessionStorage.getItem(storageKey) || '{}')
6+
} catch {
87
return
98
}
109

11-
const resolvedKey = options.key || window.history.state?.__TSR_key
12-
const elementEntries = resolvedKey ? byKey[resolvedKey] : undefined
10+
const elementEntries = byKey?.[key || history.state?.__TSR_key]
1311
let windowRestored = false
1412

15-
if (elementEntries && typeof elementEntries === 'object') {
16-
for (const elementSelector in elementEntries) {
17-
const entry = elementEntries[elementSelector]
18-
19-
if (!entry || typeof entry !== 'object') {
20-
continue
21-
}
22-
23-
const scrollX = entry.scrollX
24-
const scrollY = entry.scrollY
25-
26-
if (!Number.isFinite(scrollX) || !Number.isFinite(scrollY)) {
27-
continue
28-
}
13+
for (const elementSelector in elementEntries) {
14+
const entry = elementEntries[elementSelector]
15+
const scrollX = entry?.scrollX
16+
const scrollY = entry?.scrollY
2917

18+
if (Number.isFinite(scrollX) && Number.isFinite(scrollY)) {
3019
if (elementSelector === 'window') {
31-
window.scrollTo({
32-
top: scrollY,
33-
left: scrollX,
34-
})
20+
scrollTo(scrollX, scrollY)
3521
windowRestored = true
3622
} else if (elementSelector) {
37-
let element
38-
3923
try {
40-
element = document.querySelector(elementSelector)
41-
} catch {
42-
continue
43-
}
44-
45-
if (element) {
46-
element.scrollLeft = scrollX
47-
element.scrollTop = scrollY
48-
}
24+
const element = document.querySelector(elementSelector)
25+
if (element) {
26+
element.scrollLeft = scrollX
27+
element.scrollTop = scrollY
28+
}
29+
} catch {}
4930
}
5031
}
5132
}
5233

5334
if (windowRestored) return
5435

55-
const hash = window.location.hash.split('#', 2)[1]
36+
const hash = location.hash.slice(1)
5637

5738
if (hash) {
5839
const hashScrollIntoViewOptions =
59-
window.history.state?.__hashScrollIntoViewOptions ?? true
40+
history.state?.__hashScrollIntoViewOptions ?? true
6041

6142
if (hashScrollIntoViewOptions) {
6243
const el = document.getElementById(hash)
@@ -68,5 +49,5 @@ export default function (options: { storageKey: string; key?: string }) {
6849
return
6950
}
7051

71-
window.scrollTo({ top: 0, left: 0 })
52+
scrollTo(0, 0)
7253
}

‎packages/router-core/src/scroll-restoration-script/server.ts‎

Lines changed: 5 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,16 @@ import {
66
import { escapeHtml } from '../utils'
77
import type { AnyRouter } from '../router'
88

9-
type InlineScrollRestorationScriptOptions = {
10-
storageKey: string
11-
key?: string
12-
}
13-
149
const defaultInlineScrollRestorationScript = `(${minifiedScrollRestorationScript})(${escapeHtml(
15-
JSON.stringify({
16-
storageKey,
17-
} satisfies InlineScrollRestorationScriptOptions),
10+
JSON.stringify(storageKey),
1811
)})`
1912

20-
function getScrollRestorationScript(
21-
options: InlineScrollRestorationScriptOptions,
22-
) {
23-
if (options.storageKey === storageKey && options.key === undefined) {
13+
function getScrollRestorationScript(key?: string) {
14+
if (key === undefined) {
2415
return defaultInlineScrollRestorationScript
2516
}
2617

27-
return `(${minifiedScrollRestorationScript})(${escapeHtml(JSON.stringify(options))})`
18+
return `(${minifiedScrollRestorationScript})(${escapeHtml(JSON.stringify(storageKey))},${escapeHtml(JSON.stringify(key))})`
2819
}
2920

3021
export function getScrollRestorationScriptForRouter(router: AnyRouter) {
@@ -48,8 +39,5 @@ export function getScrollRestorationScriptForRouter(router: AnyRouter) {
4839
return defaultInlineScrollRestorationScript
4940
}
5041

51-
return getScrollRestorationScript({
52-
storageKey,
53-
key: userKey,
54-
})
42+
return getScrollRestorationScript(userKey)
5543
}

0 commit comments

Comments
 (0)