Files
supabase/apps/studio/components/ui/org-selector.tsx
Alaister YoungandAlaister Young 0a4cec0464 [FE-5108] (part 1) refactor(studio): migrate core UI & prefetchers off next/link (#54304)
Part 1 of a 6-PR stack migrating all `next/link` imports in
`apps/studio` onto TanStack Router's `Link` (or plain `<a>` for known
external URLs) and removing `compat/next/link.tsx`.

| Part | PR | Scope |
| --- | --- | --- |
| **1** | **#54304 ← this PR** |
**`data/prefetchers/PrefetchableLink.tsx` and `components/ui/**`** |
| 2 | #54305 | `components/layouts/**` and top-level shell components |
| 3 | #54306 | Database, TableGridEditor, Storage, SQLEditor,
BranchManagement, Branching, Functions, Realtime |
| 4 | #54307 | Integrations, Settings, Observability, LogDrains, Issues,
Linter, Reports, QueryPerformance, QuerySources, ConfigDrift,
DiskManagement, Compute |
| 5 | #54308 | Remaining `components/interfaces/**` (Org, Billing, Auth,
Support, Home, SignIn, ConnectSheet, etc.) |
| 6 | #54309 | Remove `compat/next/link.tsx` shim, Vite alias, and
update basePath tests/docs |

Migrates `data/prefetchers/PrefetchableLink.tsx` and all shared
`components/ui/**` components off `next/link`.

**Added:**

