Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
T
Danny White 9be9e570c3 feat(studio): adopt shared inline code defaults (#51981)
## Problem

Studio relies on repeated classes to style inline code. Bare `<code>`
elements can miss those styles.

## Solution

Import the shared styles from #51980 and remove the repeated classes.
Keep Markdown renderer behaviour and existing size overrides. Use
`data-code-style="plain"` for webhook headers, CLI and upgrade commands,
configuration comparisons and connected-resource labels that have their
own layout.

## Review instructions

Dashboard review: this PR changes Studio only.

1. Open [Database >
Extensions](https://studio-staging-git-dnywh-depr-707-code-studio-supabase.vercel.app/dashboard/project/_/database/extensions).
Search for `pg_trgm` or another disabled extension and turn on its
toggle to open the Enable dialog. Check the Extension and Schema values
and the help text under “Install in a different schema”. The SQL block
should keep its highlighting and copy control. Close without installing.
2. Open [Edge Functions >
Secrets](https://studio-staging-git-dnywh-depr-707-code-studio-supabase.vercel.app/dashboard/project/_/functions/secrets).
Scroll to “Default secrets” and check `SUPABASE_URL` and
`SUPABASE_DB_URL`: both should use the bordered inline-code style. Hover
a name to see “Click to copy”, then click it and confirm the name is
copied. No custom secret or deployed function is needed.
3. Compare light and dark themes at narrow and desktop widths.

| Before | After |
| --- | --- |
| <img width="812" height="1066" alt="CleanShot 2026-10-19 at 15 35
10@2x"
src="https://github.com/user-attachments/assets/e4a21310-1fac-4143-9ee6-d2452ab4f314"
/> | <img width="812" height="1068" alt="CleanShot 2026-10-20 at 15 39
20@2x"
src="https://github.com/user-attachments/assets/d2c91ef6-7836-4c71-8f15-d0c0df8e969d"
/> |
2026-10-22 00:48:56 +00:00

382 lines
14 KiB
TypeScript

import { zodResolver } from '@hookform/resolvers/zod'
import { IS_PLATFORM, useParams } from 'common'
import { useRouter } from 'next/router'
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 z from 'zod'
import CommandRender from '../CommandRender'
import { INVOCATION_TABS } from './EdgeFunctionDetails.constants'
import { generateCLICommands } from './EdgeFunctionDetails.utils'
import { useAPIKeys } 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'
const FormSchema = z.object({
name: z.string().min(0, 'Name is required'),
verify_jwt: z.boolean(),
})
export const EdgeFunctionDetails = () => {
const router = useRouter()
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 { can: canReadAPIKeys } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.API_GATEWAY_KEYS_READ
)
const { data: apiKeyData } = useAPIKeys({ projectRef }, { enabled: canReadAPIKeys })
const { anonKey, publishableKey } = apiKeyData ?? {}
const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef, slug: functionSlug })
const { data: endpoint } = useProjectApiUrl({ projectRef })
const functionUrl = `${endpoint}/functions/v1/${selectedFunction?.slug}`
const { mutate: updateEdgeFunction, isPending: isUpdating } = useEdgeFunctionUpdateMutation()
const { mutate: deleteEdgeFunction, isPending: isDeleting } = useEdgeFunctionDeleteMutation({
onSuccess: () => {
toast.success(`Successfully deleted "${selectedFunction?.name}"`)
router.push(`/project/${projectRef}/functions`)
},
})
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,
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 ? 'Hide' : 'Show'} anon key
</Button>
)}
</TabsList>
{invocationTabs.map((tab) => {
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>
)
}