Skip to content

Commit f7787d5

Browse files
authored
Fix for links with anchor hash on initial visit (#2719)
1 parent 14a30f4 commit f7787d5

File tree

3 files changed

+16
-0
lines changed

3 files changed

+16
-0
lines changed

packages/core/src/initialVisit.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,10 @@ export class InitialVisit {
9696
currentPage.set(currentPage.get(), { preserveScroll: true, preserveState: true }).then(() => {
9797
if (navigationType.isReload()) {
9898
Scroll.restore(history.getScrollRegions())
99+
} else {
100+
Scroll.scrollToAnchor()
99101
}
102+
100103
fireNavigateEvent(currentPage.get())
101104
})
102105
}

packages/core/src/scroll.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ export class Scroll {
3333
})
3434

3535
this.save()
36+
this.scrollToAnchor()
37+
}
38+
39+
public static scrollToAnchor(): void {
40+
const anchorHash = typeof window !== 'undefined' ? window.location.hash : null
3641

3742
if (anchorHash) {
3843
// We're using a setTimeout() here as a workaround for a bug in the React adapter where the

tests/links.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -816,6 +816,14 @@ test.describe('URL fragment navigation (& automatic scrolling)', () => {
816816
})
817817
})
818818

819+
test('scrolls to the fragment on initial page load', async ({ page }) => {
820+
await page.goto('/article#far-down')
821+
await expect(page.getByRole('heading', { name: 'Article Header' })).toBeVisible()
822+
823+
const scrollTop = await page.evaluate(() => document.documentElement.scrollTop)
824+
expect(scrollTop).toBeGreaterThan(500)
825+
})
826+
819827
test('does not scroll when clicking the same fragment link', async ({ page }) => {
820828
/** @see https://github.com/inertiajs/inertia/issues/1921 */
821829
await page.goto('/article#far-down')

0 commit comments

Comments
 (0)