import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createMemoryHistory, createRootRoute, createRouter, Link as TanStackLink, RouterContextProvider, useRouter as useTanStackRouter, useRouterState, type AnyRoute, type AnyRouter, } from '@tanstack/react-router' import { render, renderHook, type RenderOptions } from '@testing-library/react' import { AuthContext, AuthContext as AuthContextType, DefaultFrameworkImage, DefaultFrameworkLink, FrameworkProvider, resolveStaticImageSrc, type FrameworkContextValue, type FrameworkImageProps, type FrameworkLinkProps, } from 'common' import { NuqsTestingAdapter } from 'nuqs/adapters/testing' import { forwardRef, useMemo, type ForwardedRef } from 'react' import { TooltipProvider } from 'ui' import { CommandProvider } from 'ui-patterns/CommandMenu' // End of third-party imports import { applyBasePath, isAbsoluteUrl, splitInternalUrl, toRoutePattern } from '@/lib/internal-url' import { navigateToUrl } from '@/lib/navigation' import { ProfileContext, type ProfileContextType } from '@/lib/profile' import { parseSearch, stringifySearch } from '@/lib/router-search-params' type AdapterProps = Partial[0]> function normalizeParams( search: Record | undefined, params: Record | undefined ): Record { const merged = { ...search, ...params } const normalized: Record = {} 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 TestFrameworkLink = forwardRef(function TestFrameworkLink( props: FrameworkLinkProps, ref: ForwardedRef ) { 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 } const preload = prefetch === false ? false : prefetch ? 'intent' : undefined return ( to={to} search={search as never} hash={hash} replace={replace} preload={preload} ref={ref} {...rest} > {children} ) }) function TestFrameworkImage({ src, ...props }: FrameworkImageProps) { return } export const createTestRouter = ( initialUrl = '/', routeTree: AnyRoute = createRootRoute() ): AnyRouter => createRouter({ routeTree, history: createMemoryHistory({ initialEntries: [initialUrl] }), parseSearch, stringifySearch, }) const TestRouterProvider = ({ children, router, initialUrl = '/', }: { children: React.ReactNode router?: AnyRouter initialUrl?: string }) => { const activeRouter = useMemo(() => router ?? createTestRouter(initialUrl), [router, initialUrl]) return {children} } const TestFrameworkProvider = ({ children }: { children: React.ReactNode }) => { const router = useTanStackRouter() const location = useRouterState({ select: (state) => state.resolvedLocation ?? state.location, }) const stateMatches = useRouterState({ select: (state) => state.matches, }) const value = useMemo(() => { const matches = stateMatches.length > 0 ? stateMatches : router.matchRoutes(location) const leafMatch = matches[matches.length - 1] const leafRouteId = leafMatch && leafMatch.routeId !== '__root__' ? leafMatch.routeId : location.pathname const pathname = toRoutePattern(leafRouteId) const asPath = location.href const routeParams = leafMatch?.params as Record | undefined const searchParams = (leafMatch?.search as Record | undefined) ?? (location.search as Record | undefined) const params = normalizeParams(searchParams, routeParams) return { Link: TestFrameworkLink, Image: TestFrameworkImage, pathname, asPath, isReady: true, params, push: async (path: string) => { await navigateToUrl( router.navigate, resolveSearchOrHashOnlyTarget(path, location.pathname, location.searchStr) ) }, } }, [location, router, stateMatches]) return {children} } export const CustomWrapper = ({ children, queryClient, nuqs, profileContext, authContext, router, initialUrl, }: { children: React.ReactNode queryClient?: QueryClient nuqs?: AdapterProps profileContext?: ProfileContextType authContext?: AuthContext router?: AnyRouter initialUrl?: string }) => { const _queryClient = queryClient ?? new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false }, }, }) let content = ( {children} ) if (profileContext) { content = {content} } if (authContext) { content = {content} } return content } type CustomRenderOpts = RenderOptions & { queryClient?: QueryClient nuqs?: AdapterProps profileContext?: ProfileContextType authContext?: AuthContextType router?: AnyRouter initialUrl?: string } export const customRender = (component: React.ReactElement, renderOptions?: CustomRenderOpts) => { const router = renderOptions?.router ?? createTestRouter(renderOptions?.initialUrl) const result = render(component, { wrapper: ({ children }) => CustomWrapper({ queryClient: renderOptions?.queryClient, nuqs: renderOptions?.nuqs, profileContext: renderOptions?.profileContext, authContext: renderOptions?.authContext, router, children, }), ...renderOptions, }) return { ...result, router } } export const customRenderHook = (hook: () => T, renderOptions?: CustomRenderOpts) => { const router = renderOptions?.router ?? createTestRouter(renderOptions?.initialUrl) const result = renderHook(hook, { wrapper: ({ children }) => CustomWrapper({ children, queryClient: renderOptions?.queryClient, nuqs: renderOptions?.nuqs, profileContext: renderOptions?.profileContext, authContext: renderOptions?.authContext, router, }), ...renderOptions, }) return { ...result, router } }