Skip to content

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

Branches page (#37080)

Saxon Fletcher1cc71242131c
diff --git a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx b/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx
deleted file mode 100644
index c8637b7f443..00000000000
--- a/apps/studio/components/interfaces/BranchManagement/BranchManagement.tsx
+++ /dev/null
@@ -1,440 +0,0 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { partition } from 'lodash'
-import { GitMerge, MessageCircle } from 'lucide-react'
-import { useRouter } from 'next/router'
-import { useState } from 'react'
-import { toast } from 'sonner'
-
-import { useParams } from 'common'
-import { GitHubStatus } from 'components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus'
-import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
-import AlertError from 'components/ui/AlertError'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { DocsButton } from 'components/ui/DocsButton'
-import NoPermission from 'components/ui/NoPermission'
-import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
-import { useBranchesDisableMutation } from 'data/branches/branches-disable-mutation'
-import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
-import { Branch, useBranchesQuery } from 'data/branches/branches-query'
-import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { useFlag } from 'hooks/ui/useFlag'
-import { useUrlState } from 'hooks/ui/useUrlState'
-import { useAppStateSnapshot } from 'state/app-state'
-import { Button } from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'
-import { BranchLoader, BranchManagementSection, BranchRow } from './BranchPanels'
-import { BranchSelector } from './BranchSelector'
-import { PreviewBranchesEmptyState, PullRequestsEmptyState } from './EmptyStates'
-import { Overview } from './Overview'
-import { ReviewRow } from './ReviewRow'
-
-type Tab = 'overview' | 'prs' | 'branches'
-
-const BranchManagement = () => {
- const router = useRouter()
- const { ref } = useParams()
- const project = useSelectedProject()
- const selectedOrg = useSelectedOrganization()
- const gitlessBranching = useFlag('gitlessBranching')
-
- const hasBranchEnabled = project?.is_branch_enabled
-
- const isBranch = project?.parent_project_ref !== undefined
- const projectRef =
- project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
-
- const [urlParams, setParams] = useUrlState<{ tab: Tab }>()
- const tab = urlParams.tab ?? 'overview'
- const setTab = (tab: Tab) => setParams({ tab })
-
- const snap = useAppStateSnapshot()
-
- const [showDisableBranching, setShowDisableBranching] = useState(false)
- const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()
-
- const canReadBranches = useCheckPermissions(PermissionAction.READ, 'preview_branches')
- const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {
- resource: { is_default: false },
- })
-
- const {
- data: connections,
- error: connectionsError,
- isLoading: isLoadingConnections,
- isSuccess: isSuccessConnections,
- isError: isErrorConnections,
- } = useGitHubConnectionsQuery({
- organizationId: selectedOrg?.id,
- })
-
- const {
- data: branches,
- error: branchesError,
- isLoading: isLoadingBranches,
- isError: isErrorBranches,
- isSuccess: isSuccessBranches,
- } = useBranchesQuery({ projectRef })
- const [[mainBranch], previewBranchesUnsorted] = partition(branches, (branch) => branch.is_default)
- const previewBranches = previewBranchesUnsorted.sort((a, b) =>
- new Date(a.updated_at) < new Date(b.updated_at) ? 1 : -1
- )
- const branchesWithPRs = previewBranches.filter((branch) => branch.pr_number !== undefined)
- const branchesReadyForReview = previewBranches.filter(
- (branch) => branch.review_requested_at !== undefined && branch.review_requested_at !== null
- )
-
- const currentBranch = branches?.find((branch) => branch.project_ref === ref)
- const isCurrentBranchReadyForReview =
- currentBranch?.review_requested_at !== undefined && currentBranch?.review_requested_at !== null
-
- const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
- const repo = githubConnection?.repository.name ?? ''
-
- const isError = isErrorConnections || isErrorBranches
- const isLoading = isLoadingConnections || isLoadingBranches
- const isSuccess = isSuccessConnections && isSuccessBranches
-
- const { mutate: deleteBranch, isLoading: isDeleting } = useBranchDeleteMutation({
- onSuccess: () => {
- if (selectedBranchToDelete?.project_ref === ref) {
- toast.success(
- 'Successfully deleted branch. You are now currently on the main branch of your project.'
- )
- router.push(`/project/${projectRef}/branches`)
- } else {
- toast.success('Successfully deleted branch')
- }
- setSelectedBranchToDelete(undefined)
- },
- })
-
- const { mutate: disableBranching, isLoading: isDisabling } = useBranchesDisableMutation({
- onSuccess: () => {
- toast.success('Successfully disabled branching for project')
- setShowDisableBranching(false)
- },
- })
-
- const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
- onError: () => {
- toast.error(`Failed to update the branch`)
- },
- })
-
- const handleMarkBranchForReview = (branch: Branch) => {
- if (branch.id && projectRef) {
- updateBranch(
- {
- id: branch.id,
- projectRef,
- requestReview: true,
- },
- {
- onSuccess: () => {
- toast.success('Branch marked as ready for review')
- router.push(`/project/${branch.project_ref}/merge`)
- },
- }
- )
- }
- }
-
- const generateCreatePullRequestURL = (branch?: string) => {
- if (githubConnection === undefined) return 'https://github.com'
-
- return branch !== undefined
- ? `https://github.com/${githubConnection.repository.name}/compare/${mainBranch?.git_branch}...${branch}`
- : `https://github.com/${githubConnection.repository.name}/compare`
- }
-
- 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 })
- }
-
- const onConfirmDisableBranching = () => {
- if (projectRef == undefined) return console.error('Project ref is required')
- if (!previewBranches) return console.error('No branches available')
- disableBranching({ projectRef, branchIds: previewBranches?.map((branch) => branch.id) })
- }
-
- return (
- <>
- <ScaffoldContainer>
- <ScaffoldSection>
- <div className="col-span-12">
- <h3 className="text-xl mb-8">Branches</h3>
-
- <div className="space-y-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center -space-x-px">
- <Button
- type="default"
- className={`rounded-r-none transition hover:opacity-90 ${
- tab === 'overview' ? 'opacity-100' : 'opacity-60'
- }`}
- onClick={() => setTab('overview')}
- >
- Overview
- </Button>
- <Button
- type="default"
- className={`rounded-none transition hover:opacity-90 ${
- tab === 'prs' ? 'opacity-100' : 'opacity-60'
- }`}
- onClick={() => setTab('prs')}
- >
- Merge requests
- </Button>
- <Button
- type="default"
- className={`rounded-l-none transition hover:opacity-90 ${
- tab === 'branches' ? 'opacity-100' : 'opacity-60'
- }`}
- onClick={() => setTab('branches')}
- >
- All branches
- </Button>
- </div>
- <div className="flex items-center justify-between gap-x-2">
- <Button
- asChild
- type="text"
- icon={<MessageCircle className="text-muted" strokeWidth={1} />}
- >
- <a
- target="_blank"
- rel="noreferrer"
- href="https://github.com/orgs/supabase/discussions/18937"
- >
- Branching Feedback
- </a>
- </Button>
- <DocsButton href="https://supabase.com/docs/guides/platform/branching" />
- <ButtonTooltip
- type="primary"
- disabled={!canCreateBranches}
- onClick={() => snap.setShowCreateBranchModal(true)}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canCreateBranches
- ? 'You need additional permissions to create branches'
- : undefined,
- },
- }}
- >
- Create branch
- </ButtonTooltip>
- </div>
- </div>
-
- {!canReadBranches ? (
- <NoPermission resourceText="view this project's branches" />
- ) : (
- <>
- {isErrorConnections && (
- <AlertError
- error={connectionsError}
- subject="Failed to retrieve GitHub integration connection"
- />
- )}
-
- {isSuccessConnections && hasBranchEnabled && <GitHubStatus />}
-
- {isErrorBranches && tab === 'overview' && (
- <AlertError
- error={branchesError}
- subject="Failed to retrieve preview branches"
- />
- )}
-
- {!isError && (
- <>
- {tab === 'overview' && (
- <Overview
- isLoading={isLoading}
- isSuccess={isSuccess}
- repo={repo}
- mainBranch={mainBranch}
- previewBranches={previewBranches}
- onViewAllBranches={() => setTab('branches')}
- onSelectCreateBranch={() => snap.setShowCreateBranchModal(true)}
- onSelectDeleteBranch={setSelectedBranchToDelete}
- generateCreatePullRequestURL={generateCreatePullRequestURL}
- showProductionBranch={hasBranchEnabled}
- />
- )}
- {tab === 'prs' && (
- <div className="space-y-4">
- {gitlessBranching && (
- <BranchManagementSection
- header={
- <div className="flex items-center justify-between w-full">
- <span>
- {branchesReadyForReview.length} branches ready for review
- </span>
- <BranchSelector
- branches={previewBranches}
- onBranchSelected={handleMarkBranchForReview}
- disabled={!projectRef}
- isUpdating={isUpdating}
- />
- </div>
- }
- >
- {isBranch && !isCurrentBranchReadyForReview && currentBranch && (
- <div className="bg-background px-6 py-4">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 text-sm text-foreground-light">
- <GitMerge
- strokeWidth={1.5}
- size={16}
- className="text-brand"
- />
- Mark{' '}
- <span className="text-foreground">{currentBranch.name}</span>{' '}
- ready for review
- </div>
- <Button
- type="primary"
- size="tiny"
- onClick={() =>
- currentBranch && handleMarkBranchForReview(currentBranch)
- }
- >
- Ready for review
- </Button>
- </div>
- </div>
- )}
- {branchesReadyForReview.length > 0 ? (
- branchesReadyForReview.map((branch) => {
- return <ReviewRow key={branch.id} branch={branch} />
- })
- ) : (
- <div className="px-6 py-4 text-sm text-foreground-light">
- No branches are currently ready for review
- </div>
- )}
- </BranchManagementSection>
- )}
- <BranchManagementSection
- header={`${branchesWithPRs.length} branches with pull requests`}
- >
- {branchesWithPRs.length > 0 ? (
- branchesWithPRs.map((branch) => {
- return (
- <BranchRow
- key={branch.id}
- repo={repo}
- branch={branch}
- generateCreatePullRequestURL={generateCreatePullRequestURL}
- onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}
- />
- )
- })
- ) : (
- <PullRequestsEmptyState
- url={generateCreatePullRequestURL()}
- projectRef={projectRef ?? '_'}
- hasBranches={previewBranches.length > 0}
- githubConnection={githubConnection}
- gitlessBranching={gitlessBranching}
- />
- )}
- </BranchManagementSection>
- </div>
- )}
- {tab === 'branches' && (
- <BranchManagementSection
- header={`${previewBranches.length} branches found`}
- >
- {isLoadingBranches && <BranchLoader />}
- {isErrorBranches && (
- <AlertError
- error={branchesError}
- subject="Failed to retrieve preview branches"
- />
- )}
- {isSuccessBranches && previewBranches.length === 0 && (
- <PreviewBranchesEmptyState
- onSelectCreateBranch={() => snap.setShowCreateBranchModal(true)}
- />
- )}
- {isSuccessBranches &&
- previewBranches.map((branch) => {
- return (
- <BranchRow
- key={branch.id}
- repo={repo}
- branch={branch}
- generateCreatePullRequestURL={generateCreatePullRequestURL}
- onSelectDeleteBranch={() => setSelectedBranchToDelete(branch)}
- />
- )
- })}
- </BranchManagementSection>
- )}
- </>
- )}
- </>
- )}
- </div>
- </div>
- </ScaffoldSection>
- </ScaffoldContainer>
-
- <TextConfirmModal
- variant={'warning'}
- visible={selectedBranchToDelete !== undefined}
- onCancel={() => setSelectedBranchToDelete(undefined)}
- onConfirm={() => onConfirmDeleteBranch()}
- loading={isDeleting}
- title="Delete branch"
- confirmLabel="Delete branch"
- confirmPlaceholder="Type in name of branch"
- confirmString={selectedBranchToDelete?.name ?? ''}
- alert={{ title: 'You cannot recover this branch once deleted' }}
- text={
- <>
- This will delete your database preview branch{' '}
- <span className="text-bold text-foreground">{selectedBranchToDelete?.name}</span>.
- </>
- }
- />
-
- <ConfirmationModal
- variant={'destructive'}
- size="medium"
- loading={isDisabling}
- visible={showDisableBranching}
- title="Confirm disable branching for project"
- confirmLabel="Confirm disable branching"
- confirmLabelLoading="Disabling branching..."
- onConfirm={() => onConfirmDisableBranching()}
- onCancel={() => setShowDisableBranching(false)}
- alert={{
- title: 'This action cannot be undone',
- description:
- 'All database preview branches will be removed upon disabling branching. You may still re-enable branching again thereafter, but your existing preview branches will not be restored.',
- }}
- >
- <p className="text-sm">Before you disable branching, consider:</p>
- <ul className="space-y-2 mt-2 text-sm text-foreground-light">
- <li className="list-disc ml-6">Your project no longer requires database previews.</li>
- <li className="list-disc ml-6">
- None of your database previews are currently being used in any app.
- </li>
- </ul>
- </ConfirmationModal>
- </>
- )
-}
-
-export default BranchManagement
diff --git a/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx b/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx
index dc7c142d066..a34c813599d 100644
--- a/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/BranchPanels.tsx
@@ -1,47 +1,13 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
import dayjs from 'dayjs'
-import {
- ArrowRight,
- Clock,
- ExternalLink,
- GitPullRequest,
- Github,
- Infinity,
- MoreVertical,
- Pencil,
- RefreshCw,
- Shield,
- Trash2,
-} from 'lucide-react'
-import Link from 'next/link'
-import { PropsWithChildren, ReactNode, useState } from 'react'
-import { useInView } from 'react-intersection-observer'
-import { toast } from 'sonner'
+import { Github } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { PropsWithChildren, ReactNode } from 'react'
-import { useParams } from 'common'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { useBranchQuery } from 'data/branches/branch-query'
-import { useBranchResetMutation } from 'data/branches/branch-reset-mutation'
-import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
import type { Branch } from 'data/branches/branches-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useFlag } from 'hooks/ui/useFlag'
-import {
- Badge,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from 'ui'
-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import BranchStatusBadge from './BranchStatusBadge'
-import { EditBranchModal } from './EditBranchModal'
-import WorkflowLogs from './WorkflowLogs'
+import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { WorkflowLogs } from './WorkflowLogs'
interface BranchManagementSectionProps {
header: string | ReactNode
@@ -55,7 +21,7 @@ export const BranchManagementSection = ({
}: PropsWithChildren<BranchManagementSectionProps>) => {
return (
<div className="border rounded-lg">
- <div className="bg-surface-100 shadow-sm flex justify-between items-center px-6 py-2 rounded-t-lg text-sm">
+ <div className="bg-surface-100 shadow-sm flex justify-between items-center px-4 py-3 rounded-t-lg text-xs font-mono uppercase">
{typeof header === 'string' ? <span>{header}</span> : header}
</div>
<div className="bg-surface border-t shadow-sm rounded-b-lg text-sm divide-y">{children}</div>
@@ -93,344 +59,72 @@ export const BranchLoader = () => {
interface BranchRowProps {
repo: string
+ label?: string | ReactNode
branch: Branch
- isMain?: boolean
- generateCreatePullRequestURL?: (branchName?: string) => string
- onSelectDeleteBranch: () => void
+ rowLink?: string
+ external?: boolean
+ rowActions?: ReactNode
}
export const BranchRow = ({
branch,
- isMain = false,
+ label,
repo,
- generateCreatePullRequestURL,
- onSelectDeleteBranch,
+ rowLink,
+ external = false,
+ rowActions,
}: BranchRowProps) => {
- const { ref: projectRef } = useParams()
- const isActive = projectRef === branch?.project_ref
- const gitlessBranching = useFlag('gitlessBranching')
-
- const canDeleteBranches = useCheckPermissions(PermissionAction.DELETE, 'preview_branches')
- const canUpdateBranches = useCheckPermissions(PermissionAction.UPDATE, 'preview_branches')
+ const router = useRouter()
const daysFromNow = dayjs().diff(dayjs(branch.updated_at), 'day')
const formattedTimeFromNow = dayjs(branch.updated_at).fromNow()
const formattedUpdatedAt = dayjs(branch.updated_at).format('DD MMM YYYY, HH:mm:ss (ZZ)')
- const createPullRequestURL =
- generateCreatePullRequestURL?.(branch.git_branch) ?? 'https://github.com'
-
- const { ref, inView } = useInView()
- const { data } = useBranchQuery(
- { projectRef, id: branch.id },
- {
- enabled: inView,
- refetchInterval(data) {
- if (data?.status !== 'ACTIVE_HEALTHY') {
- return 1000 * 3 // 3 seconds
- }
+ const navigateUrl = rowLink ?? `/project/${branch.project_ref}`
- return false
- },
+ const handleRowClick = () => {
+ if (external) {
+ window.open(navigateUrl, '_blank', 'noopener noreferrer')
+ } else {
+ router.push(navigateUrl)
}
- )
-
- const isBranchActiveHealthy = data?.status === 'ACTIVE_HEALTHY'
-
- const [showConfirmResetModal, setShowConfirmResetModal] = useState(false)
- const [showBranchModeSwitch, setShowBranchModeSwitch] = useState(false)
- const [showEditBranchModal, setShowEditBranchModal] = useState(false)
-
- const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
- onSuccess() {
- toast.success('Successfully updated branch')
- setShowBranchModeSwitch(false)
- },
- })
-
- const onUpdateBranchPersistentMode = () => {
- if (projectRef == undefined) return console.error('Project ref is required')
- updateBranch({ id: branch.id, projectRef, persistent: !branch.persistent })
- }
-
- const { mutate: resetBranch, isLoading: isResetting } = useBranchResetMutation({
- onSuccess() {
- toast.success('Success! Please allow a few seconds for the branch to reset.')
- setShowConfirmResetModal(false)
- },
- })
-
- function onConfirmReset() {
- if (!projectRef) throw new Error('Invalid project reference')
- resetBranch({ id: branch.id, projectRef })
}
return (
- <div className="w-full flex items-center justify-between px-6 py-2.5" ref={ref}>
+ <div className="w-full flex items-center justify-between px-4 py-2.5 transition hover:bg-surface-100">
+ <div className="flex items-center gap-x-3">
+ {branch.git_branch && (
+ <ButtonTooltip
+ asChild
+ type="default"
+ className="px-1.5"
+ tooltip={{ content: { side: 'bottom', text: 'View branch on GitHub' } }}
+ >
+ <a
+ target="_blank"
+ rel="noreferrer noopener"
+ href={`https://github.com/${repo}/tree/${branch.git_branch}`}
+ >
+ <Github size={14} className="text-foreground-light" />
+ </a>
+ </ButtonTooltip>
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div className="flex items-center cursor-pointer" onClick={handleRowClick}>
+ {label || branch.name}
+ </div>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">Switch to branch</TooltipContent>
+ </Tooltip>
+ </div>
<div className="flex items-center gap-x-4">
- <ButtonTooltip
- asChild
- type="default"
- className="max-w-[300px]"
- icon={
- isMain ? (
- <Shield strokeWidth={2} className="text-amber-900" />
- ) : branch.persistent ? (
- <Infinity size={16} />
- ) : null
- }
- tooltip={{
- content: {
- side: 'bottom',
- text: branch.persistent
- ? `${branch.name} is a persistent branch and will remain active even after the
- underlying PR is closed`
- : 'Switch to branch',
- },
- }}
- >
- <Link href={`/project/${branch.project_ref}`} title={branch.name}>
- {branch.name}
- </Link>
- </ButtonTooltip>
-
- {branch.git_branch && <Github size={14} className="text-foreground-light" />}
-
- {isActive && <Badge>Current</Badge>}
- <BranchStatusBadge
- status={
- branch.status === 'CREATING_PROJECT' ? data?.status ?? branch.status : branch.status
- }
- />
<p className="text-xs text-foreground-lighter">
{daysFromNow > 1 ? `Updated on ${formattedUpdatedAt}` : `Updated ${formattedTimeFromNow}`}
</p>
+ <WorkflowLogs projectRef={branch.project_ref} status={branch.status} />
+ {rowActions}
</div>
- <div className="flex items-center gap-x-8">
- {isMain ? (
- <div className="flex items-center gap-x-2">
- {repo && (
- <Button asChild type="default" iconRight={<ExternalLink size={14} />}>
- <Link target="_blank" rel="noreferrer" passHref href={`https://github.com/${repo}`}>
- View Repository
- </Link>
- </Button>
- )}
- <WorkflowLogs projectRef={branch.project_ref} />
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button type="text" icon={<MoreVertical />} className="px-1" />
- </DropdownMenuTrigger>
- <DropdownMenuContent className="p-0 w-56" side="bottom" align="end">
- {repo ? (
- <Link passHref href={`/project/${projectRef}/settings/integrations`}>
- <DropdownMenuItem asChild className="gap-x-2">
- <a>Change production branch</a>
- </DropdownMenuItem>
- </Link>
- ) : (
- <Tooltip>
- <TooltipTrigger
- asChild={canUpdateBranches && isBranchActiveHealthy}
- className="w-full"
- >
- <DropdownMenuItem
- className="gap-x-2"
- disabled={!canUpdateBranches || !isBranchActiveHealthy || isUpdating}
- onSelect={() => setShowEditBranchModal(true)}
- onClick={() => setShowEditBranchModal(true)}
- >
- <Pencil size={14} />
- Edit Branch
- </DropdownMenuItem>
- </TooltipTrigger>
- {(!canUpdateBranches || !isBranchActiveHealthy) && (
- <TooltipContent side="left">
- {!canUpdateBranches
- ? 'You need additional permissions to edit branches'
- : 'Branch is still initializing. Please wait for the branch to become healthy before editing.'}
- </TooltipContent>
- )}
- </Tooltip>
- )}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- ) : (
- <div className="flex items-center gap-x-2">
- {branch.git_branch && branch.pr_number === undefined ? (
- <Button asChild type="default" iconRight={<ExternalLink size={14} />}>
- <Link passHref target="_blank" rel="noreferrer" href={createPullRequestURL}>
- Create Pull Request
- </Link>
- </Button>
- ) : branch.pr_number !== undefined ? (
- <div className="flex items-center">
- <Link
- href={`https://github.com/${repo}/pull/${branch.pr_number}`}
- target="_blank"
- rel="noreferrer"
- className="flex items-center gap-x-2 transition px-3 py-1 rounded-full bg-background-surface-400 hover:text-foreground"
- >
- <GitPullRequest size={14} />#{branch.pr_number}
- </Link>
- <ArrowRight className="mx-1 text-foreground-light" strokeWidth={1.5} size={16} />
- <Button asChild type="default">
- <Link
- passHref
- target="_blank"
- rel="noreferer"
- href={`http://github.com/${repo}/tree/${branch.git_branch}`}
- >
- {branch.git_branch}
- </Link>
- </Button>
- </div>
- ) : null}
- <WorkflowLogs projectRef={branch.project_ref} />
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button type="text" icon={<MoreVertical />} className="px-1" />
- </DropdownMenuTrigger>
- <DropdownMenuContent className="w-56" side="bottom" align="end">
- <Tooltip>
- <TooltipTrigger asChild={isBranchActiveHealthy} className="w-full">
- <DropdownMenuItem
- className="gap-x-2"
- onSelect={() => setShowConfirmResetModal(true)}
- onClick={() => setShowConfirmResetModal(true)}
- disabled={isResetting || !isBranchActiveHealthy}
- >
- <RefreshCw size={14} />
- Reset Branch
- </DropdownMenuItem>
- </TooltipTrigger>
- {!isBranchActiveHealthy && (
- <TooltipContent side="left">
- Branch is still initializing. Please wait for the branch to become healthy
- before resetting
- </TooltipContent>
- )}
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild={isBranchActiveHealthy} className="w-full">
- <DropdownMenuItem
- className="gap-x-2"
- onSelect={() => setShowBranchModeSwitch(true)}
- onClick={() => setShowBranchModeSwitch(true)}
- disabled={!isBranchActiveHealthy}
- >
- {branch.persistent ? (
- <>
- <Clock size={14} /> Switch to ephemeral
- </>
- ) : (
- <>
- <Infinity size={14} className="scale-110" /> Switch to persistent
- </>
- )}
- </DropdownMenuItem>
- </TooltipTrigger>
- {!isBranchActiveHealthy && (
- <TooltipContent side="left">
- Branch is still initializing. Please wait for the branch to become healthy
- before switching modes
- </TooltipContent>
- )}
- </Tooltip>
- {gitlessBranching && (
- <Tooltip>
- <TooltipTrigger
- asChild={canUpdateBranches && isBranchActiveHealthy}
- className="w-full"
- >
- <DropdownMenuItem
- className="gap-x-2"
- disabled={!canUpdateBranches || !isBranchActiveHealthy || isUpdating}
- onSelect={() => setShowEditBranchModal(true)}
- onClick={() => setShowEditBranchModal(true)}
- >
- <Pencil size={14} />
- Edit Branch
- </DropdownMenuItem>
- </TooltipTrigger>
- {(!canUpdateBranches || !isBranchActiveHealthy) && (
- <TooltipContent side="left">
- {!canUpdateBranches
- ? 'You need additional permissions to edit branches'
- : 'Branch is still initializing. Please wait for the branch to become healthy before editing.'}
- </TooltipContent>
- )}
- </Tooltip>
- )}
-
- <Tooltip>
- <TooltipTrigger asChild={canDeleteBranches} className="w-full">
- <DropdownMenuItem
- className="gap-x-2"
- disabled={!canDeleteBranches}
- onSelect={() => onSelectDeleteBranch?.()}
- onClick={() => onSelectDeleteBranch?.()}
- >
- <Trash2 size={14} />
- Delete branch
- </DropdownMenuItem>
- </TooltipTrigger>
- {!canDeleteBranches && (
- <TooltipContent side="left">
- You need additional permissions to delete branches
- </TooltipContent>
- )}
- </Tooltip>
- </DropdownMenuContent>
- </DropdownMenu>
-
- <ConfirmationModal
- variant={'destructive'}
- visible={showConfirmResetModal}
- confirmLabel="Reset branch"
- title="Confirm branch reset"
- loading={isResetting}
- onCancel={() => {
- setShowConfirmResetModal(false)
- }}
- onConfirm={onConfirmReset}
- >
- <p className="text-sm text-foreground-light">
- Are you sure you want to reset the "{branch.name}" branch? All data will be deleted.
- </p>
- </ConfirmationModal>
-
- <ConfirmationModal
- variant={'default'}
- visible={showBranchModeSwitch}
- confirmLabel={branch.persistent ? 'Switch to ephemeral' : 'Switch to persistent'}
- title={`Confirm branch mode switch`}
- loading={isUpdating}
- onCancel={() => {
- setShowBranchModeSwitch(false)
- }}
- onConfirm={onUpdateBranchPersistentMode}
- >
- <p className="text-sm text-foreground-light">
- Are you sure you want to switch the branch "{branch.name}" to{' '}
- {branch.persistent ? 'ephemeral' : 'persistent'} mode?
- <br />
- <br />
- {branch.persistent
- ? 'Ephemeral branches will be deleted once the underlying PR closes.'
- : 'Persistent branches will remain active even after the underlying PR is closed.'}
- </p>
- </ConfirmationModal>
- </div>
- )}
- </div>
-
- <EditBranchModal
- branch={branch}
- visible={showEditBranchModal}
- onClose={() => setShowEditBranchModal(false)}
- />
</div>
)
}
diff --git a/apps/studio/components/interfaces/BranchManagement/BranchSelector.tsx b/apps/studio/components/interfaces/BranchManagement/BranchSelector.tsx
index 3c9b4c277c1..51c2c5528e1 100644
--- a/apps/studio/components/interfaces/BranchManagement/BranchSelector.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/BranchSelector.tsx
@@ -1,9 +1,9 @@
-import { Check, Plus, Shield } from 'lucide-react'
+import { Check, GitMerge, Shield } from 'lucide-react'
import { useState } from 'react'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { Branch } from 'data/branches/branches-query'
import {
- Button,
CommandEmpty_Shadcn_,
CommandGroup_Shadcn_,
CommandInput_Shadcn_,
@@ -21,6 +21,7 @@ interface BranchSelectorProps {
onBranchSelected?: (branch: Branch) => void
disabled?: boolean
isUpdating?: boolean
+ type?: 'primary' | 'outline'
}
export const BranchSelector = ({
@@ -28,6 +29,7 @@ export const BranchSelector = ({
onBranchSelected,
disabled = false,
isUpdating = false,
+ type = 'primary',
}: BranchSelectorProps) => {
const [open, setOpen] = useState(false)
const [selectedBranch, setSelectedBranch] = useState<Branch | null>(null)
@@ -46,16 +48,24 @@ export const BranchSelector = ({
return (
<Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
<PopoverTrigger_Shadcn_ asChild>
- <Button
- type="outline"
- size="tiny"
+ <ButtonTooltip
+ icon={<GitMerge size={14} strokeWidth={1.5} />}
+ type={type}
disabled={disabled || availableBranches.length === 0 || isUpdating}
- icon={<Plus size={14} strokeWidth={1.5} />}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text:
+ availableBranches.length === 0
+ ? 'All branches currently have merge requests'
+ : undefined,
+ },
+ }}
>
- {isUpdating ? 'Creating...' : 'Create review'}
- </Button>
+ {isUpdating ? 'Creating...' : 'New merge request'}
+ </ButtonTooltip>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0 w-80" side="bottom">
+ <PopoverContent_Shadcn_ portal className="p-0 w-80" side="bottom" align="end">
<Command_Shadcn_>
<CommandInput_Shadcn_ placeholder="Find branch to review..." />
<CommandList_Shadcn_>
diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
index 92a6a77db2f..fca9784bed0 100644
--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
@@ -1,14 +1,15 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { useQueryClient } from '@tanstack/react-query'
-import { useParams } from 'common'
-import { DollarSign, Github, GitMerge, Loader2, Merge } from 'lucide-react'
+import { DollarSign, GitMerge, Github, Loader2 } from 'lucide-react'
import Image from 'next/image'
import Link from 'next/link'
+import { useRouter } from 'next/router'
import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
+import { useParams } from 'common'
import { BranchingPITRNotice } from 'components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice'
import AlertError from 'components/ui/AlertError'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
@@ -42,7 +43,6 @@ import {
cn,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import { useRouter } from 'next/router'
export const CreateBranchModal = () => {
const { ref } = useParams()
diff --git a/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx b/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
index eb003f42937..6bcd2ba8bbb 100644
--- a/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/EdgeFunctionsDiffPanel.tsx
@@ -142,7 +142,9 @@ const EdgeFunctionsDiffPanel = ({
return <Skeleton className="h-64" />
}
- if (!diffResults.hasChanges) {
+ const noChanges = diffResults.addedSlugs.length === 0 && diffResults.modifiedSlugs.length === 0
+
+ if (noChanges) {
return (
<div className="p-6 text-center">
<Wind size={32} strokeWidth={1.5} className="text-foreground-muted mx-auto mb-8" />
diff --git a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
index 2ab15c74e3d..7161c91db31 100644
--- a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
@@ -219,7 +219,7 @@ export const EditBranchModal = ({ branch, visible, onClose }: EditBranchModalPro
control={form.control}
name="branchName"
render={({ field }) => (
- <FormItemLayout label="Preview Branch Name">
+ <FormItemLayout label="Preview branch name">
<FormControl_Shadcn_>
<Input_Shadcn_
{...field}
diff --git a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx
index 8d6f55ce550..ed5c505cdd6 100644
--- a/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/EmptyStates.tsx
@@ -1,125 +1,55 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { ExternalLink, GitBranch, GitPullRequest, Github } from 'lucide-react'
+import type { Branch } from 'data/branches/branches-query'
+import { Github } from 'lucide-react'
import Link from 'next/link'
+import { BranchSelector } from './BranchSelector'
-import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useAppStateSnapshot } from 'state/app-state'
-import { sidePanelsState } from 'state/side-panels'
+import { DocsButton } from 'components/ui/DocsButton'
import { Button } from 'ui'
-export const BranchingEmptyState = () => {
- const snap = useAppStateSnapshot()
-
- const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {
- resource: { is_default: false },
- })
-
- return (
- <ProductEmptyState title="Database Branching">
- <p className="text-sm text-light">
- Create preview branches to experiment with changes to your database schema in a safe,
- non-destructive environment.
- </p>
- <div className="flex items-center space-x-2 !mt-4">
- <ButtonTooltip
- disabled={!canCreateBranches}
- icon={<GitBranch strokeWidth={1.5} />}
- onClick={() => snap.setShowCreateBranchModal(true)}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canCreateBranches
- ? 'You need additional permissions to create branches'
- : undefined,
- },
- }}
- >
- Create branch
- </ButtonTooltip>
-
- <Button type="default" icon={<ExternalLink strokeWidth={1.5} />} asChild>
- <a
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/guides/platform/branching"
- >
- View the docs
- </a>
- </Button>
- </div>
- </ProductEmptyState>
- )
-}
-
export const PullRequestsEmptyState = ({
url,
projectRef,
- hasBranches,
+ branches,
+ onBranchSelected,
+ isUpdating,
githubConnection,
- gitlessBranching,
+ gitlessBranching = false,
}: {
url: string
projectRef: string
- hasBranches: boolean
+ branches: Branch[]
+ onBranchSelected: (branch: Branch) => void
+ isUpdating: boolean
githubConnection?: any
- gitlessBranching?: boolean
+ gitlessBranching: boolean
}) => {
- // Show GitHub connection message if GitHub is not connected and gitless branching is enabled
- if (!githubConnection && gitlessBranching) {
- return (
- <div className="p-16 text-center">
- <div>
- <h3 className="mb-1">Connect to GitHub for seamless branching</h3>
- <p className="text-sm text-foreground-light mb-4">
- Sync GitHub repos to Supabase projects for automatic branch creation and merging
- </p>
- </div>
-
- <Button type="default" icon={<Github />} asChild>
- <Link href={`/project/${projectRef}/settings/integrations`}>Connect to GitHub</Link>
- </Button>
- </div>
- )
- }
-
return (
<div className="flex items-center flex-col justify-center w-full py-10">
- <p>No pull requests made yet for this repository</p>
+ <p>No merge requests</p>
<p className="text-foreground-light">
- Only pull requests with the ./migration directory changes will show here.
+ Create your first merge request to merge changes back to the main branch
</p>
- {hasBranches && (
- <div className="w-96 border rounded-md mt-4">
- <div className="px-5 py-3 bg-surface-100 flex items-center justify-between">
- <div className="flex items-center space-x-4">
- <GitPullRequest size={18} strokeWidth={2} className="text-foreground-light" />
- <p>Create a pull request</p>
- </div>
- <Button asChild type="default" iconRight={<ExternalLink size={14} />}>
- <Link passHref target="_blank" rel="noreferrer" href={url}>
- Github
- </Link>
- </Button>
- </div>
- <div className="px-5 py-3 border-t flex items-center justify-between">
- <div>
- <p>Not sure what to do?</p>
- <p className="text-foreground-light">Browse our documentation</p>
- </div>
- <Button type="default" iconRight={<ExternalLink size={14} />}>
- <Link
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/guides/platform/branching"
- >
- Docs
- </Link>
- </Button>
- </div>
- </div>
- )}
+ <div className="flex items-center space-x-2 mt-4">
+ {githubConnection ? (
+ <Button type="outline" asChild icon={<Github />}>
+ <a href={url} target="_blank" rel="noopener noreferrer">
+ Create pull request
+ </a>
+ </Button>
+ ) : (
+ <Button asChild type="outline">
+ <Link href={`/project/${projectRef}/settings/integrations`}>Connect to GitHub</Link>
+ </Button>
+ )}
+ {gitlessBranching && (
+ <BranchSelector
+ type="outline"
+ branches={branches}
+ onBranchSelected={onBranchSelected}
+ isUpdating={isUpdating}
+ />
+ )}
+ </div>
</div>
)
}
@@ -137,15 +67,7 @@ export const PreviewBranchesEmptyState = ({
non-destructive environment.
</p>
<div className="flex items-center space-x-2">
- <Button type="default" iconRight={<ExternalLink size={14} />}>
- <Link
- target="_blank"
- rel="noreferrer"
- href="https://supabase.com/docs/guides/platform/branching"
- >
- Docs
- </Link>
- </Button>
+ <DocsButton href="https://supabase.com/docs/guides/platform/branching" />
<Button type="primary" onClick={() => onSelectCreateBranch()}>
Create your first branch
</Button>
diff --git a/apps/studio/components/interfaces/BranchManagement/Overview.tsx b/apps/studio/components/interfaces/BranchManagement/Overview.tsx
index 487ad934292..dc3a9dfcbf0 100644
--- a/apps/studio/components/interfaces/BranchManagement/Overview.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/Overview.tsx
@@ -1,20 +1,47 @@
-import { noop } from 'lodash'
-import { Button } from 'ui'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import { partition } from 'lodash'
+import {
+ Clock,
+ ExternalLink,
+ Infinity,
+ MoreVertical,
+ Pencil,
+ RefreshCw,
+ Shield,
+ Trash2,
+} from 'lucide-react'
+import Link from 'next/link'
+import { useState } from 'react'
+import { toast } from 'sonner'
+import { useParams } from 'common'
+import { DropdownMenuItemTooltip } from 'components/ui/DropdownMenuItemTooltip'
+import { useBranchQuery } from 'data/branches/branch-query'
+import { useBranchResetMutation } from 'data/branches/branch-reset-mutation'
+import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
import type { Branch } from 'data/branches/branches-query'
-import { ChevronRight } from 'lucide-react'
+import { branchKeys } from 'data/branches/keys'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useFlag } from 'hooks/ui/useFlag'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { BranchLoader, BranchManagementSection, BranchRow, BranchRowLoader } from './BranchPanels'
+import { EditBranchModal } from './EditBranchModal'
import { PreviewBranchesEmptyState } from './EmptyStates'
-const MAX_BRANCHES_OVERVIEW = 10
-
interface OverviewProps {
isLoading: boolean
isSuccess: boolean
repo: string
mainBranch: Branch
previewBranches: Branch[]
- onViewAllBranches: () => void
onSelectCreateBranch: () => void
onSelectDeleteBranch: (branch: Branch) => void
generateCreatePullRequestURL: (branchName?: string) => string
@@ -27,48 +54,89 @@ export const Overview = ({
repo,
mainBranch,
previewBranches,
- onViewAllBranches,
onSelectCreateBranch,
onSelectDeleteBranch,
generateCreatePullRequestURL,
showProductionBranch = true,
}: OverviewProps) => {
+ const [persistentBranches, ephemeralBranches] = partition(
+ previewBranches,
+ (branch) => branch.persistent
+ )
+
return (
<>
{showProductionBranch && (
<BranchManagementSection header="Production branch">
{isLoading && <BranchRowLoader />}
{isSuccess && mainBranch !== undefined && (
- <BranchRow isMain branch={mainBranch} repo={repo} onSelectDeleteBranch={noop} />
+ <BranchRow
+ branch={mainBranch}
+ label={
+ <div className="flex items-center gap-x-2">
+ <Shield size={14} strokeWidth={1.5} className="text-warning" />
+ {mainBranch.name}
+ </div>
+ }
+ repo={repo}
+ rowActions={<MainBranchActions branch={mainBranch} repo={repo} />}
+ />
)}
</BranchManagementSection>
)}
- <BranchManagementSection
- header="Preview branches"
- footer={
- isSuccess && (
- <div className="flex items-center justify-center">
- <Button type="text" iconRight={<ChevronRight />} onClick={() => onViewAllBranches()}>
- View all branches
- </Button>
- </div>
- )
- }
- >
+ {/* Persistent Branches Section */}
+ <BranchManagementSection header="Persistent branches">
+ {isLoading && <BranchLoader />}
+ {isSuccess && persistentBranches.length === 0 && (
+ <div className="flex items-center flex-col justify-center w-full py-10">
+ <p>No persistent branches</p>
+ <p className="text-foreground-light">
+ Persistent branches are long-lived and not automatically deleted.
+ </p>
+ </div>
+ )}
+ {isSuccess &&
+ persistentBranches.map((branch) => {
+ return (
+ <BranchRow
+ key={branch.id}
+ repo={repo}
+ branch={branch}
+ rowActions={
+ <PreviewBranchActions
+ branch={branch}
+ repo={repo}
+ onSelectDeleteBranch={() => onSelectDeleteBranch(branch)}
+ generateCreatePullRequestURL={generateCreatePullRequestURL}
+ />
+ }
+ />
+ )
+ })}
+ </BranchManagementSection>
+
+ {/* Ephemeral/Preview Branches Section */}
+ <BranchManagementSection header="Preview branches">
{isLoading && <BranchLoader />}
- {isSuccess && previewBranches.length === 0 && (
+ {isSuccess && ephemeralBranches.length === 0 && (
<PreviewBranchesEmptyState onSelectCreateBranch={onSelectCreateBranch} />
)}
{isSuccess &&
- previewBranches.slice(0, MAX_BRANCHES_OVERVIEW).map((branch) => {
+ ephemeralBranches.map((branch) => {
return (
<BranchRow
key={branch.id}
repo={repo}
branch={branch}
- generateCreatePullRequestURL={generateCreatePullRequestURL}
- onSelectDeleteBranch={() => onSelectDeleteBranch(branch)}
+ rowActions={
+ <PreviewBranchActions
+ branch={branch}
+ repo={repo}
+ onSelectDeleteBranch={() => onSelectDeleteBranch(branch)}
+ generateCreatePullRequestURL={generateCreatePullRequestURL}
+ />
+ }
/>
)
})}
@@ -76,3 +144,267 @@ export const Overview = ({
</>
)
}
+
+// Row actions for preview branches (non-main)
+const PreviewBranchActions = ({
+ branch,
+ onSelectDeleteBranch,
+ generateCreatePullRequestURL,
+}: {
+ branch: Branch
+ repo: string
+ onSelectDeleteBranch: () => void
+ generateCreatePullRequestURL: (branchName?: string) => string
+}) => {
+ const gitlessBranching = useFlag('gitlessBranching')
+ const queryClient = useQueryClient()
+ const projectRef = branch.parent_project_ref ?? branch.project_ref
+
+ const canDeleteBranches = useCheckPermissions(PermissionAction.DELETE, 'preview_branches')
+ const canUpdateBranches = useCheckPermissions(PermissionAction.UPDATE, 'preview_branches')
+
+ const { data } = useBranchQuery({ projectRef, id: branch.id })
+ const isBranchActiveHealthy = data?.status === 'ACTIVE_HEALTHY'
+
+ const [showConfirmResetModal, setShowConfirmResetModal] = useState(false)
+ const [showBranchModeSwitch, setShowBranchModeSwitch] = useState(false)
+ const [showEditBranchModal, setShowEditBranchModal] = useState(false)
+
+ const { mutate: resetBranch, isLoading: isResetting } = useBranchResetMutation({
+ onSuccess() {
+ toast.success('Success! Please allow a few seconds for the branch to reset.')
+ setShowConfirmResetModal(false)
+ },
+ })
+
+ const { mutate: updateBranch, isLoading: isUpdatingBranch } = useBranchUpdateMutation({
+ onSuccess() {
+ toast.success('Successfully updated branch')
+ setShowBranchModeSwitch(false)
+ if (projectRef) {
+ queryClient.invalidateQueries({ queryKey: branchKeys.list(projectRef) })
+ }
+ },
+ })
+
+ const onConfirmReset = () => {
+ if (!projectRef) return
+ resetBranch({ id: branch.id, projectRef })
+ }
+
+ const onTogglePersistent = () => {
+ if (!projectRef) return
+ updateBranch({ id: branch.id, projectRef, persistent: !branch.persistent })
+ }
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="text"
+ icon={<MoreVertical />}
+ className="px-1"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" side="bottom" align="end">
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={isResetting || !isBranchActiveHealthy}
+ onSelect={(e) => {
+ e.stopPropagation()
+ setShowConfirmResetModal(true)
+ }}
+ onClick={(e) => {
+ e.stopPropagation()
+ setShowConfirmResetModal(true)
+ }}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: !isBranchActiveHealthy
+ ? 'Branch is still initializing. Please wait for it to become healthy before resetting.'
+ : undefined,
+ },
+ }}
+ >
+ <RefreshCw size={14} /> Reset branch
+ </DropdownMenuItemTooltip>
+
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={!isBranchActiveHealthy}
+ onSelect={(e) => {
+ e.stopPropagation()
+ setShowBranchModeSwitch(true)
+ }}
+ onClick={(e) => {
+ e.stopPropagation()
+ setShowBranchModeSwitch(true)
+ }}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: !isBranchActiveHealthy
+ ? 'Branch is still initializing. Please wait for it to become healthy before switching.'
+ : undefined,
+ },
+ }}
+ >
+ {branch.persistent ? (
+ <>
+ <Clock size={14} /> Switch to preview
+ </>
+ ) : (
+ <>
+ <Infinity size={14} className="scale-110" /> Switch to persistent
+ </>
+ )}
+ </DropdownMenuItemTooltip>
+
+ {/* Edit Branch (gitless) */}
+ {gitlessBranching && (
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={!canUpdateBranches || !isBranchActiveHealthy || isUpdatingBranch}
+ onSelect={(e) => {
+ e.stopPropagation()
+ setShowEditBranchModal(true)
+ }}
+ onClick={(e) => {
+ e.stopPropagation()
+ setShowEditBranchModal(true)
+ }}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: !canUpdateBranches
+ ? 'You need additional permissions to edit branches'
+ : !isBranchActiveHealthy
+ ? 'Branch is still initializing. Please wait for it to become healthy before editing.'
+ : undefined,
+ },
+ }}
+ >
+ <Pencil size={14} /> Edit branch
+ </DropdownMenuItemTooltip>
+ )}
+
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={!canDeleteBranches}
+ onSelect={(e) => {
+ e.stopPropagation()
+ onSelectDeleteBranch()
+ }}
+ onClick={(e) => {
+ e.stopPropagation()
+ onSelectDeleteBranch()
+ }}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: !canDeleteBranches
+ ? 'You need additional permissions to delete branches'
+ : undefined,
+ },
+ }}
+ >
+ <Trash2 size={14} /> Delete branch
+ </DropdownMenuItemTooltip>
+
+ {/* Create PR if applicable */}
+ {branch.git_branch && branch.pr_number === undefined && (
+ <DropdownMenuItem asChild className="gap-x-2">
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href={generateCreatePullRequestURL(branch.git_branch)}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <ExternalLink size={14} /> Create pull request
+ </a>
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <ConfirmationModal
+ variant="destructive"
+ visible={showConfirmResetModal}
+ confirmLabel="Reset branch"
+ title="Confirm branch reset"
+ loading={isResetting}
+ onCancel={() => setShowConfirmResetModal(false)}
+ onConfirm={onConfirmReset}
+ >
+ <p className="text-sm text-foreground-light">
+ Are you sure you want to reset the "{branch.name}" branch? All data will be deleted.
+ </p>
+ </ConfirmationModal>
+
+ <ConfirmationModal
+ variant="default"
+ visible={showBranchModeSwitch}
+ confirmLabel={branch.persistent ? 'Switch to preview' : 'Switch to persistent'}
+ title="Confirm branch mode switch"
+ loading={isUpdatingBranch}
+ onCancel={() => setShowBranchModeSwitch(false)}
+ onConfirm={onTogglePersistent}
+ >
+ <p className="text-sm text-foreground-light">
+ Are you sure you want to switch the branch "{branch.name}" to{' '}
+ {branch.persistent ? 'preview' : 'persistent'}?
+ </p>
+ </ConfirmationModal>
+
+ <EditBranchModal
+ branch={branch}
+ visible={showEditBranchModal}
+ onClose={() => setShowEditBranchModal(false)}
+ />
+ </>
+ )
+}
+
+// Actions for main (production) branch
+const MainBranchActions = ({ branch, repo }: { branch: Branch; repo: string }) => {
+ const { ref: projectRef } = useParams()
+ const canUpdateBranches = useCheckPermissions(PermissionAction.UPDATE, 'preview_branches')
+ const [showEditBranchModal, setShowEditBranchModal] = useState(false)
+
+ return (
+ <>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button type="text" icon={<MoreVertical />} className="px-1" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" side="bottom" align="end">
+ {repo ? (
+ <Link passHref href={`/project/${projectRef}/settings/integrations`}>
+ <DropdownMenuItem asChild className="gap-x-2">
+ <a>Change production branch</a>
+ </DropdownMenuItem>
+ </Link>
+ ) : (
+ <DropdownMenuItem
+ className="gap-x-2"
+ disabled={!canUpdateBranches}
+ onSelect={() => setShowEditBranchModal(true)}
+ onClick={() => setShowEditBranchModal(true)}
+ >
+ <Pencil size={14} /> Edit Branch
+ </DropdownMenuItem>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+
+ <EditBranchModal
+ branch={branch}
+ visible={showEditBranchModal}
+ onClose={() => setShowEditBranchModal(false)}
+ />
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx b/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx
index a412150f120..fddc2017c14 100644
--- a/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/WorkflowLogs.tsx
@@ -1,6 +1,8 @@
+import type { Branch } from 'data/branches/branches-query'
import dayjs from 'dayjs'
import { ArrowLeft, ArrowRight } from 'lucide-react'
import { useState } from 'react'
+import { StatusIcon } from 'ui'
import AlertError from 'components/ui/AlertError'
import { useWorkflowRunLogsQuery } from 'data/workflow-runs/workflow-run-logs-query'
@@ -22,9 +24,20 @@ import BranchStatusBadge from './BranchStatusBadge'
interface WorkflowLogsProps {
projectRef: string
+ status?: Branch['status'] | string
}
-const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {
+type StatusType = Branch['status'] | string
+
+const UNHEALTHY_STATUSES: StatusType[] = [
+ 'ACTIVE_UNHEALTHY',
+ 'INIT_FAILED',
+ 'UNKNOWN',
+ 'MIGRATIONS_FAILED',
+ 'FUNCTIONS_FAILED',
+]
+
+export const WorkflowLogs = ({ projectRef, status }: WorkflowLogsProps) => {
const [isOpen, setIsOpen] = useState(false)
const {
@@ -33,14 +46,7 @@ const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {
isLoading: isWorkflowRunsLoading,
isError: isWorkflowRunsError,
error: workflowRunsError,
- } = useWorkflowRunsQuery(
- {
- projectRef,
- },
- {
- enabled: isOpen,
- }
- )
+ } = useWorkflowRunsQuery({ projectRef }, { enabled: isOpen })
const [selectedWorkflowRunId, setSelectedWorkflowRunId] = useState<string | undefined>(undefined)
@@ -51,24 +57,36 @@ const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {
isError: isWorkflowRunLogsError,
error: workflowRunLogsError,
} = useWorkflowRunLogsQuery(
- {
- workflowRunId: selectedWorkflowRunId,
- },
- {
- enabled: isOpen && selectedWorkflowRunId !== undefined,
- }
+ { workflowRunId: selectedWorkflowRunId },
+ { enabled: isOpen && selectedWorkflowRunId !== undefined }
)
+ const showStatusIcon =
+ status !== undefined &&
+ status !== 'ACTIVE_HEALTHY' &&
+ status !== 'FUNCTIONS_DEPLOYED' &&
+ status !== 'MIGRATIONS_PASSED'
+ const isUnhealthy = status !== undefined && UNHEALTHY_STATUSES.includes(status)
+
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
- <Button type="default">View Logs</Button>
+ <Button
+ type="default"
+ icon={
+ showStatusIcon ? (
+ <StatusIcon variant={isUnhealthy ? 'destructive' : 'default'} hideBackground />
+ ) : undefined
+ }
+ onClick={(e) => e.stopPropagation()}
+ >
+ View Logs
+ </Button>
</DialogTrigger>
<DialogContent size="xlarge">
<DialogHeader>
<DialogTitle>Workflow Logs</DialogTitle>
-
<DialogDescription>Select a workflow run to view logs</DialogDescription>
</DialogHeader>
@@ -143,5 +161,3 @@ const WorkflowLogs = ({ projectRef }: WorkflowLogsProps) => {
</Dialog>
)
}
-
-export default WorkflowLogs
diff --git a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx
index b120389a4e4..c525ced88a6 100644
--- a/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx
+++ b/apps/studio/components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus.tsx
@@ -1,6 +1,6 @@
-import { useRouter } from 'next/router'
-import { CheckCircle2, Settings, AlertCircle } from 'lucide-react'
+import { AlertCircle, ArrowUpRight, CheckCircle2 } from 'lucide-react'
import Image from 'next/image'
+import Link from 'next/link'
import { useParams } from 'common'
import { useBranchesQuery } from 'data/branches/branches-query'
@@ -8,8 +8,7 @@ import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { BASE_PATH } from 'lib/constants'
-import { Button, Card, CardContent } from 'ui'
-import Link from 'next/link'
+import { HoverCard, HoverCardContent, HoverCardTrigger } from 'ui'
export const GitHubStatus = () => {
const { ref: projectRef } = useParams()
@@ -33,13 +32,42 @@ export const GitHubStatus = () => {
const mainBranch = branches?.find((branch) => branch.is_default)
const isConnected = Boolean(githubConnection)
+
const hasGitBranchSync = Boolean(mainBranch?.git_branch?.trim())
const hasAutomaticBranching = Boolean(githubConnection?.new_branch_per_pr)
return (
- <Card>
- <CardContent className="flex items-center justify-between">
- <div className="flex items-center gap-4">
+ <HoverCard openDelay={300} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <Link
+ href={`/project/${parentProjectRef}/settings/integrations`}
+ className="block w-full transition truncate text-sm text-foreground-light hover:text-foreground"
+ >
+ <div className="w-full flex items-center justify-between">
+ <h3 className="">GitHub Integration</h3>
+ <ArrowUpRight strokeWidth={1} className="h-4 w-4" />
+ </div>
+ <p className="mt-1 text-xs text-foreground-lighter flex items-center gap-2">
+ {isConnected ? (
+ <>
+ <Image
+ className="dark:invert"
+ src={`${BASE_PATH}/img/icons/github-icon.svg`}
+ width={16}
+ height={16}
+ alt="GitHub"
+ />
+ {githubConnection?.repository.name}
+ </>
+ ) : (
+ 'Not connected'
+ )}
+ </p>
+ </Link>
+ </HoverCardTrigger>
+
+ <HoverCardContent side="right" align="start" className="w-80 p-4 space-y-2">
+ <div className="flex items-center gap-2 text-sm">
<Image
className="dark:invert"
src={`${BASE_PATH}/img/icons/github-icon.svg`}
@@ -47,53 +75,42 @@ export const GitHubStatus = () => {
height={20}
alt="GitHub"
/>
+ <span className="truncate">
+ {isConnected ? githubConnection?.repository.name : 'Not connected'}
+ </span>
+ </div>
- <div className="flex flex-col gap-1">
- <h3 className="text-sm text-foreground">
- {isConnected
- ? `Connected to ${githubConnection?.repository.name}`
- : 'GitHub Integration'}
- </h3>
-
- <div className="flex items-center gap-4 text-xs text-foreground-light">
- {isConnected ? (
- <>
- <div className="flex items-center gap-1">
- {hasGitBranchSync ? (
- <CheckCircle2 size={12} className="text-brand-600" />
- ) : (
- <AlertCircle size={12} className="text-warning-600" />
- )}
- <span>
- {hasGitBranchSync
- ? `Syncing production (${mainBranch?.git_branch})`
- : 'Production sync disabled'}
- </span>
- </div>
- <div className="flex items-center gap-1">
- {hasAutomaticBranching ? (
- <CheckCircle2 size={12} className="text-brand-600" />
- ) : (
- <AlertCircle size={12} className="text-warning-600" />
- )}
- <span>
- {hasAutomaticBranching
- ? 'Automatically creating branches'
- : 'Automatic branching disabled'}
- </span>
- </div>
- </>
+ {isConnected ? (
+ <div className="flex flex-col gap-2 text-xs text-foreground-light">
+ <div className="flex items-center gap-2">
+ {hasGitBranchSync ? (
+ <CheckCircle2 size={12} className="text-brand-600" />
+ ) : (
+ <AlertCircle size={12} className="text-warning-600" />
+ )}
+ <span>
+ {hasGitBranchSync
+ ? `Syncing production (${mainBranch?.git_branch})`
+ : 'Production sync disabled'}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {hasAutomaticBranching ? (
+ <CheckCircle2 size={12} className="text-brand-600" />
) : (
- <span>Not connected to any repository</span>
+ <AlertCircle size={12} className="text-warning-600" />
)}
+ <span>
+ {hasAutomaticBranching
+ ? 'Automatically creating branches'
+ : 'Automatic branching disabled'}
+ </span>
</div>
</div>
- </div>
-
- <Button asChild type="default" icon={<Settings size={14} />}>
- <Link href={`/project/${projectRef}/settings/integrations`}>Configure</Link>
- </Button>
- </CardContent>
- </Card>
+ ) : (
+ <p className="text-xs text-foreground-light">Not connected to any repository</p>
+ )}
+ </HoverCardContent>
+ </HoverCard>
)
}
diff --git a/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx b/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx
index af8a2f25e6c..21266c321a1 100644
--- a/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx
+++ b/apps/studio/components/layouts/AppLayout/BranchDropdown.tsx
@@ -2,7 +2,6 @@ import {
AlertCircle,
Check,
ChevronsUpDown,
- GitMerge,
ListTree,
MessageCircle,
Plus,
@@ -15,7 +14,6 @@ import { useState } from 'react'
import { useParams } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { Branch, useBranchesQuery } from 'data/branches/branches-query'
-import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { useAppStateSnapshot } from 'state/app-state'
import {
@@ -35,8 +33,6 @@ import {
cn,
} from 'ui'
import { sanitizeRoute } from './ProjectDropdown'
-import { useFlag } from 'hooks/ui/useFlag'
-import { toast } from 'sonner'
const BranchLink = ({
branch,
@@ -78,21 +74,12 @@ const BranchLink = ({
export const BranchDropdown = () => {
const router = useRouter()
const { ref } = useParams()
- const gitlessBranching = useFlag('gitlessBranching')
- const projectDetails = useSelectedProject()
const snap = useAppStateSnapshot()
+ const projectDetails = useSelectedProject()
- const projectRef = projectDetails?.parent_project_ref || ref
+ const [open, setOpen] = useState(false)
- const { mutate: updateBranch, isLoading: isUpdatingBranch } = useBranchUpdateMutation({
- onSuccess: (_, variables) => {
- if (variables.requestReview) {
- router.push(`/project/${ref}/merge`)
- }
- setOpen(false)
- toast.success('Branch marked as ready for review')
- },
- })
+ const projectRef = projectDetails?.parent_project_ref || ref
const {
data: branches,
@@ -122,135 +109,10 @@ export const BranchDropdown = () => {
? [mainBranch].concat(restOfBranches ?? [])
: restOfBranches ?? []
: [defaultMainBranch]
+ const branchList = isBranchingEnabled ? sortedBranches ?? [] : [defaultMainBranch]
const BRANCHING_GITHUB_DISCUSSION_LINK = 'https://github.com/orgs/supabase/discussions/18937'
- const [open, setOpen] = useState(false)
-
- const MenuContent = ({
- branchList,
- showSearch,
- }: {
- branchList: Branch[]
- showSearch?: boolean
- }) => (
- <Command_Shadcn_>
- {showSearch && <CommandInput_Shadcn_ placeholder="Find branch..." />}
- <CommandList_Shadcn_>
- {showSearch && <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>}
-
- <CommandGroup_Shadcn_>
- <ScrollArea className="max-h-[210px] overflow-y-auto">
- {branchList.map((branch) => (
- <BranchLink
- key={branch.id}
- branch={branch}
- isSelected={branch.id === selectedBranch?.id || branches?.length === 0}
- setOpen={setOpen}
- />
- ))}
- </ScrollArea>
- </CommandGroup_Shadcn_>
-
- <CommandSeparator_Shadcn_ />
-
- <CommandGroup_Shadcn_>
- <CommandItem_Shadcn_
- className="cursor-pointer w-full"
- onSelect={() => {
- setOpen(false)
- snap.setShowCreateBranchModal(true)
- }}
- onClick={() => {
- setOpen(false)
- snap.setShowCreateBranchModal(true)
- }}
- >
- <div className="w-full flex items-center gap-2">
- <Plus size={14} strokeWidth={1.5} />
- <p>Create branch</p>
- </div>
- </CommandItem_Shadcn_>
- {gitlessBranching &&
- isBranchingEnabled &&
- selectedBranch &&
- !selectedBranch.is_default && (
- <>
- <CommandItem_Shadcn_
- className="cursor-pointer w-full"
- disabled={isUpdatingBranch}
- onSelect={() => {
- if (selectedBranch?.review_requested_at) {
- router.push(`/project/${ref}/merge`)
- } else {
- if (selectedBranch?.id && projectRef) {
- updateBranch({
- id: selectedBranch.id,
- projectRef,
- requestReview: true,
- })
- }
- }
- }}
- onClick={() => setOpen(false)}
- >
- <div className="w-full flex items-center gap-2">
- <GitMerge size={14} strokeWidth={1.5} />
- {isUpdatingBranch
- ? 'Updating...'
- : selectedBranch?.review_requested_at
- ? 'Review changes'
- : 'Ready for review'}
- </div>
- </CommandItem_Shadcn_>
- </>
- )}
- <CommandItem_Shadcn_
- className="cursor-pointer w-full"
- onSelect={() => {
- setOpen(false)
- router.push(`/project/${ref}/branches`)
- }}
- onClick={() => setOpen(false)}
- >
- <Link href={`/project/${ref}/branches`} className="w-full flex items-center gap-2">
- <ListTree size={14} strokeWidth={1.5} />
- <p>Manage branches</p>
- </Link>
- </CommandItem_Shadcn_>
- </CommandGroup_Shadcn_>
-
- <CommandSeparator_Shadcn_ />
-
- <CommandGroup_Shadcn_>
- <CommandItem_Shadcn_
- className="cursor-pointer w-full"
- onSelect={() => {
- setOpen(false)
- window?.open(BRANCHING_GITHUB_DISCUSSION_LINK, '_blank')?.focus()
- }}
- onClick={() => setOpen(false)}
- >
- <Link
- href={BRANCHING_GITHUB_DISCUSSION_LINK}
- target="_blank"
- onClick={() => {
- setOpen(false)
- }}
- className="w-full flex gap-2"
- >
- <MessageCircle size={14} strokeWidth={1} className="text-muted mt-0.5" />
- <div>
- <p>Branching feedback</p>
- <p className="text-lighter">Join Github Discussion</p>
- </div>
- </Link>
- </CommandItem_Shadcn_>
- </CommandGroup_Shadcn_>
- </CommandList_Shadcn_>
- </Command_Shadcn_>
- )
-
return (
<>
{isLoading && <ShimmeringLoader className="w-[90px]" />}
@@ -288,10 +150,91 @@ export const BranchDropdown = () => {
/>
</PopoverTrigger_Shadcn_>
<PopoverContent_Shadcn_ className="p-0" side="bottom" align="start">
- <MenuContent
- branchList={isBranchingEnabled ? sortedBranches ?? [] : [defaultMainBranch]}
- showSearch={isBranchingEnabled}
- />
+ <Command_Shadcn_>
+ {isBranchingEnabled && <CommandInput_Shadcn_ placeholder="Find branch..." />}
+ <CommandList_Shadcn_>
+ {isBranchingEnabled && (
+ <CommandEmpty_Shadcn_>No branches found</CommandEmpty_Shadcn_>
+ )}
+
+ <CommandGroup_Shadcn_>
+ <ScrollArea className="max-h-[210px] overflow-y-auto">
+ {branchList.map((branch) => (
+ <BranchLink
+ key={branch.id}
+ branch={branch}
+ isSelected={branch.id === selectedBranch?.id || branches?.length === 0}
+ setOpen={setOpen}
+ />
+ ))}
+ </ScrollArea>
+ </CommandGroup_Shadcn_>
+
+ <CommandSeparator_Shadcn_ />
+
+ <CommandGroup_Shadcn_>
+ <CommandItem_Shadcn_
+ className="cursor-pointer w-full"
+ onSelect={() => {
+ setOpen(false)
+ snap.setShowCreateBranchModal(true)
+ }}
+ onClick={() => {
+ setOpen(false)
+ snap.setShowCreateBranchModal(true)
+ }}
+ >
+ <div className="w-full flex items-center gap-2">
+ <Plus size={14} strokeWidth={1.5} />
+ <p>Create branch</p>
+ </div>
+ </CommandItem_Shadcn_>
+ <CommandItem_Shadcn_
+ className="cursor-pointer w-full"
+ onSelect={() => {
+ setOpen(false)
+ router.push(`/project/${ref}/branches`)
+ }}
+ onClick={() => setOpen(false)}
+ >
+ <Link
+ href={`/project/${ref}/branches`}
+ className="w-full flex items-center gap-2"
+ >
+ <ListTree size={14} strokeWidth={1.5} />
+ <p>Manage branches</p>
+ </Link>
+ </CommandItem_Shadcn_>
+ </CommandGroup_Shadcn_>
+
+ <CommandSeparator_Shadcn_ />
+
+ <CommandGroup_Shadcn_>
+ <CommandItem_Shadcn_
+ className="cursor-pointer w-full"
+ onSelect={() => {
+ setOpen(false)
+ window?.open(BRANCHING_GITHUB_DISCUSSION_LINK, '_blank')?.focus()
+ }}
+ onClick={() => setOpen(false)}
+ >
+ <a
+ target="_blank"
+ rel="noreferrer noopener"
+ href={BRANCHING_GITHUB_DISCUSSION_LINK}
+ onClick={() => setOpen(false)}
+ className="w-full flex gap-2"
+ >
+ <MessageCircle size={14} strokeWidth={1} className="text-muted mt-0.5" />
+ <div>
+ <p>Branching feedback</p>
+ <p className="text-lighter">Join Github Discussion</p>
+ </div>
+ </a>
+ </CommandItem_Shadcn_>
+ </CommandGroup_Shadcn_>
+ </CommandList_Shadcn_>
+ </Command_Shadcn_>
</PopoverContent_Shadcn_>
</Popover_Shadcn_>
</>
diff --git a/apps/studio/components/layouts/BranchLayout/BranchLayout.tsx b/apps/studio/components/layouts/BranchLayout/BranchLayout.tsx
new file mode 100644
index 00000000000..9ce4fb7d2f7
--- /dev/null
+++ b/apps/studio/components/layouts/BranchLayout/BranchLayout.tsx
@@ -0,0 +1,40 @@
+import { useRouter } from 'next/router'
+import { PropsWithChildren } from 'react'
+
+import { useParams } from 'common'
+import { GitHubStatus } from 'components/interfaces/Settings/Integrations/GithubIntegration/GitHubStatus'
+import { ProductMenu } from 'components/ui/ProductMenu'
+import { withAuth } from 'hooks/misc/withAuth'
+import ProjectLayout from '../ProjectLayout/ProjectLayout'
+import { generateBranchMenu } from './BranchLayout.utils'
+
+const BranchProductMenu = () => {
+ const router = useRouter()
+ const { ref: projectRef = 'default' } = useParams()
+ const page = router.pathname.split('/')[4] ?? 'branches'
+
+ return (
+ <>
+ <ProductMenu page={page} menu={generateBranchMenu(projectRef)} />
+ <div className="px-6">
+ <h3 className="text-sm font-mono text-foreground-lighter uppercase mb-3">Configure</h3>
+ <GitHubStatus />
+ </div>
+ </>
+ )
+}
+
+const BranchLayout = ({ children }: PropsWithChildren<{}>) => {
+ return (
+ <ProjectLayout
+ title="Branching"
+ product="Branching"
+ productMenu={<BranchProductMenu />}
+ isBlocking={false}
+ >
+ {children}
+ </ProjectLayout>
+ )
+}
+
+export default withAuth(BranchLayout)
diff --git a/apps/studio/components/layouts/BranchLayout/BranchLayout.utils.ts b/apps/studio/components/layouts/BranchLayout/BranchLayout.utils.ts
new file mode 100644
index 00000000000..40785ed8827
--- /dev/null
+++ b/apps/studio/components/layouts/BranchLayout/BranchLayout.utils.ts
@@ -0,0 +1,23 @@
+import type { ProductMenuGroup } from 'components/ui/ProductMenu/ProductMenu.types'
+
+export const generateBranchMenu = (ref: string): ProductMenuGroup[] => {
+ return [
+ {
+ title: 'Manage',
+ items: [
+ {
+ name: 'Branches',
+ key: 'branches',
+ url: `/project/${ref}/branches`,
+ items: [],
+ },
+ {
+ name: 'Merge requests',
+ key: 'merge-requests',
+ url: `/project/${ref}/branches/merge-requests`,
+ items: [],
+ },
+ ],
+ },
+ ]
+}
diff --git a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
index 25991f5b885..fa41c5735f3 100644
--- a/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ProjectLayout.tsx
@@ -86,7 +86,7 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
const [isClient, setIsClient] = useState(false)
const selectedOrganization = useSelectedOrganization()
const selectedProject = useSelectedProject()
- const projectRefForGitHubLinker = selectedProject?.parent_project_ref ?? selectedProject?.ref
+
const {
editorPanel,
mobileMenuOpen,
@@ -108,7 +108,8 @@ const ProjectLayout = forwardRef<HTMLDivElement, PropsWithChildren<ProjectLayout
const showProductMenu = selectedProject
? selectedProject.status === PROJECT_STATUS.ACTIVE_HEALTHY ||
(selectedProject.status === PROJECT_STATUS.COMING_UP &&
- router.pathname.includes('/project/[ref]/settings'))
+ router.pathname.includes('/project/[ref]/settings')) ||
+ router.pathname.includes('/project/[ref]/branches')
: true
const ignorePausedState =
@@ -324,6 +325,7 @@ const ContentWrapper = ({ isLoading, isBlocking = true, children }: ContentWrapp
const state = useDatabaseSelectorStateSnapshot()
const selectedProject = useSelectedProject()
+ const isBranchesPage = router.pathname.includes('/project/[ref]/branches')
const isSettingsPages = router.pathname.includes('/project/[ref]/settings')
const isVaultPage = router.pathname === '/project/[ref]/settings/vault'
const isBackupsPage = router.pathname.includes('/project/[ref]/database/backups')
@@ -387,7 +389,7 @@ const ContentWrapper = ({ isLoading, isBlocking = true, children }: ContentWrapp
return <RestoreFailedState />
}
- if (requiresDbConnection && isProjectBuilding) {
+ if (requiresDbConnection && isProjectBuilding && !isBranchesPage) {
return <BuildingState />
}
diff --git a/apps/studio/pages/project/[ref]/branches.tsx b/apps/studio/pages/project/[ref]/branches.tsx
deleted file mode 100644
index 355bee32e2a..00000000000
--- a/apps/studio/pages/project/[ref]/branches.tsx
+++ /dev/null
@@ -1,16 +0,0 @@
-import BranchManagement from 'components/interfaces/BranchManagement/BranchManagement'
-import { ProjectLayoutWithAuth } from 'components/layouts/ProjectLayout/ProjectLayout'
-import DefaultLayout from 'components/layouts/DefaultLayout'
-import type { NextPageWithLayout } from 'types'
-
-const BranchManagementPage: NextPageWithLayout = () => {
- return <BranchManagement />
-}
-
-BranchManagementPage.getLayout = (page) => (
- <DefaultLayout>
- <ProjectLayoutWithAuth>{page}</ProjectLayoutWithAuth>
- </DefaultLayout>
-)
-
-export default BranchManagementPage
diff --git a/apps/studio/pages/project/[ref]/branches/index.tsx b/apps/studio/pages/project/[ref]/branches/index.tsx
new file mode 100644
index 00000000000..fdff72d9dbc
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/branches/index.tsx
@@ -0,0 +1,232 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { partition } from 'lodash'
+import { MessageCircle } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { useState } from 'react'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import { Overview } from 'components/interfaces/BranchManagement/Overview'
+import BranchLayout from 'components/layouts/BranchLayout/BranchLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
+import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import AlertError from 'components/ui/AlertError'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { DocsButton } from 'components/ui/DocsButton'
+import NoPermission from 'components/ui/NoPermission'
+import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
+import { Branch, useBranchesQuery } from 'data/branches/branches-query'
+import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { useAppStateSnapshot } from 'state/app-state'
+import type { NextPageWithLayout } from 'types'
+import { Button } from 'ui'
+import TextConfirmModal from 'ui-patterns/Dialogs/TextConfirmModal'
+
+const BranchesPage: NextPageWithLayout = () => {
+ const router = useRouter()
+ const { ref } = useParams()
+ const snap = useAppStateSnapshot()
+ const project = useSelectedProject()
+ const selectedOrg = useSelectedOrganization()
+
+ const [selectedBranchToDelete, setSelectedBranchToDelete] = useState<Branch>()
+
+ const hasBranchEnabled = project?.is_branch_enabled
+
+ const isBranch = project?.parent_project_ref !== undefined
+ const projectRef =
+ project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
+
+ const canReadBranches = useCheckPermissions(PermissionAction.READ, 'preview_branches')
+
+ const {
+ data: connections,
+ error: connectionsError,
+ isLoading: isLoadingConnections,
+ isSuccess: isSuccessConnections,
+ isError: isErrorConnections,
+ } = useGitHubConnectionsQuery({
+ organizationId: selectedOrg?.id,
+ })
+
+ const {
+ data: branches,
+ error: branchesError,
+ isLoading: isLoadingBranches,
+ isError: isErrorBranches,
+ isSuccess: isSuccessBranches,
+ } = useBranchesQuery({ projectRef })
+ const [[mainBranch], previewBranchesUnsorted] = partition(branches, (branch) => branch.is_default)
+ const previewBranches = previewBranchesUnsorted.sort((a, b) =>
+ new Date(a.updated_at) < new Date(b.updated_at) ? 1 : -1
+ )
+
+ const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
+ const repo = githubConnection?.repository.name ?? ''
+
+ const isError = isErrorConnections || isErrorBranches
+ const isLoading = isLoadingConnections || isLoadingBranches
+ const isSuccess = isSuccessConnections && isSuccessBranches
+
+ const { mutate: deleteBranch, isLoading: isDeleting } = useBranchDeleteMutation({
+ onSuccess: () => {
+ toast.success('Successfully deleted branch')
+ setSelectedBranchToDelete(undefined)
+ },
+ })
+
+ const generateCreatePullRequestURL = (branch?: string) => {
+ if (githubConnection === undefined) return 'https://github.com'
+
+ return branch !== undefined
+ ? `https://github.com/${githubConnection.repository.name}/compare/${mainBranch?.git_branch}...${branch}`
+ : `https://github.com/${githubConnection.repository.name}/compare`
+ }
+
+ 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 },
+ {
+ onSuccess: () => {
+ if (selectedBranchToDelete.project_ref === ref) {
+ router.push(`/project/${selectedBranchToDelete.parent_project_ref}/branches`)
+ }
+ },
+ }
+ )
+ }
+
+ return (
+ <>
+ <ScaffoldContainer>
+ <ScaffoldSection>
+ <div className="col-span-12">
+ <div className="space-y-4">
+ {!canReadBranches ? (
+ <NoPermission resourceText="view this project's branches" />
+ ) : (
+ <>
+ {isErrorConnections && (
+ <AlertError
+ error={connectionsError}
+ subject="Failed to retrieve GitHub integration connection"
+ />
+ )}
+
+ {isErrorBranches && (
+ <AlertError
+ error={branchesError}
+ subject="Failed to retrieve preview branches"
+ />
+ )}
+
+ {!isError && (
+ <Overview
+ isLoading={isLoading}
+ isSuccess={isSuccess}
+ repo={repo}
+ mainBranch={mainBranch}
+ previewBranches={previewBranches}
+ onSelectCreateBranch={() => snap.setShowCreateBranchModal(true)}
+ onSelectDeleteBranch={setSelectedBranchToDelete}
+ generateCreatePullRequestURL={generateCreatePullRequestURL}
+ showProductionBranch={hasBranchEnabled}
+ />
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
+
+ <TextConfirmModal
+ variant="warning"
+ visible={selectedBranchToDelete !== undefined}
+ onCancel={() => setSelectedBranchToDelete(undefined)}
+ onConfirm={() => onConfirmDeleteBranch()}
+ loading={isDeleting}
+ title="Delete branch"
+ confirmLabel="Delete branch"
+ confirmPlaceholder="Type in name of branch"
+ confirmString={selectedBranchToDelete?.name ?? ''}
+ alert={{ title: 'You cannot recover this branch once deleted' }}
+ text={
+ <>
+ This will delete your database preview branch{' '}
+ <span className="text-bold text-foreground">{selectedBranchToDelete?.name}</span>.
+ </>
+ }
+ />
+ </>
+ )
+}
+
+BranchesPage.getLayout = (page) => {
+ const BranchesPageWrapper = () => {
+ const snap = useAppStateSnapshot()
+ const canCreateBranches = useCheckPermissions(PermissionAction.CREATE, 'preview_branches', {
+ resource: { is_default: false },
+ })
+
+ const primaryActions = (
+ <ButtonTooltip
+ type="primary"
+ disabled={!canCreateBranches}
+ onClick={() => snap.setShowCreateBranchModal(true)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canCreateBranches
+ ? 'You need additional permissions to create branches'
+ : undefined,
+ },
+ }}
+ >
+ Create branch
+ </ButtonTooltip>
+ )
+
+ const secondaryActions = (
+ <div className="flex items-center gap-x-2">
+ <Button asChild type="text" icon={<MessageCircle className="text-muted" strokeWidth={1} />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://github.com/orgs/supabase/discussions/18937"
+ >
+ Branching Feedback
+ </a>
+ </Button>
+ <DocsButton href="https://supabase.com/docs/guides/platform/branching" />
+ </div>
+ )
+
+ return (
+ <PageLayout
+ title="Branches"
+ subtitle="Manage your database preview branches and deployments"
+ primaryActions={primaryActions}
+ secondaryActions={secondaryActions}
+ >
+ {page}
+ </PageLayout>
+ )
+ }
+
+ return (
+ <DefaultLayout>
+ <BranchLayout>
+ <BranchesPageWrapper />
+ </BranchLayout>
+ </DefaultLayout>
+ )
+}
+
+export default BranchesPage
diff --git a/apps/studio/pages/project/[ref]/branches/merge-requests.tsx b/apps/studio/pages/project/[ref]/branches/merge-requests.tsx
new file mode 100644
index 00000000000..7aed9e003b4
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/branches/merge-requests.tsx
@@ -0,0 +1,364 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { partition } from 'lodash'
+import { ArrowRight, GitMerge, MessageCircle, MoreVertical, Shield, X } from 'lucide-react'
+import { useRouter } from 'next/router'
+import { PropsWithChildren } from 'react'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import {
+ BranchManagementSection,
+ BranchRow,
+} from 'components/interfaces/BranchManagement/BranchPanels'
+import { BranchSelector } from 'components/interfaces/BranchManagement/BranchSelector'
+import { PullRequestsEmptyState } from 'components/interfaces/BranchManagement/EmptyStates'
+import BranchLayout from 'components/layouts/BranchLayout/BranchLayout'
+import DefaultLayout from 'components/layouts/DefaultLayout'
+import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
+import AlertError from 'components/ui/AlertError'
+import { DocsButton } from 'components/ui/DocsButton'
+import NoPermission from 'components/ui/NoPermission'
+import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
+import { Branch, useBranchesQuery } from 'data/branches/branches-query'
+import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { useFlag } from 'hooks/ui/useFlag'
+import type { NextPageWithLayout } from 'types'
+import {
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ Tooltip,
+} from 'ui'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
+
+const MergeRequestsPage: NextPageWithLayout = () => {
+ const router = useRouter()
+ const { ref } = useParams()
+ const project = useSelectedProject()
+ const selectedOrg = useSelectedOrganization()
+ const gitlessBranching = useFlag('gitlessBranching')
+
+ const isBranch = project?.parent_project_ref !== undefined
+ const projectRef =
+ project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
+
+ const canReadBranches = useCheckPermissions(PermissionAction.READ, 'preview_branches')
+
+ const {
+ data: connections,
+ error: connectionsError,
+ isError: isErrorConnections,
+ } = useGitHubConnectionsQuery({
+ organizationId: selectedOrg?.id,
+ })
+
+ const {
+ data: branches = [],
+ error: branchesError,
+ isLoading: isLoadingBranches,
+ isError: isErrorBranches,
+ } = useBranchesQuery({ projectRef })
+ const [[mainBranch], previewBranchesUnsorted] = partition(branches, (branch) => branch.is_default)
+ const previewBranches = previewBranchesUnsorted.sort((a, b) =>
+ new Date(a.updated_at) < new Date(b.updated_at) ? 1 : -1
+ )
+
+ const mergeRequestBranches = previewBranches.filter(
+ (branch) =>
+ branch.pr_number !== undefined ||
+ (branch.review_requested_at !== undefined && branch.review_requested_at !== null)
+ )
+
+ const currentBranch = branches?.find((branch) => branch.project_ref === ref)
+ const isCurrentBranchReadyForReview = !!currentBranch?.review_requested_at
+
+ const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
+ const repo = githubConnection?.repository.name ?? ''
+
+ const isError = isErrorConnections || isErrorBranches
+
+ const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
+ onError: () => {
+ toast.error(`Failed to update the branch`)
+ },
+ })
+
+ const handleMarkBranchForReview = (branch: Branch) => {
+ if (branch.id && projectRef) {
+ updateBranch(
+ {
+ id: branch.id,
+ projectRef,
+ requestReview: true,
+ },
+ {
+ onSuccess: () => {
+ toast.success('Merge request created')
+ router.push(`/project/${branch.project_ref}/merge`)
+ },
+ }
+ )
+ }
+ }
+
+ const handleCloseMergeRequest = (branch: Branch) => {
+ if (branch.id && projectRef) {
+ updateBranch(
+ {
+ id: branch.id,
+ projectRef,
+ requestReview: false,
+ },
+ {
+ onSuccess: () => {
+ toast.success('Merge request closed')
+ },
+ }
+ )
+ }
+ }
+
+ const generateCreatePullRequestURL = (branch?: string) => {
+ if (githubConnection === undefined) return 'https://github.com'
+
+ return branch !== undefined
+ ? `https://github.com/${githubConnection.repository.name}/compare/${mainBranch?.git_branch}...${branch}`
+ : `https://github.com/${githubConnection.repository.name}/compare`
+ }
+
+ return (
+ <ScaffoldContainer>
+ <ScaffoldSection>
+ <div className="col-span-12">
+ <div className="space-y-4">
+ {!canReadBranches ? (
+ <NoPermission resourceText="view this project's branches" />
+ ) : (
+ <>
+ {isErrorConnections && (
+ <AlertError
+ error={connectionsError}
+ subject="Failed to retrieve GitHub integration connection"
+ />
+ )}
+
+ {isErrorBranches && (
+ <AlertError error={branchesError} subject="Failed to retrieve preview branches" />
+ )}
+
+ {!isError && (
+ <div className="space-y-4">
+ {gitlessBranching && (
+ <>
+ {isBranch && !isCurrentBranchReadyForReview && currentBranch && (
+ <div className="rounded border rounded-lg bg-background px-6 py-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2 text-sm text-foreground-light">
+ <GitMerge strokeWidth={1.5} size={16} className="text-brand" />
+ <span className="text-foreground">{currentBranch.name}</span>
+ last viewed
+ </div>
+ <Button
+ type="primary"
+ size="tiny"
+ loading={currentBranch && isUpdating}
+ onClick={() =>
+ currentBranch && handleMarkBranchForReview(currentBranch)
+ }
+ >
+ Create merge request
+ </Button>
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ <BranchManagementSection
+ header={`${mergeRequestBranches.length} merge requests`}
+ >
+ {isLoadingBranches && (
+ <div className="p-4">
+ <GenericSkeletonLoader />
+ </div>
+ )}
+ {mergeRequestBranches.length > 0 ? (
+ mergeRequestBranches.map((branch) => {
+ const isPR = branch.pr_number !== undefined
+ const rowLink = isPR
+ ? `https://github.com/${repo}/pull/${branch.pr_number}`
+ : `/project/${branch.project_ref}/merge`
+ return (
+ <BranchRow
+ key={branch.id}
+ label={
+ <div className="flex items-center gap-x-4">
+ {branch.name}
+ <ArrowRight
+ size={14}
+ strokeWidth={1.5}
+ className="text-foreground-lighter"
+ />
+ <div className="flex items-center gap-x-2">
+ {branch.pr_number ? (
+ <p className="text-foreground-lighter">#{branch.pr_number}</p>
+ ) : (
+ <>
+ <Shield
+ size={14}
+ strokeWidth={1.5}
+ className="text-warning"
+ />
+ <p className="text-foreground-lighter">{mainBranch.name}</p>
+ </>
+ )}
+ </div>
+ </div>
+ }
+ repo={repo}
+ branch={branch}
+ rowLink={rowLink}
+ external={isPR}
+ rowActions={
+ !isPR && (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ type="text"
+ icon={<MoreVertical />}
+ className="px-1"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent className="w-56" side="bottom" align="end">
+ <Tooltip>
+ <DropdownMenuItem
+ className="gap-x-2"
+ disabled={isUpdating}
+ onSelect={(e) => {
+ e.stopPropagation()
+ handleCloseMergeRequest(branch)
+ }}
+ >
+ <X size={14} /> Close this merge request
+ </DropdownMenuItem>
+ </Tooltip>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+ }
+ />
+ )
+ })
+ ) : (
+ <PullRequestsEmptyState
+ url={generateCreatePullRequestURL()}
+ gitlessBranching={gitlessBranching}
+ projectRef={projectRef ?? '_'}
+ branches={previewBranches}
+ onBranchSelected={handleMarkBranchForReview}
+ isUpdating={isUpdating}
+ githubConnection={githubConnection}
+ />
+ )}
+ </BranchManagementSection>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
+ )
+}
+
+const MergeRequestsPageWrapper = ({ children }: PropsWithChildren<{}>) => {
+ const router = useRouter()
+ const { ref } = useParams()
+ const project = useSelectedProject()
+ const gitlessBranching = useFlag('gitlessBranching')
+
+ const isBranch = project?.parent_project_ref !== undefined
+ const projectRef =
+ project !== undefined ? (isBranch ? project.parent_project_ref : ref) : undefined
+
+ const { data: branches } = useBranchesQuery({ projectRef })
+ const previewBranches = (branches || []).filter((b) => !b.is_default)
+
+ const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
+ onError: () => {
+ toast.error(`Failed to update the branch`)
+ },
+ })
+
+ const handleMarkBranchForReview = (branch: Branch) => {
+ if (branch.id && projectRef) {
+ updateBranch(
+ {
+ id: branch.id,
+ projectRef,
+ requestReview: true,
+ },
+ {
+ onSuccess: () => {
+ toast.success('Merge request created')
+ router.push(`/project/${branch.project_ref}/merge`)
+ },
+ }
+ )
+ }
+ }
+
+ const primaryActions = gitlessBranching ? (
+ <BranchSelector
+ branches={previewBranches}
+ onBranchSelected={handleMarkBranchForReview}
+ disabled={!projectRef}
+ isUpdating={isUpdating}
+ />
+ ) : null
+
+ const secondaryActions = (
+ <div className="flex items-center gap-x-2">
+ <Button asChild type="text" icon={<MessageCircle className="text-muted" strokeWidth={1} />}>
+ <a
+ target="_blank"
+ rel="noreferrer"
+ href="https://github.com/orgs/supabase/discussions/18937"
+ >
+ Branching Feedback
+ </a>
+ </Button>
+ <DocsButton href="https://supabase.com/docs/guides/platform/branching" />
+ </div>
+ )
+
+ return (
+ <PageLayout
+ title="Merge requests"
+ subtitle="Review and merge changes from one branch into another"
+ primaryActions={primaryActions}
+ secondaryActions={secondaryActions}
+ >
+ {children}
+ </PageLayout>
+ )
+}
+
+MergeRequestsPage.getLayout = (page) => {
+ return (
+ <DefaultLayout>
+ <BranchLayout>
+ <MergeRequestsPageWrapper>{page}</MergeRequestsPageWrapper>
+ </BranchLayout>
+ </DefaultLayout>
+ )
+}
+
+export default MergeRequestsPage
diff --git a/apps/studio/pages/project/[ref]/merge.tsx b/apps/studio/pages/project/[ref]/merge.tsx
index ccd69fe17df..699b5d44024 100644
--- a/apps/studio/pages/project/[ref]/merge.tsx
+++ b/apps/studio/pages/project/[ref]/merge.tsx
@@ -1,61 +1,60 @@
-import { useState, useEffect, useMemo, useCallback } from 'react'
-import { useRouter } from 'next/router'
import dayjs from 'dayjs'
+import {
+ AlertTriangle,
+ ExternalLink,
+ GitBranchIcon,
+ GitMerge,
+ MoreVertical,
+ Shield,
+ X,
+} from 'lucide-react'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useCallback, useEffect, useMemo, useState } from 'react'
+import { toast } from 'sonner'
import { useParams } from 'common'
-import { ProjectLayoutWithAuth } from 'components/layouts/ProjectLayout/ProjectLayout'
+import DatabaseDiffPanel from 'components/interfaces/BranchManagement/DatabaseDiffPanel'
+import EdgeFunctionsDiffPanel from 'components/interfaces/BranchManagement/EdgeFunctionsDiffPanel'
+import { OutOfDateNotice } from 'components/interfaces/BranchManagement/OutOfDateNotice'
+import { ReviewWithAI } from 'components/interfaces/BranchManagement/ReviewWithAI'
+import WorkflowLogsCard from 'components/interfaces/BranchManagement/WorkflowLogsCard'
import DefaultLayout from 'components/layouts/DefaultLayout'
import { PageLayout } from 'components/layouts/PageLayout/PageLayout'
-import { useProjectByRef, useSelectedProject } from 'hooks/misc/useSelectedProject'
-import { useBranchesQuery } from 'data/branches/branches-query'
+import { ProjectLayoutWithAuth } from 'components/layouts/ProjectLayout/ProjectLayout'
+import { ScaffoldContainer } from 'components/layouts/Scaffold'
+import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
import { useBranchMergeMutation } from 'data/branches/branch-merge-mutation'
import { useBranchPushMutation } from 'data/branches/branch-push-mutation'
-import { useBranchDeleteMutation } from 'data/branches/branch-delete-mutation'
import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
+import { useBranchesQuery } from 'data/branches/branches-query'
import { useBranchMergeDiff } from 'hooks/branches/useBranchMergeDiff'
import { useWorkflowManagement } from 'hooks/branches/useWorkflowManagement'
-import DatabaseDiffPanel from 'components/interfaces/BranchManagement/DatabaseDiffPanel'
-import EdgeFunctionsDiffPanel from 'components/interfaces/BranchManagement/EdgeFunctionsDiffPanel'
-import { OutOfDateNotice } from 'components/interfaces/BranchManagement/OutOfDateNotice'
+import { useProjectByRef, useSelectedProject } from 'hooks/misc/useSelectedProject'
+import { useFlag } from 'hooks/ui/useFlag'
+import type { NextPageWithLayout } from 'types'
import {
Badge,
Button,
- NavMenu,
- NavMenuItem,
cn,
- DropdownMenuTrigger,
- DropdownMenuItem,
- DropdownMenuContent,
DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ NavMenu,
+ NavMenuItem,
} from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
-import { toast } from 'sonner'
-import type { NextPageWithLayout } from 'types'
-
-import { ScaffoldContainer } from 'components/layouts/Scaffold'
-import {
- GitBranchIcon,
- GitMerge,
- Shield,
- ExternalLink,
- AlertTriangle,
- X,
- MoreVertical,
-} from 'lucide-react'
-import Link from 'next/link'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
-import WorkflowLogsCard from 'components/interfaces/BranchManagement/WorkflowLogsCard'
-import ProductEmptyState from 'components/to-be-cleaned/ProductEmptyState'
-import { useFlag } from 'hooks/ui/useFlag'
-import { ReviewWithAI } from 'components/interfaces/BranchManagement/ReviewWithAI'
const MergePage: NextPageWithLayout = () => {
const router = useRouter()
const { ref } = useParams()
+ const project = useSelectedProject()
const gitlessBranching = useFlag('gitlessBranching')
- const project = useSelectedProject()
const [isSubmitting, setIsSubmitting] = useState(false)
const [workflowFinalStatus, setWorkflowFinalStatus] = useState<string | null>(null)
const [showConfirmDialog, setShowConfirmDialog] = useState(false)
@@ -103,10 +102,7 @@ const MergePage: NextPageWithLayout = () => {
currentBranchCreatedAt: currentBranch?.created_at,
})
- const { mutate: updateBranch } = useBranchUpdateMutation({
- onSuccess: () => {
- toast.success('Branch updated successfully')
- },
+ const { mutate: updateBranch, isLoading: isUpdating } = useBranchUpdateMutation({
onError: (error) => {
toast.error(`Failed to update branch: ${error.message}`)
},
@@ -116,10 +112,6 @@ const MergePage: NextPageWithLayout = () => {
const currentWorkflowRunId = router.query.workflow_run_id as string | undefined
- useEffect(() => {
- setWorkflowFinalStatus(null)
- }, [currentWorkflowRunId])
-
const handleCurrentBranchWorkflowComplete = useCallback(
(status: string) => {
setWorkflowFinalStatus(status)
@@ -135,11 +127,16 @@ const MergePage: NextPageWithLayout = () => {
refetchDiff()
clearDiffsOptimistically()
if (parentProjectRef && currentBranch?.id && currentBranch.review_requested_at) {
- updateBranch({
- id: currentBranch.id,
- projectRef: parentProjectRef,
- requestReview: false,
- })
+ updateBranch(
+ {
+ id: currentBranch.id,
+ projectRef: parentProjectRef,
+ requestReview: false,
+ },
+ {
+ onSuccess: () => toast.success('Branch updated successfully'),
+ }
+ )
}
},
[
@@ -267,31 +264,23 @@ const MergePage: NextPageWithLayout = () => {
const handleReadyForReview = () => {
if (!currentBranch?.id || !parentProjectRef) return
- updateBranch({
- id: currentBranch.id,
- projectRef: parentProjectRef,
- requestReview: true,
- })
- }
-
- const handleShowConfirmDialog = () => {
- setShowConfirmDialog(true)
- }
-
- const handleConfirmMerge = () => {
- setShowConfirmDialog(false)
- handleMerge()
- }
-
- const handleCancelMerge = () => {
- setShowConfirmDialog(false)
+ updateBranch(
+ {
+ id: currentBranch.id,
+ projectRef: parentProjectRef,
+ requestReview: true,
+ },
+ {
+ onSuccess: () => toast.success('Successfully marked as ready for review'),
+ }
+ )
}
const breadcrumbs = useMemo(
() => [
{
- label: 'Branches',
- href: `/project/${project?.ref}/branches?tab=prs`,
+ label: 'Merge requests',
+ href: `/project/${project?.ref}/branches/merge-requests`,
},
],
[parentProjectRef]
@@ -321,6 +310,10 @@ const MergePage: NextPageWithLayout = () => {
]
}, [currentWorkflowRunId, currentTab])
+ useEffect(() => {
+ setWorkflowFinalStatus(null)
+ }, [currentWorkflowRunId])
+
if (!gitlessBranching) {
return (
<PageLayout>
@@ -387,7 +380,7 @@ const MergePage: NextPageWithLayout = () => {
disabled={!combinedHasChanges || isCombinedDiffLoading}
icon={<Shield size={16} strokeWidth={1.5} className="text-brand" />}
>
- Ready for review
+ Mark as ready for review
</Button>
) : isMergeDisabled ? (
<ButtonTooltip
@@ -403,7 +396,7 @@ const MergePage: NextPageWithLayout = () => {
type="primary"
loading={isMerging || isSubmitting}
disabled={isMergeDisabled}
- onClick={handleShowConfirmDialog}
+ onClick={() => setShowConfirmDialog(true)}
icon={<GitMerge size={16} strokeWidth={1.5} className="text-brand" />}
>
Merge branch
@@ -412,7 +405,7 @@ const MergePage: NextPageWithLayout = () => {
<Button
type="primary"
loading={isMerging || isSubmitting}
- onClick={handleShowConfirmDialog}
+ onClick={() => setShowConfirmDialog(true)}
disabled={isBranchOutOfDateOverall}
icon={<GitMerge size={16} strokeWidth={1.5} className="text-brand" />}
>
@@ -421,22 +414,29 @@ const MergePage: NextPageWithLayout = () => {
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
- <Button type="default" className="px-1.5" icon={<MoreVertical />} />
+ <Button type="default" loading={isUpdating} className="px-1.5" icon={<MoreVertical />} />
</DropdownMenuTrigger>
<DropdownMenuContent side="bottom" align="end" className="w-52">
<DropdownMenuItem
className="gap-x-2"
onClick={() => {
if (!currentBranch?.id || !parentProjectRef) return
- updateBranch({
- id: currentBranch.id,
- projectRef: parentProjectRef,
- requestReview: false,
- })
- router.push(`/project/${project?.ref}/branches?tab=prs`)
+ updateBranch(
+ {
+ id: currentBranch.id,
+ projectRef: parentProjectRef,
+ requestReview: false,
+ },
+ {
+ onSuccess: () => {
+ toast.success('Successfully closed merge request')
+ router.push(`/project/${project?.ref}/branches?tab=prs`)
+ },
+ }
+ )
}}
>
- Not ready for review
+ Close this merge request
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
@@ -594,8 +594,11 @@ const MergePage: NextPageWithLayout = () => {
description={`Are you sure you want to merge "${currentBranch?.name}" into "${mainBranch?.name || 'main'}"? This action cannot be undone.`}
confirmLabel="Merge Branch"
confirmLabelLoading="Merging..."
- onConfirm={handleConfirmMerge}
- onCancel={handleCancelMerge}
+ onConfirm={() => {
+ setShowConfirmDialog(false)
+ handleMerge()
+ }}
+ onCancel={() => setShowConfirmDialog(false)}
loading={isMerging || isSubmitting}
/>
</PageLayout>