Skip to content

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

chore(studio): Update GH branch field input for CreateBranchModal to debounce the same behaviour as EditBranchModal (#42059)

Joshen Lim021c5c163481
diff --git a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
index d437e1c7973..50631d6e6b1 100644
--- a/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/CreateBranchModal.tsx
@@ -1,15 +1,16 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
-import { DatabaseZap, DollarSign, GitMerge, Github, Loader2 } from 'lucide-react'
+import { Check, DatabaseZap, 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 { useCallback, useEffect, useState } from 'react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
+import { useDebounce } from '@uidotdev/usehooks'
import { useFlag, useParams } from 'common'
import { useIsBranching2Enabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { BranchingPITRNotice } from 'components/layouts/AppLayout/EnableBranchingButton/BranchingPITRNotice'
@@ -72,6 +73,8 @@ export const CreateBranchModal = () => {
const gitlessBranching = useIsBranching2Enabled()
const allowDataBranching = useFlag('allowDataBranching')
+ const [isGitBranchValid, setIsGitBranchValid] = useState(false)
+
const { can: canCreateBranch } = useAsyncCheckPermissions(
PermissionAction.CREATE,
'preview_branches'
@@ -86,44 +89,26 @@ export const CreateBranchModal = () => {
projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined
const formId = 'create-branch-form'
- const FormSchema = z
- .object({
- branchName: z
- .string()
- .min(1, 'Branch name cannot be empty')
- .refine(
- (val) => /^[a-zA-Z0-9\-_]+$/.test(val),
- 'Branch name can only contain alphanumeric characters, hyphens, and underscores.'
- )
- .refine(
- (val) => (branches ?? []).every((branch) => branch.name !== val),
- 'A branch with this name already exists'
- ),
- gitBranchName: z
- .string()
- .refine(
- (val) => gitlessBranching || !githubConnection || (val && val.length > 0),
- 'Git branch name is required when GitHub is connected'
- ),
- withData: z.boolean().default(false).optional(),
- })
- .superRefine(async (val, ctx) => {
- if (val.gitBranchName && val.gitBranchName.length > 0 && githubConnection?.repository.id) {
- try {
- await checkGithubBranchValidity({
- repositoryId: githubConnection.repository.id,
- branchName: val.gitBranchName,
- })
- // valid – no issues added
- } catch (error) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: `Unable to find branch "${val.gitBranchName}" in ${repoOwner}/${repoName}`,
- path: ['gitBranchName'],
- })
- }
- }
- })
+ const FormSchema = z.object({
+ branchName: z
+ .string()
+ .min(1, 'Branch name cannot be empty')
+ .refine(
+ (val) => /^[a-zA-Z0-9\-_]+$/.test(val),
+ 'Branch name can only contain alphanumeric characters, hyphens, and underscores.'
+ )
+ .refine(
+ (val) => (branches ?? []).every((branch) => branch.name !== val),
+ 'A branch with this name already exists'
+ ),
+ gitBranchName: z
+ .string()
+ .refine(
+ (val) => gitlessBranching || !githubConnection || (val && val.length > 0),
+ 'Git branch name is required when GitHub is connected'
+ ),
+ withData: z.boolean().default(false).optional(),
+ })
const form = useForm<z.infer<typeof FormSchema>>({
mode: 'onSubmit',
@@ -131,7 +116,9 @@ export const CreateBranchModal = () => {
resolver: zodResolver(FormSchema),
defaultValues: { branchName: '', gitBranchName: '', withData: false },
})
- const withData = form.watch('withData')
+
+ const { withData, gitBranchName } = form.watch()
+ const debouncedGitBranchName = useDebounce(gitBranchName, 500)
const {
data: connections,
@@ -178,7 +165,7 @@ export const CreateBranchModal = () => {
const { mutate: sendEvent } = useSendEventMutation()
- const { mutateAsync: checkGithubBranchValidity, isPending: isCheckingGHBranchValidity } =
+ const { mutate: checkGithubBranchValidity, isPending: isCheckingGHBranchValidity } =
useCheckGithubBranchValidity({
onError: () => {},
})
@@ -215,8 +202,10 @@ export const CreateBranchModal = () => {
const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
const prodBranch = branches?.find((branch) => branch.is_default)
const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []
+ const isFormValid = form.formState.isValid && (!gitBranchName || isGitBranchValid)
const isDisabled =
+ !isFormValid ||
!canCreateBranch ||
!isSuccessAddons ||
!isSuccessConnections ||
@@ -226,6 +215,44 @@ export const CreateBranchModal = () => {
isCreatingBranch ||
isCheckingGHBranchValidity
+ const tooltipText = promptPlanUpgrade
+ ? 'Upgrade to unlock branching'
+ : !gitlessBranching && !githubConnection
+ ? 'Set up a GitHub connection first to create branches'
+ : undefined
+
+ const validateGitBranchName = useCallback(
+ (branchName: string) => {
+ if (!githubConnection) {
+ return console.error(
+ '[CreateBranchModal > validateGitBranchName] GitHub Connection is missing'
+ )
+ }
+
+ const repositoryId = githubConnection.repository.id
+
+ checkGithubBranchValidity(
+ { repositoryId, branchName },
+ {
+ onSuccess: () => {
+ if (form.getValues('gitBranchName') !== branchName) return
+ setIsGitBranchValid(true)
+ form.clearErrors('gitBranchName')
+ },
+ onError: (error) => {
+ if (form.getValues('gitBranchName') !== branchName) return
+ setIsGitBranchValid(false)
+ form.setError('gitBranchName', {
+ ...error,
+ message: `Unable to find branch "${branchName}" in ${repoOwner}/${repoName}`,
+ })
+ },
+ }
+ )
+ },
+ [githubConnection, form, checkGithubBranchValidity, repoOwner, repoName]
+ )
+
const onSubmit = (data: z.infer<typeof FormSchema>) => {
if (!projectRef) return console.error('Project ref is required')
createBranch({
@@ -249,12 +276,16 @@ export const CreateBranchModal = () => {
}
}, [form, showCreateBranchModal])
- let tooltipText: string | undefined
- if (promptPlanUpgrade) {
- tooltipText = 'Upgrade to unlock branching'
- } else if (!gitlessBranching && !githubConnection) {
- tooltipText = 'Set up a GitHub connection first to create branches'
- }
+ useEffect(() => {
+ if (!githubConnection || !debouncedGitBranchName) {
+ setIsGitBranchValid(gitlessBranching)
+ form.clearErrors('gitBranchName')
+ return
+ }
+
+ form.clearErrors('gitBranchName')
+ validateGitBranchName(debouncedGitBranchName)
+ }, [debouncedGitBranchName, validateGitBranchName, form, githubConnection, gitlessBranching])
return (
<Dialog open={showCreateBranchModal} onOpenChange={(open) => setShowCreateBranchModal(open)}>
@@ -343,12 +374,20 @@ export const CreateBranchModal = () => {
{...field}
placeholder="e.g. main, feat/some-feature"
autoComplete="off"
+ onChange={(e) => {
+ field.onChange(e)
+ setIsGitBranchValid(false)
+ }}
/>
</FormControl_Shadcn_>
<div className="absolute top-2.5 right-3 flex items-center gap-2">
- {isCheckingGHBranchValidity && (
- <Loader2 size={14} className="animate-spin" />
- )}
+ {field.value ? (
+ isCheckingGHBranchValidity ? (
+ <Loader2 size={14} className="animate-spin" />
+ ) : isGitBranchValid ? (
+ <Check size={14} className="text-brand" strokeWidth={2} />
+ ) : null
+ ) : null}
</div>
</div>
</FormItemLayout>
diff --git a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
index c8116b201ae..bb290791dd6 100644
--- a/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/EditBranchModal.tsx
@@ -1,4 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
+import { useDebounce } from '@uidotdev/usehooks'
import { Check, Github, Loader2 } from 'lucide-react'
import Image from 'next/image'
import { useRouter } from 'next/router'
@@ -8,7 +9,6 @@ import { toast } from 'sonner'
import * as z from 'zod'
import { InlineLink } from '@/components/ui/InlineLink'
-import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import { useIsBranching2Enabled } from 'components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { AlertError } from 'components/ui/AlertError'
diff --git a/apps/studio/components/interfaces/BranchManagement/Overview.tsx b/apps/studio/components/interfaces/BranchManagement/Overview.tsx
index 20f9e947c25..3fa46a5e86d 100644
--- a/apps/studio/components/interfaces/BranchManagement/Overview.tsx
+++ b/apps/studio/components/interfaces/BranchManagement/Overview.tsx
@@ -21,6 +21,7 @@ import { DropdownMenuItemTooltip } from 'components/ui/DropdownMenuItemTooltip'
import { TextConfirmModal } from 'components/ui/TextConfirmModalWrapper'
import { useBranchQuery } from 'data/branches/branch-query'
import { useBranchResetMutation } from 'data/branches/branch-reset-mutation'
+import { useBranchRestoreMutation } from 'data/branches/branch-restore-mutation'
import { useBranchUpdateMutation } from 'data/branches/branch-update-mutation'
import type { Branch } from 'data/branches/branches-query'
import { branchKeys } from 'data/branches/keys'
@@ -33,13 +34,13 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
+ DropdownMenuSeparator,
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'
-import { useBranchRestoreMutation } from 'data/branches/branch-restore-mutation'
interface OverviewProps {
isGithubConnected: boolean
@@ -320,6 +321,34 @@ const PreviewBranchActions = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-56" side="bottom" align="end">
+ {/* 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>
+ )}
+
{!branch.deletion_scheduled_at && (
<DropdownMenuItemTooltip
className="gap-x-2"
@@ -344,6 +373,7 @@ const PreviewBranchActions = ({
<RefreshCw size={14} /> Reset branch
</DropdownMenuItemTooltip>
)}
+
{!branch.deletion_scheduled_at && (
<DropdownMenuItemTooltip
className="gap-x-2"
@@ -380,50 +410,6 @@ const PreviewBranchActions = ({
)}
</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={onDeleteBranch}
- onClick={onDeleteBranch}
- 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 && (
@@ -464,6 +450,25 @@ const PreviewBranchActions = ({
<Clock size={14} /> Restore branch
</DropdownMenuItemTooltip>
)}
+
+ <DropdownMenuSeparator />
+
+ <DropdownMenuItemTooltip
+ className="gap-x-2"
+ disabled={!canDeleteBranches}
+ onSelect={onDeleteBranch}
+ onClick={onDeleteBranch}
+ tooltip={{
+ content: {
+ side: 'left',
+ text: !canDeleteBranches
+ ? 'You need additional permissions to delete branches'
+ : undefined,
+ },
+ }}
+ >
+ <Trash2 size={14} /> Delete branch
+ </DropdownMenuItemTooltip>
</DropdownMenuContent>
</DropdownMenu>