Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
Alaister YoungandAlaister Young d8568215ad [FE-5109] (part 4) refactor(studio): migrate database, editor, storage, and functions interfaces off next/router (#54056)
Part 4 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 ← this PR** | **Database, Branching, Compute, Edge
Functions, Explorer, SQL Editor, Storage, Table Editor** |
| 5 | #54057 | 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 the database, branching, compute, functions, explorer, SQL
editor, storage, and table editor interfaces off `next/router` and
`next/compat/router`.

**Changed:**

- Migrated the sole `next/compat/router` consumer
(`components/interfaces/Database/Replication/Destinations.tsx`) to
`useNavigate`
- Replaced `useRouter` across `BranchManagement`, `Branching`,
`Compute`, `Database` (`Backups`, `Functions`, `Replication`, `Schemas`,
`Tables`, `Triggers`), `EdgeFunctions`, `Explorer`, `Functions`,
`SQLEditor`, `Storage` (`AnalyticsBuckets`, `FilesBuckets`,
`VectorBuckets`, `StorageMenuV2`, `Storage.utils`), and
`TableGridEditor` with TanStack Router hooks (`useNavigate`,
`useLocation`, `useRoutePattern`) and `useParams` from `common`
- Updated unit and component tests across `Database/Replication`,
`Explorer`, `Functions`, and
`Storage/FilesBuckets/DeleteBucketModal.test.tsx` to use TanStack Router

**Simplified:**

- `useSnippetEditor` and `useRedirectLegacyReadReplicaDestination` read
search values from `useParams` instead of casting `location.search`
- `resolveSourceSwitch` returns `replace: boolean` instead of a
`push`/`replace` method name
- `ExplorerQueryTab` and `EdgeFunctionDetails` guard on a defined ref
instead of navigating with `ref ?? ''`
- `useFunctionsDetailShortcuts` and `StorageMenuV2` use a local `goTo`
helper for their navigation shortcuts
- Tests use the shared `createTestRouter` and `customRender` router, use
`toMatchObject` for search assertions, and drop duplicate assertions

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] SQL Editor: creating, renaming, moving, opening
templates/examples, and keyboard shortcuts navigate between snippets
cleanly
- [ ] Table Editor & Database: opening tables, schema table nodes,
triggers, functions, backups/PITR, and replication destination flows
navigate as expected
- [ ] Storage: switching between Files, Analytics, and Vector buckets
and deleting a bucket navigates cleanly
- [ ] Edge Functions & Explorer: opening function details/logs, explorer
chat/query tabs, and branch management actions navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:44:59 +08:00

