Files
Alaister YoungandAlaister Young 0f14ef4d67 [FE-5109] (part 5) refactor(studio): migrate remaining interfaces and router events off next/router (#54057)
Part 5 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| 4 | #54056 | Database, Branching, Compute, Edge Functions, Explorer,
SQL Editor, Storage, Table Editor |
| **5** | **#54057 ← this PR** | **Remaining `components/interfaces/**`
and `QueryInsightsTable` router events** |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates all remaining `apps/studio/components/interfaces/**`
directories off `next/router`, including the last production
`router.events` consumer (`QueryInsightsTable`) and the only default
`next/router` import (`DiscordCTACard`). After this PR, zero files under
`apps/studio/components/**` import `next/router` or
`next/compat/router`.

**Added:**

-
`apps/studio/components/interfaces/QueryInsights/QueryInsightsTable/QueryInsightsTable.test.tsx`:
verifies that pathname changes clear selected query state without
mutating destination or history search params, while same-pathname
search updates preserve selection

**Changed:**

- Replaced the sole production `router.events.on('routeChangeStart',
...)` consumer in `QueryInsightsTable.tsx` with a `pathname` effect that
clears `onCurrentSelectQuery` on pathname changes, and derived
`searchQuery` directly from `nuqs` (`urlSearch`) instead of mirroring it
in local state. Drops the legacy `setQueryStates({ search: null })` call
on leave, which ran after `history.push` on TanStack Router (targeting
the destination URL rather than the previous history entry, while
browser Back is expected to restore previous search params).
- Removed the `router: NextRouter` prop from `ReportWidgetRendererProps`
in `Reports/ReportWidget.tsx` and updated its callers (`ChartBlock`,
`ReportHeader`, `CreateReportModal`)
- Updated `LOG_ROUTES_WITH_REPLICA_SUPPORT` in
`Settings/Logs/Logs.constants.ts` from `[ref]` to `$ref` for TanStack
route patterns
- Replaced the default `import router from 'next/router'` in
`Support/DiscordCTACard.tsx` with `useNavigate`
- Replaced `useRouter` across `Account`, `Advisors`, `App`, `Auth`,
`ErrorHandling`, `Home`, `HomePageActions`, `Integrations`, `Linter`,
`LocalDropdown`, `Observability`, `Organization`, `OrganizationInvite`,
`Platform/Webhooks`, `Project`, `ProjectCreation`, `ProjectHome`,
`QueryPerformance`, `RedeemCredits`, `Settings`, `Sidebar`, `SignIn`,
`Support`, `UnifiedLogs`, and `UserDropdown`
- Updated affected tests (`Auth/Users/UserPanel`, `Home/ProjectList`,
`LocalDropdown`, `Organization/*`, `OrganizationInvite`,
`RedeemCredits`, `Settings/General/*`, `SignIn/SignInRecoveryCodeForm`,
`UnifiedLogs/*`)

**Simplified:**

- `LocalDropdown`, `UserDropdown` and `RedeemCredits` build the current
route from `location.href`, so the hash keeps its leading `#`
- `NewOrgForm` navigates to the `returnTo` path instead of an absolute
URL, which was being treated as external. It also uses a typed
`/new/$slug` navigate.
- Read search params from `useParams()` instead of `location.search`
casts (`CronJobPage`, `QueuePage`, `LogsPreviewer`,
`LinkSupportTicketPage`, `MarketplaceSidebar`, `PlanCards`,
`SignUpForm`)
- Dropped the dead `isReady`/`isRouterReady` constants and the
`navigate<AnyRouter, string>` casts where typed routes work
(`ForgotPasswordWizard`, `SignInPartner`, `ReportWidget`,
`ProjectUpgradeAlert`)
- Linter, `ReportHeader` and `LogsPreviewer` use `to: '.'` instead of a
separate pathname subscription. `CreateReportModal` builds the preserved
query params in `onSuccess` instead of a `useMemo`.
- Tests use the shared `createTestRouter` and `customRender` router.
`LocalDropdown` now tests that the hash is kept.

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [x] Query Insights: select a query and confirm search/filter updates
keep selection while switching projects/routes clears it; navigating to
Logs keeps Logs' query params intact and pressing Back restores Query
Insights' `?search=` param cleanly
- [x] Auth / Sign-in flows: sign in, sign up, MFA, recovery code,
forgot/reset password, and partner sign-in preserve `returnTo` and
redirect as expected
- [x] Organization & Project flows: creating an org/project, accepting
an org invite, claiming a project, redeeming credits, and
deleting/pausing/restarting a project or branch navigate cleanly
- [ ] Logs & Reports: replica selector appears on supported log routes
(`LOG_ROUTES_WITH_REPLICA_SUPPORT`), saved log queries open, and custom
reports create/navigate properly
- [ ] Sidebar, LocalDropdown, UserDropdown, Integrations
(Cron/Queues/Marketplace), Advisors/Linter, and Unified Logs navigate
cleanly

---------

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

162 lines
6.6 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { CopyIcon, MoreVerticalIcon, SettingsIcon } from 'lucide-react'
import InlineSVG from 'react-inlinesvg'
import { toast } from 'sonner'
import {
Button,
copyToClipboard,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
GithubIcon,
} from 'ui'
import { inferProjectStatus } from './ProjectCard.utils'
import { ProjectCardStatus } from './ProjectCardStatus'
import CardButton from '@/components/ui/CardButton'
import { ComputeBadgeWrapper } from '@/components/ui/ComputeBadgeWrapper'
import PartnerIcon from '@/components/ui/PartnerIcon'
import type { IntegrationProjectConnection } from '@/data/integrations/integrations.types'
import { getManagedByFromOrganizationPartner } from '@/data/organizations/managed-by-utils'
import { ProjectIndexPageLink } from '@/data/prefetchers/project.$ref'
import { getComputeSize, OrgProject } from '@/data/projects/org-projects-infinite-query'
import type { ResourceWarning } from '@/data/usage/resource-warnings-query'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { BASE_PATH } from '@/lib/constants'
import type { Organization } from '@/types'
export interface ProjectCardProps {
slug?: string
project: OrgProject
organization?: Organization
rewriteHref?: string
githubIntegration?: IntegrationProjectConnection
vercelIntegration?: IntegrationProjectConnection
resourceWarnings?: ResourceWarning
}
export const ProjectCard = ({
slug,
project,
rewriteHref,
githubIntegration,
vercelIntegration,
resourceWarnings,
}: ProjectCardProps) => {
const navigate = useNavigate()
const { name, ref: projectRef } = project
const { projectHomepageShowInstanceSize } = useIsFeatureEnabled([
'project_homepage:show_instance_size',
])
const isGithubIntegrated = githubIntegration !== undefined
const isVercelIntegrated = vercelIntegration !== undefined
const githubRepository = githubIntegration?.metadata.name ?? undefined
const projectManagedBy = getManagedByFromOrganizationPartner(
undefined,
project.integration_source
)
const projectStatus = inferProjectStatus(project.status)
return (
<>
<li className="list-none h-min">
<CardButton
tabIndex={0}
linkHref={rewriteHref ? rewriteHref : `/project/${projectRef}`}
className="h-44 px-0! group pt-5 pb-0 overflow-hidden relative"
hideChevron
title={
<div className="w-full flex flex-col gap-y-4 justify-between px-5">
<div className="flex flex-col gap-y-0.5 relative">
<div className="flex items-center justify-between">
<h2 className="text-sm shrink truncate pr-5">{name}</h2>
<div onClick={(e) => e.preventDefault()}>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="text"
icon={<MoreVerticalIcon size={14} />}
className="w-6 h-6 px-0"
onClick={(e) => {
e.stopPropagation()
e.preventDefault()
}}
onPointerDown={(e) => e.stopPropagation()}
aria-label={`Project ${name} actions`}
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
<DropdownMenuItem
className="gap-x-2"
onClick={(e) => {
e.stopPropagation()
copyToClipboard(projectRef)
toast.success('Copied project ID to clipboard')
}}
>
<CopyIcon size={14} />
<span>Copy project ID</span>
</DropdownMenuItem>
<DropdownMenuItem
className="gap-x-2"
onClick={(e) => {
e.stopPropagation()
navigate({
to: '/project/$ref/settings/general',
params: { ref: projectRef },
})
}}
>
<SettingsIcon size={14} />
<span>Settings</span>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<p className="text-sm text-foreground-lighter">{project.region}</p>
</div>
<div className="flex items-center gap-x-1.5 relative overflow-hidden">
{project.status !== 'INACTIVE' && projectHomepageShowInstanceSize && (
<ComputeBadgeWrapper
slug={slug}
projectRef={project.ref}
cloudProvider={project.cloud_provider}
computeSize={getComputeSize(project)}
badgeClassName="text-[10px] leading-none tracking-[0.07em]"
/>
)}
{isVercelIntegrated && (
<div className="bg-surface-100 w-5 h-5 p-1 border border-strong rounded-md flex items-center justify-center text-black dark:text-white">
<InlineSVG
src={`${BASE_PATH}/img/icons/vercel-icon.svg`}
title="Vercel Icon"
className="w-3"
/>
</div>
)}
<PartnerIcon organization={{ managed_by: projectManagedBy }} />
{isGithubIntegrated && (
<div className="bg-surface-100 flex items-center gap-x-0.5 h-5 pr-1 border border-strong rounded-md min-w-0">
<div className="w-5 h-5 p-1 flex items-center justify-center shrink-0">
<GithubIcon size={12} strokeWidth={1.5} />
</div>
<p className="text-xs text-foreground-light truncate">{githubRepository}</p>
</div>
)}
</div>
</div>
}
footer={
<ProjectCardStatus projectStatus={projectStatus} resourceWarnings={resourceWarnings} />
}
containerElement={<ProjectIndexPageLink projectRef={projectRef} />}
/>
</li>
</>
)
}