Files
supabase/apps/studio/components/interfaces/Settings/General/DeleteProjectPanel/DeleteProjectModal.tsx
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

228 lines
8.7 KiB
TypeScript

import { useNavigate, useRouter } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { Card, CardContent, cn, TextArea } from 'ui'
import { CollapsibleCardSection } from 'ui-patterns/CollapsibleCardSection'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { CANCELLATION_REASONS } from '@/components/interfaces/Billing/Billing.constants'
import { LogicalBackupCliInstructions } from '@/components/layouts/ProjectLayout/LogicalBackupCliInstructions'
import { InlineLink } from '@/components/ui/InlineLink'
import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'
import { useSendDowngradeFeedbackMutation } from '@/data/feedback/exit-survey-send'
import type { OrgProject } from '@/data/projects/org-projects-infinite-query'
import { useProjectDeleteMutation } from '@/data/projects/project-delete-mutation'
import { useOrgSubscriptionQuery } from '@/data/subscriptions/org-subscription-query'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { DOCS_URL } from '@/lib/constants'
import type { Organization } from '@/types'
export const DeleteProjectModal = ({
visible,
onClose,
project: projectProp,
organization: organizationProp,
}: {
visible: boolean
onClose: () => void
project?: OrgProject
organization?: Organization
}) => {
const navigate = useNavigate()
const router = useRouter()
const { data: projectFromQuery } = useSelectedProjectQuery()
const { data: organizationFromQuery } = useSelectedOrganizationQuery()
// Use props if provided, otherwise fall back to hooks
const project = projectProp || projectFromQuery
const organization = organizationProp || organizationFromQuery
const { lastVisitedOrganization } = useLastVisitedOrganization()
const projectRef = project?.ref
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
const projectPlan = subscription?.plan?.id ?? 'free'
const shouldShowExitSurvey = ['pro', 'team'].includes(projectPlan)
const [message, setMessage] = useState<string>('')
const [selectedReason, setSelectedReason] = useState<string[]>([])
// Single select for cancellation reason
const onSelectCancellationReason = (reason: string) => {
setSelectedReason([reason])
}
// Helper to get label for selected reason
const getReasonLabel = (reason: string | undefined) => {
const found = CANCELLATION_REASONS.find((r) => r.value === reason)
return found?.label || 'What can we improve on?'
}
const textareaLabel = getReasonLabel(selectedReason[0])
const [shuffledReasons] = useState(() => [
...CANCELLATION_REASONS.sort(() => Math.random() - 0.5),
{ value: 'None of the above' },
])
const { mutate: deleteProject, isPending: isDeleting } = useProjectDeleteMutation({
onSuccess: async () => {
toast.success(`Successfully deleted ${project?.name}`)
// Only redirect if still viewing the deleted project. The modal may have unmounted since
// the deletion started, so read the live location rather than one from the last render.
if (router.state.location.pathname.startsWith(`/project/${projectRef}`)) {
if (lastVisitedOrganization) {
navigate({ to: '/org/$slug', params: { slug: lastVisitedOrganization } })
} else {
navigate({ to: '/organizations' })
}
}
},
})
const { mutateAsync: sendExitSurvey, isPending: isSending } = useSendDowngradeFeedbackMutation({
// The user should not get a toast saying "submitting survey failed"
onError: () => {},
})
const isSubmitting = isDeleting || isSending
async function handleDeleteProject() {
if (project === undefined) return
if (shouldShowExitSurvey && selectedReason.length === 0) {
return toast.error('Please select a reason for deleting your project')
}
if (shouldShowExitSurvey) {
// The survey must be sent before the delete: deleting the project removes its permissions,
// so the survey endpoint would reject the request afterwards.
try {
await sendExitSurvey({
orgSlug: organization?.slug,
projectRef: project.ref,
message,
reasons: selectedReason.reduce((a, b) => `${a}- ${b}\n`, ''),
exitAction: 'delete',
})
} catch {
// A failed survey should never block the user from deleting their project
}
}
deleteProject({ projectRef: project.ref, organizationSlug: organization?.slug })
}
useEffect(() => {
if (visible) {
setSelectedReason([])
setMessage('')
}
}, [visible])
return (
<TextConfirmModal
visible={visible}
loading={isSubmitting}
size={shouldShowExitSurvey ? 'xlarge' : 'medium'}
title={`Confirm deletion of ${project?.name}`}
variant="destructive"
alert={{
title: shouldShowExitSurvey
? `This will permanently delete the ${project?.name}`
: 'This action cannot be undone.',
description: (
<>
{shouldShowExitSurvey
? 'All project data will be lost, and cannot be undone. '
: `This will permanently delete the ${project?.name} project and all of its data. `}
<span>Read the</span>{' '}
<InlineLink href={`${DOCS_URL}/guides/platform/delete-project`}>
documentation
</InlineLink>{' '}
<span>for prerequisites, implications, and recovery information.</span>
</>
),
}}
confirmPlaceholder="Type the project name in here"
confirmString={project?.name || ''}
confirmLabel="I understand, delete this project"
onConfirm={handleDeleteProject}
onCancel={() => {
if (!isSubmitting) onClose()
}}
>
<div className="space-y-6">
<Card>
<CardContent
className={cn(
'[&>div>button]:tracking-normal',
'[&>div>button]:text-foreground [&>div>button]:hover:text-foreground',
'[&>div>button]:data-open:text-foreground [&>div>button]:text-sm'
)}
>
<CollapsibleCardSection title="Back up your database with the Supabase CLI">
<LogicalBackupCliInstructions enabled={visible} showResetPassword={false} />
</CollapsibleCardSection>
</CardContent>
</Card>
{/*
[Joshen] This is basically ExitSurvey.tsx, ideally we have one shared component but the one
in ExitSurvey has a Form wrapped around it already. Will probably need some effort to refactor
but leaving that for the future.
*/}
{shouldShowExitSurvey && (
<div className="flex flex-col gap-y-6">
<FormItemLayout
isReactForm={false}
label="What made you decide to delete your project?"
>
<div className="flex flex-wrap gap-2" data-toggle="buttons">
{shuffledReasons.map((option) => {
const active = selectedReason[0] === option.value
return (
<label
key={option.value}
className={[
'flex cursor-pointer items-center space-x-2 rounded-md py-1',
'pl-2 pr-3 text-center text-sm shadow-xs transition-all duration-100',
`${
active
? ` bg-foreground text-background opacity-100 hover:bg-foreground/75`
: ` bg-border-strong text-foreground opacity-50 hover:opacity-75`
}`,
].join(' ')}
>
<input
aria-label="reasons"
type="radio"
name="options"
value={option.value}
className="hidden"
checked={active}
onChange={() => onSelectCancellationReason(option.value)}
/>
<div>{option.value}</div>
</label>
)
})}
</div>
</FormItemLayout>
<FormItemLayout isReactForm={false} label={textareaLabel}>
<TextArea
autoFocus
name="message"
rows={3}
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
</FormItemLayout>
</div>
)}
</div>
</TextConfirmModal>
)
}