Files
supabase/apps/studio/components/interfaces/ProjectCreation/ProjectCreationFooter.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

261 lines
10 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useFlag } from 'common'
import { ClockIcon } from 'lucide-react'
import { useEffect, useState } from 'react'
import { UseFormReturn } from 'react-hook-form'
import {
Badge,
Button,
cn,
PopoverSeparator,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { CreateProjectForm } from './ProjectCreation.schema'
import { instanceLabel, monthlyInstancePrice } from './ProjectCreation.utils'
import { InlineLink } from '@/components/ui/InlineLink'
import { OrgProject } from '@/data/projects/org-projects-infinite-query'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { DOCS_URL } from '@/lib/constants'
/** `close` = close the popup (Vercel interstitial); `studio` = navigate into Studio. */
export type ProjectCreationCancelAction = 'studio' | 'close' | 'hidden'
interface ProjectCreationFooterProps {
form: UseFormReturn<CreateProjectForm>
canCreateProject: boolean
instanceSize?: string
highAvailability?: boolean
organizationProjects: OrgProject[]
isCreatingNewProject: boolean
isSuccessNewProject: boolean
isLoadingAvailableRegions?: boolean
cancelAction?: ProjectCreationCancelAction
}
export const ProjectCreationFooter = ({
form,
canCreateProject,
instanceSize,
highAvailability = false,
organizationProjects,
isCreatingNewProject,
isSuccessNewProject,
isLoadingAvailableRegions = false,
cancelAction = 'studio',
}: ProjectCreationFooterProps) => {
const navigate = useNavigate()
const { data: currentOrg } = useSelectedOrganizationQuery()
const isFreePlan = currentOrg?.plan?.id === 'free'
const { lastVisitedOrganization } = useLastVisitedOrganization()
const [showCloseWindowHint, setShowCloseWindowHint] = useState(false)
const projectCreationDisabled = useFlag('disableProjectCreationAndUpdate')
const availableComputeCredits = organizationProjects.length === 0 ? 10 : 0
const additionalMonthlySpend = isFreePlan
? 0
: monthlyInstancePrice(instanceSize) - availableComputeCredits
const showAdditionalCosts =
!isFreePlan && !projectCreationDisabled && canCreateProject && additionalMonthlySpend > 0
// High availability is free during Alpha, so the new project costs $0 and is excluded from
// the totals below — the tooltip table still shows the usual compute price struck through.
const displayedAdditionalMonthlySpend = highAvailability ? 0 : additionalMonthlySpend
const newProjectComputeCosts = highAvailability ? 0 : monthlyInstancePrice(instanceSize)
// [kevin] This will eventually all be provided by a new API endpoint to preview and validate project creation, this is just for kaizen now
// Clamped since a free HA project can leave the compute credits larger than the costs
const monthlyComputeCosts = Math.max(
0,
// current project costs
organizationProjects.reduce((prev, acc) => {
const primaryDatabase = acc.databases.find((db) => db.identifier === acc.ref)
const cost = !!primaryDatabase ? monthlyInstancePrice(primaryDatabase.infra_compute_size) : 0
return prev + cost
}, 0) +
// selected compute size
newProjectComputeCosts -
// compute credits
10
)
const onCancel = () => {
if (cancelAction === 'close') {
window.close()
return
}
if (!!lastVisitedOrganization) {
navigate({ to: '/org/$slug', params: { slug: lastVisitedOrganization } })
} else {
navigate({ to: '/organizations' })
}
}
useEffect(() => {
// Browsers only allow closing windows that were opened by script (i.e. have a live `opener`).
// Detect this upfront so we don't need to attempt-and-check after the user clicks cancel.
if (cancelAction === 'close' && !window.opener) setShowCloseWindowHint(true)
}, [cancelAction])
return (
<div key="panel-footer" className="grid grid-cols-12 w-full gap-4 items-center py-3">
{showAdditionalCosts && (
<div className="col-span-7">
<div className="flex items-baseline gap-2">
<span className="text-base text-foreground">Compute cost</span>
<span
role="status"
className="text-base font-mono font-medium text-warning"
translate="no"
>
+${displayedAdditionalMonthlySpend}/mo
</span>
</div>
<div className="mt-1 flex items-center gap-1.5 text-sm text-foreground-light">
<ClockIcon size={14} className="shrink-0" aria-hidden="true" />
<Tooltip>
<TooltipTrigger className="text-left underline decoration-dotted underline-offset-4">
Billed hourly, busy or idle
</TooltipTrigger>
<TooltipContent side="top" align="start" className="max-w-[450px] p-0">
<div className="p-4 text-sm text-foreground-light space-y-1">
<p>
Each project includes a dedicated Postgres instance running on its own server.
You are charged for the{' '}
<InlineLink href={`${DOCS_URL}/guides/platform/billing-on-supabase`}>
Compute resource
</InlineLink>{' '}
of that server, independent of your database usage.
</p>
{highAvailability && (
<p>High availability projects are free during Alpha for up to 2 projects.</p>
)}
{monthlyComputeCosts > 0 && (
<p>Compute costs are applied on top of your subscription plan costs.</p>
)}
</div>
<Table className="mt-2">
<TableHeader className="[&_th]:h-7">
<TableRow className="py-2">
<TableHead className="w-[170px]">Project</TableHead>
<TableHead>Compute Size</TableHead>
<TableHead className="text-right">Monthly Costs</TableHead>
</TableRow>
</TableHeader>
<TableBody className="[&_td]:py-2">
{organizationProjects.map((project) => {
const primaryDb = project.databases.find(
(db) => db.identifier === project.ref
)
return (
<TableRow key={project.ref} className="text-foreground-light">
<TableCell className="w-[170px] truncate">{project.name}</TableCell>
<TableCell className="text-center">
{instanceLabel(primaryDb?.infra_compute_size)}
</TableCell>
<TableCell className="text-right">
${monthlyInstancePrice(primaryDb?.infra_compute_size)}
</TableCell>
</TableRow>
)
})}
<TableRow>
<TableCell className="w-[170px] flex gap-2">
<span className="truncate">
{form.getValues('projectName') || 'New project'}
</span>
<Badge variant="success">New</Badge>
</TableCell>
<TableCell className="text-center">{instanceLabel(instanceSize)}</TableCell>
<TableCell className="text-right">
<span className={cn(highAvailability && 'line-through')}>
${monthlyInstancePrice(instanceSize)}
</span>
{highAvailability && (
<p className="text-xs text-foreground-lighter">Free during Alpha</p>
)}
</TableCell>
</TableRow>
</TableBody>
</Table>
<PopoverSeparator />
<Table>
<TableHeader className="[&_th]:h-7">
<TableRow>
<TableHead colSpan={2}>Compute Credits</TableHead>
<TableHead colSpan={1} className="text-right">
-$10
</TableHead>
</TableRow>
</TableHeader>
<TableBody className="[&_td]:py-2">
<TableRow className="text-foreground">
<TableCell colSpan={2}>
Total Monthly Compute Costs
{/**
* API currently doesnt output replica information on the projects list endpoint. Until then, we cannot correctly calculate the costs including RRs.
* Will be adjusted in the future [kevin]
*/}
{organizationProjects.length > 0 && (
<p className="text-xs text-foreground-lighter">Excluding Read replicas</p>
)}
</TableCell>
<TableCell colSpan={1} className="text-right">
${monthlyComputeCosts}
</TableCell>
</TableRow>
</TableBody>
</Table>
</TooltipContent>
</Tooltip>
</div>
</div>
)}
<div
className={cn(
showAdditionalCosts ? 'col-span-5' : 'col-span-12',
'flex items-center gap-x-2 ml-auto'
)}
>
{cancelAction === 'hidden' ? null : showCloseWindowHint ? (
<p role="status" aria-live="polite" className="text-xs text-foreground-muted mr-3">
Close window to cancel
</p>
) : (
<Button
type="button"
disabled={isCreatingNewProject || isSuccessNewProject}
onClick={onCancel}
>
Cancel
</Button>
)}
<Button
variant="primary"
type="submit"
loading={isCreatingNewProject || isSuccessNewProject}
disabled={!canCreateProject || isLoadingAvailableRegions}
>
Create new project
</Button>
</div>
</div>
)
}