426 lines
16 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { useQuery } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { IS_PLATFORM, useParams } from 'common'
import { useEffect, useMemo, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import {
Alert,
AlertDescription,
AlertTitle,
Button,
Card,
CardContent,
CardFooter,
cn,
copyToClipboard,
CriticalIcon,
Form,
FormControl,
FormField,
Switch,
Tabs,
TabsContent,
TabsList,
TabsTrigger,
} from 'ui'
import { CodeBlock } from 'ui-patterns/CodeBlock'
import { Input } from 'ui-patterns/DataInputs/Input'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { PageContainer } from 'ui-patterns/PageContainer'
import {
PageSection,
PageSectionContent,
PageSectionMeta,
PageSectionSummary,
PageSectionTitle,
} from 'ui-patterns/PageSection'
import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
import z from 'zod'
import CommandRender from '../CommandRender'
import { INVOCATION_TABS } from './EdgeFunctionDetails.constants'
import { generateCLICommands } from './EdgeFunctionDetails.utils'
import { AlertError } from '@/components/ui/AlertError'
import { ApiKeysAccessNote } from '@/components/ui/ApiKeysAccessNote'
import { apiKeysQueryOptions, getKeys } from '@/data/api-keys/api-keys-query'
import { useProjectApiUrl } from '@/data/config/project-endpoint-query'
import { useEdgeFunctionQuery } from '@/data/edge-functions/edge-function-query'
import { useEdgeFunctionDeleteMutation } from '@/data/edge-functions/edge-functions-delete-mutation'
import { useEdgeFunctionUpdateMutation } from '@/data/edge-functions/edge-functions-update-mutation'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useGrant } from '@/lib/grants'
const FormSchema = z.object({
name: z.string().min(0, 'Name is required'),
verify_jwt: z.boolean(),
})
export const EdgeFunctionDetails = () => {
const navigate = useNavigate()
const { ref: projectRef, functionSlug } = useParams()
const showAllEdgeFunctionInvocationExamples = useIsFeatureEnabled(
'edge_functions:show_all_edge_function_invocation_examples'
)
const invocationTabs = useMemo(() => {
if (showAllEdgeFunctionInvocationExamples) return INVOCATION_TABS
return INVOCATION_TABS.filter((tab) => tab.id === 'curl' || tab.id === 'supabase-js')
}, [showAllEdgeFunctionInvocationExamples])
const [showKey, setShowKey] = useState(false)
const [selectedTab, setSelectedTab] = useState(invocationTabs[0].id)
const [showDeleteModal, setShowDeleteModal] = useState(false)
const { can: canUpdateEdgeFunctionPermission } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_WRITE
)
const canUpdateEdgeFunction = IS_PLATFORM && canUpdateEdgeFunctionPermission
const apiKeysGrant = useGrant('GET /v1/projects/{ref}/api-keys', { projectRef })
const { data: apiKeyData } = useQuery(
apiKeysQueryOptions(
{ projectRef, grant: apiKeysGrant.grant },
{
// A skipped query still returns cached data, so ignore it unless the grant is granted
select: (data) => getKeys(apiKeysGrant.status === 'granted' ? data : []),
}
)
)
const { anonKey, publishableKey } = apiKeyData ?? {}
const {
data: selectedFunction,
error: functionError,
isPending: isFunctionPending,
} = useEdgeFunctionQuery({ projectRef, slug: functionSlug })
const {
data: endpoint,
error: endpointError,
isPending: isEndpointPending,
} = useProjectApiUrl({ projectRef })
const functionUrl =
endpoint && selectedFunction ? `${endpoint}/functions/v1/${selectedFunction.slug}` : undefined
const isFunctionUrlLoading = !functionUrl && (isEndpointPending || isFunctionPending)
const functionUrlError =
!functionUrl && !isFunctionUrlLoading ? (endpointError ?? functionError) : null
const { mutate: updateEdgeFunction, isPending: isUpdating } = useEdgeFunctionUpdateMutation()
const { mutate: deleteEdgeFunction, isPending: isDeleting } = useEdgeFunctionDeleteMutation({
onSuccess: () => {
toast.success(`Successfully deleted "${selectedFunction?.name}"`)
if (projectRef) void navigate({ to: '/project/$ref/functions', params: { ref: projectRef } })
},
})
const form = useForm({
resolver: zodResolver(FormSchema),
defaultValues: { name: '', verify_jwt: false },
})
const apiKey = publishableKey?.api_key ?? anonKey?.api_key ?? '[YOUR ANON KEY]'
const { managementCommands } = generateCLICommands({
selectedFunction,
functionUrl: functionUrl ?? '',
anonKey: apiKey,
})
const onUpdateFunction: SubmitHandler<z.infer<typeof FormSchema>> = async (values: any) => {
if (!projectRef) return console.error('Project ref is required')
if (selectedFunction === undefined) return console.error('No edge function selected')
updateEdgeFunction(
{
projectRef,
slug: selectedFunction.slug,
payload: values,
},
{
onSuccess: () => {
toast.success(`Successfully updated edge function`)
},
}
)
}
const onConfirmDelete = async () => {
if (!projectRef) return console.error('Project ref is required')
if (selectedFunction === undefined) return console.error('No edge function selected')
deleteEdgeFunction({ projectRef, slug: selectedFunction.slug })
}
useEffect(() => {
if (selectedFunction) {
form.reset({
name: selectedFunction.name,
verify_jwt: selectedFunction.verify_jwt,
})
}
}, [selectedFunction])
return (
<PageContainer size="small">
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Function configuration</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Form {...form}>
<form onSubmit={form.handleSubmit(onUpdateFunction)}>
<Card>
<CardContent>
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItemLayout
label="Name"
layout="flex-row-reverse"
description="Your slug and endpoint URL will remain the same"
>
<FormControl>
<Input {...field} className="w-64" disabled={!canUpdateEdgeFunction} />
</FormControl>
</FormItemLayout>
)}
/>
</CardContent>
{IS_PLATFORM && (
<>
<CardContent>
<FormField
control={form.control}
name="verify_jwt"
render={({ field }) => (
<FormItemLayout
label="Verify JWT with legacy secret"
layout="flex-row-reverse"
description={
<>
<p className="mb-2">
Requires a JWT signed{' '}
<em className="text-foreground not-italic">
only by the legacy secret
</em>{' '}
in the <code className="break-keep!">Authorization</code> header.
The <code>anon</code> key satisfies this.
</p>
<p>
Recommended: OFF with JWT and custom auth logic in your function
code.
</p>
</>
}
>
<FormControl>
<Switch
checked={field.value}
onCheckedChange={field.onChange}
disabled={!canUpdateEdgeFunction}
/>
</FormControl>
</FormItemLayout>
)}
/>
</CardContent>
<CardFooter className="flex justify-end space-x-2">
{form.formState.isDirty && (
<Button onClick={() => form.reset()}>Cancel</Button>
)}
<Button
variant="primary"
type="submit"
loading={isUpdating}
disabled={!canUpdateEdgeFunction || !form.formState.isDirty}
>
Save changes
</Button>
</CardFooter>
</>
)}
</Card>
</form>
</Form>
</PageSectionContent>
</PageSection>
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Invoke function</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Card>
<CardContent className="px-0">
<Tabs
className="w-full"
defaultValue="curl"
value={selectedTab}
onValueChange={setSelectedTab}
>
<TabsList className="flex flex-wrap gap-4 px-6">
{invocationTabs.map((tab) => (
<TabsTrigger key={tab.id} value={tab.id}>
{tab.label}
</TabsTrigger>
))}
{selectedTab === 'curl' && (
<Button
className="ml-auto -translate-y-2 translate-x-3"
onClick={() => setShowKey(!showKey)}
>
{showKey ? <span>Hide</span> : <span>Show</span>} <span>anon key</span>
</Button>
)}
</TabsList>
<ApiKeysAccessNote
grant={apiKeysGrant}
fallback="Replace the placeholder with your own key."
className="px-6 pb-2"
/>
{isFunctionUrlLoading && (
<div className="mt-4 px-6">
<GenericSkeletonLoader />
</div>
)}
{functionUrlError && (
<div className="mt-4 px-6">
<AlertError
error={functionUrlError}
subject="Failed to retrieve function URL"
projectRef={projectRef}
/>
</div>
)}
{invocationTabs.map((tab) => {
if (!functionUrl) return null
const code = tab.code({
showKey,
functionUrl,
functionName: selectedFunction?.name ?? '',
apiKey,
})
return (
<TabsContent key={tab.id} value={tab.id}>
<CodeBlock
value={code}
wrapperClassName="[&>div]:top-0 [&>div]:right-3 px-6"
className={cn(
'p-0 text-xs mt-0! border-none ',
showKey ? '[&>code]:break-all' : '[&>code]:wrap-break-word'
)}
language={tab.language}
wrapLines={false}
hideLineNumbers={tab.hideLineNumbers}
handleCopy={() => {
copyToClipboard(
tab.code({
showKey: true,
functionUrl,
functionName: selectedFunction?.name ?? '',
apiKey,
})
)
}}
/>
</TabsContent>
)
})}
</Tabs>
</CardContent>
</Card>
</PageSectionContent>
</PageSection>
{IS_PLATFORM && (
<>
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Develop locally</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<div className="rounded-sm border bg-surface-100 px-6 py-4 drop-shadow-xs">
<div className="space-y-6">
<CommandRender
commands={[
{
command: `supabase functions download ${selectedFunction?.slug}`,
description: 'Download the function to your local machine',
jsx: () => (
<>
<span className="text-primary">supabase</span> functions download{' '}
{selectedFunction?.slug}
</>
),
comment: '1. Download the function',
},
]}
/>
<CommandRender commands={[managementCommands[0]]} />
<CommandRender commands={[managementCommands[1]]} />
</div>
</div>
</PageSectionContent>
</PageSection>
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Delete function</PageSectionTitle>
</PageSectionSummary>
</PageSectionMeta>
<PageSectionContent>
<Alert variant="destructive">
<CriticalIcon />
<AlertTitle>Once your function is deleted, it can no longer be restored</AlertTitle>
<AlertDescription>
Make sure you have made a backup if you want to restore your edge function
</AlertDescription>
<AlertDescription className="mt-3">
<Button
variant="danger"
disabled={!canUpdateEdgeFunction}
loading={selectedFunction?.id === undefined}
onClick={() => setShowDeleteModal(true)}
>
Delete edge function
</Button>
</AlertDescription>
</Alert>
</PageSectionContent>
</PageSection>
<ConfirmationModal
visible={showDeleteModal}
loading={isDeleting}
variant="destructive"
confirmLabel="Delete"
confirmLabelLoading="Deleting"
title={`Confirm to delete ${selectedFunction?.name}`}
onCancel={() => setShowDeleteModal(false)}
onConfirm={onConfirmDelete}
alert={{
base: { variant: 'destructive' },
title: 'This action cannot be undone',
description:
'Ensure that you have made a backup if you want to restore your edge function',
}}
/>
</>
)}
</PageContainer>
)
}