Files
supabase/apps/studio/components/interfaces/App/HashScrollController.test.tsx
K-Dog (Kevin) 27c4433a3e feat: revised project add-ons page (#54186)
The current add-ons page only lists a subset of available add-ons, which
often causes confusion with things like Advanced MFA Auth (customers
cant find where to configure it).

The revised add-on page covers all potentially configured project
add-ons including replicas and advanced disk. This should help the
customer locate configured add-ons and at the same time discover
potentially interesting add-ons. This can be enhanced further in the
future with "smart" suggestions based on usage.
2026-11-30 21:54:44 +08:00

228 lines
7.4 KiB
TypeScript

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: () => (
<>
<HashScrollController />
<Outlet />
</>
),
})
const pageRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/page',
component: () => <>{children}</>,
})
const otherRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/other',
component: () => <div>Other</div>,
})
const router = createRouter({
routeTree: rootRoute.addChildren([pageRoute, otherRoute]),
history: createMemoryHistory({ initialEntries: [initialUrl] }),
defaultHashScrollIntoView: false,
})
await act(() => router.load())
render(<RouterProvider router={router} />)
return router
}
const navigate = (
router: AnyRouter,
opts: { to: string; hash: string | true; search?: Record<string, string> }
) => act(() => router.navigate<AnyRouter, string>(opts))
// Flushes pending MutationObserver callbacks.
const flushMutations = () => act(async () => {})
/** Renders `target` (or `<section id={id}>`) only after "Finish loading" is clicked, like a query skeleton. */
const LateSection = ({ id, children }: { id: string; children?: ReactNode }) => {
const [isLoaded, setIsLoaded] = useState(false)
return (
<div>
<button type="button" tabIndex={0} onClick={() => setIsLoaded(true)}>
Finish loading
</button>
{isLoaded && (children ?? <section id={id}>Section</section>)}
</div>
)
}
describe('HashScrollController', () => {
let scrollIntoView: ReturnType<typeof vi.spyOn>
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: <section id="sms-mfa">SMS MFA</section> })
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: <section id="sms-mfa">SMS MFA</section> })
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: <LateSection id="sms-mfa" /> })
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: <LateSection id="sms-mfa" /> })
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: <LateSection id="sms-mfa" /> })
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: (
<>
<LateSection id="banner" />
<section id="compute">Compute</section>
</>
),
})
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: (
<>
<section id="compute">Compute</section>
<section id="advanced">Advanced</section>
</>
),
})
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: <section id="read-replicas">Read replicas</section>,
})
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()
})
})