Files
Alaister YoungandAlaister Young 953e508a3e [FE-5110] refactor(studio): replace next/navigation with TanStack (#54041)
Moves the remaining `next/navigation` imports in Studio onto TanStack
Router hooks (and `useParams` from `common`), finishes migrating the
remaining `next/link` and `next/router` usages in the touched
components, and removes the `compat/next/navigation.ts` shim and its
Vite alias. Shared packages (`packages/**`) no longer import
`next/navigation`, so the alias can be dropped now.

**Removed:**

- `apps/studio/compat/next/navigation.ts` and the `'next/navigation'`
entry in `apps/studio/vite.config.ts`
- Global `next/navigation` mock in `apps/studio/tests/vitestSetup.ts`
and the obsolete `apps/studio/tests/lib/route-mock.test.tsx`

**Changed:**

- Replaced `usePathname` (12 files) and `useSearchParams` (3 files) with
`useLocation({ select })` from `@tanstack/react-router`
- Replaced `useRouter` in Storage bucket tables, SQL Editor commands,
and `SignInMfaForm` with `useNavigate` from `@tanstack/react-router`,
and updated `createNavigationHandler` in `lib/navigation.ts` to accept
either `NextRouter` or TanStack's `useNavigate`
- Replaced remaining `next/link` imports in touched components
(`SignInMfaForm`, `Restriction`, `DownloadLogsButton`,
`DownloadResultsButton`, `AuthEmailsLayout`, `AuthProvidersLayout`,
`JWTKeysLayout`, `StorageBucketsLayout`) with TanStack Router's `Link`
- Replaced `useParams` in `CreatePublishableAPIKeyDialog` with
`useParams` from `common` (matching `CreateSecretAPIKeyDialog`)
- Wrapped `CustomWrapper` (`tests/lib/custom-render.tsx`) in a default
TanStack `RouterContextProvider` (with optional `router` / `initialUrl`
overrides) and updated affected component tests to drop their
`next/navigation` mocks

Addresses
[FE-5110](https://linear.app/supabase/issue/FE-5110/replace-the-nextnavigation-shim-with-tanstack-router-hooks)

## To test

1. Check active tab highlighting and navigation across Auth Emails, Auth
Providers, JWT Keys, Storage Buckets, and Editor layouts
2. Verify clicking, Cmd/Ctrl-clicking, middle-clicking, and pressing
Enter on Storage bucket rows (Files, Analytics, Vector) navigates as
before
3. Run "Query a table..." and open SQL snippets from the Command Menu
and confirm `/project/$ref/sql/$id` opens with multi-line SQL preserved
in `?content=`
4. In the MFA sign-in flow, verify the recovery code link and
`forgot-password` completion preserve query params (`returnTo`,
`context=forgot-password`), and Cancel signs out and replaces history
with `/sign-in`
5. Confirm Table Editor sort/filter URL sync persists filters per table
without leaking across table switches

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-11-26 17:18:49 +08:00

208 lines
8.6 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import { AnalyticsBucket as AnalyticsBucketIcon } from 'icons'
import { ChevronRightIcon, SearchIcon } from 'lucide-react'
import { parseAsBoolean, useQueryState } from 'nuqs'
import { useState } from 'react'
import {
Card,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
Tooltip,
TooltipContent,
TooltipTrigger,
} from 'ui'
import { Input } from 'ui-patterns/DataInputs/Input'
import { PageContainer } from 'ui-patterns/PageContainer'
import { PageSection, PageSectionContent, PageSectionTitle } from 'ui-patterns/PageSection'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import { TimestampInfo } from 'ui-patterns/TimestampInfo'
import { EmptyBucketState } from '../EmptyBucketState'
import { CreateBucketButton } from '../NewBucketButton'
import { CreateAnalyticsBucketModal } from './CreateAnalyticsBucketModal'
import { AlertError } from '@/components/ui/AlertError'
import { AlphaNotice } from '@/components/ui/AlphaNotice'
import { TableRowNoResults } from '@/components/ui/TableRowNoResults'
import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'
import { useAnalyticsBucketsQuery } from '@/data/storage/analytics-buckets-query'
import { createNavigationHandler } from '@/lib/navigation'
export const AnalyticsBuckets = () => {
const { ref } = useParams()
const navigate = useNavigate()
const [filterString, setFilterString] = useState('')
const [visible, setVisible] = useQueryState(
'new',
parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })
)
const { data: config } = useProjectStorageConfigQuery({ projectRef: ref })
const maxAnalyticsBuckets = config?.features.icebergCatalog.maxCatalogs ?? 2
const {
data: buckets = [],
error: bucketsError,
isError: isErrorBuckets,
isPending: isLoadingBuckets,
isSuccess: isSuccessBuckets,
} = useAnalyticsBucketsQuery({
projectRef: ref,
})
const analyticsBuckets = buckets.filter((bucket) =>
filterString.length === 0
? true
: bucket.name.toLowerCase().includes(filterString.toLowerCase())
)
const hasNoBuckets = buckets.length === 0
return (
<>
<PageContainer>
<PageSection>
<PageSectionContent className="flex flex-col gap-y-8">
<AlphaNotice
entity="Analytics buckets"
feedbackUrl="https://github.com/orgs/supabase/discussions/40116"
/>
{isLoadingBuckets && <GenericSkeletonLoader />}
{isErrorBuckets && (
<AlertError error={bucketsError} subject="Failed to retrieve analytics buckets" />
)}
{isSuccessBuckets && (
<>
{hasNoBuckets ? (
<EmptyBucketState
bucketType="analytics"
onCreateBucket={() => setVisible(true)}
/>
) : (
<div className="flex flex-col gap-y-4">
<div className="flex flex-row items-center gap-x-2">
<PageSectionTitle>Buckets</PageSectionTitle>
{analyticsBuckets.length > 0 && (
<Tooltip>
<TooltipTrigger>
<span className="bg-surface-200 rounded-full px-2 py-1 leading-none text-xs text-foreground-lighter tracking-widest">
{analyticsBuckets.length}/{maxAnalyticsBuckets}
</span>
</TooltipTrigger>
<TooltipContent side="bottom" className="w-72 text-center">
Each project can only have up to {maxAnalyticsBuckets} buckets while
analytics buckets are in alpha{' '}
</TooltipContent>
</Tooltip>
)}
</div>
<div className="flex grow justify-between gap-x-2 items-center">
<Input
size="tiny"
className="grow lg:grow-0 w-52"
placeholder="Search for a bucket"
value={filterString}
onChange={(e) => setFilterString(e.target.value)}
icon={<SearchIcon />}
/>
<CreateBucketButton onClick={() => setVisible(true)} />
</div>
{isLoadingBuckets ? (
<GenericSkeletonLoader />
) : (
<Card>
<Table>
<TableHeader>
<TableRow>
{analyticsBuckets.length > 0 && (
<TableHead className="w-2 pr-1">
<span className="sr-only">Icon</span>
</TableHead>
)}
<TableHead>Name</TableHead>
<TableHead>Created at</TableHead>
<TableHead>
<span className="sr-only">Actions</span>
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{analyticsBuckets.length === 0 && filterString.length > 0 && (
<TableRowNoResults
className="[&>td]:hover:bg-inherit"
colSpan={3}
search={filterString}
/>
)}
{analyticsBuckets.map((bucket) => {
const handleBucketNavigation = createNavigationHandler(
`/project/${ref}/storage/analytics/buckets/${encodeURIComponent(bucket.name)}`,
navigate
)
return (
<TableRow
key={bucket.name}
className="relative cursor-pointer h-16 focus-inset"
onClick={handleBucketNavigation}
onAuxClick={handleBucketNavigation}
onKeyDown={handleBucketNavigation}
tabIndex={0}
>
<TableCell className="w-2 pr-1">
<AnalyticsBucketIcon
size={16}
className="text-foreground-muted"
/>
</TableCell>
<TableCell>
<p className="whitespace-nowrap max-w-[512px] truncate">
{bucket.name}
</p>
</TableCell>
<TableCell>
<p className="text-foreground-light">
<TimestampInfo
utcTimestamp={bucket.created_at}
className="text-sm text-foreground-light"
/>
</p>
</TableCell>
<TableCell>
<div className="flex justify-end items-center h-full">
<ChevronRightIcon
size={14}
className="text-foreground-muted/60"
/>
</div>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Card>
)}
</div>
)}
</>
)}
</PageSectionContent>
</PageSection>
</PageContainer>
<CreateAnalyticsBucketModal open={visible} onOpenChange={setVisible} />
</>
)
}