Skip to content

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

Scaffold branch management branch, list branches, implement delete branch

Joshen Lim53c058f93110
diff --git a/packages/ui/src/components/shadcn/ui/dropdown-menu.tsx b/packages/ui/src/components/shadcn/ui/dropdown-menu.tsx
index e4141e48221..f275d7401de 100644
--- a/packages/ui/src/components/shadcn/ui/dropdown-menu.tsx
+++ b/packages/ui/src/components/shadcn/ui/dropdown-menu.tsx
@@ -79,7 +79,7 @@ const DropdownMenuItem = React.forwardRef<
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
- 'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-overlay-hover focus:text-strong data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
+ 'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-overlay-hover focus:text-strong data-[disabled]:pointer-events-none data-[disabled]:opacity-50 cursor-pointer',
inset && 'pl-8',
className
)}
diff --git a/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/studio/components/interfaces/BranchManagement/BranchManagement.tsx
new file mode 100644
index 00000000000..012f82d1cf7
--- /dev/null
+++ b/studio/components/interfaces/BranchManagement/BranchManagement.tsx
@@ -0,0 +1,88 @@
+import { partition } from 'lodash'
+import { useState } from 'react'
+
+import { useParams } from 'common'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import AlertError from 'components/ui/AlertError'
+import TextConfirmModal from 'components/ui/Modals/TextConfirmModal'
+import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
+import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
+import { Branch, useBranchesQuery } from 'data/branches/branches-query'
+import { useStore } from 'hooks'
+import { BranchHeader, BranchPanel } from './BranchPanels'
+
+const BranchManagement = () => {
+ const { ui } = useStore()
+ const { ref: projectRef } = useParams()
+ const [selectedBranchToUpdate, setSelectedBranchToUpdate] = useState<Branch>()
+ const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()
+
+ const { data: branches, error, isLoading, isError, isSuccess } = useBranchesQuery({ projectRef })
+ const [[mainBranch], previewBranches] = partition(branches, (branch) => branch.is_default)
+
+ const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
+ onSuccess: () => {
+ setSelectedBranchToUpdate(undefined)
+ ui.setNotification({ category: 'success', message: 'Successfully updated branch' })
+ },
+ })
+ const { mutate: deleteBranch, isLoading: isDeleting } = useBranchDeleteMutation({
+ onSuccess: () => {
+ setSelectedBranchToDelete(undefined)
+ ui.setNotification({ category: 'success', message: 'Successfully deleted branch' })
+ },
+ })
+
+ const onConfirmDeleteBranch = () => {
+ if (selectedBranchToDelete == undefined) return console.error('No branch selected')
+ if (projectRef == undefined) return console.error('Project ref is required')
+ deleteBranch({ id: selectedBranchToDelete?.id, projectRef })
+ }
+
+ return (
+ <>
+ <ScaffoldContainer>
+ <ScaffoldSection>
+ <div className="col-span-12">
+ <h3 className="text-lg">Branches</h3>
+ <div className="mt-8">
+ {isLoading && <GenericSkeletonLoader />}
+ {isError && <AlertError error={error} subject="Failed to retrieve branches" />}
+ {isSuccess && (
+ <>
+ <BranchPanel branch={mainBranch} onSelectUpdate={() => {}} />
+ <BranchHeader markdown={`#### Preview branches`} />
+ {previewBranches.map((branch) => (
+ <BranchPanel
+ key={branch.id}
+ branch={branch}
+ onSelectUpdate={() => {}}
+ onSelectDelete={() => setSelectedBranchToDelete(branch)}
+ />
+ ))}
+ </>
+ )}
+ </div>
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
+
+ <TextConfirmModal
+ size="medium"
+ visible={selectedBranchToDelete !== undefined}
+ onCancel={() => setSelectedBranchToDelete(undefined)}
+ onConfirm={() => onConfirmDeleteBranch()}
+ title="Delete branch"
+ loading={isDeleting}
+ confirmLabel={`Delete branch`}
+ confirmPlaceholder="Type in name of branch"
+ confirmString={selectedBranchToDelete?.name ?? ''}
+ text={`This will delete your branch "${selectedBranchToDelete?.name}"`}
+ alert="You cannot recover this branch once it is deleted!"
+ />
+ </>
+ )
+}
+
+export default BranchManagement
diff --git a/studio/components/interfaces/BranchManagement/BranchPanels.tsx b/studio/components/interfaces/BranchManagement/BranchPanels.tsx
new file mode 100644
index 00000000000..92667e38dc1
--- /dev/null
+++ b/studio/components/interfaces/BranchManagement/BranchPanels.tsx
@@ -0,0 +1,132 @@
+import dayjs from 'dayjs'
+import { forwardRef, useState } from 'react'
+import {
+ Badge,
+ Button,
+ DropdownMenuContent_Shadcn_,
+ DropdownMenuItem_Shadcn_,
+ DropdownMenuTrigger_Shadcn_,
+ DropdownMenu_Shadcn_,
+ IconEdit,
+ IconGitBranch,
+ IconMoreVertical,
+ IconShield,
+ IconTrash,
+ cn,
+} from 'ui'
+
+import { Markdown } from 'components/interfaces/Markdown'
+import { Branch } from 'data/branches/branches-query'
+import { noop } from 'lodash'
+import { useParams } from 'common'
+
+interface BranchPanelProps {
+ branch?: Branch
+ onSelectUpdate?: () => void
+ onSelectDelete?: () => void
+}
+
+const BranchPanel = ({
+ branch,
+ onSelectUpdate = noop,
+ onSelectDelete = noop,
+}: BranchPanelProps) => {
+ const { ref } = useParams()
+ const [open, setOpen] = useState(false)
+
+ const isActive = ref === branch?.project_ref
+ const daysFromNow = dayjs().diff(dayjs(branch?.created_at), 'day')
+ const formattedTimeFromNow = dayjs(branch?.created_at).fromNow()
+ const formattedCreatedAt = dayjs(branch?.created_at).format('DD MMM YYYY, HH:mm:ss (ZZ)')
+
+ if (branch?.is_default) {
+ return (
+ <div className="bg-scale-300 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm">
+ <div className="flex items-center space-x-4">
+ <IconShield size={16} strokeWidth={2} />
+ <p>{branch?.name}</p>
+ <Badge color="amber">Production</Badge>
+ {isActive && <Badge color="green">Selected</Badge>}
+ </div>
+ <div className="flex items-center space-x-4">
+ <Button>Create new branch</Button>
+ <DropdownMenu_Shadcn_ open={open} onOpenChange={() => setOpen(!open)} modal={false}>
+ <DropdownMenuTrigger_Shadcn_>
+ <Button asChild type="text" className="px-1" icon={<IconMoreVertical size={14} />}>
+ <span></span>
+ </Button>
+ </DropdownMenuTrigger_Shadcn_>
+ <DropdownMenuContent_Shadcn_ side="bottom" align="end">
+ <DropdownMenuItem_Shadcn_ className="flex gap-2" onSelect={() => onSelectUpdate()}>
+ <IconEdit size={14} />
+ Edit branch
+ </DropdownMenuItem_Shadcn_>
+ </DropdownMenuContent_Shadcn_>
+ </DropdownMenu_Shadcn_>
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <li className="list-none ml-6 pl-8 pb-4 border-l border-scale-600 dark:border-scale-400 relative last:!border-transparent">
+ <div className="absolute w-[33px] rounded-bl-full border-b border-l border-scale-600 dark:border-scale-400 h-10 -left-px" />
+ <div className="bg-scale-300 border shadow-sm flex justify-between items-center pl-8 pr-6 py-4 rounded-lg text-sm">
+ <div className="flex items-center space-x-4">
+ <IconGitBranch className="text-brand-900" size={16} strokeWidth={2} />
+ <p>{branch?.name}</p>
+ {isActive && <Badge color="green">Selected</Badge>}
+ <p className="text-scale-1000">
+ {daysFromNow > 1
+ ? `Created on ${formattedCreatedAt}`
+ : `Created ${formattedTimeFromNow}`}
+ </p>
+ </div>
+ <div>
+ <DropdownMenu_Shadcn_ open={open} onOpenChange={() => setOpen(!open)} modal={false}>
+ <DropdownMenuTrigger_Shadcn_>
+ <Button asChild type="text" className="px-1" icon={<IconMoreVertical size={14} />}>
+ <span></span>
+ </Button>
+ </DropdownMenuTrigger_Shadcn_>
+ <DropdownMenuContent_Shadcn_ side="bottom" align="end">
+ <DropdownMenuItem_Shadcn_ className="flex gap-2" onSelect={() => onSelectUpdate()}>
+ <IconEdit size={14} />
+ Edit branch
+ </DropdownMenuItem_Shadcn_>
+ <DropdownMenuItem_Shadcn_ className="flex gap-2" onSelect={() => onSelectDelete()}>
+ <IconTrash size={14} />
+ Delete branch
+ </DropdownMenuItem_Shadcn_>
+ </DropdownMenuContent_Shadcn_>
+ </DropdownMenu_Shadcn_>
+ </div>
+ </div>
+ </li>
+ )
+}
+
+interface BranchHeader extends React.HTMLAttributes<HTMLDivElement> {
+ name?: string
+ markdown?: string
+}
+
+const BranchHeader = forwardRef<HTMLDivElement, BranchHeader>(
+ ({ className, name, markdown = '', ...props }, ref) => {
+ return (
+ <div
+ {...props}
+ ref={ref}
+ className={cn(
+ 'border-l border-scale-600 dark:border-scale-400 ml-6 pl-8 pt-6 pb-3',
+ className
+ )}
+ >
+ <Markdown content={markdown} className="" />
+ </div>
+ )
+ }
+)
+
+BranchHeader.displayName = 'BranchHeader'
+export { BranchHeader, BranchPanel }
diff --git a/studio/components/interfaces/Markdown.tsx b/studio/components/interfaces/Markdown.tsx
index 1755f86c843..8aff7074cd5 100644
--- a/studio/components/interfaces/Markdown.tsx
+++ b/studio/components/interfaces/Markdown.tsx
@@ -9,7 +9,11 @@ interface Props extends Omit<ReactMarkdownProps, 'children' | 'node'> {
const Markdown = ({ className, content, ...props }: Props) => {
return (
- <ReactMarkdown {...props} className={cn('prose text-sm', className)}>
+ <ReactMarkdown
+ components={{ h3: ({ children }) => <h3 className="mb-1">{children}</h3> }}
+ {...props}
+ className={cn('prose text-sm', className)}
+ >
{content}
</ReactMarkdown>
)
diff --git a/studio/components/layouts/AppLayout/BranchDropdown.tsx b/studio/components/layouts/AppLayout/BranchDropdown.tsx
index 8c225f4de19..47c8b62150c 100644
--- a/studio/components/layouts/AppLayout/BranchDropdown.tsx
+++ b/studio/components/layouts/AppLayout/BranchDropdown.tsx
@@ -1,17 +1,130 @@
+import { useRouter } from 'next/router'
+import { useRef, useState } from 'react'
+import Link from 'next/link'
+
import { useParams } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useBranchesQuery } from 'data/branches/branches-query'
+import {
+ Badge,
+ Button,
+ CommandEmpty_Shadcn_,
+ CommandGroup_Shadcn_,
+ CommandInput_Shadcn_,
+ CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
+ IconCheck,
+ IconCode,
+ IconPlus,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+} from 'ui'
const BranchDropdown = () => {
+ const router = useRouter()
const { ref: projectRef } = useParams()
+ const branchNameRef = useRef<HTMLAnchorElement>(null)
const { data: branches, isLoading, isError, isSuccess } = useBranchesQuery({ projectRef })
- console.log({ branches })
+
+ const [open, setOpen] = useState(false)
+ const popoverOffset = (branchNameRef.current?.offsetWidth ?? 0) + 12
+ const selectedBranch = branches?.find((branch) => branch.project_ref === projectRef)
+
+ const onSwitchBranch = async () => {
+ console.log('Fetch branch details and update connection string or something')
+ }
return (
<>
{isLoading && <ShimmeringLoader className="w-[90px]" />}
+
{isError && <div></div>}
- {isSuccess && <div></div>}
+
+ {isSuccess && branches.length > 0 && (
+ <div className="flex items-center space-x-2 px-2">
+ <Link passHref href={`/project/${projectRef}/branches`}>
+ <a ref={branchNameRef} className="flex items-center space-x-2">
+ <p className="text-sm">{selectedBranch?.name}</p>
+ {selectedBranch?.is_default && <Badge color="amber">Production</Badge>}
+ </a>
+ </Link>
+
+ <Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
+ <PopoverTrigger_Shadcn_ asChild>
+ <Button
+ type="text"
+ className="px-1"
+ icon={<IconCode className="text-scale-1100 rotate-90" strokeWidth={2} size={12} />}
+ />
+ </PopoverTrigger_Shadcn_>
+ <PopoverContent_Shadcn_
+ className="p-0"
+ side="bottom"
+ align="start"
+ style={{ marginLeft: `-${popoverOffset}px` }}
+ >
+ <Command_Shadcn_>
+ <CommandInput_Shadcn_ placeholder="Find branch..." />
+ <CommandList_Shadcn_>
+ <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>
+ <CommandGroup_Shadcn_>
+ {branches?.map((branch) => {
+ const href = {
+ pathname: router.pathname,
+ query: { ...router.query, ref: branch.project_ref },
+ }
+
+ return (
+ <Link passHref href={href} key={branch.id}>
+ <CommandItem_Shadcn_
+ asChild
+ value={branch.id}
+ className="cursor-pointer w-full flex items-center justify-between"
+ onSelect={() => {
+ setOpen(false)
+ onSwitchBranch()
+ router.push(href)
+ }}
+ onClick={() => {
+ onSwitchBranch()
+ setOpen(false)
+ }}
+ >
+ <a>
+ {branch.name}
+ {branch.id === selectedBranch?.id && <IconCheck />}
+ </a>
+ </CommandItem_Shadcn_>
+ </Link>
+ )
+ })}
+ </CommandGroup_Shadcn_>
+ {/* <CommandGroup_Shadcn_ className="border-t">
+ <Link passHref href={'/'}>
+ <CommandItem_Shadcn_
+ asChild
+ className="cursor-pointer flex items-center space-x-2 w-full"
+ onSelect={(e) => {
+ setOpen(false)
+ router.push('/')
+ }}
+ onClick={() => setOpen(false)}
+ >
+ <a>
+ <IconPlus size={14} strokeWidth={1.5} />
+ <p>New branch</p>
+ </a>
+ </CommandItem_Shadcn_>
+ </Link>
+ </CommandGroup_Shadcn_> */}
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
+ </PopoverContent_Shadcn_>
+ </Popover_Shadcn_>
+ </div>
+ )}
</>
)
}
diff --git a/studio/components/layouts/AppLayout/ProjectDropdown.tsx b/studio/components/layouts/AppLayout/ProjectDropdown.tsx
index 2d467b1864a..3053db7a22c 100644
--- a/studio/components/layouts/AppLayout/ProjectDropdown.tsx
+++ b/studio/components/layouts/AppLayout/ProjectDropdown.tsx
@@ -105,6 +105,8 @@ const ProjectDropdown = () => {
const projectNameRef = useRef<HTMLAnchorElement>(null)
const { data: allProjects, isLoading: isLoadingProjects } = useProjectsQuery()
+ console.log({ selectedProject })
+
const isOrgBilling = !!selectedOrganization?.subscription_id
const { data: subscription, isSuccess } = useProjectSubscriptionV2Query(
{ projectRef: selectedProject?.ref },
diff --git a/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx b/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
index b1e37ff0ef9..9a52dda2c84 100644
--- a/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
+++ b/studio/components/layouts/AppLayout/UserSettingsDropdown.tsx
@@ -1,7 +1,6 @@
-import Link from 'next/link'
+import Link from 'components/ui/ProjectLink'
import { useRouter } from 'next/router'
import {
- DropdownMenuCheckboxItem_Shadcn_,
DropdownMenuContent_Shadcn_,
DropdownMenuGroup_Shadcn_,
DropdownMenuItem_Shadcn_,
@@ -10,12 +9,8 @@ import {
DropdownMenuRadioItem_Shadcn_,
DropdownMenuSeparator_Shadcn_,
DropdownMenuShortcut_Shadcn_,
- DropdownMenuSubContent_Shadcn_,
- DropdownMenuSubTrigger_Shadcn_,
- DropdownMenuSub_Shadcn_,
DropdownMenuTrigger_Shadcn_,
DropdownMenu_Shadcn_,
- IconCheck,
IconUser,
useCommandMenu,
} from 'ui'
diff --git a/studio/components/ui/ProjectLink.tsx b/studio/components/ui/ProjectLink.tsx
new file mode 100644
index 00000000000..5e956142497
--- /dev/null
+++ b/studio/components/ui/ProjectLink.tsx
@@ -0,0 +1,103 @@
+import NextLink, { LinkProps as NextLinkProps } from 'next/link'
+import { useRouter } from 'next/router'
+import { forwardRef, PropsWithChildren, PropsWithoutRef, useMemo } from 'react'
+
+export type Override<T1, T2> = Omit<T1, keyof T2> & T2
+
+function isValidUrl(urlString: string) {
+ try {
+ return Boolean(new URL(urlString))
+ } catch (e) {
+ return false
+ }
+}
+
+const ProjectLink = forwardRef<
+ HTMLAnchorElement,
+ Override<
+ Override<PropsWithoutRef<JSX.IntrinsicElements['a']>, NextLinkProps>,
+ PropsWithChildren<{}>
+ >
+>(
+ (
+ {
+ href,
+ as: nextAs,
+ prefetch,
+ replace,
+ scroll,
+ shallow,
+ children,
+ className: overrideClassName,
+ ...props
+ },
+ ref
+ ) => {
+ const { query } = useRouter()
+ const { branch } = query
+
+ const hrefWithBranch = useMemo(() => {
+ if (typeof href === 'string') {
+ const url = isValidUrl(href)
+ ? new URL(href)
+ : new URL(`https://supabase.com/${href.replace(/^\//, '')}`)
+ const branchId = url.searchParams.get('branch')
+ url.searchParams.delete('branch')
+
+ const existingSearchParams = [...url.searchParams.entries()].reduce(
+ (acc, [key, value]) => {
+ let temp = acc[key]
+ if (temp) {
+ if (Array.isArray(temp)) {
+ temp.push(value)
+ } else {
+ temp = [temp, value]
+ }
+ } else {
+ temp = value
+ }
+ acc[key] = temp
+ return acc
+ },
+ {} as {
+ [key: string]: string | string[]
+ }
+ )
+
+ return {
+ pathname: url.pathname,
+ query: {
+ ...((branch !== undefined || branchId !== null) && { branch: branchId || branch }),
+ ...existingSearchParams,
+ },
+ }
+ } else {
+ return {
+ ...href,
+ query: { ...(branch !== undefined && { branch }), ...(href.query as object) },
+ }
+ }
+ }, [branch, href])
+
+ return (
+ <NextLink
+ ref={ref}
+ {...{
+ href: hrefWithBranch,
+ as: nextAs,
+ prefetch,
+ replace,
+ scroll,
+ shallow,
+ className: overrideClassName,
+ ...props,
+ }}
+ >
+ {children}
+ </NextLink>
+ )
+ }
+)
+
+ProjectLink.displayName = 'ProjectLink'
+export default ProjectLink
diff --git a/studio/data/api.d.ts b/studio/data/api.d.ts
index c7f8b7dc44a..5a30a524614 100644
--- a/studio/data/api.d.ts
+++ b/studio/data/api.d.ts
@@ -3127,6 +3127,7 @@ export interface components {
id: string;
name: string;
project_ref: string;
+ parent_project_ref: string;
is_default: boolean;
git_branch: string;
created_at: string;
diff --git a/studio/data/branches/branches-query.ts b/studio/data/branches/branches-query.ts
index d7ed5e31e66..6b8bfe4966c 100644
--- a/studio/data/branches/branches-query.ts
+++ b/studio/data/branches/branches-query.ts
@@ -2,18 +2,27 @@ import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get } from 'data/fetchers'
import { branchKeys } from './keys'
import { ResponseError } from 'types'
+import { components } from 'data/api'
export type BranchesVariables = {
projectRef?: string
}
+export type Branch = components['schemas']['BranchResponse']
+
export async function getBranches({ projectRef }: BranchesVariables, signal?: AbortSignal) {
const { data, error } = await get(`/v1/projects/{ref}/branches`, {
params: { path: { ref: projectRef ?? '' } },
signal,
})
- if (error) throw error
+ if (error) {
+ if ((error as ResponseError).message === 'Preview branching is not enabled for this project.') {
+ return []
+ } else {
+ throw error
+ }
+ }
return data
}
diff --git a/studio/pages/project/[ref]/branches.tsx b/studio/pages/project/[ref]/branches.tsx
new file mode 100644
index 00000000000..bee6a18c20a
--- /dev/null
+++ b/studio/pages/project/[ref]/branches.tsx
@@ -0,0 +1,17 @@
+import BranchManagement from 'components/interfaces/BranchManagement/BranchManagement'
+import { ProjectLayoutWithAuth } from 'components/layouts'
+import { NextPageWithLayout } from 'types'
+
+const BranchManagementPage: NextPageWithLayout = () => {
+ return <BranchManagement />
+}
+
+BranchManagementPage.getLayout = (page) => (
+ <ProjectLayoutWithAuth>
+ <main style={{ maxHeight: '100vh' }} className="flex-1 overflow-y-auto">
+ {page}
+ </main>
+ </ProjectLayoutWithAuth>
+)
+
+export default BranchManagementPage