Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Improve single edge function layout (#33725)

Saxon Fletcher904d8e448280
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
new file mode 100644
index 00000000000..edf13395e10
--- /dev/null
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.constants.ts
@@ -0,0 +1,68 @@
+interface InvocationTab {
+ id: string
+ label: string
+ language: 'bash' | 'js' | 'ts' | 'dart' | 'python'
+ hideLineNumbers?: boolean
+ code: (functionUrl: string, functionName: string, apiKey: string) => string
+}
+
+export const INVOCATION_TABS: InvocationTab[] = [
+ {
+ id: 'curl',
+ label: 'cURL',
+ language: 'bash',
+ code: (functionUrl, _, apiKey) => `curl -L -X POST '${functionUrl}' \\
+ -H 'Authorization: Bearer ${apiKey}' \\
+ -H 'Content-Type: application/json' \\
+ --data '{"name":"Functions"}'`,
+ },
+ {
+ id: 'supabase-js',
+ label: 'JavaScript',
+ language: 'js',
+ hideLineNumbers: true,
+ code: (_, functionName) => `import { createClient } from '@supabase/supabase-js'
+const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_ANON_KEY)
+const { data, error } = await supabase.functions.invoke('${functionName}', {
+ body: { name: 'Functions' },
+})`,
+ },
+ {
+ id: 'swift',
+ label: 'Swift',
+ language: 'ts',
+ hideLineNumbers: true,
+ code: (_, functionName) => `struct Response: Decodable {
+ // Expected response definition
+}
+
+let response: Response = try await supabase.functions
+ .invoke(
+ "${functionName}",
+ options: FunctionInvokeOptions(
+ body: ["name": "Functions"]
+ )
+ )`,
+ },
+ {
+ id: 'flutter',
+ label: 'Flutter',
+ language: 'dart',
+ hideLineNumbers: true,
+ code: (
+ _,
+ functionName
+ ) => `final res = await supabase.functions.invoke('${functionName}', body: {'name': 'Functions'});
+final data = res.data;`,
+ },
+ {
+ id: 'python',
+ label: 'Python',
+ language: 'python',
+ hideLineNumbers: true,
+ code: (_, functionName) => `response = supabase.functions.invoke(
+ "${functionName}",
+ invoke_options={"body": {"name": "Functions"}}
+)`,
+ },
+]
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
index 06071962e59..a88a5a16ebf 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
@@ -1,17 +1,16 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import dayjs from 'dayjs'
-import { ExternalLink, Maximize2, Minimize2, Terminal } from 'lucide-react'
+import { ExternalLink } from 'lucide-react'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
+import z from 'zod'
import { useParams } from 'common'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { FormActions } from 'components/ui/Forms/FormActions'
-import { FormHeader } from 'components/ui/Forms/FormHeader'
-import { FormPanel } from 'components/ui/Forms/FormPanel'
-import { FormSection, FormSectionContent, FormSectionLabel } from 'components/ui/Forms/FormSection'
+import { ScaffoldSection, ScaffoldSectionTitle } from 'components/layouts/Scaffold'
import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
@@ -19,29 +18,50 @@ import { useEdgeFunctionDeleteMutation } from 'data/edge-functions/edge-function
import { useEdgeFunctionUpdateMutation } from 'data/edge-functions/edge-functions-update-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import {
+ Alert_Shadcn_,
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
- Alert_Shadcn_,
Button,
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ cn,
+ CodeBlock,
CriticalIcon,
- Form,
+ Form_Shadcn_,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
Input,
- Modal,
- Toggle,
- cn,
+ Input_Shadcn_,
+ Switch,
+ Tabs_Shadcn_ as Tabs,
+ TabsContent_Shadcn_ as TabsContent,
+ TabsList_Shadcn_ as TabsList,
+ TabsTrigger_Shadcn_ as TabsTrigger,
} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import CommandRender from '../CommandRender'
+import { INVOCATION_TABS } from './EdgeFunctionDetails.constants'
import { generateCLICommands } from './EdgeFunctionDetails.utils'
+const FormSchema = z.object({
+ name: z.string().min(0, 'Name is required'),
+ verify_jwt: z.boolean(),
+})
+
const EdgeFunctionDetails = () => {
const router = useRouter()
const { ref: projectRef, functionSlug } = useParams()
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [showInstructions, setShowInstructions] = useState(true)
+ const canUpdateEdgeFunction = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')
const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: customDomainData } = useCustomDomainsQuery({ projectRef })
const { data: selectedFunction } = useEdgeFunctionQuery({ projectRef, slug: functionSlug })
+
const { mutate: updateEdgeFunction, isLoading: isUpdating } = useEdgeFunctionUpdateMutation()
const { mutate: deleteEdgeFunction, isLoading: isDeleting } = useEdgeFunctionDeleteMutation({
onSuccess: () => {
@@ -50,8 +70,10 @@ const EdgeFunctionDetails = () => {
},
})
- const formId = 'edge-function-update-form'
- const canUpdateEdgeFunction = useCheckPermissions(PermissionAction.FUNCTIONS_WRITE, '*')
+ const form = useForm({
+ resolver: zodResolver(FormSchema),
+ defaultValues: { name: '', verify_jwt: false },
+ })
const { anonKey } = getAPIKeys(settings)
const apiKey = anonKey?.api_key ?? '[YOUR ANON KEY]'
@@ -62,14 +84,17 @@ const EdgeFunctionDetails = () => {
customDomainData?.customDomain?.status === 'active'
? `https://${customDomainData.customDomain.hostname}/functions/v1/${selectedFunction?.slug}`
: `${protocol}://${endpoint}/functions/v1/${selectedFunction?.slug}`
-
- const { managementCommands, secretCommands, invokeCommands } = generateCLICommands({
+ const hasImportMap = useMemo(
+ () => selectedFunction?.import_map || selectedFunction?.import_map_path,
+ [selectedFunction]
+ )
+ const { managementCommands } = generateCLICommands({
selectedFunction,
functionUrl,
anonKey: apiKey,
})
- const onUpdateFunction = async (values: any, { resetForm }: any) => {
+ 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')
@@ -81,7 +106,6 @@ const EdgeFunctionDetails = () => {
},
{
onSuccess: () => {
- resetForm({ values, initialValues: values })
toast.success(`Successfully updated edge function`)
},
}
@@ -94,153 +118,138 @@ const EdgeFunctionDetails = () => {
deleteEdgeFunction({ projectRef, slug: selectedFunction.slug })
}
- const hasImportMap = useMemo(
- () => selectedFunction?.import_map || selectedFunction?.import_map_path,
- [selectedFunction]
- )
+ useEffect(() => {
+ if (selectedFunction) {
+ form.reset({
+ name: selectedFunction.name,
+ verify_jwt: selectedFunction.verify_jwt,
+ })
+ }
+ }, [selectedFunction])
return (
- <>
- <div className="space-y-4 pb-16 pt-3">
- <Form id={formId} initialValues={{}} onSubmit={onUpdateFunction}>
- {({ handleReset, values, initialValues, resetForm }: any) => {
- const hasChanges = JSON.stringify(values) !== JSON.stringify(initialValues)
-
- // [Alaister] although this "technically" is breaking the rules of React hooks
- // it won't error because the hooks are always rendered in the same order
- // eslint-disable-next-line react-hooks/rules-of-hooks
- useEffect(() => {
- if (selectedFunction !== undefined) {
- const formValues = {
- name: selectedFunction?.name,
- verify_jwt: selectedFunction?.verify_jwt,
- }
- resetForm({ values: formValues, initialValues: formValues })
- }
- }, [selectedFunction])
-
- return (
- <>
- <FormPanel
- disabled={!canUpdateEdgeFunction}
- footer={
- <div className="flex py-4 px-8">
- <FormActions
- form={formId}
- isSubmitting={isUpdating}
- hasChanges={hasChanges}
- handleReset={handleReset}
- helper={
- !canUpdateEdgeFunction
- ? 'You need additional permissions to update this function'
- : undefined
- }
- />
- </div>
- }
- >
- <FormSection header={<FormSectionLabel>Function Details</FormSectionLabel>}>
- <FormSectionContent loading={selectedFunction === undefined}>
- <Input id="name" name="name" label="Name" disabled={!canUpdateEdgeFunction} />
- <Input
- disabled
- id="slug"
- name="slug"
- label="Slug"
- value={selectedFunction?.slug}
- />
- <Input disabled copy label="Endpoint URL" value={functionUrl} />
- <Input disabled label="Region" value="All functions are deployed globally" />
- <Input
- disabled
- label="Created at"
- value={dayjs(selectedFunction?.created_at ?? 0).format(
- 'dddd, MMMM D, YYYY h:mm A'
- )}
- />
- <Input
- disabled
- label="Last updated at"
- value={dayjs(selectedFunction?.updated_at ?? 0).format(
- 'dddd, MMMM D, YYYY h:mm A'
- )}
- />
- <Input disabled label="Deployments" value={selectedFunction?.version ?? 0} />
- </FormSectionContent>
- </FormSection>
- <FormSection header={<FormSectionLabel>Function Configuration</FormSectionLabel>}>
- <FormSectionContent loading={selectedFunction === undefined}>
- <Toggle
- id="verify_jwt"
- name="verify_jwt"
- disabled={!canUpdateEdgeFunction}
+ <div className="mx-auto flex flex-col-reverse 2xl:flex-row gap-8 pb-8">
+ <div className="flex-1 min-w-0 overflow-hidden">
+ <ScaffoldSection isFullWidth className="!pt-0 2xl:first:!pt-12">
+ <ScaffoldSectionTitle className="mb-4">Function Configuration</ScaffoldSectionTitle>
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onUpdateFunction)}>
+ <Card>
+ <CardContent>
+ <FormField_Shadcn_
+ 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_Shadcn_>
+ <Input_Shadcn_
+ {...field}
+ className="w-full"
+ disabled={!canUpdateEdgeFunction}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </CardContent>
+ <CardContent>
+ <FormField_Shadcn_
+ control={form.control}
+ name="verify_jwt"
+ render={({ field }) => (
+ <FormItemLayout
label="Enforce JWT Verification"
- descriptionText="Require a valid JWT in the authorization header when invoking the function"
+ layout="flex-row-reverse"
+ description="Require a valid JWT in the authorization header when invoking the function"
+ >
+ <FormControl_Shadcn_>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={!canUpdateEdgeFunction}
+ />
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </CardContent>
+ <CardFooter className="flex justify-end space-x-2">
+ {form.formState.isDirty && (
+ <Button type="default" onClick={() => form.reset()}>
+ Cancel
+ </Button>
+ )}
+ <Button
+ type="primary"
+ htmlType="submit"
+ loading={isUpdating}
+ disabled={!canUpdateEdgeFunction || !form.formState.isDirty}
+ >
+ Save changes
+ </Button>
+ </CardFooter>
+ </Card>
+ </form>
+ </Form_Shadcn_>
+ </ScaffoldSection>
+ <ScaffoldSection isFullWidth>
+ <ScaffoldSectionTitle className="mb-4">Invoke function</ScaffoldSectionTitle>
+ <Card>
+ <CardContent>
+ <Tabs defaultValue="curl" className="w-full">
+ <TabsList className="flex flex-wrap gap-4">
+ {INVOCATION_TABS.map((tab) => (
+ <TabsTrigger key={tab.id} value={tab.id}>
+ {tab.label}
+ </TabsTrigger>
+ ))}
+ </TabsList>
+ {INVOCATION_TABS.map((tab) => (
+ <TabsContent key={tab.id} value={tab.id} className="mt-4">
+ <div className="overflow-x-auto">
+ <CodeBlock
+ language={tab.language}
+ hideLineNumbers={tab.hideLineNumbers}
+ className="p-0 text-xs !mt-0 border-none"
+ value={tab.code(functionUrl, selectedFunction?.name ?? '', apiKey)}
/>
- <div className="space-y-1 border rounded border-default bg-surface-200 px-4 py-4">
- <div className="flex items-center space-x-2">
- <p className="text-sm">
- Import maps are{' '}
- <span className={cn(hasImportMap ? 'text-brand' : 'text-amber-900')}>
- {hasImportMap ? 'used' : 'not used'}
- </span>{' '}
- for this function
- </p>
- </div>
- <p className="text-sm text-foreground-light">
- Import maps allow the use of bare specifiers in functions instead of
- explicit import URLs
- </p>
- <div className="!mt-4">
- <Button asChild type="default" icon={<ExternalLink strokeWidth={1.5} />}>
- <Link
- href="https://supabase.com/docs/guides/functions/dependencies"
- target="_blank"
- rel="noreferrer"
- >
- More about import maps
- </Link>
- </Button>
- </div>
- </div>
- </FormSectionContent>
- </FormSection>
- </FormPanel>
- </>
- )
- }}
- </Form>
-
- <div
- className="space-y-6 rounded border bg-surface-100 px-6 py-4 drop-shadow-sm transition-all overflow-hidden"
- style={{ maxHeight: showInstructions ? 800 : 66 }}
- >
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-3">
- <div className="flex h-8 w-8 items-center justify-center rounded border bg-foreground p-2 text-background">
- <Terminal size={18} strokeWidth={2} />
- </div>
- <h4>Deploy, invoke and manage secrets</h4>
- </div>
- <div className="cursor-pointer" onClick={() => setShowInstructions(!showInstructions)}>
- {showInstructions ? (
- <Minimize2 size={14} strokeWidth={1.5} />
- ) : (
- <Maximize2 size={14} strokeWidth={1.5} />
- )}
+ </div>
+ </TabsContent>
+ ))}
+ </Tabs>
+ </CardContent>
+ </Card>
+ </ScaffoldSection>
+ <ScaffoldSection isFullWidth>
+ <ScaffoldSectionTitle className="mb-4">Develop locally</ScaffoldSectionTitle>
+ <div className="rounded border bg-surface-100 px-6 py-4 drop-shadow-sm">
+ <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-brand-600">supabase</span> functions download{' '}
+ {selectedFunction?.slug}
+ </>
+ ),
+ comment: '1. Download the function',
+ },
+ ]}
+ />
+ <CommandRender commands={[managementCommands[0]]} />
+ <CommandRender commands={[managementCommands[1]]} />
</div>
</div>
-
- <h5 className="text-base">Deploy your function</h5>
- <CommandRender commands={managementCommands} />
- <h5 className="text-base">Invoke your function</h5>
- <CommandRender commands={invokeCommands} />
- <h5 className="text-base">Manage secrets</h5>
- <CommandRender commands={secretCommands} />
- </div>
-
- <div className="!mt-8">
- <FormHeader title="Delete Edge Function" description="" />
+ </ScaffoldSection>
+ <ScaffoldSection isFullWidth>
+ <ScaffoldSectionTitle className="mb-4">Delete function</ScaffoldSectionTitle>
<Alert_Shadcn_ variant="destructive">
<CriticalIcon />
<AlertTitle_Shadcn_>
@@ -250,47 +259,110 @@ const EdgeFunctionDetails = () => {
Make sure you have made a backup if you want to restore your edge function
</AlertDescription_Shadcn_>
<AlertDescription_Shadcn_ className="mt-3">
- <ButtonTooltip
+ <Button
type="danger"
disabled={!canUpdateEdgeFunction}
loading={selectedFunction?.id === undefined}
onClick={() => setShowDeleteModal(true)}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canUpdateEdgeFunction
- ? 'You need additional permissions to delete edge functions'
- : undefined,
- },
- }}
>
Delete edge function
- </ButtonTooltip>
+ </Button>
</AlertDescription_Shadcn_>
</Alert_Shadcn_>
- </div>
+ </ScaffoldSection>
+
+ <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',
+ }}
+ />
</div>
- <Modal
- size="small"
- alignFooter="right"
- header={<h3>Confirm to delete {selectedFunction?.name}</h3>}
- visible={showDeleteModal}
- loading={isDeleting}
- onCancel={() => setShowDeleteModal(false)}
- onConfirm={onConfirmDelete}
- >
- <Modal.Content>
- <Alert_Shadcn_ variant="warning">
- <CriticalIcon />
- <AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- Ensure that you have made a backup if you want to restore your edge function
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- </Modal.Content>
- </Modal>
- </>
+ <div className="w-full 2xl:max-w-[600px] shrink-0">
+ <ScaffoldSection isFullWidth className="!pt-6 2xl:first:!pt-12">
+ <Card>
+ <CardHeader>
+ <CardTitle>Details</CardTitle>
+ </CardHeader>
+ <CardContent className="pt-6 space-y-6">
+ <dl className="grid grid-cols-1 xl:grid-cols-[auto_1fr] gap-y-4 xl:gap-y-6 gap-x-10">
+ <dt className="text-sm text-foreground-light">Slug</dt>
+ <dd className="text-sm lg:text-left">{selectedFunction?.slug}</dd>
+
+ <dt className="text-sm text-foreground-light">Endpoint URL</dt>
+ <dd className="text-sm lg:text-left">
+ <Input
+ className="font-mono input-mono"
+ disabled
+ copy
+ size="small"
+ value={functionUrl}
+ />
+ </dd>
+
+ <dt className="text-sm text-foreground-light">Region</dt>
+ <dd className="text-sm lg:text-left">All functions are deployed globally</dd>
+
+ <dt className="text-sm text-foreground-light">Created at</dt>
+ <dd className="text-sm lg:text-left">
+ {dayjs(selectedFunction?.created_at ?? 0).format('dddd, MMMM D, YYYY h:mm A')}
+ </dd>
+
+ <dt className="text-sm text-foreground-light">Last updated at</dt>
+ <dd className="text-sm lg:text-left">
+ {dayjs(selectedFunction?.updated_at ?? 0).format('dddd, MMMM D, YYYY h:mm A')}
+ </dd>
+
+ <dt className="text-sm text-foreground-light">Deployments</dt>
+ <dd className="text-sm lg:text-left">{selectedFunction?.version ?? 0}</dd>
+
+ <dt className="text-sm text-foreground-light">Import Maps</dt>
+ <dd className="text-sm lg:text-left">
+ <p>
+ Import maps are{' '}
+ <span className={cn(hasImportMap ? 'text-brand' : 'text-amber-900')}>
+ {hasImportMap ? 'used' : 'not used'}
+ </span>{' '}
+ for this function
+ </p>
+ <p className="text-foreground-light mt-1">
+ Import maps allow the use of bare specifiers in functions instead of explicit
+ import URLs
+ </p>
+ <div className="mt-4">
+ <Button
+ asChild
+ type="default"
+ size="tiny"
+ icon={<ExternalLink strokeWidth={1.5} />}
+ >
+ <Link
+ href="https://supabase.com/docs/guides/functions/dependencies"
+ target="_blank"
+ rel="noreferrer"
+ >
+ More about import maps
+ </Link>
+ </Button>
+ </div>
+ </dd>
+ </dl>
+ </CardContent>
+ </Card>
+ </ScaffoldSection>
+ </div>
+ </div>
)
}
diff --git a/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx b/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx
index 74cdf9c6736..e9b1ab5ef55 100644
--- a/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx
+++ b/apps/studio/components/layouts/AuthLayout/AuthLayout.tsx
@@ -12,12 +12,11 @@ import ProjectLayout from '../ProjectLayout/ProjectLayout'
import { generateAuthMenu } from './AuthLayout.utils'
const AuthProductMenu = () => {
+ const router = useRouter()
const { ref: projectRef = 'default' } = useParams()
const columnLevelPrivileges = useIsColumnLevelPrivilegesEnabled()
useAuthConfigPrefetch({ projectRef })
-
- const router = useRouter()
const page = router.pathname.split('/')[4]
return (
diff --git a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx
new file mode 100644
index 00000000000..4ec3562d33d
--- /dev/null
+++ b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout.tsx
@@ -0,0 +1,113 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useEffect, type PropsWithChildren } from 'react'
+
+import { useParams } from 'common'
+import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
+import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
+import APIDocsButton from 'components/ui/APIDocsButton'
+import { DocsButton } from 'components/ui/DocsButton'
+import NoPermission from 'components/ui/NoPermission'
+import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { withAuth } from 'hooks/misc/withAuth'
+import { useRouter } from 'next/router'
+import { toast } from 'sonner'
+import ProjectLayout from '../ProjectLayout/ProjectLayout'
+import EdgeFunctionsLayout from './EdgeFunctionsLayout'
+
+interface EdgeFunctionDetailsLayoutProps {
+ title?: string
+}
+
+const EdgeFunctionDetailsLayout = ({
+ title,
+ children,
+}: PropsWithChildren<EdgeFunctionDetailsLayoutProps>) => {
+ const router = useRouter()
+ const { functionSlug, ref } = useParams()
+ const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
+ const canReadFunctions = useCheckPermissions(PermissionAction.FUNCTIONS_READ, '*')
+
+ const {
+ data: selectedFunction,
+ error,
+ isError,
+ } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })
+
+ const name = selectedFunction?.name || ''
+ const breadcrumbItems = [
+ {
+ label: 'Edge Functions',
+ href: `/project/${ref}/functions`,
+ },
+ ]
+ const navigationItems = functionSlug
+ ? [
+ {
+ label: 'Overview',
+ href: `/project/${ref}/functions/${functionSlug}`,
+ },
+ {
+ label: 'Invocations',
+ href: `/project/${ref}/functions/${functionSlug}/invocations`,
+ },
+ {
+ label: 'Logs',
+ href: `/project/${ref}/functions/${functionSlug}/logs`,
+ },
+ {
+ label: 'Details',
+ href: `/project/${ref}/functions/${functionSlug}/details`,
+ },
+ ]
+ : []
+
+ useEffect(() => {
+ let cancel = false
+
+ if (!!functionSlug && isError && error.code === 404 && !cancel) {
+ toast('Edge function cannot be found in your project')
+ router.push(`/project/${ref}/functions`)
+ }
+
+ return () => {
+ cancel = true
+ }
+ }, [isError])
+
+ if (!canReadFunctions) {
+ return (
+ <ProjectLayout title={title || 'Edge Functions'} product="Edge Functions">
+ <NoPermission isFullPage resourceText="access your project's edge functions" />
+ </ProjectLayout>
+ )
+ }
+
+ return (
+ <EdgeFunctionsLayout>
+ <PageLayout
+ isCompact
+ size="full"
+ title={functionSlug ? name : 'Edge Functions'}
+ breadcrumbs={breadcrumbItems}
+ navigationItems={navigationItems}
+ primaryActions={
+ <div className="flex items-center space-x-2">
+ {isNewAPIDocsEnabled && (
+ <APIDocsButton
+ section={
+ functionSlug !== undefined ? ['edge-functions', functionSlug] : ['edge-functions']
+ }
+ />
+ )}
+ <DocsButton href="https://supabase.com/docs/guides/functions" />
+ </div>
+ }
+ >
+ {children}
+ </PageLayout>
+ </EdgeFunctionsLayout>
+ )
+}
+
+export default withAuth(EdgeFunctionDetailsLayout)
diff --git a/apps/studio/components/layouts/FunctionsLayout/Functions.Commands.tsx b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctions.Commands.tsx
similarity index 100%
rename from apps/studio/components/layouts/FunctionsLayout/Functions.Commands.tsx
rename to apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctions.Commands.tsx
diff --git a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
index 2573afff9d0..d4406e3d899 100644
--- a/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
+++ b/apps/studio/components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout.tsx
@@ -19,6 +19,7 @@ const EdgeFunctionsProductMenu = () => {
{
name: 'Functions',
key: 'main',
+ pages: [undefined, '[functionSlug]'],
url: `/project/${projectRef}/functions`,
items: [],
},
diff --git a/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx b/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx
deleted file mode 100644
index 98e96f2e616..00000000000
--- a/apps/studio/components/layouts/FunctionsLayout/FunctionsLayout.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import Link from 'next/link'
-import { useEffect, type PropsWithChildren } from 'react'
-
-import { useParams } from 'common'
-import { useIsAPIDocsSidePanelEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
-import APIDocsButton from 'components/ui/APIDocsButton'
-import { DocsButton } from 'components/ui/DocsButton'
-import NoPermission from 'components/ui/NoPermission'
-import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
-import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { withAuth } from 'hooks/misc/withAuth'
-import { Code } from 'lucide-react'
-import { useRouter } from 'next/router'
-import { toast } from 'sonner'
-import { Button, cn } from 'ui'
-import FunctionsNav from '../../interfaces/Functions/FunctionsNav'
-import ProjectLayout from '../ProjectLayout/ProjectLayout'
-
-interface FunctionsLayoutProps {
- title?: string
-}
-
-const FunctionsLayout = ({ title, children }: PropsWithChildren<FunctionsLayoutProps>) => {
- const router = useRouter()
- const { functionSlug, ref } = useParams()
- const isNewAPIDocsEnabled = useIsAPIDocsSidePanelEnabled()
-
- const { data: functions, isLoading } = useEdgeFunctionsQuery({ projectRef: ref })
- const {
- data: selectedFunction,
- error,
- isError,
- } = useEdgeFunctionQuery({ projectRef: ref, slug: functionSlug })
-
- const canReadFunctions = useCheckPermissions(PermissionAction.FUNCTIONS_READ, '*')
-
- const name = selectedFunction?.name || ''
- const hasFunctions = (functions ?? []).length > 0
- const centered = !hasFunctions
-
- useEffect(() => {
- let cancel = false
-
- if (!!functionSlug && isError && error.code === 404 && !cancel) {
- toast('Edge function cannot be found in your project')
- router.push(`/project/${ref}/functions`)
- }
-
- return () => {
- cancel = true
- }
- }, [isError])
-
- if (!canReadFunctions) {
- return (
- <ProjectLayout title={title || 'Edge Functions'} product="Edge Functions">
- <NoPermission isFullPage resourceText="access your project's edge functions" />
- </ProjectLayout>
- )
- }
-
- return (
- <ProjectLayout isLoading={isLoading} title={title || 'Edge Functions'} product="Edge Functions">
- {centered ? (
- <>
- <div className="mx-auto max-w-full md:max-w-5xl py-12 md:py-20 px-4 md:px-5">
- <div
- className="item-center
- flex
- flex-col
- justify-between
- gap-y-4
- xl:flex-row"
- >
- <div className="flex items-center gap-3">
- <div className="flex items-center space-x-4">
- <h1 className="text-2xl text-foreground">Edge Functions</h1>
- </div>
- </div>
- </div>
-
- {children}
- </div>
- </>
- ) : (
- <div className="flex h-full flex-grow flex-col py-6">
- <div
- className={cn(
- 'mx-auto flex w-full flex-col transition-all',
- '1xl:px-28 gap-4 px-5 lg:px-16 xl:px-24 2xl:px-32'
- )}
- >
- <div className="item-center flex flex-col justify-between gap-y-4 xl:flex-row">
- <div className="flex items-center gap-3 w-full">
- <div
- className={cn(
- 'h-6 w-6 rounded border border-brand-600 bg-brand-300',
- 'flex items-center justify-center text-brand'
- )}
- >
- <Code size={14} strokeWidth={3} />
- </div>
-
- <div className="flex items-center justify-between w-full">
- <div className="flex items-center space-x-4">
- <Link href={`/project/${ref}/functions`}>
- <h1 className="cursor-pointer text-2xl text-foreground transition-colors hover:text-foreground-light">
- Edge Functions
- </h1>
- </Link>
- {name && (
- <div className="flex items-center space-x-4">
- <span className="text-foreground-light">
- <svg
- viewBox="0 0 24 24"
- width="24"
- height="24"
- stroke="currentColor"
- strokeWidth="1"
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- shapeRendering="geometricPrecision"
- >
- <path d="M16 3.549L7.12 20.600"></path>
- </svg>
- </span>
- <h1 className="text-2xl text-foreground">{name}</h1>
- </div>
- )}
- </div>
- <div className="flex items-center space-x-2">
- <Button asChild type="default">
- <Link href={`/project/${ref}/settings/functions`}>Manage secrets</Link>
- </Button>
- {isNewAPIDocsEnabled && (
- <APIDocsButton
- section={
- functionSlug !== undefined
- ? ['edge-functions', functionSlug]
- : ['edge-functions']
- }
- />
- )}
- <DocsButton href="https://supabase.com/docs/guides/functions" />
- </div>
- </div>
- </div>
- </div>
- {functionSlug !== undefined && <FunctionsNav item={selectedFunction} />}
- </div>
- <div
- className={[
- 'mx-auto flex h-full w-full flex-grow flex-col transition-all',
- '1xl:px-28 gap-4 px-5 lg:px-16 xl:px-24 2xl:px-32',
- ].join(' ')}
- >
- {children}
- </div>
- </div>
- )}
- </ProjectLayout>
- )
-}
-
-export default withAuth(FunctionsLayout)
diff --git a/apps/studio/components/layouts/PageLayout/PageHeader.tsx b/apps/studio/components/layouts/PageLayout/PageHeader.tsx
index e929f97817a..69f56e325ee 100644
--- a/apps/studio/components/layouts/PageLayout/PageHeader.tsx
+++ b/apps/studio/components/layouts/PageLayout/PageHeader.tsx
@@ -1,6 +1,7 @@
+import { useParams } from 'common'
+import { ChevronLeft } from 'lucide-react'
import { Fragment, ReactNode } from 'react'
-import { useParams } from 'common'
import { cn } from 'ui'
import {
Breadcrumb,
@@ -17,8 +18,9 @@ interface PageHeaderProps {
subtitle?: string
icon?: ReactNode
breadcrumbs?: Array<{
- label: string
+ label?: string
href?: string
+ element?: ReactNode
}>
primaryActions?: ReactNode
secondaryActions?: ReactNode
@@ -45,28 +47,51 @@ export const PageHeader = ({
{(displayBreadcrumbs.length > 0 ||
(isCompact && (title || primaryActions || secondaryActions))) && (
<div className={cn('flex items-center gap-4', isCompact ? 'justify-between' : 'mb-4')}>
- {displayBreadcrumbs.length > 0 ? (
- <Breadcrumb className={cn('text-foreground-muted', isCompact && 'text-base')}>
- <BreadcrumbList className={isCompact ? 'text-base' : 'text-xs'}>
- {displayBreadcrumbs.map((item, index) => (
- <Fragment key={item.label}>
- <BreadcrumbItem>
- {item.href ? (
- <BreadcrumbLink href={!!ref ? item.href.replace('[ref]', ref) : item.href}>
- {item.label}
- </BreadcrumbLink>
- ) : (
- <BreadcrumbPageItem>{item.label}</BreadcrumbPageItem>
- )}
- </BreadcrumbItem>
- {index < displayBreadcrumbs.length - 1 && <BreadcrumbSeparator />}
- </Fragment>
- ))}
- </BreadcrumbList>
- </Breadcrumb>
- ) : isCompact ? (
- title
- ) : null}
+ <div className="flex items-center gap-4">
+ {breadcrumbs.length > 0 ? (
+ <Breadcrumb className={cn('text-foreground-muted', isCompact && 'text-base')}>
+ <BreadcrumbList className={isCompact ? 'text-base' : 'text-xs'}>
+ {breadcrumbs.map((item, index) => (
+ <Fragment key={item.label || `breadcrumb-${index}`}>
+ <BreadcrumbItem>
+ {item.element ? (
+ item.element
+ ) : item.href ? (
+ <BreadcrumbLink
+ className="flex items-center gap-2"
+ href={!!ref ? item.href.replace('[ref]', ref) : item.href}
+ >
+ {breadcrumbs.length === 1 && !isCompact && (
+ <ChevronLeft size={16} strokeWidth={1.5} />
+ )}
+ {item.label}
+ </BreadcrumbLink>
+ ) : (
+ <BreadcrumbPageItem className="flex items-center gap-2">
+ {breadcrumbs.length === 1 && (
+ <ChevronLeft size={16} strokeWidth={1.5} />
+ )}
+ {item.label}
+ </BreadcrumbPageItem>
+ )}
+ </BreadcrumbItem>
+ {index < breadcrumbs.length - 1 && <BreadcrumbSeparator />}
+ </Fragment>
+ ))}
+ {isCompact && title && (
+ <>
+ <BreadcrumbSeparator />
+ <BreadcrumbItem>
+ <BreadcrumbPageItem>{title}</BreadcrumbPageItem>
+ </BreadcrumbItem>
+ </>
+ )}
+ </BreadcrumbList>
+ </Breadcrumb>
+ ) : isCompact ? (
+ title
+ ) : null}
+ </div>
{isCompact && (
<div className="flex items-center gap-2">
{secondaryActions && (
diff --git a/apps/studio/components/layouts/PageLayout/PageLayout.tsx b/apps/studio/components/layouts/PageLayout/PageLayout.tsx
index e01c4201830..6048e6def85 100644
--- a/apps/studio/components/layouts/PageLayout/PageLayout.tsx
+++ b/apps/studio/components/layouts/PageLayout/PageLayout.tsx
@@ -20,8 +20,9 @@ interface PageLayoutProps {
subtitle?: string
icon?: ReactNode
breadcrumbs?: Array<{
- label: string
+ label?: string
href?: string
+ element?: ReactNode
}>
primaryActions?: ReactNode
secondaryActions?: ReactNode
@@ -46,7 +47,7 @@ interface PageLayoutProps {
* @param title - Title rendered in page header
* @param subtitle - Subtitle rendered in page header, below title
* @param icon - Icon rendered in Page header, to the left of title and subtitle
- * @param breadcrumbs - Breadcrumbs rendered in page header, above title
+ * @param breadcrumbs - Breadcrumbs rendered in page header, above title. Can be string labels with hrefs or custom elements
* @param primaryActions - TBD
* @param secondaryActions - TBD
* @param navigationItems - Tab navigation rendered below the page header
@@ -70,7 +71,7 @@ export const PageLayout = ({
const router = useRouter()
return (
- <div className="w-full">
+ <div className="w-full min-h-full flex flex-col items-stretch">
<ScaffoldContainer
size={size}
className={cn(
@@ -97,7 +98,7 @@ export const PageLayout = ({
{/* Navigation section */}
{navigationItems.length > 0 && (
- <NavMenu className={cn('mt-4', size === 'full' && 'border-none')}>
+ <NavMenu className={cn(isCompact ? 'mt-2' : 'mt-4', size === 'full' && 'border-none')}>
{navigationItems.map((item) => (
<NavMenuItem key={item.label} active={router.asPath === item.href}>
{item.href ? (
diff --git a/apps/studio/components/layouts/useLayoutNavCommands.ts b/apps/studio/components/layouts/useLayoutNavCommands.ts
index d67bbec45f6..63d19540e11 100644
--- a/apps/studio/components/layouts/useLayoutNavCommands.ts
+++ b/apps/studio/components/layouts/useLayoutNavCommands.ts
@@ -1,15 +1,15 @@
+import { useIsLoggedIn } from 'common'
import { useApiDocsGotoCommands } from 'components/interfaces/ProjectAPIDocs/ProjectAPIDocs.Commands'
import { useAdvisorsGoToCommands } from './AdvisorsLayout/Advisors.Commands'
import { useAuthGotoCommands } from './AuthLayout/Auth.Commands'
import { useDatabaseGotoCommands } from './DatabaseLayout/Database.Commands'
-import { useFunctionsGotoCommands } from './FunctionsLayout/Functions.Commands'
+import { useFunctionsGotoCommands } from './EdgeFunctionsLayout/EdgeFunctions.Commands'
import { useLogsGotoCommands } from './LogsLayout/Logs.Commands'
import { useProjectSettingsGotoCommands } from './ProjectSettingsLayout/ProjectSettings.Commands'
import { useReportsGotoCommands } from './ReportsLayout/Reports.Commands'
-import { useStorageGotoCommands } from './StorageLayout/Storage.Commands'
import { useSqlEditorGotoCommands } from './SQLEditorLayout/SqlEditor.Commands'
+import { useStorageGotoCommands } from './StorageLayout/Storage.Commands'
import { useTableEditorGotoCommands } from './TableEditorLayout/TableEditor.Commands'
-import { useIsLoggedIn } from 'common'
export function useLayoutNavCommands() {
const isLoggedIn = useIsLoggedIn()
diff --git a/apps/studio/components/ui/ProductMenu/ProductMenu.tsx b/apps/studio/components/ui/ProductMenu/ProductMenu.tsx
index ecc808441e7..8576e6f002d 100644
--- a/apps/studio/components/ui/ProductMenu/ProductMenu.tsx
+++ b/apps/studio/components/ui/ProductMenu/ProductMenu.tsx
@@ -28,9 +28,7 @@ const ProductMenu = ({ page, menu }: ProductMenuProps) => {
/>
<div>
{group.items.map((item) => {
- const isActive = !!item.pages
- ? item.pages.includes(page ?? '')
- : page === item.key || (page === undefined && item.key === 'main')
+ const isActive = !!item.pages ? item.pages.includes(page) : page === item.key
return (
<ProductMenuItem
diff --git a/apps/studio/components/ui/ProductMenu/ProductMenu.types.ts b/apps/studio/components/ui/ProductMenu/ProductMenu.types.ts
index b9c87105754..4a40e51c24b 100644
--- a/apps/studio/components/ui/ProductMenu/ProductMenu.types.ts
+++ b/apps/studio/components/ui/ProductMenu/ProductMenu.types.ts
@@ -18,5 +18,5 @@ export interface ProductMenuGroupItem {
isExternal?: boolean
disabled?: boolean
label?: string
- pages?: string[]
+ pages?: (string | undefined)[]
}
diff --git a/apps/studio/pages/project/[ref]/database/functions.tsx b/apps/studio/pages/project/[ref]/database/functions.tsx
index c51ff1136e6..0fba9273945 100644
--- a/apps/studio/pages/project/[ref]/database/functions.tsx
+++ b/apps/studio/pages/project/[ref]/database/functions.tsx
@@ -1,20 +1,20 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useState } from 'react'
+import { useIsInlineEditorEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { CreateFunction, DeleteFunction } from 'components/interfaces/Database'
import FunctionsList from 'components/interfaces/Database/Functions/FunctionsList/FunctionsList'
import DatabaseLayout from 'components/layouts/DatabaseLayout/DatabaseLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import NoPermission from 'components/ui/NoPermission'
import { DatabaseFunction } from 'data/database-functions/database-functions-query'
import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
-import type { NextPageWithLayout } from 'types'
-import DefaultLayout from 'components/layouts/DefaultLayout'
-import { useIsInlineEditorEnabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { useAppStateSnapshot } from 'state/app-state'
+import type { NextPageWithLayout } from 'types'
-const FunctionsPage: NextPageWithLayout = () => {
+const DatabaseFunctionsPage: NextPageWithLayout = () => {
const [selectedFunction, setSelectedFunction] = useState<DatabaseFunction | undefined>()
const [showCreateFunctionForm, setShowCreateFunctionForm] = useState(false)
const [showDeleteFunctionForm, setShowDeleteFunctionForm] = useState(false)
@@ -101,10 +101,10 @@ $$;`,
)
}
-FunctionsPage.getLayout = (page) => (
+DatabaseFunctionsPage.getLayout = (page) => (
<DefaultLayout>
<DatabaseLayout title="Database">{page}</DatabaseLayout>
</DefaultLayout>
)
-export default FunctionsPage
+export default DatabaseFunctionsPage
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
index 169b1c57e2c..df1d37567b0 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/details.tsx
@@ -1,12 +1,17 @@
import { EdgeFunctionDetails } from 'components/interfaces/Functions'
-import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
+import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'
import type { NextPageWithLayout } from 'types'
-const PageLayout: NextPageWithLayout = () => <EdgeFunctionDetails />
+const PageLayout: NextPageWithLayout = () => (
+ <div className="px-6">
+ <EdgeFunctionDetails />
+ </div>
+)
+
PageLayout.getLayout = (page) => (
<DefaultLayout>
- <FunctionsLayout>{page}</FunctionsLayout>
+ <EdgeFunctionDetailsLayout>{page}</EdgeFunctionDetailsLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
index 077b1818dd3..ae12244addd 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/index.tsx
@@ -7,7 +7,8 @@ import { useRouter } from 'next/router'
import { useMemo, useState } from 'react'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
-import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
+import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'
import AreaChart from 'components/ui/Charts/AreaChart'
import StackedBarChart from 'components/ui/Charts/StackedBarChart'
import NoPermission from 'components/ui/NoPermission'
@@ -30,7 +31,6 @@ import {
Button,
WarningIcon,
} from 'ui'
-import DefaultLayout from 'components/layouts/DefaultLayout'
const CHART_INTERVALS: ChartIntervals[] = [
{
@@ -80,7 +80,6 @@ const PageLayout: NextPageWithLayout = () => {
slug: functionSlug,
})
const id = selectedFunction?.id
-
const reqStatsResult = useFunctionsReqStatsQuery({
projectRef,
functionId: id,
@@ -157,174 +156,183 @@ const PageLayout: NextPageWithLayout = () => {
if (!canReadFunction) {
return <NoPermission isFullPage resourceText="access this edge function" />
}
- return (
- <div className="space-y-6 py-3">
- <div className="flex flex-row items-center gap-2">
- <div className="flex items-center">
- {CHART_INTERVALS.map((item, i) => {
- const classes = []
- if (i === 0) {
- classes.push('rounded-tr-none rounded-br-none')
- } else if (i === CHART_INTERVALS.length - 1) {
- classes.push('rounded-tl-none rounded-bl-none')
- } else {
- classes.push('rounded-none')
- }
+ return (
+ <div className="px-6 w-full pt-6">
+ <div className="space-y-6">
+ <div className="flex flex-row items-center gap-2">
+ <div className="flex items-center">
+ {CHART_INTERVALS.map((item, i) => {
+ const classes = []
- return (
- <Button
- key={`function-filter-${i}`}
- type={interval === item.key ? 'secondary' : 'default'}
- onClick={() => setInterval(item.key)}
- className={classes.join(' ')}
- >
- {item.label}
- </Button>
- )
- })}
- </div>
+ if (i === 0) {
+ classes.push('rounded-tr-none rounded-br-none')
+ } else if (i === CHART_INTERVALS.length - 1) {
+ classes.push('rounded-tl-none rounded-bl-none')
+ } else {
+ classes.push('rounded-none')
+ }
- <span className="text-xs text-foreground-light">
- Statistics for past {selectedInterval.label}
- </span>
- </div>
- <div>
- <div className="grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-2 lg:gap-8">
- <ReportWidget
- title="Execution time"
- tooltip="Average execution time of function invocations"
- data={execTimeChartData}
- isLoading={reqStatsResult.isLoading}
- renderer={(props) => {
- return isErrorExecTime ? (
- <Alert_Shadcn_ variant="warning">
- <WarningIcon />
- <AlertTitle_Shadcn_>Failed to reterieve execution time</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{execTimeError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- ) : (
- <AreaChart
- className="w-full"
- xAxisKey="timestamp"
- customDateFormat={selectedInterval.format}
- yAxisKey="avg_execution_time"
- data={props.data}
- format="ms"
- highlightedValue={meanBy(props.data, 'avg_execution_time')}
- />
+ return (
+ <Button
+ key={`function-filter-${i}`}
+ type={interval === item.key ? 'secondary' : 'default'}
+ onClick={() => setInterval(item.key)}
+ className={classes.join(' ')}
+ >
+ {item.label}
+ </Button>
)
- }}
- />
- <ReportWidget
- title="Invocations"
- data={invocationsChartData}
- isLoading={reqStatsResult.isLoading}
- renderer={(props) => {
- if (isErrorInvocations) {
- return (
+ })}
+ </div>
+
+ <span className="text-xs text-foreground-light">
+ Statistics for past {selectedInterval.label}
+ </span>
+ </div>
+ <div>
+ <div className="grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-2 lg:gap-8">
+ <ReportWidget
+ title="Execution time"
+ tooltip="Average execution time of function invocations"
+ data={execTimeChartData}
+ isLoading={reqStatsResult.isLoading}
+ renderer={(props) => {
+ return isErrorExecTime ? (
<Alert_Shadcn_ variant="warning">
<WarningIcon />
- <AlertTitle_Shadcn_>Failed to reterieve invocations</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{invocationsError.message}</AlertDescription_Shadcn_>
+ <AlertTitle_Shadcn_>Failed to reterieve execution time</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>{execTimeError.message}</AlertDescription_Shadcn_>
</Alert_Shadcn_>
+ ) : (
+ <AreaChart
+ className="w-full"
+ xAxisKey="timestamp"
+ customDateFormat={selectedInterval.format}
+ yAxisKey="avg_execution_time"
+ data={props.data}
+ format="ms"
+ highlightedValue={meanBy(props.data, 'avg_execution_time')}
+ />
)
- } else {
- const data = props.data
- .map((d: any) => [
- {
- status: '2xx',
- count: d.success_count,
- timestamp: d.timestamp,
- },
- {
- status: '3xx',
- count: d.redirect_count,
- timestamp: d.timestamp,
- },
- {
- status: '4xx',
- count: d.client_err_count,
- timestamp: d.timestamp,
- },
- {
- status: '5xx',
- count: d.server_err_count,
- timestamp: d.timestamp,
- },
- ])
- .flat()
+ }}
+ />
+ <ReportWidget
+ title="Invocations"
+ data={invocationsChartData}
+ isLoading={reqStatsResult.isLoading}
+ renderer={(props) => {
+ if (isErrorInvocations) {
+ return (
+ <Alert_Shadcn_ variant="warning">
+ <WarningIcon />
+ <AlertTitle_Shadcn_>Failed to reterieve invocations</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ {invocationsError.message}
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )
+ } else {
+ const data = props.data
+ .map((d: any) => [
+ {
+ status: '2xx',
+ count: d.success_count,
+ timestamp: d.timestamp,
+ },
+ {
+ status: '3xx',
+ count: d.redirect_count,
+ timestamp: d.timestamp,
+ },
+ {
+ status: '4xx',
+ count: d.client_err_count,
+ timestamp: d.timestamp,
+ },
+ {
+ status: '5xx',
+ count: d.server_err_count,
+ timestamp: d.timestamp,
+ },
+ ])
+ .flat()
- return (
- <StackedBarChart
+ return (
+ <StackedBarChart
+ className="w-full"
+ xAxisKey="timestamp"
+ yAxisKey="count"
+ stackKey="status"
+ data={data}
+ highlightedValue={sumBy(data, 'count')}
+ customDateFormat={selectedInterval.format}
+ stackColors={['brand', 'slate', 'yellow', 'red']}
+ onBarClick={() => {
+ router.push(
+ `/project/${projectRef}/functions/${functionSlug}/invocations?its=${startDate.toISOString()}`
+ )
+ }}
+ />
+ )
+ }
+ }}
+ />
+ <ReportWidget
+ title="CPU time"
+ tooltip="Average CPU time usage for the function"
+ data={resourceUsageChartData}
+ isLoading={resourceUsageResult.isLoading}
+ renderer={(props) => {
+ return isErrorResourceUsage ? (
+ <Alert_Shadcn_ variant="warning">
+ <WarningIcon />
+ <AlertTitle_Shadcn_>Failed to retrieve CPU time</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ {resourceUsageError.message}
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ ) : (
+ <AreaChart
className="w-full"
xAxisKey="timestamp"
- yAxisKey="count"
- stackKey="status"
- data={data}
- highlightedValue={sumBy(data, 'count')}
customDateFormat={selectedInterval.format}
- stackColors={['brand', 'slate', 'yellow', 'red']}
- onBarClick={() => {
- router.push(
- `/project/${projectRef}/functions/${functionSlug}/invocations?its=${startDate.toISOString()}`
- )
- }}
+ yAxisKey="avg_cpu_time_used"
+ data={props.data}
+ format="ms"
+ highlightedValue={meanBy(props.data, 'avg_cpu_time_used')}
/>
)
- }
- }}
- />
- <ReportWidget
- title="CPU time"
- tooltip="Average CPU time usage for the function"
- data={resourceUsageChartData}
- isLoading={resourceUsageResult.isLoading}
- renderer={(props) => {
- return isErrorResourceUsage ? (
- <Alert_Shadcn_ variant="warning">
- <WarningIcon />
- <AlertTitle_Shadcn_>Failed to retrieve CPU time</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{resourceUsageError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- ) : (
- <AreaChart
- className="w-full"
- xAxisKey="timestamp"
- customDateFormat={selectedInterval.format}
- yAxisKey="avg_cpu_time_used"
- data={props.data}
- format="ms"
- highlightedValue={meanBy(props.data, 'avg_cpu_time_used')}
- />
- )
- }}
- />
- <ReportWidget
- title="Memory"
- tooltip="Average memory usage for the function"
- data={resourceUsageChartData}
- isLoading={resourceUsageResult.isLoading}
- renderer={(props) => {
- return isErrorResourceUsage ? (
- <Alert_Shadcn_ variant="warning">
- <WarningIcon />
- <AlertTitle_Shadcn_>Failed to retrieve memory usage</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>{resourceUsageError.message}</AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- ) : (
- <AreaChart
- className="w-full"
- xAxisKey="timestamp"
- customDateFormat={selectedInterval.format}
- yAxisKey="avg_memory_used"
- data={props.data}
- format="MB"
- highlightedValue={meanBy(props.data, 'avg_memory_used')}
- />
- )
- }}
- />
+ }}
+ />
+ <ReportWidget
+ title="Memory"
+ tooltip="Average memory usage for the function"
+ data={resourceUsageChartData}
+ isLoading={resourceUsageResult.isLoading}
+ renderer={(props) => {
+ return isErrorResourceUsage ? (
+ <Alert_Shadcn_ variant="warning">
+ <WarningIcon />
+ <AlertTitle_Shadcn_>Failed to retrieve memory usage</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ {resourceUsageError.message}
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ ) : (
+ <AreaChart
+ className="w-full"
+ xAxisKey="timestamp"
+ customDateFormat={selectedInterval.format}
+ yAxisKey="avg_memory_used"
+ data={props.data}
+ format="MB"
+ highlightedValue={meanBy(props.data, 'avg_memory_used')}
+ />
+ )
+ }}
+ />
+ </div>
</div>
</div>
</div>
@@ -333,7 +341,7 @@ const PageLayout: NextPageWithLayout = () => {
PageLayout.getLayout = (page) => (
<DefaultLayout>
- <FunctionsLayout>{page}</FunctionsLayout>
+ <EdgeFunctionDetailsLayout>{page}</EdgeFunctionDetailsLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
index 63cb65a8620..6925123da72 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/invocations.tsx
@@ -1,14 +1,10 @@
import { useParams } from 'common'
-
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
-import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
+import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import type { NextPageWithLayout } from 'types'
-/**
- * Placeholder page for logs previewers until we figure out where to slot them
- */
export const LogPage: NextPageWithLayout = () => {
const { ref, functionSlug } = useParams()
const { data: selectedFunction, isLoading } = useEdgeFunctionQuery({
@@ -19,19 +15,20 @@ export const LogPage: NextPageWithLayout = () => {
if (selectedFunction === undefined || isLoading) return null
return (
- <LogsPreviewer
- condensedLayout
- projectRef={ref as string}
- queryType={'fn_edge'}
- filterOverride={{ function_id: selectedFunction.id }}
- filterPanelClassName="px-0"
- />
+ <div className="flex-1">
+ <LogsPreviewer
+ condensedLayout
+ projectRef={ref as string}
+ queryType="fn_edge"
+ filterOverride={{ function_id: selectedFunction.id }}
+ />
+ </div>
)
}
LogPage.getLayout = (page) => (
<DefaultLayout>
- <FunctionsLayout>{page}</FunctionsLayout>
+ <EdgeFunctionDetailsLayout>{page}</EdgeFunctionDetailsLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
index abf9396d1e8..ff82efab095 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/logs.tsx
@@ -1,7 +1,7 @@
-import { useParams } from 'common/hooks'
+import { useParams } from 'common'
import LogsPreviewer from 'components/interfaces/Settings/Logs/LogsPreviewer'
-import FunctionsLayout from 'components/layouts/FunctionsLayout/FunctionsLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
+import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'
import { useEdgeFunctionQuery } from 'data/edge-functions/edge-function-query'
import type { NextPageWithLayout } from 'types'
@@ -16,19 +16,20 @@ export const LogPage: NextPageWithLayout = () => {
if (selectedFunction === undefined || isLoading) return null
return (
- <LogsPreviewer
- condensedLayout
- projectRef={ref as string}
- queryType={'functions'}
- filterOverride={{ 'metadata.function_id': selectedFunction.id }}
- filterPanelClassName="px-0"
- />
+ <div className="flex-1">
+ <LogsPreviewer
+ condensedLayout
+ projectRef={ref as string}
+ queryType="functions"
+ filterOverride={{ 'metadata.function_id': selectedFunction.id }}
+ />
+ </div>
)
}
LogPage.getLayout = (page) => (
<DefaultLayout>
- <FunctionsLayout>{page}</FunctionsLayout>
+ <EdgeFunctionDetailsLayout>{page}</EdgeFunctionDetailsLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/project/[ref]/functions/index.tsx b/apps/studio/pages/project/[ref]/functions/index.tsx
index ceb7d1655b9..6ce1e9e9e0f 100644
--- a/apps/studio/pages/project/[ref]/functions/index.tsx
+++ b/apps/studio/pages/project/[ref]/functions/index.tsx
@@ -1,6 +1,6 @@
-import { useParams } from 'common'
-import { AiIconAnimation, Button, Dialog, DialogContent, DialogSection, DialogTrigger } from 'ui'
+import { ExternalLink } from 'lucide-react'
+import { useParams } from 'common'
import {
EdgeFunctionsListItem,
FunctionsEmptyState,
@@ -17,10 +17,10 @@ import { DocsButton } from 'components/ui/DocsButton'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
import { useAppStateSnapshot } from 'state/app-state'
-import { ExternalLink } from 'lucide-react'
import type { NextPageWithLayout } from 'types'
+import { AiIconAnimation, Button, Dialog, DialogContent, DialogSection, DialogTrigger } from 'ui'
-const FunctionsPage: NextPageWithLayout = () => {
+const EdgeFunctionsPage: NextPageWithLayout = () => {
const { ref } = useParams()
const { setAiAssistantPanel } = useAppStateSnapshot()
@@ -48,8 +48,22 @@ const FunctionsPage: NextPageWithLayout = () => {
)
const secondaryActions = [
+ ...(!hasFunctions
+ ? [
+ <Button asChild key="edge-function-examples" type="default" icon={<ExternalLink />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions"
+ >
+ Examples
+ </a>
+ </Button>,
+ ]
+ : []),
<DocsButton key="docs" href="https://supabase.com/docs/guides/functions" />,
<ButtonTooltip
+ key="edge-function-create"
type="default"
className="px-1 pointer-events-auto"
icon={<AiIconAnimation size={16} />}
@@ -77,20 +91,6 @@ const FunctionsPage: NextPageWithLayout = () => {
/>,
]
- if (!hasFunctions) {
- secondaryActions.unshift(
- <Button asChild type="default" icon={<ExternalLink />}>
- <a
- target="_blank"
- rel="noreferrer"
- href="https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions"
- >
- Examples
- </a>
- </Button>
- )
- }
-
return (
<PageLayout
size="large"
@@ -142,7 +142,7 @@ const FunctionsPage: NextPageWithLayout = () => {
)
}
-FunctionsPage.getLayout = (page) => {
+EdgeFunctionsPage.getLayout = (page) => {
return (
<DefaultLayout>
<EdgeFunctionsLayout>{page}</EdgeFunctionsLayout>
@@ -150,4 +150,4 @@ FunctionsPage.getLayout = (page) => {
)
}
-export default FunctionsPage
+export default EdgeFunctionsPage