mirror of
https://github.com/supabase/supabase.git
synced 2026-12-06 00:19:08 +00:00
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>
295 lines
11 KiB
TypeScript
295 lines
11 KiB
TypeScript
import { zodResolver } from '@hookform/resolvers/zod'
|
||
import { useNavigate } from '@tanstack/react-router'
|
||
import { useFlag, useParams } from 'common'
|
||
import Link from 'next/link'
|
||
import { useMemo, useRef, useState, type ComponentPropsWithoutRef } from 'react'
|
||
import { useForm } from 'react-hook-form'
|
||
import { AWS_REGIONS, CloudProvider } from 'shared-data'
|
||
import { toast } from 'sonner'
|
||
import {
|
||
Button,
|
||
cn,
|
||
Dialog,
|
||
DialogContent,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogSection,
|
||
DialogTitle,
|
||
Form,
|
||
FormField,
|
||
} from 'ui'
|
||
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
|
||
import { z } from 'zod'
|
||
|
||
import { ResumeProjectCost } from './ResumeProjectCost'
|
||
import { PostgresVersionSelector } from '@/components/interfaces/ProjectCreation/PostgresVersionSelector'
|
||
import { extractPostgresVersionDetails } from '@/components/interfaces/ProjectCreation/ProjectCreation.utils'
|
||
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
|
||
import { ExceedFreeProjectLimitMembers } from '@/components/ui/ExceedFreeProjectLimitMembers'
|
||
import { FreeProjectLimitActions } from '@/components/ui/FreeProjectLimitActions'
|
||
import { useFreeProjectLimitCheckQuery } from '@/data/organizations/free-project-limit-check-query'
|
||
import { useOrganizationMembersQuery } from '@/data/organizations/organization-members-query'
|
||
import { useSetProjectStatus } from '@/data/projects/project-detail-query'
|
||
import { useProjectPauseStatusQuery } from '@/data/projects/project-pause-status-query'
|
||
import { useProjectRestoreMutation } from '@/data/projects/project-restore-mutation'
|
||
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
|
||
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
|
||
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
|
||
import { PROJECT_STATUS } from '@/lib/constants'
|
||
import { useTrack } from '@/lib/telemetry/track'
|
||
|
||
const FormSchema = z.object({
|
||
postgresVersionSelection: z.string(),
|
||
})
|
||
|
||
type ResumeProjectButtonProps = Pick<
|
||
ComponentPropsWithoutRef<typeof ButtonTooltip>,
|
||
'className' | 'size' | 'variant'
|
||
> & {
|
||
label?: string
|
||
/** Where the button is rendered, sent with the resume telemetry event */
|
||
source: 'settings_general' | 'project_layout_paused'
|
||
}
|
||
|
||
export const ResumeProjectButton = ({
|
||
className,
|
||
label = 'Resume project',
|
||
size,
|
||
variant = 'default',
|
||
source,
|
||
}: ResumeProjectButtonProps) => {
|
||
const navigate = useNavigate()
|
||
const track = useTrack()
|
||
const { ref } = useParams()
|
||
const { data: project } = useSelectedProjectQuery()
|
||
const { data: selectedOrganization } = useSelectedOrganizationQuery()
|
||
const { setProjectStatus } = useSetProjectStatus()
|
||
|
||
const newProjectInternalOnlyConfiguration = useFlag('newProjectInternalOnlyConfiguration')
|
||
const region = Object.values(AWS_REGIONS).find((x) => x.code === project?.region)
|
||
const orgSlug = selectedOrganization?.slug
|
||
const isFreePlan = selectedOrganization?.plan?.id === 'free'
|
||
|
||
const {
|
||
data: pauseStatus,
|
||
isPending: isPauseStatusPending,
|
||
isSuccess: isPauseStatusSuccess,
|
||
} = useProjectPauseStatusQuery({ ref }, { enabled: project?.status === PROJECT_STATUS.INACTIVE })
|
||
|
||
const isRestoreDisabled = isPauseStatusSuccess && !pauseStatus.can_restore
|
||
|
||
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery(
|
||
{ slug: orgSlug },
|
||
{ enabled: isFreePlan }
|
||
)
|
||
|
||
const hasMembersExceedingFreeTierLimit = (membersExceededLimit ?? []).length > 0
|
||
|
||
const [showConfirmRestore, setShowConfirmRestore] = useState(false)
|
||
const [showFreeProjectLimitWarning, setShowFreeProjectLimitWarning] = useState(false)
|
||
|
||
const { data: orgMembers } = useOrganizationMembersQuery(
|
||
{ slug: orgSlug },
|
||
{ enabled: showFreeProjectLimitWarning }
|
||
)
|
||
const hasMultipleMembers = (orgMembers ?? []).filter((member) => !member.invited_id).length > 1
|
||
const [billingBlockReason, setBillingBlockReason] = useState<string>()
|
||
|
||
const { can: canResumeProject } = useAsyncCheckPermissionsV2(FGA_PERMISSIONS.PROJECT.ADMIN_WRITE)
|
||
|
||
const { mutate: restoreProject, isPending: isRestoring } = useProjectRestoreMutation({
|
||
onSuccess: async (_, variables) => {
|
||
setProjectStatus({ ref: variables.ref, status: PROJECT_STATUS.RESTORING })
|
||
toast.success('Restoring project, project will be ready in a few minutes')
|
||
await navigate({ to: '/project/$ref', params: { ref: variables.ref } })
|
||
},
|
||
onError: (error) => {
|
||
// 402s from restore (unpaid invoices, restrictions, Free Plan limits) are all resolved from billing
|
||
if (error.code === 402) {
|
||
setShowConfirmRestore(false)
|
||
return setBillingBlockReason(error.message)
|
||
}
|
||
toast.error(`Failed to restore project: ${error.message}`)
|
||
},
|
||
})
|
||
|
||
const form = useForm<z.infer<typeof FormSchema>>({
|
||
resolver: zodResolver(FormSchema),
|
||
mode: 'onChange',
|
||
defaultValues: { postgresVersionSelection: '' },
|
||
})
|
||
const lastValidPostgresVersionSelection = useRef('')
|
||
|
||
const onSelectRestore = () => {
|
||
if (project?.status !== PROJECT_STATUS.INACTIVE) {
|
||
return toast.error('Unable to resume: project is not paused')
|
||
}
|
||
|
||
if (isRestoreDisabled) {
|
||
return toast.error('This project can no longer be resumed from the dashboard')
|
||
}
|
||
|
||
if (!canResumeProject) {
|
||
return toast.error('You do not have the required permissions to restore this project')
|
||
}
|
||
|
||
if (hasMembersExceedingFreeTierLimit) {
|
||
return setShowFreeProjectLimitWarning(true)
|
||
}
|
||
|
||
setShowConfirmRestore(true)
|
||
}
|
||
|
||
const onConfirmRestore = async (values: z.infer<typeof FormSchema>) => {
|
||
if (!project) {
|
||
return toast.error('Unable to restore: project is required')
|
||
}
|
||
|
||
track('project_lifecycle_action_submitted', { action: 'resume', source })
|
||
|
||
if (!newProjectInternalOnlyConfiguration) {
|
||
return restoreProject({ ref: project.ref })
|
||
}
|
||
|
||
const postgresVersionDetails = extractPostgresVersionDetails(values.postgresVersionSelection)
|
||
|
||
restoreProject({
|
||
ref: project.ref,
|
||
releaseChannel: postgresVersionDetails.releaseChannel,
|
||
postgresEngine: postgresVersionDetails.postgresEngine,
|
||
})
|
||
}
|
||
|
||
const buttonDisabled =
|
||
project?.status !== PROJECT_STATUS.INACTIVE ||
|
||
project === undefined ||
|
||
isPauseStatusPending ||
|
||
isRestoring ||
|
||
isRestoreDisabled ||
|
||
!canResumeProject
|
||
|
||
const tooltipText = useMemo(() => {
|
||
if (isPauseStatusPending) return 'Checking whether this project can be resumed'
|
||
if (project?.status !== PROJECT_STATUS.INACTIVE) {
|
||
return 'Project must be paused before it can be resumed'
|
||
}
|
||
if (isRestoreDisabled) return 'This project can no longer be resumed from the dashboard'
|
||
if (!canResumeProject) return 'You need additional permissions to resume this project'
|
||
return undefined
|
||
}, [canResumeProject, isPauseStatusPending, isRestoreDisabled, project?.status])
|
||
|
||
return (
|
||
<>
|
||
<ButtonTooltip
|
||
className={className}
|
||
size={size}
|
||
variant={variant}
|
||
disabled={buttonDisabled}
|
||
loading={isRestoring}
|
||
onClick={onSelectRestore}
|
||
tooltip={{
|
||
content: {
|
||
side: 'bottom',
|
||
text: tooltipText,
|
||
},
|
||
}}
|
||
>
|
||
{label}
|
||
</ButtonTooltip>
|
||
|
||
<ConfirmationModal
|
||
visible={showConfirmRestore}
|
||
size="small"
|
||
title="Resume this project"
|
||
onCancel={() => setShowConfirmRestore(false)}
|
||
onConfirm={() => form.handleSubmit(onConfirmRestore)()}
|
||
loading={isRestoring}
|
||
confirmLabel="Resume"
|
||
confirmLabelLoading="Resuming"
|
||
cancelLabel="Cancel"
|
||
>
|
||
<div className={cn(newProjectInternalOnlyConfiguration && 'flex flex-col gap-y-4')}>
|
||
{isFreePlan ? (
|
||
<p className="text-sm">
|
||
Your project’s data will be restored to when it was initially paused.
|
||
</p>
|
||
) : (
|
||
<ResumeProjectCost />
|
||
)}
|
||
<Form {...form}>
|
||
<form onSubmit={form.handleSubmit(onConfirmRestore)}>
|
||
{newProjectInternalOnlyConfiguration && (
|
||
<div className="space-y-2">
|
||
<FormField
|
||
control={form.control}
|
||
name="postgresVersionSelection"
|
||
render={({ field }) => (
|
||
<PostgresVersionSelector
|
||
field={field}
|
||
form={form}
|
||
type="unpause"
|
||
label="Postgres version"
|
||
layout="vertical"
|
||
dbRegion={region?.displayName ?? ''}
|
||
cloudProvider={(project?.cloud_provider ?? 'AWS') as CloudProvider}
|
||
organizationSlug={selectedOrganization?.slug}
|
||
lastValidSelectionRef={lastValidPostgresVersionSelection}
|
||
/>
|
||
)}
|
||
/>
|
||
</div>
|
||
)}
|
||
</form>
|
||
</Form>
|
||
</div>
|
||
</ConfirmationModal>
|
||
|
||
<Dialog
|
||
open={showFreeProjectLimitWarning}
|
||
onOpenChange={() => setShowFreeProjectLimitWarning(false)}
|
||
>
|
||
<DialogContent size="medium" className="gap-0 pb-0" aria-describedby={undefined}>
|
||
<DialogHeader className="border-b">
|
||
<DialogTitle className="leading-normal">Unable to resume project</DialogTitle>
|
||
</DialogHeader>
|
||
<DialogSection className="flex flex-col gap-y-2 text-sm">
|
||
<p className="text-foreground-light">
|
||
Owners and administrators are limited in how many active Free Plan projects they can
|
||
have across all organizations.
|
||
</p>
|
||
<ExceedFreeProjectLimitMembers membersExceededLimit={membersExceededLimit ?? []} />
|
||
<FreeProjectLimitActions
|
||
goal="resume this project"
|
||
hasMultipleMembers={hasMultipleMembers}
|
||
/>
|
||
</DialogSection>
|
||
<DialogFooter>
|
||
<Button type="button" onClick={() => setShowFreeProjectLimitWarning(false)}>
|
||
Understood
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
|
||
<Dialog open={!!billingBlockReason} onOpenChange={() => setBillingBlockReason(undefined)}>
|
||
<DialogContent size="small" aria-describedby={undefined} className="gap-0 pb-0">
|
||
<DialogHeader className="border-b">
|
||
<DialogTitle>Unable to resume project</DialogTitle>
|
||
</DialogHeader>
|
||
<DialogSection className="text-sm text-foreground-light">
|
||
{billingBlockReason}
|
||
</DialogSection>
|
||
<DialogFooter>
|
||
<Button variant="default" onClick={() => setBillingBlockReason(undefined)}>
|
||
Cancel
|
||
</Button>
|
||
<Button asChild variant="primary">
|
||
<Link href={`/org/${orgSlug}/billing`}>Go to billing</Link>
|
||
</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
</>
|
||
)
|
||
}
|