Files
supabase/apps/studio/components/interfaces/Database/Policies/Policies.tsx
Alaister YoungandAlaister Young e0635f2f38 [FE-5108] (part 3) refactor(studio): migrate database, editors & storage off next/link (#54306)
Part 3 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 | `data/prefetchers/PrefetchableLink.tsx` and
`components/ui/**` |
| 2 | #54305 | `components/layouts/**` and top-level shell components |
| **3** | **#54306 ← this PR** | **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
`components/interfaces/{Database,TableGridEditor,Storage,SQLEditor,BranchManagement,Branching,Functions,Realtime}/`
off `next/link`.

**Changed:**

- Replaced `next/link` across all 60 importing files in Database,
TableGridEditor, Storage, SQLEditor, BranchManagement, Branching,
Functions, and Realtime interfaces
- Updated legacy permanent-redirect hrefs (`/reports` →
`/observability`, `/database/schema` → `/database/schemas`) to their
canonical TanStack routes
- Dropped legacy `passHref` in `GridHeaderActions.tsx`, removed
duplicate `RouterLink` alias in `ChooseFunctionForm.tsx`, and removed
`vi.mock('next/link', ...)` in `ReplicationPipelineLayout.test.tsx`

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

## To test

- [ ] Check Table Editor, SQL Editor, Database (tables, policies,
functions, triggers, replication, backups), Storage
(files/analytics/vector buckets), Edge Functions, Branching, and
Realtime links
- [ ] Verify SQL Editor and Table Editor links with query parameters
(`schema`, `content`, `search`) do not double-encode values

---------

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

230 lines
7.3 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Link } from '@tanstack/react-router'
import { useParams } from 'common'
import { isEmpty } from 'lodash'
import { useCallback, useState } from 'react'
import { toast } from 'sonner'
import { Button, Card, CardContent } from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { usePoliciesData } from './PoliciesDataContext'
import {
PolicyTableRow,
PolicyTableRowProps,
} from '@/components/interfaces/Database/Policies/PolicyTableRow'
import type { Policy } from '@/components/interfaces/Database/Policies/PolicyTableRow/PolicyTableRow.utils'
import { ProtectedSchemaWarning } from '@/components/interfaces/Database/ProtectedSchemaWarning'
import { RLSToggleDialog } from '@/components/interfaces/Database/RLSToggleDialog'
import { InlineLink } from '@/components/ui/InlineLink'
import { NoSearchResults } from '@/components/ui/NoSearchResults'
import { useDatabasePolicyDeleteMutation } from '@/data/database-policies/database-policy-delete-mutation'
import { useTableUpdateMutation } from '@/data/tables/table-update-mutation'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
interface PoliciesProps {
search?: string
schema: string
tables: PolicyTableRowProps['table'][]
hasTables: boolean
isLocked: boolean
visibleTableIds: Set<number>
onSelectCreatePolicy: (table: string) => void
onSelectEditPolicy: (policy: Policy) => void
onResetSearch?: () => void
}
export const Policies = ({
search,
schema,
tables,
hasTables,
isLocked,
visibleTableIds,
onSelectCreatePolicy,
onSelectEditPolicy: onSelectEditPolicyAI,
onResetSearch,
}: PoliciesProps) => {
const { ref } = useParams()
const { data: project } = useSelectedProjectQuery()
const { exposedSchemas } = usePoliciesData()
const isSchemaExposedAPI = exposedSchemas.has(schema)
const [selectedTableToToggleRLS, setSelectedTableToToggleRLS] = useState<{
id: number
schema: string
name: string
rls_enabled: boolean
}>()
const [selectedPolicyToDelete, setSelectedPolicyToDelete] = useState<any>({})
const { mutateAsync: updateTable, isPending: isUpdatingTable } = useTableUpdateMutation({
onError: (error) => {
toast.error(`Failed to toggle RLS: ${error.message}`)
},
})
const { mutate: deleteDatabasePolicy, isPending: isDeletingPolicy } =
useDatabasePolicyDeleteMutation({
onSuccess: () => {
toast.success('Successfully deleted policy!')
},
onSettled: () => {
closeConfirmModal()
},
})
const closeConfirmModal = useCallback(() => {
setSelectedPolicyToDelete({})
setSelectedTableToToggleRLS(undefined)
}, [])
const onSelectToggleRLS = useCallback(
(table: { id: number; schema: string; name: string; rls_enabled: boolean }) => {
setSelectedTableToToggleRLS(table)
},
[]
)
const onSelectEditPolicy = useCallback(
(policy: Policy) => {
onSelectEditPolicyAI(policy)
},
[onSelectEditPolicyAI]
)
const onSelectDeletePolicy = useCallback((policy: Policy) => {
setSelectedPolicyToDelete(policy)
}, [])
// Methods that involve some API
const onToggleRLS = async () => {
if (!selectedTableToToggleRLS) return console.error('Table is required')
const payload = {
id: selectedTableToToggleRLS.id,
rls_enabled: !selectedTableToToggleRLS.rls_enabled,
}
return updateTable({
projectRef: project?.ref!,
connectionString: project?.connectionString,
id: selectedTableToToggleRLS.id,
name: selectedTableToToggleRLS.name,
schema: selectedTableToToggleRLS.schema,
payload: payload,
})
}
const onDeletePolicy = async () => {
if (!project) return console.error('Project is required')
deleteDatabasePolicy({
projectRef: project.ref,
connectionString: project.connectionString,
originalPolicy: selectedPolicyToDelete,
})
}
const handleCreatePolicy = useCallback(
(tableData: PolicyTableRowProps['table']) => {
onSelectCreatePolicy(tableData.name)
},
[onSelectCreatePolicy]
)
if (!hasTables) {
return (
<Card className="w-full bg-transparent">
<CardContent className="flex flex-col items-center justify-center p-8">
<h2 className="heading-default">No tables to create policies for</h2>
<p className="text-sm text-foreground-light text-center mb-4">
RLS Policies control per-user access to table rows. Create a table in this schema first
before creating a policy.
</p>
<Button asChild>
<Link to="/project/$ref/editor" params={{ ref: ref ?? '_' }}>
Create a table
</Link>
</Button>
</CardContent>
</Card>
)
}
return (
<>
<div className="flex flex-col gap-y-4 pb-4">
{isLocked && <ProtectedSchemaWarning schema={schema} entity="policies" />}
{!isSchemaExposedAPI && (
<Admonition
type="warning"
title="No data from any table in this schema will be selectable via Supabase APIs"
>
This schema is not exposed via the Supabase APIs. You may configure this in your
project’s{' '}
<InlineLink href={`/project/${ref}/integrations/data_api/settings`}>
Data API settings
</InlineLink>
.
</Admonition>
)}
{tables.length > 0 ? (
<>
{tables.map((table) => {
const isVisible = visibleTableIds.has(table.id)
return (
<section
key={table.id}
hidden={!isVisible}
aria-hidden={!isVisible}
data-testid={`policy-table-${table.name}`}
>
<PolicyTableRow
table={table}
isLocked={schema === 'realtime' ? true : isLocked}
onSelectToggleRLS={onSelectToggleRLS}
onSelectCreatePolicy={handleCreatePolicy}
onSelectEditPolicy={onSelectEditPolicy}
onSelectDeletePolicy={onSelectDeletePolicy}
/>
</section>
)
})}
{!!search && visibleTableIds.size === 0 && (
<NoSearchResults searchString={search ?? ''} onResetFilter={onResetSearch} />
)}
</>
) : hasTables ? (
<NoSearchResults searchString={search ?? ''} onResetFilter={onResetSearch} />
) : null}
</div>
<ConfirmationModal
visible={!isEmpty(selectedPolicyToDelete)}
variant="destructive"
title="Delete policy"
description={`Are you sure you want to delete the policy “${selectedPolicyToDelete.name}”? This action cannot be undone.`}
confirmLabel="Delete"
confirmLabelLoading="Deleting"
loading={isDeletingPolicy}
onCancel={closeConfirmModal}
onConfirm={onDeletePolicy}
/>
<RLSToggleDialog
open={selectedTableToToggleRLS !== undefined}
tableName={selectedTableToToggleRLS?.name}
isEnabled={selectedTableToToggleRLS?.rls_enabled ?? false}
isSubmitting={isUpdatingTable}
onOpenChange={(open) => {
if (!open) closeConfirmModal()
}}
onConfirm={onToggleRLS}
/>
</>
)
}