import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
Outlet,
RouterProvider,
type AnyRouter,
} from '@tanstack/react-router'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { useState, type ReactNode } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
HASH_LAYOUT_SETTLE_TIMEOUT_MS,
HASH_TARGET_MOUNT_TIMEOUT_MS,
HashScrollController,
} from './HashScrollController'
async function renderWithRouter({
initialUrl = '/other',
children,
}: {
initialUrl?: string
children: ReactNode
}) {
const rootRoute = createRootRoute({
component: () => (
<>
>
),
})
const pageRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/page',
component: () => <>{children}>,
})
const otherRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/other',
component: () =>
Other
,
})
const router = createRouter({
routeTree: rootRoute.addChildren([pageRoute, otherRoute]),
history: createMemoryHistory({ initialEntries: [initialUrl] }),
defaultHashScrollIntoView: false,
})
await act(() => router.load())
render()
return router
}
const navigate = (
router: AnyRouter,
opts: { to: string; hash: string | true; search?: Record }
) => act(() => router.navigate(opts))
// Flushes pending MutationObserver callbacks.
const flushMutations = () => act(async () => {})
/** Renders `target` (or ``) only after "Finish loading" is clicked, like a query skeleton. */
const LateSection = ({ id, children }: { id: string; children?: ReactNode }) => {
const [isLoaded, setIsLoaded] = useState(false)
return (
{isLoaded && (children ?? )}
)
}
describe('HashScrollController', () => {
let scrollIntoView: ReturnType
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true })
scrollIntoView = vi.spyOn(HTMLElement.prototype, 'scrollIntoView').mockImplementation(() => {})
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
})
it('smoothly scrolls to the target when navigating to a hash', async () => {
const router = await renderWithRouter({ children: })
await navigate(router, { to: '/page', hash: 'sms-mfa' })
expect(scrollIntoView).toHaveBeenCalledOnce()
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'start' })
expect(scrollIntoView.mock.contexts[0]).toBe(document.getElementById('sms-mfa'))
})
it('jumps instead of animating when the user prefers reduced motion', async () => {
vi.spyOn(window, 'matchMedia').mockImplementation(
(query) => ({ matches: query === '(prefers-reduced-motion: reduce)' }) as MediaQueryList
)
const router = await renderWithRouter({ children: })
await navigate(router, { to: '/page', hash: 'sms-mfa' })
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'instant', block: 'start' })
})
it('waits for a target that mounts after the initial render', async () => {
await renderWithRouter({ initialUrl: '/page#sms-mfa', children: })
expect(scrollIntoView).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Finish loading' }))
await flushMutations()
expect(scrollIntoView).toHaveBeenCalledOnce()
expect(scrollIntoView.mock.contexts[0]).toBe(document.getElementById('sms-mfa'))
})
it('gives up once the user scrolls before the target mounts', async () => {
await renderWithRouter({ initialUrl: '/page#sms-mfa', children: })
fireEvent.wheel(window)
fireEvent.click(screen.getByRole('button', { name: 'Finish loading' }))
await flushMutations()
expect(scrollIntoView).not.toHaveBeenCalled()
})
it('gives up if the target has not mounted by the timeout', async () => {
await renderWithRouter({ initialUrl: '/page#sms-mfa', children: })
await act(() => vi.advanceTimersByTimeAsync(HASH_TARGET_MOUNT_TIMEOUT_MS))
fireEvent.click(screen.getByRole('button', { name: 'Finish loading' }))
await flushMutations()
expect(scrollIntoView).not.toHaveBeenCalled()
})
describe('when content above the target shifts', () => {
let targetTop: number
beforeEach(() => {
targetTop = 400
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
this: HTMLElement
) {
return { top: this.id === 'compute' ? targetTop : 0 } as DOMRect
})
})
// "Finish loading" mounts a banner above the already-mounted target.
const renderShiftingPage = () =>
renderWithRouter({
children: (
<>
>
),
})
it('re-aligns instantly until the settle timeout', async () => {
const router = await renderShiftingPage()
await navigate(router, { to: '/page', hash: 'compute' })
expect(scrollIntoView).toHaveBeenCalledOnce()
targetTop = 650
fireEvent.click(screen.getByRole('button', { name: 'Finish loading' }))
await flushMutations()
expect(scrollIntoView).toHaveBeenCalledTimes(2)
expect(scrollIntoView).toHaveBeenLastCalledWith({ behavior: 'instant', block: 'start' })
await act(() => vi.advanceTimersByTimeAsync(HASH_LAYOUT_SETTLE_TIMEOUT_MS))
targetTop = 900
const unrelatedNode = document.body.appendChild(document.createElement('div'))
await flushMutations()
unrelatedNode.remove()
expect(scrollIntoView).toHaveBeenCalledTimes(2)
})
it('ignores mutations that do not move the target', async () => {
const router = await renderShiftingPage()
await navigate(router, { to: '/page', hash: 'compute' })
fireEvent.click(screen.getByRole('button', { name: 'Finish loading' }))
await flushMutations()
expect(scrollIntoView).toHaveBeenCalledOnce()
})
})
it('scrolls again when only the hash changes', async () => {
const router = await renderWithRouter({
children: (
<>
>
),
})
await navigate(router, { to: '/page', hash: 'compute' })
await navigate(router, { to: '/page', hash: 'advanced' })
expect(scrollIntoView).toHaveBeenCalledTimes(2)
expect(scrollIntoView.mock.contexts[1]).toBe(document.getElementById('advanced'))
})
it('does not scroll back to the anchor on search-param updates or invalidation', async () => {
const router = await renderWithRouter({
children: ,
})
await navigate(router, { to: '/page', hash: 'read-replicas' })
scrollIntoView.mockClear()
// Mirrors nuqs setting `?addReplica=true` while keeping `#read-replicas`.
await navigate(router, { to: '/page', search: { addReplica: 'true' }, hash: true })
await act(() => router.invalidate())
expect(scrollIntoView).not.toHaveBeenCalled()
})
})