Files
supabase/apps/studio/components/interfaces/App/StudioFrameworkProvider.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

146 lines
4.4 KiB
TypeScript

import {
Link as TanStackLink,
useMatches,
useRouterState,
useSearch,
useParams as useTanStackParams,
useRouter as useTanStackRouter,
type AnyRouter,
} from '@tanstack/react-router'
import {
DefaultFrameworkImage,
DefaultFrameworkLink,
FrameworkProvider,
resolveStaticImageSrc,
type FrameworkContextValue,
type FrameworkImageProps,
type FrameworkLinkProps,
} from 'common'
import { forwardRef, useMemo, type ForwardedRef, type ReactNode } from 'react'
import { applyBasePath, isAbsoluteUrl, splitInternalUrl, toRoutePattern } from '@/lib/internal-url'
import { navigateToUrl } from '@/lib/navigation'
function normalizeParams(
search: Record<string, unknown> | undefined,
params: Record<string, unknown> | undefined
): Record<string, string | string[] | undefined> {
const merged = { ...search, ...params }
const normalized: Record<string, string | string[] | undefined> = {}
for (const [key, value] of Object.entries(merged)) {
if (typeof value === 'string') {
normalized[key] = value
} else if (Array.isArray(value)) {
normalized[key] = value.map(String)
} else if (value !== undefined && value !== null) {
normalized[key] = String(value)
}
}
return normalized
}
function resolveSearchOrHashOnlyTarget(
target: string,
currentPathname: string,
currentSearch: string
): string {
if (target.startsWith('?')) {
return `${currentPathname}${target}`
}
if (target.startsWith('#')) {
return `${currentPathname}${currentSearch}${target}`
}
return target
}
const StudioLink = forwardRef(function StudioLink(
props: FrameworkLinkProps,
ref: ForwardedRef<HTMLAnchorElement>
) {
const { href, prefetch, replace, scroll: _scroll, shallow: _shallow, children, ...rest } = props
const currentPathname = useRouterState({
select: (state) => (state.resolvedLocation ?? state.location).pathname,
})
const currentSearch = useRouterState({
select: (state) => (state.resolvedLocation ?? state.location).searchStr,
})
const resolvedHref = resolveSearchOrHashOnlyTarget(href, currentPathname, currentSearch)
const { to, search, hash } = splitInternalUrl(resolvedHref)
if (isAbsoluteUrl(to)) {
return <DefaultFrameworkLink ref={ref} {...props} />
}
const preload = prefetch === false ? false : prefetch ? 'intent' : undefined
return (
<TanStackLink<AnyRouter, string>
to={to}
search={search as never}
hash={hash}
replace={replace}
preload={preload}
ref={ref}
{...rest}
>
{children}
</TanStackLink>
)
})
function StudioImage({ src, ...props }: FrameworkImageProps) {
return <DefaultFrameworkImage {...props} src={applyBasePath(resolveStaticImageSrc(src))} />
}
export function StudioFrameworkProvider({ children }: { children: ReactNode }) {
const router = useTanStackRouter()
const committedLocation = useRouterState({
select: (state) => state.resolvedLocation ?? state.location,
})
// `resolvedLocation` stays unset until the first load commits. Before then `location` can already
// point at a redirect target while the initial matches are still pending.
const isReady = useRouterState({ select: (state) => state.resolvedLocation !== undefined })
const leafRouteId =
useMatches({ select: (matches) => matches[matches.length - 1]?.routeId }) ??
committedLocation.pathname
const routeParams = useTanStackParams({ strict: false })
const searchParams = useSearch({ strict: false })
const value = useMemo<FrameworkContextValue>(() => {
const pathname = toRoutePattern(leafRouteId)
const asPath = committedLocation.href
const currentPathname = committedLocation.pathname
const currentSearch = committedLocation.searchStr
const params = normalizeParams(
searchParams as Record<string, unknown> | undefined,
routeParams as Record<string, unknown> | undefined
)
return {
Link: StudioLink,
Image: StudioImage,
pathname,
asPath,
isReady,
params,
push: async (path: string) => {
await navigateToUrl(
router.navigate,
resolveSearchOrHashOnlyTarget(path, currentPathname, currentSearch)
)
},
}
}, [
committedLocation.href,
committedLocation.pathname,
committedLocation.searchStr,
isReady,
leafRouteId,
routeParams,
router,
searchParams,
])
return <FrameworkProvider value={value}>{children}</FrameworkProvider>
}