Files
supabase/apps/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.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

196 lines
6.0 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { DeleteOrganizationButtonListAck } from './DeleteOrganizationButton.ListAck'
import { DeleteOrganizationButtonSingleAck } from './DeleteOrganizationButton.SingleAck'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
import { TextConfirmModal } from '@/components/ui/TextConfirmModalWrapper'
import { useOrganizationDeleteMutation } from '@/data/organizations/organization-delete-mutation'
import { useOrgProjectsInfiniteQuery } from '@/data/projects/org-projects-infinite-query'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
const MAX_PROJECT_ACKNOWLEDGEMENTS = 10
export const DeleteOrganizationButton = () => {
const navigate = useNavigate()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { slug: orgSlug, name: orgName } = selectedOrganization ?? {}
const [checkedProjects, setCheckedProjects] = useState<Record<string, boolean>>({})
const [acknowledgedAll, setAcknowledgedAll] = useState(false)
const [isOpen, setIsOpen] = useState(false)
useEffect(() => {
setCheckedProjects({})
setAcknowledgedAll(false)
}, [orgSlug])
const {
data: projectsData,
isLoading,
isFetching,
isError,
} = useOrgProjectsInfiniteQuery(
{ slug: orgSlug },
{
enabled: isOpen,
refetchOnMount: 'always',
}
)
// When an organization slug is present but the projects query has not yet
// produced any data (and hasn't errored), treat this as a "pending" state
// rather than as "no projects". This avoids interpreting lack of data as
// an empty list, which could allow deletion to proceed without any project
// acknowledgement.
const isProjectsDataPending = orgSlug !== undefined && projectsData === undefined && !isError
const projects =
!isProjectsDataPending && projectsData !== undefined
? projectsData.pages.flatMap((page) => page.projects ?? [])
: undefined
const shouldRenderChecklist =
projects !== undefined && projects.length > 0 && projects.length <= MAX_PROJECT_ACKNOWLEDGEMENTS
const exceedsLimit = projects !== undefined && projects.length > MAX_PROJECT_ACKNOWLEDGEMENTS
const toggleProject = (ref: string, checked?: boolean | 'indeterminate') => {
setCheckedProjects((prev) => ({
...prev,
[ref]: checked === undefined ? !prev[ref] : checked === true,
}))
}
const isDeletionConfirmed = () => {
// While project data is pending or unavailable, treat deletion as not confirmed
if (!projects) return false
if (projects.length === 0) return true
if (shouldRenderChecklist) {
return projects.every((p) => checkedProjects[p.ref])
}
if (exceedsLimit) {
return acknowledgedAll
}
return false
}
const allChecked = isDeletionConfirmed()
const { setLastVisitedOrganization } = useLastVisitedOrganization()
const { can: canDeleteOrganization } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.ORGANIZATION.ADMIN_WRITE
)
const { mutate: deleteOrganization, isPending: isDeleting } = useOrganizationDeleteMutation({
onSuccess: () => {
toast.success(`Successfully deleted ${orgName}`)
setLastVisitedOrganization('')
navigate({ to: '/organizations' })
},
})
const onConfirmDelete = () => {
if (!canDeleteOrganization) {
toast.error('You do not have permission to delete this organization')
return
}
if (!orgSlug) {
console.error('Org slug is required')
return
}
if (isLoading || isFetching || isProjectsDataPending) {
toast.error('Projects are still loading, please wait')
return
}
if (isError) {
toast.error('Failed to load projects')
return
}
if (!allChecked) {
toast.error('Please acknowledge all projects before deleting the organization')
return
}
deleteOrganization({ slug: orgSlug })
}
return (
<>
<ButtonTooltip
variant="danger"
disabled={!canDeleteOrganization || !orgSlug}
loading={!orgSlug}
onClick={() => {
setCheckedProjects({})
setAcknowledgedAll(false)
setIsOpen(true)
}}
tooltip={{
content: {
side: 'bottom',
text: !canDeleteOrganization
? 'You need additional permissions to delete this organization'
: undefined,
},
}}
>
Delete organization
</ButtonTooltip>
<TextConfirmModal
visible={isOpen}
size="small"
variant="destructive"
title="Delete organization"
loading={isDeleting}
confirmString={orgSlug ?? ''}
confirmPlaceholder="Enter the string above"
confirmLabel="I understand, delete this organization"
onConfirm={onConfirmDelete}
onCancel={() => setIsOpen(false)}
>
{/* ≤ MAX → checklist */}
{shouldRenderChecklist && (
<DeleteOrganizationButtonListAck
projects={projects}
checkedProjects={checkedProjects}
toggleProject={toggleProject}
/>
)}
{/* > MAX → single confirmation */}
{exceedsLimit && (
<DeleteOrganizationButtonSingleAck
acknowledgedAll={acknowledgedAll}
setAcknowledgedAll={setAcknowledgedAll}
max={MAX_PROJECT_ACKNOWLEDGEMENTS}
/>
)}
{/* Final warning */}
<p
className={`text-sm text-foreground-lighter ${(projects?.length ?? 0) > 0 ? 'mt-4' : ''}`}
>
This action <span className="text-foreground">cannot</span> be undone. This will
permanently delete the <span className="text-foreground">{orgName}</span> organization and
remove all of its projects.
</p>
</TextConfirmModal>
</>
)
}