Skip to content

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

Add UX guardrails for edge functions RE unsaved and unimported files (#41921)

Joshen Limf293036ec78c
diff --git a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts
deleted file mode 100644
index 67207cc4cce..00000000000
--- a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunction.types.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export type EdgeFunctionFile = {
- id: number
- name: string
- content: string
- selected?: boolean
-}
diff --git a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
index f1e2c0fbc8a..0eb953d73cf 100644
--- a/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
+++ b/apps/studio/components/interfaces/EdgeFunctions/EdgeFunctions.utils.ts
@@ -1,12 +1,15 @@
-import { EdgeFunctionFile } from './EdgeFunction.types'
+import { common, dirname, relative } from '@std/path/posix'
-export const getFallbackImportMapPath = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {
+import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
+import { EdgeFunctionBodyData } from '@/data/edge-functions/edge-function-body-query'
+
+export const getFallbackImportMapPath = (files: Omit<FileData, 'id' | 'content' | 'state'>[]) => {
// try to find a deno.json or import_map.json file
const regex = /^.*?(deno|import_map).json*$/i
return files.find(({ name }) => regex.test(name))?.name
}
-export const getFallbackEntrypointPath = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {
+export const getFallbackEntrypointPath = (files: Omit<FileData, 'id' | 'content' | 'state'>[]) => {
// when there's no matching entrypoint path is set,
// we use few heuristics to find an entrypoint file
// 1. If the function has only a single TS / JS file, if so set it as entrypoint
@@ -28,8 +31,76 @@ export const getFallbackEntrypointPath = (files: Omit<EdgeFunctionFile, 'id' | '
}
}
-export const getStaticPatterns = (files: Omit<EdgeFunctionFile, 'id' | 'content'>[]) => {
+export const getStaticPatterns = (files: Omit<FileData, 'id' | 'content' | 'state'>[]) => {
return files
.filter(({ name }) => !name.match(/\.(js|ts|jsx|tsx|json|wasm)$/i))
.map(({ name }) => name)
}
+
+function getBasePath(entrypoint: string | undefined, fileNames: string[]): string {
+ if (!entrypoint) {
+ return '/'
+ }
+
+ let candidate = fileNames.find((name) => entrypoint.endsWith(name))
+
+ if (candidate) {
+ return dirname(candidate)
+ } else {
+ try {
+ return dirname(new URL(entrypoint).pathname)
+ } catch (e) {
+ console.error('Failed to parse entrypoint', entrypoint)
+ return '/'
+ }
+ }
+}
+
+export const formatFunctionBodyToFiles = ({
+ functionBody,
+ entrypointPath,
+}: {
+ functionBody: EdgeFunctionBodyData
+ entrypointPath?: string
+}) => {
+ const entrypoint_path = functionBody.metadata?.deno2_entrypoint_path ?? entrypointPath
+
+ // Set files from API response when available
+ if (entrypoint_path) {
+ const base_path = getBasePath(
+ entrypoint_path,
+ functionBody.files.map((file) => file.name)
+ )
+ const filesWithRelPath = functionBody.files
+ // set file paths relative to entrypoint
+ .map((file: { name: string; content: string }) => {
+ try {
+ // if the current file and base path doesn't share a common path,
+ // return unmodified file
+ const common_path = common([base_path, file.name])
+ if (common_path === '' || common_path === '/tmp/') {
+ return file
+ }
+
+ // prepend "/" to turn relative paths to absolute
+ file.name = relative('/' + base_path, '/' + file.name)
+ return file
+ } catch (e) {
+ console.error(e)
+ // return unmodified file
+ return file
+ }
+ })
+
+ return filesWithRelPath.map((file: { name: string; content: string }, index: number) => {
+ return {
+ id: index + 1,
+ name: file.name,
+ content: file.content,
+ state: 'unchanged',
+ } as FileData
+ })
+ }
+
+ return []
+}
diff --git a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
index f88fa07ce42..2bc1979e236 100644
--- a/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
+++ b/apps/studio/components/interfaces/Functions/EdgeFunctionDetails/EdgeFunctionDetails.tsx
@@ -10,7 +10,7 @@ import { toast } from 'sonner'
import z from 'zod'
import { useParams } from 'common'
-import AlertError from 'components/ui/AlertError'
+import { AlertError } from 'components/ui/AlertError'
import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
@@ -35,8 +35,6 @@ import {
Form_Shadcn_,
FormControl_Shadcn_,
FormField_Shadcn_,
- Input,
- Input_Shadcn_,
Switch,
Tabs_Shadcn_ as Tabs,
TabsContent_Shadcn_ as TabsContent,
@@ -44,6 +42,7 @@ import {
TabsTrigger_Shadcn_ as TabsTrigger,
} from 'ui'
import { GenericSkeletonLoader } from 'ui-patterns'
+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'
@@ -172,7 +171,7 @@ export const EdgeFunctionDetails = () => {
return (
<PageContainer size="full">
<PageSection orientation="horizontal">
- <PageSectionSummary className="gap-6">
+ <PageSectionSummary className="gap-6 !self-start">
<PageSectionTitle>Details</PageSectionTitle>
{isLoading && <GenericSkeletonLoader />}
{isError && (
@@ -190,10 +189,10 @@ export const EdgeFunctionDetails = () => {
<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
+ readOnly
size="small"
+ className="font-mono input-mono"
value={functionUrl}
/>
</dd>
@@ -269,7 +268,7 @@ export const EdgeFunctionDetails = () => {
description="Your slug and endpoint URL will remain the same"
>
<FormControl_Shadcn_>
- <Input_Shadcn_
+ <Input
{...field}
className="w-64"
disabled={!canUpdateEdgeFunction}
diff --git a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts
index 4853d7ff8f7..aead3169d71 100644
--- a/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts
+++ b/apps/studio/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types.ts
@@ -2,7 +2,7 @@ export type FileData = {
id: number
name: string
content: string
- selected?: boolean
+ state: 'new' | 'modified' | 'unchanged'
}
export enum FileAction {
@@ -15,3 +15,13 @@ export type FileActionResult =
| { action: FileAction.CREATE_NEW }
| { action: FileAction.REPLACE_EXISTING; index: number }
| { action: FileAction.REPLACE_NEW; index: number }
+
+export type TreeChildData = {
+ id: string
+ name: string
+ metadata: {
+ isEditing: boolean
+ originalId: number
+ state: FileData['state']
+ }
+}
diff --git a/apps/studio/components/ui/FileExplorerAndEditor/index.tsx b/apps/studio/components/ui/FileExplorerAndEditor/index.tsx
index 94dfb1f52f1..ba93da877cd 100644
--- a/apps/studio/components/ui/FileExplorerAndEditor/index.tsx
+++ b/apps/studio/components/ui/FileExplorerAndEditor/index.tsx
@@ -6,16 +6,20 @@ import { toast } from 'sonner'
import { AIEditor } from 'components/ui/AIEditor'
import {
Button,
+ cn,
ContextMenu_Shadcn_,
ContextMenuContent_Shadcn_,
ContextMenuItem_Shadcn_,
ContextMenuSeparator_Shadcn_,
ContextMenuTrigger_Shadcn_,
flattenTree,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
TreeView,
TreeViewItem,
} from 'ui'
-import { FileAction, type FileData } from './FileExplorerAndEditor.types'
+import { FileAction, TreeChildData, type FileData } from './FileExplorerAndEditor.types'
import {
extractZipFile,
getFileAction,
@@ -33,6 +37,9 @@ interface FileExplorerAndEditorProps {
connectionString?: string | null
orgSlug?: string
}
+
+ selectedFileId?: number
+ setSelectedFileId?: (id: number) => void
}
const denoJsonDefaultContent = JSON.stringify({ imports: {} }, null, '\t')
@@ -42,17 +49,23 @@ export const FileExplorerAndEditor = ({
onFilesChange,
aiEndpoint,
aiMetadata,
+ selectedFileId: extSelectedFileId,
+ setSelectedFileId: extSetSelectedFileId,
}: FileExplorerAndEditorProps) => {
const [isDragOver, setIsDragOver] = useState(false)
+ const [_selectedFileId, _setSelectedFileId] = useState<number>(files[0]?.id)
const [extractionProgress, setExtractionProgress] = useState<{
current: number
total: number
} | null>(null)
- const selectedFile = files.find((f) => f.selected) ?? files[0]
+ const selectedFileId = extSelectedFileId ?? _selectedFileId
+ const setSelectedFileId = extSetSelectedFileId ?? _setSelectedFileId
+
+ const selectedFile = files.find((f) => f.id === selectedFileId)
const isExtractingZip = extractionProgress !== null
- const [treeData, setTreeData] = useState({
+ const [treeData, setTreeData] = useState<{ name: string; children: TreeChildData[] }>({
name: '',
children: files.map((file) => ({
id: file.id.toString(),
@@ -60,28 +73,27 @@ export const FileExplorerAndEditor = ({
metadata: {
isEditing: false,
originalId: file.id,
+ state: file.state,
},
})),
})
const handleChange = (value: string) => {
const updatedFiles = files.map((file) =>
- file.id === selectedFile.id ? { ...file, content: value } : file
+ file.id === selectedFileId ? { ...file, content: value } : file
)
+
onFilesChange(updatedFiles)
}
const addNewFile = () => {
const newId = Math.max(0, ...files.map((f) => f.id)) + 1
const updatedFiles = files.map((f) => ({ ...f, selected: false }))
+
+ setSelectedFileId(newId)
onFilesChange([
...updatedFiles,
- {
- id: newId,
- name: `file${newId}.ts`,
- content: '',
- selected: true,
- },
+ { id: newId, name: `file${newId}.ts`, content: '', state: 'new' },
])
}
@@ -141,7 +153,6 @@ export const FileExplorerAndEditor = ({
updatedFiles[actionResult.index] = {
...updatedFiles[actionResult.index],
content: file.content,
- selected: false,
}
replacedCount++
hasReplacedFiles = true
@@ -151,7 +162,6 @@ export const FileExplorerAndEditor = ({
newFiles[actionResult.index] = {
...newFiles[actionResult.index],
content: file.content,
- selected: false,
}
replacedCount++
break
@@ -168,7 +178,7 @@ export const FileExplorerAndEditor = ({
id: newId,
name: file.name,
content: file.content,
- selected: false,
+ state: 'new',
})
extractedCount++
break
@@ -199,11 +209,11 @@ export const FileExplorerAndEditor = ({
// Select the last added/modified file
if (newFiles.length > 0) {
- newFiles[newFiles.length - 1].selected = true
+ setSelectedFileId(newFiles[newFiles.length - 1].id)
onFilesChange([...updatedFiles, ...newFiles])
} else if (hasReplacedFiles) {
// If we only replaced files, select the first one
- updatedFiles[0].selected = true
+ setSelectedFileId(updatedFiles[0].id)
onFilesChange(updatedFiles)
}
}
@@ -218,6 +228,7 @@ export const FileExplorerAndEditor = ({
metadata: {
isEditing: file.id === id,
originalId: file.id,
+ state: file.state,
},
})),
})
@@ -233,6 +244,7 @@ export const FileExplorerAndEditor = ({
metadata: {
isEditing: false,
originalId: file.id,
+ state: file.state,
},
})),
})
@@ -254,8 +266,8 @@ export const FileExplorerAndEditor = ({
return exitEditMode()
}
- const updatedFiles = files.map((file) =>
- file.id === id
+ const updatedFiles = files.map((file) => {
+ return file.id === id
? {
...file,
name: newName,
@@ -265,7 +277,7 @@ export const FileExplorerAndEditor = ({
: file.content,
}
: file
- )
+ })
onFilesChange(updatedFiles)
}
@@ -276,26 +288,17 @@ export const FileExplorerAndEditor = ({
}
const fileToDelete = files.find((f) => f.id === id)
- const isSelected = fileToDelete?.selected
-
+ const isSelected = fileToDelete?.id === selectedFileId
const updatedFiles = files.filter((file) => file.id !== id)
// If the deleted file was selected, select another file
if (isSelected && updatedFiles.length > 0) {
- updatedFiles[0].selected = true
+ setSelectedFileId(updatedFiles[0].id)
}
onFilesChange(updatedFiles)
}
- const handleFileSelect = (id: number) => {
- const updatedFiles = files.map((file) => ({
- ...file,
- selected: file.id === id,
- }))
- onFilesChange(updatedFiles)
- }
-
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
setIsDragOver(true)
@@ -326,9 +329,12 @@ export const FileExplorerAndEditor = ({
metadata: {
isEditing: false,
originalId: file.id,
+ state: file.state,
},
})),
})
+
+ if (!selectedFileId && files.length > 0) setSelectedFileId(files[0].id)
}, [files])
return (
@@ -381,6 +387,8 @@ export const FileExplorerAndEditor = ({
typeof element.metadata?.originalId === 'number'
? element.metadata.originalId
: null
+ const state = element.metadata?.state as FileData['state']
+ const isEditing = Boolean(element.metadata?.isEditing)
return (
<ContextMenu_Shadcn_ modal={false}>
@@ -390,20 +398,29 @@ export const FileExplorerAndEditor = ({
{...nodeProps}
isExpanded={isExpanded}
isBranch={isBranch}
- isSelected={files.find((f) => f.id === originalId)?.selected}
+ isSelected={files.find((f) => f.id === originalId)?.id === selectedFileId}
level={level}
xPadding={16}
name={element.name}
+ className={cn(
+ isEditing
+ ? ''
+ : state === 'new'
+ ? 'text-brand-600'
+ : state === 'modified'
+ ? 'text-code_block-2'
+ : ''
+ )}
icon={<File size={14} className="text-foreground-light shrink-0" />}
- isEditing={Boolean(element.metadata?.isEditing)}
+ isEditing={isEditing}
onEditSubmit={(value) => {
if (originalId !== null) {
handleFileNameChange(originalId, value)
}
}}
onClick={() => {
- if (originalId !== null && !element.metadata?.isEditing) {
- handleFileSelect(originalId)
+ if (originalId !== null && !isEditing) {
+ setSelectedFileId(originalId)
}
}}
onDoubleClick={() => {
@@ -411,6 +428,20 @@ export const FileExplorerAndEditor = ({
handleStartRename(originalId)
}
}}
+ actions={
+ state !== 'unchanged' && (
+ <div className="flex items-center justify-center w-3">
+ <Tooltip>
+ <TooltipTrigger className="text-xs">
+ {state === 'new' ? 'U' : 'M'}
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ {state === 'new' ? 'Unsaved' : 'Modified'}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ )
+ }
/>
</div>
</ContextMenuTrigger_Shadcn_>
diff --git a/apps/studio/data/edge-functions/edge-function-body-query.ts b/apps/studio/data/edge-functions/edge-function-body-query.ts
index b2594c490e5..772a91ca6f2 100644
--- a/apps/studio/data/edge-functions/edge-function-body-query.ts
+++ b/apps/studio/data/edge-functions/edge-function-body-query.ts
@@ -1,6 +1,7 @@
import { getMultipartBoundary, parseMultipartStream } from '@mjackson/multipart-parser'
import { useQuery } from '@tanstack/react-query'
-import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'
+
+import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
import { get, handleError } from 'data/fetchers'
import { IS_PLATFORM } from 'lib/constants'
import type { ResponseError, UseCustomQueryOptions } from 'types'
@@ -54,7 +55,7 @@ export async function getEdgeFunctionBody(
return {
metadata,
- files: files as Omit<EdgeFunctionFile, 'id' | 'selected'>[],
+ files: files as Omit<FileData, 'id' | 'selected' | 'state'>[],
}
}
diff --git a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
index 97c15b9ba20..d0026fc5c0c 100644
--- a/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
+++ b/apps/studio/pages/project/[ref]/functions/[functionSlug]/code.tsx
@@ -1,13 +1,15 @@
-import { common, dirname, relative } from '@std/path/posix'
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { isEqual } from 'lodash'
import { AlertCircle, CornerDownLeft, Loader2 } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
+import { formatFunctionBodyToFiles } from '@/components/interfaces/EdgeFunctions/EdgeFunctions.utils'
+import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
+import { useLatest } from '@/hooks/misc/useLatest'
import { useParams } from 'common'
import { DeployEdgeFunctionWarningModal } from 'components/interfaces/EdgeFunctions/DeployEdgeFunctionWarningModal'
-import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'
-import DefaultLayout from 'components/layouts/DefaultLayout'
+import { DefaultLayout } from 'components/layouts/DefaultLayout'
import EdgeFunctionDetailsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionDetailsLayout'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { FileExplorerAndEditor } from 'components/ui/FileExplorerAndEditor'
@@ -59,12 +61,26 @@ const CodePage = () => {
refetchIntervalInBackground: false,
}
)
- const [files, setFiles] = useState<EdgeFunctionFile[]>([])
+ const [files, setFiles] = useState<FileData[]>([])
+
+ const initialFiles = useMemo(() => {
+ return !!functionBody
+ ? formatFunctionBodyToFiles({
+ functionBody,
+ entrypointPath: selectedFunction?.entrypoint_path,
+ })
+ : []
+ }, [functionBody, selectedFunction?.entrypoint_path])
const { mutate: deployFunction, isPending: isDeploying } = useEdgeFunctionDeployMutation({
onSuccess: () => {
toast.success('Successfully updated edge function')
setShowDeployWarning(false)
+ setFiles((files) =>
+ files.map((f) => {
+ return { ...f, state: 'unchanged' }
+ })
+ )
},
})
@@ -102,25 +118,6 @@ const CodePage = () => {
}
}
- function getBasePath(entrypoint: string | undefined, fileNames: string[]): string {
- if (!entrypoint) {
- return '/'
- }
-
- let candidate = fileNames.find((name) => entrypoint.endsWith(name))
-
- if (candidate) {
- return dirname(candidate)
- } else {
- try {
- return dirname(new URL(entrypoint).pathname)
- } catch (e) {
- console.error('Failed to parse entrypoint', entrypoint)
- return '/'
- }
- }
- }
-
const handleDeployClick = () => {
if (files.length === 0 || isLoadingFiles) return
setShowDeployWarning(true)
@@ -145,54 +142,31 @@ const CodePage = () => {
}
useEffect(() => {
- if (!functionBody) {
- return
- }
-
- const entrypoint_path =
- functionBody.metadata?.deno2_entrypoint_path ?? selectedFunction?.entrypoint_path
+ if (initialFiles.length === 0) return
+ setFiles(initialFiles)
+ }, [initialFiles])
- // Set files from API response when available
- if (entrypoint_path) {
- const base_path = getBasePath(
- entrypoint_path,
- functionBody.files.map((file) => file.name)
+ // [Joshen] Probably a candidate for useStaticEffectEvent
+ const filesRef = useLatest(files)
+ const initialFilesRef = useLatest(initialFiles)
+ useEffect(() => {
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ const normalizeFiles = (list: FileData[]) =>
+ list.map(({ id, name, content }) => ({ id, name, content }))
+ const hasUnsavedChanges = !isEqual(
+ normalizeFiles(initialFilesRef.current),
+ normalizeFiles(filesRef.current)
)
- const filesWithRelPath = functionBody.files
- // set file paths relative to entrypoint
- .map((file: { name: string; content: string }) => {
- try {
- // if the current file and base path doesn't share a common path,
- // return unmodified file
- const common_path = common([base_path, file.name])
- if (common_path === '' || common_path === '/tmp/') {
- return file
- }
-
- // prepend "/" to turn relative paths to absolute
- file.name = relative('/' + base_path, '/' + file.name)
- return file
- } catch (e) {
- console.error(e)
- // return unmodified file
- return file
- }
- })
- setFiles((prev) => {
- return filesWithRelPath.map((file: { name: string; content: string }, index: number) => {
- const prevState = prev.find((x) => x.name === file.name)
- return {
- id: index + 1,
- name: file.name,
- content: file.content,
- selected: prevState?.selected ?? index === 0,
- }
- })
- })
+ if (hasUnsavedChanges) {
+ e.preventDefault()
+ e.returnValue = '' // deprecated, but older browsers still require this
+ }
}
+ window.addEventListener('beforeunload', handleBeforeUnload)
+ return () => window.removeEventListener('beforeunload', handleBeforeUnload)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [functionBody])
+ }, [])
return (
<div className="flex flex-col h-full">
@@ -219,7 +193,20 @@ const CodePage = () => {
<>
<FileExplorerAndEditor
files={files}
- onFilesChange={setFiles}
+ onFilesChange={(files) => {
+ const formattedFiles: FileData[] = files.map((f) => {
+ const originalFile = initialFiles.find((x) => x.id === f.id)
+ if (!originalFile) {
+ return f
+ } else if (originalFile.name !== f.name) {
+ return { ...f, state: 'new' }
+ } else if (originalFile.content !== f.content) {
+ return { ...f, state: 'modified' }
+ }
+ return { ...f, state: 'unchanged' }
+ })
+ setFiles(formattedFiles)
+ }}
aiEndpoint={`${BASE_PATH}/api/ai/code/complete`}
aiMetadata={{
projectRef: project?.ref,
diff --git a/apps/studio/pages/project/[ref]/functions/new.tsx b/apps/studio/pages/project/[ref]/functions/new.tsx
index 027e33b597d..bc75bfcdef9 100644
--- a/apps/studio/pages/project/[ref]/functions/new.tsx
+++ b/apps/studio/pages/project/[ref]/functions/new.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { isEqual } from 'lodash'
import { AlertCircle, Book, Check } from 'lucide-react'
import { useRouter } from 'next/router'
import { useEffect, useMemo, useState } from 'react'
@@ -6,10 +7,11 @@ import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
+import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
+import { useLatest } from '@/hooks/misc/useLatest'
import { useParams } from 'common'
-import { EdgeFunctionFile } from 'components/interfaces/EdgeFunctions/EdgeFunction.types'
import { EDGE_FUNCTION_TEMPLATES } from 'components/interfaces/Functions/Functions.templates'
-import DefaultLayout from 'components/layouts/DefaultLayout'
+import { DefaultLayout } from 'components/layouts/DefaultLayout'
import EdgeFunctionsLayout from 'components/layouts/EdgeFunctionsLayout/EdgeFunctionsLayout'
import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
import { SIDEBAR_KEYS } from 'components/layouts/ProjectLayout/LayoutSidebar/LayoutSidebarProvider'
@@ -99,6 +101,15 @@ const sanitizeFunctionName = (name: string): string => {
// Type for the form values
type FormValues = z.infer<typeof FormSchema>
+const INITIAL_FILES: FileData[] = [
+ {
+ id: 1,
+ name: 'index.ts',
+ content: EDGE_FUNCTION_TEMPLATES[0].content,
+ state: 'new',
+ },
+]
+
const NewFunctionPage = () => {
const router = useRouter()
const { ref, template } = useParams()
@@ -109,14 +120,8 @@ const NewFunctionPage = () => {
const showStripeExample = useIsFeatureEnabled('edge_functions:show_stripe_example')
const { openSidebar } = useSidebarManagerSnapshot()
- const [files, setFiles] = useState<EdgeFunctionFile[]>([
- {
- id: 1,
- name: 'index.ts',
- selected: true,
- content: EDGE_FUNCTION_TEMPLATES[0].content,
- },
- ])
+ const [files, setFiles] = useState<FileData[]>(INITIAL_FILES)
+ const [selectedFileId, setSelectedFileId] = useState<number>(INITIAL_FILES[0].id)
const [open, setOpen] = useState(false)
const [isPreviewingTemplate, setIsPreviewingTemplate] = useState(false)
const [savedCode, setSavedCode] = useState<string>('')
@@ -165,11 +170,12 @@ const NewFunctionPage = () => {
}
const handleChat = () => {
- const selectedFile = files.find((f) => f.selected) ?? files[0]
+ const selectedFile = files.find((f) => f.id === selectedFileId)
+
openSidebar(SIDEBAR_KEYS.AI_ASSISTANT)
snap.newChat({
name: 'Explain edge function',
- sqlSnippets: [selectedFile.content],
+ sqlSnippets: [selectedFile?.content ?? ''],
initialInput: 'Help me understand and improve this edge function...',
suggestions: {
title:
@@ -205,7 +211,9 @@ const NewFunctionPage = () => {
const template = EDGE_FUNCTION_TEMPLATES.find((t) => t.value === templateValue)
if (template) {
setFiles((prev) =>
- prev.map((file) => (file.selected ? { ...file, content: template.content } : file))
+ prev.map((file) =>
+ file.id === selectedFileId ? { ...file, content: template.content } : file
+ )
)
setOpen(false)
sendEvent({
@@ -214,22 +222,23 @@ const NewFunctionPage = () => {
groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
})
}
+ setIsPreviewingTemplate(false)
}
const handleTemplateMouseEnter = (content: string) => {
if (!isPreviewingTemplate) {
- const selectedFile = files.find((f) => f.selected) ?? files[0]
+ const selectedFile = files.find((f) => f.id === selectedFileId) ?? files[0]
setSavedCode(selectedFile.content)
}
setIsPreviewingTemplate(true)
- setFiles((prev) => prev.map((file) => (file.selected ? { ...file, content } : file)))
+ setFiles((prev) => prev.map((f) => (f.id === selectedFileId ? { ...f, content } : f)))
}
const handleTemplateMouseLeave = () => {
if (isPreviewingTemplate) {
setIsPreviewingTemplate(false)
setFiles((prev) =>
- prev.map((file) => (file.selected ? { ...file, content: savedCode } : file))
+ prev.map((f) => (f.id === selectedFileId ? { ...f, content: savedCode } : f))
)
}
}
@@ -252,12 +261,13 @@ const NewFunctionPage = () => {
const templateMeta = EDGE_FUNCTION_TEMPLATES.find((x) => x.value === template)
if (templateMeta) {
form.reset({ functionName: template })
+ setSelectedFileId(1)
setFiles([
{
id: 1,
name: 'index.ts',
- selected: true,
content: templateMeta.content,
+ state: 'new',
},
])
}
@@ -265,6 +275,22 @@ const NewFunctionPage = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [template])
+ // [Joshen] Probably a candidate for useStaticEffectEvent
+ const filesRef = useLatest(files)
+ useEffect(() => {
+ const handleBeforeUnload = (e: BeforeUnloadEvent) => {
+ const hasUnsavedChanges = !isEqual(INITIAL_FILES, filesRef.current)
+
+ if (hasUnsavedChanges) {
+ e.preventDefault()
+ e.returnValue = '' // deprecated, but older browsers still require this
+ }
+ }
+ window.addEventListener('beforeunload', handleBeforeUnload)
+ return () => window.removeEventListener('beforeunload', handleBeforeUnload)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+
return (
<PageLayout
size="full"
@@ -310,7 +336,7 @@ const NewFunctionPage = () => {
<Check
className={cn(
'mr-2 h-4 w-4',
- files.some((f) => f.selected && f.content === template.content)
+ files.some((f) => f.content === template.content)
? 'opacity-100'
: 'opacity-0'
)}
@@ -348,6 +374,8 @@ const NewFunctionPage = () => {
connectionString: project?.connectionString,
orgSlug: org?.slug,
}}
+ selectedFileId={selectedFileId}
+ setSelectedFileId={setSelectedFileId}
/>
<Form_Shadcn_ {...form}>
diff --git a/packages/ui/src/components/TreeView/TreeView.tsx b/packages/ui/src/components/TreeView/TreeView.tsx
index d8003cf382d..ff4a1da3640 100644
--- a/packages/ui/src/components/TreeView/TreeView.tsx
+++ b/packages/ui/src/components/TreeView/TreeView.tsx
@@ -74,6 +74,8 @@ const TreeViewItem = forwardRef<
isLoading?: boolean
/** Callback for double-click */
onDoubleClick?: (e: React.MouseEvent) => void
+ /** Actions to render on the right end of the item */
+ actions?: ReactNode
}
>(
(
@@ -92,6 +94,7 @@ const TreeViewItem = forwardRef<
isEditing = false,
onEditSubmit,
onDoubleClick,
+ actions,
...props
},
ref
@@ -182,7 +185,12 @@ const TreeViewItem = forwardRef<
aria-selected={isSelected}
aria-expanded={!isEditing && isExpanded}
onDoubleClick={onDoubleClick}
- className={cn(TreeViewItemVariant({ isSelected, isOpened, isPreview }), props.className)}
+ className={cn(
+ TreeViewItemVariant({ isSelected, isOpened, isPreview }),
+ !!actions && 'pr-2',
+ !isEditing && !!actions && 'justify-between',
+ props.className
+ )}
style={{
paddingLeft: xPadding + ((level - 1) * levelPadding) / 2,
...props.style,
@@ -199,54 +207,60 @@ const TreeViewItem = forwardRef<
className={'absolute h-full w-px bg-border-strong'}
></div>
))}
+
{isSelected && <div className="absolute left-0 h-full w-0.5 bg-foreground" />}
- {isBranch ? (
- <>
- {isLoading ? (
- <Loader2 className={cn('text-foreground-muted animate-spin')} size={14} />
- ) : (
- <ChevronRight
+
+ <div className="flex items-center gap-x-3 truncate">
+ {isBranch ? (
+ <>
+ {isLoading ? (
+ <Loader2 className={cn('text-foreground-muted animate-spin')} size={14} />
+ ) : (
+ <ChevronRight
+ className={cn(
+ 'text-foreground-muted',
+ 'group-aria-selected:text-foreground-light',
+ 'group-aria-expanded:text-foreground-light',
+ 'transition-transform duration-200',
+ 'group-aria-expanded:rotate-90'
+ )}
+ size={CHEVRON_ICON_SIZE}
+ strokeWidth={1.5}
+ />
+ )}
+ <TreeViewFolderIcon
className={cn(
- 'text-foreground-muted',
+ 'transition-colors',
+ ' text-foreground-muted',
'group-aria-selected:text-foreground-light',
- 'group-aria-expanded:text-foreground-light',
- 'transition-transform duration-200',
- 'group-aria-expanded:rotate-90'
+ 'group-aria-expanded:text-foreground-light'
)}
- size={CHEVRON_ICON_SIZE}
+ isOpen={isExpanded}
+ size={ENTITY_ICON_SIZE}
strokeWidth={1.5}
/>
- )}
- <TreeViewFolderIcon
- className={cn(
- 'transition-colors',
- ' text-foreground-muted',
- 'group-aria-selected:text-foreground-light',
- 'group-aria-expanded:text-foreground-light'
- )}
- isOpen={isExpanded}
- size={ENTITY_ICON_SIZE}
- strokeWidth={1.5}
- />
- </>
- ) : (
- icon || (
- <SQL_ICON
- className={cn(
- 'transition-colors',
- 'fill-foreground-muted',
- 'group-aria-selected:fill-foreground',
- 'w-5 h-5 shrink-0',
- '-ml-0.5'
- )}
- size={ENTITY_ICON_SIZE}
- strokeWidth={1.5}
- />
- )
- )}
- <span className={cn(isEditing && 'hidden', 'truncate text-sm')} title={name}>
- {name}
- </span>
+ </>
+ ) : (
+ icon || (
+ <SQL_ICON
+ className={cn(
+ 'transition-colors',
+ 'fill-foreground-muted',
+ 'group-aria-selected:fill-foreground',
+ 'w-5 h-5 shrink-0'
+ )}
+ size={ENTITY_ICON_SIZE}
+ strokeWidth={1.5}
+ />
+ )
+ )}
+ <span className={cn(isEditing && 'hidden', 'truncate text-sm')} title={name}>
+ {name}
+ </span>
+ </div>
+
+ {!isEditing && actions}
+
<form onSubmit={handleSubmit} className={cn(!isEditing && 'hidden')}>
<Input
autoFocus