Files
supabase/apps/studio/lib/nuqs-tanstack-adapter.test.tsx
Alaister YoungandAlaister Young 07101b6894 [FE-3200] chore(studio): lift bundler workarounds and stabilize hooks (#54121)
Cleans up obsolete Rolldown/Vite bundler workarounds from the TanStack
Start migration and fixes unstable router selectors and inline default
array props that could cause unnecessary re-renders or render loops.

Addresses
[FE-3200](https://linear.app/supabase/issue/FE-3200/lift-bundler-workarounds-and-fix-latent-issues-next-was-masking).

**Removed:**

- Emptied `KNOWN_CHUNK_CYCLES` in `apps/studio/vite.config.ts` while
keeping the `assertNoChunkCycles` build guard enabled
- Removed obsolete `manualChunks` workarounds
(`class-variance-authority`, `ui-field`, `ui-drawer`, `ui-form`,
`ui-sidebar`, `ui-slider`, `ui-avatar`), keeping the React and
`lucide-react` vendor chunks so React stays a single leaf chunk and
Lucide does not fan out into per-icon modulepreload requests
- Removed the obsolete `sharedDefines` (`global: 'globalThis'`)
substitution from `apps/studio/vite.config.ts`

**Changed:**

- `StudioLink` (`StudioFrameworkProvider.tsx`): split `useRouterState`
into primitive `currentPathname` and `currentSearch` selectors instead
of returning a fresh object on every router state tick
- `useNuqsTanStackRouterAdapter` (`nuqs-tanstack-adapter.tsx`): select a
serialized query string key from `useLocation` so `useQueryState`
consumers do not re-render when unwatched search params change
- `FilterPopover`: replaced inline `[]` defaults for `options` and
`activeOptions` with shared `EMPTY_ARR` (`@/lib/void`), and guarded
`setSelectedOptions` with an element-wise equality check when closed
- `InputWithSuggestions`: replaced inline `[]` default for `suggestions`
with shared `EMPTY_ARR` (`@/lib/void`) so `useEffect` does not loop when
`suggestions` is omitted at runtime

**Added:**

- Regression tests covering router selector stability and default-prop
render loops in `StudioFrameworkProvider.test.tsx`,
`nuqs-tanstack-adapter.test.tsx`, `FilterPopover.test.tsx`, and
`InputWithSuggestions.test.tsx`

## To test

- Run `pnpm --filter studio run build` and verify the build passes with
`KNOWN_CHUNK_CYCLES` empty and `assertNoChunkCycles` enabled
- Run the new/updated unit tests in `apps/studio`
(`StudioFrameworkProvider.test.tsx`, `nuqs-tanstack-adapter.test.tsx`,
`FilterPopover.test.tsx`, `InputWithSuggestions.test.tsx`)
- Smoke-test Studio navigation, URL search-param filters (`nuqs`), Table
Editor column suggestions, `FilterPopover` interactions, and
`/auth/hooks` (confirming no `global` ReferenceError)

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 23:45:00 +08:00

144 lines
5.2 KiB
TypeScript

import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
Outlet,
RouterContextProvider,
RouterProvider,
type AnyRouter,
} from '@tanstack/react-router'
import { act, render, renderHook, screen, waitFor } from '@testing-library/react'
import { parseAsBoolean, useQueryState } from 'nuqs'
import type { ReactNode } from 'react'
import { describe, expect, it } from 'vitest'
import { buildSearchUpdateArgs, NuqsAdapter } from './nuqs-tanstack-adapter'
import { parseSearch, stringifySearch } from './router-search-params'
import { createTestRouter } from '@/tests/lib/custom-render'
describe('buildSearchUpdateArgs (custom nuqs adapter)', () => {
it('targets the current pathname with the search state as a record', () => {
// The regression we fixed: the stock tanstack-router adapter navigated to
// a relative `?provider=...`, which TanStack resolved by appending —
// landing on `/auth/providers/?provider=...` (trailing slash injected).
expect(buildSearchUpdateArgs('/auth/providers', new URLSearchParams('provider=apple'))).toEqual(
{ to: '/auth/providers', search: { provider: 'apple' } }
)
})
it('returns an empty search record when every param is cleared', () => {
// `search: {}` on TanStack navigate clears every param.
expect(buildSearchUpdateArgs('/auth/providers', new URLSearchParams())).toEqual({
to: '/auth/providers',
search: {},
})
})
it('keeps values verbatim, including newlines and other control chars', () => {
// The second regression we fixed: rendering the query string into the
// navigate `to` sent it through TanStack's path interpolation, which
// percent-decodes and strips control characters — Logs Explorer's
// multi-line SQL in `s` lost every newline (`desc\nlimit 5` became
// `desclimit 5`). Passing a search *record* keeps values untouched.
const sql = "select *\nfrom logs\nwhere source = 'edge'\norder by timestamp desc\nlimit 5"
const params = new URLSearchParams()
params.set('s', sql)
expect(buildSearchUpdateArgs('/project/abc/logs/explorer', params).search).toEqual({ s: sql })
})
it('preserves repeated keys as arrays', () => {
expect(
buildSearchUpdateArgs('/advisors/security', new URLSearchParams('f=a&f=b&page=2')).search
).toEqual({ f: ['a', 'b'], page: '2' })
})
it('strips a trailing slash from the pathname, but keeps the root "/"', () => {
const empty = new URLSearchParams()
expect(buildSearchUpdateArgs('/auth/providers/', empty).to).toBe('/auth/providers')
expect(buildSearchUpdateArgs('/', empty).to).toBe('/')
expect(buildSearchUpdateArgs('', empty).to).toBe('/')
})
})
describe('NuqsAdapter', () => {
it('writes to the current route when called through a setter from an earlier render', async () => {
const rootRoute = createRootRoute()
const routes = ['/project/$ref/settings/general', '/project/$ref/database/settings'].map(
(path) => createRoute({ getParentRoute: () => rootRoute, path })
)
const router: AnyRouter = createTestRouter(
'/project/abc/settings/general',
rootRoute.addChildren(routes)
)
await router.load()
const wrapper = ({ children }: { children: ReactNode }) => (
<RouterContextProvider router={router}>
<NuqsAdapter>{children}</NuqsAdapter>
</RouterContextProvider>
)
const { result } = renderHook(() => useQueryState('showConnect', parseAsBoolean), { wrapper })
const [, retainedSetter] = result.current
await act(() => router.navigate<AnyRouter, string>({ to: '/project/abc/database/settings' }))
await act(() => retainedSetter(true))
await waitFor(() => {
expect(router.state.location.pathname).toBe('/project/abc/database/settings')
expect(router.state.location.search).toEqual({ showConnect: 'true' })
})
})
it('does not re-render a useQueryState consumer when an unwatched search param changes', async () => {
let renderCount = 0
function WatchedProbe() {
renderCount++
const [watched] = useQueryState('watched')
return <span data-testid="watched">{watched ?? 'empty'}</span>
}
const rootRoute = createRootRoute({
component: () => (
<NuqsAdapter>
<Outlet />
</NuqsAdapter>
),
})
const pageRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/items',
component: WatchedProbe,
})
const router: AnyRouter = createRouter({
routeTree: rootRoute.addChildren([pageRoute]),
history: createMemoryHistory({ initialEntries: ['/items?watched=a&other=1'] }),
parseSearch,
stringifySearch,
})
render(<RouterProvider router={router} />)
expect(await screen.findByTestId('watched')).toHaveTextContent('a')
const rendersAfterMount = renderCount
await act(async () => {
await router.navigate<AnyRouter, string>({
to: '/items',
search: { watched: 'a', other: '2' },
})
})
expect(renderCount).toBe(rendersAfterMount)
await act(async () => {
await router.navigate<AnyRouter, string>({
to: '/items',
search: { watched: 'b', other: '2' },
})
})
await waitFor(() => expect(screen.getByTestId('watched')).toHaveTextContent('b'))
})
})