- `apps/studio/components/ui/DynamicLink.tsx` (with unit tests) — shared
`forwardRef` link wrapper for dynamic URL strings that runs
`splitInternalUrl` and renders a plain `<a>` for external URLs (or
same-origin URLs outside the app's `basePath`) vs TanStack `<Link>` for
internal paths

**Changed:**

- Replaced `next/link` in
`apps/studio/data/prefetchers/PrefetchableLink.tsx` and all 30 importing
components under `apps/studio/components/ui/**` (`InlineLink`,
`CardButton`, `CommandItemLink`, `ObservabilityLink`, `ProductMenuItem`,
`ResourceItem`, `UpgradePlanButton`, `ToggleSpendCapButton`, banners, AI
assistant panel links, etc.)
- Used typed `<Link to="..." params={...} search={...} hash="..." />`
for known internal routes, `<DynamicLink href={...} />` for
dynamic/untyped URL strings (whether internal with query/hash or
external), and plain `<a>` for known external links
- Updated `apps/studio/routes/index.tsx` `validateSearch` return type to
`{ next?: string }` so `<Link to="/">` compiles without requiring
`search={{ next: undefined }}`
- Updated
`hooks/misc/__tests__/useTableEditorFiltersSort.navigation.test.tsx`,
`PolicyTableRow.utils.test.ts`, `SupportAssistantSuccessCard.test.tsx`,
and `useOrganizationRestrictions.test.tsx` to render inside a TanStack
Router context (`customRender` / `RouterContextProvider`)

Addresses
[FE-5108](https://linear.app/supabase/issue/FE-5108/replace-the-nextlink-shim-with-tanstack-link)

## To test

- [ ] Click internal and external `InlineLink`, `CardButton`,
`ProductMenuItem`, and `PrefetchableLink` targets and verify client-side
navigation vs external anchors
- [ ] Verify banner links (upgrade, resource exhaustion, queue
operations) preserve query params and hashes
- [ ] Confirm Studio typecheck, lint, and unit tests pass

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 16:23:48 +08:00

190 lines
6.5 KiB
TypeScript

import { Link } from '@tanstack/react-router'
import { ChevronDownIcon } from 'lucide-react'
import { parseAsString, useQueryState } from 'nuqs'
import { useMemo, useState } from 'react'
import { Badge, Button, Card, CardHeader, CardTitle, Input } from 'ui'
import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
import { ButtonTooltip } from './ButtonTooltip'
import { useFreeProjectLimitCheckQuery } from '@/data/organizations/free-project-limit-check-query'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { searchParamsToRecord } from '@/lib/router-search-params'
import type { Organization } from '@/types'
export interface ProjectClaimChooseOrgProps {
onSelect: (orgSlug: string) => void
maxOrgsToShow?: number
canCreateNewOrg: boolean
}
const OrganizationCard = ({
org,
onSelect,
}: {
org: Organization
onSelect: (orgSlug: string) => void
}) => {
const isFreePlan = org.plan?.id === 'free'
const { data: membersExceededLimit, isSuccess } = useFreeProjectLimitCheckQuery(
{ slug: org.slug },
{ enabled: isFreePlan }
)
const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0
const freePlanWithExceedingLimits = isFreePlan && hasMembersExceedingFreeTierLimit
return (
<Card
key={org.id}
className="hover:bg-surface-200 rounded-none first:rounded-t-lg last:rounded-b-lg -mb-px"
>
<CardHeader className="flex flex-row justify-between border-none space-y-0 space-x-2">
<CardTitle className="flex items-center gap-2 min-w-0 flex-1">
<span className="truncate min-w-0" title={org.name}>
{org.name}
</span>
<Badge className="shrink-0">{org.plan?.name}</Badge>
</CardTitle>
<ButtonTooltip
tooltip={{
content: {
text:
isSuccess && freePlanWithExceedingLimits ? (
<div className="flex flex-col gap-y-2 w-96 p-2">
<p className="leading-normal">
Owners and administrators are limited in how many active Free Plan projects
they can have across all organizations. Members over the limit:
</p>
<ul className="pl-6 list-disc">
{membersExceededLimit?.map((member, idx: number) => (
<li key={`member-${idx}`}>
<span>{`${member.primary_email} (Limit: ${member.free_project_limit} free projects)`}</span>
<ul className="text-foreground-light list-disc pl-4">
{member.free_plan_organizations.map((org) => (
<li key={org.slug || org.organization_name}>
{org.organization_name}:{' '}
{org.projects.map((x) => x.name).join(', ')}
</li>
))}
</ul>
</li>
))}
</ul>
<p className="leading-normal">
They will need to delete, pause, or upgrade one or more of these projects
before you can create a free project within this organization.
</p>
</div>
) : undefined,
},
}}
size="small"
className="shrink-0"
onClick={() => onSelect(org.slug)}
disabled={isSuccess && freePlanWithExceedingLimits}
>
Choose
</ButtonTooltip>
</CardHeader>
</Card>
)
}
export function OrganizationSelector({
onSelect,
maxOrgsToShow = 5,
canCreateNewOrg,
}: ProjectClaimChooseOrgProps) {
const {
data: organizations = [],
isPending: isLoadingOrgs,
isSuccess: isSuccessOrgs,
isError: isErrorOrgs,
} = useOrganizationsQuery()
const [search, setSearch] = useQueryState(
'org',
parseAsString.withDefault('').withOptions({ clearOnDefault: true })
)
const [showAll, setShowAll] = useState(false)
const filteredOrgs = useMemo(() => {
if (!search) {
return showAll ? organizations : organizations.slice(0, maxOrgsToShow)
}
return organizations.filter((org) => org.name.toLowerCase().includes(search.toLowerCase()))
}, [organizations, search, showAll, maxOrgsToShow])
const searchParams = new URLSearchParams(location.search)
let pathname = location.pathname
const basePath = process.env.NEXT_PUBLIC_BASE_PATH
if (basePath) {
pathname = pathname.replace(basePath, '')
}
searchParams.set('returnTo', pathname)
const onSelectOrg = (orgSlug: string) => {
onSelect(orgSlug)
setSearch('')
}
return (
<div className="w-full flex flex-col gap-y-4">
{isLoadingOrgs ? (
<ShimmeringLoader />
) : isErrorOrgs ? (
<div>Error</div>
) : isSuccessOrgs && organizations.length === 0 ? (
<span className="text-sm text-foreground-light">
It seems you don't have any organizations yet.
</span>
) : (
<>
<Input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Search..."
/>
<div>
{filteredOrgs.length === 0 && (
<div className="text-center text-foreground-light py-6">No organizations found.</div>
)}
{filteredOrgs.map((org) => (
<OrganizationCard key={org.id} org={org} onSelect={onSelectOrg} />
))}
{organizations.length > maxOrgsToShow && !showAll && !search && (
<div className="flex justify-center py-2">
<Button
icon={<ChevronDownIcon className="w-4 h-4" />}
size="tiny"
onClick={() => {
setSearch('')
setShowAll(true)
}}
>
Show all organizations
</Button>
</div>
)}
</div>
</>
)}
{canCreateNewOrg && (
<Card className="flex items-center justify-between border-dashed pr-6">
<CardHeader className="border-none">
<CardTitle>Need a new organization?</CardTitle>
</CardHeader>
<Button size="small" className="" asChild>
<Link to="/new" search={searchParamsToRecord(searchParams)}>
New Organization
</Link>
</Button>
</Card>
)}
</div>
)
}