EditBranchModal.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. import { zodResolver } from '@hookform/resolvers/zod'
  2. import { useDebounce } from '@uidotdev/usehooks'
  3. import { useParams } from 'common'
  4. import { Check, Github, Loader2 } from 'lucide-react'
  5. import Image from 'next/image'
  6. import { useRouter } from 'next/router'
  7. import { useCallback, useEffect, useState } from 'react'
  8. import { useForm, useWatch } from 'react-hook-form'
  9. import { toast } from 'sonner'
  10. import {
  11. Button,
  12. cn,
  13. Dialog,
  14. DialogContent,
  15. DialogFooter,
  16. DialogHeader,
  17. DialogSection,
  18. DialogSectionSeparator,
  19. DialogTitle,
  20. Form,
  21. FormControl,
  22. FormField,
  23. Input,
  24. Label,
  25. } from 'ui'
  26. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  27. import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'
  28. import * as z from 'zod'
  29. import { AlertError } from '@/components/ui/AlertError'
  30. import { InlineLink } from '@/components/ui/InlineLink'
  31. import { useBranchUpdateMutation } from '@/data/branches/branch-update-mutation'
  32. import { Branch, useBranchesQuery } from '@/data/branches/branches-query'
  33. import { useCheckGithubBranchValidity } from '@/data/integrations/github-branch-check-query'
  34. import { useGitHubConnectionsQuery } from '@/data/integrations/github-connections-query'
  35. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  36. import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
  37. import { BASE_PATH } from '@/lib/constants'
  38. interface EditBranchModalProps {
  39. branch?: Branch
  40. visible: boolean
  41. onClose: () => void
  42. }
  43. export const EditBranchModal = ({ branch, visible, onClose }: EditBranchModalProps) => {
  44. const { ref } = useParams()
  45. const router = useRouter()
  46. const { data: projectDetails } = useSelectedProjectQuery()
  47. const { data: selectedOrg } = useSelectedOrganizationQuery()
  48. const [isGitBranchValid, setIsGitBranchValid] = useState(true)
  49. const isBranch = projectDetails?.parent_project_ref !== undefined
  50. const projectRef =
  51. projectDetails !== undefined ? (isBranch ? projectDetails.parent_project_ref : ref) : undefined
  52. const {
  53. data: connections,
  54. error: connectionsError,
  55. isPending: isLoadingConnections,
  56. isSuccess: isSuccessConnections,
  57. isError: isErrorConnections,
  58. } = useGitHubConnectionsQuery({
  59. organizationId: selectedOrg?.id,
  60. })
  61. const { data: branches } = useBranchesQuery({ projectRef })
  62. const { mutate: checkGithubBranchValidity, isPending: isChecking } = useCheckGithubBranchValidity(
  63. { onError: () => {} }
  64. )
  65. const { mutate: updateBranch, isPending: isUpdating } = useBranchUpdateMutation({
  66. onSuccess: (data) => {
  67. toast.success(`Successfully updated branch "${data.name}"`)
  68. onClose()
  69. },
  70. onError: (error) => {
  71. toast.error(`Failed to update branch: ${error.message}`)
  72. },
  73. })
  74. const githubConnection = connections?.find((connection) => connection.project.ref === projectRef)
  75. const [repoOwner, repoName] = githubConnection?.repository.name.split('/') ?? []
  76. const formId = 'edit-branch-form'
  77. const FormSchema = z.object({
  78. branchName: z
  79. .string()
  80. .min(1, 'Branch name cannot be empty')
  81. .refine(
  82. (val) => /^[a-zA-Z0-9\-_]+$/.test(val),
  83. 'Branch name can only contain alphanumeric characters, hyphens, and underscores.'
  84. )
  85. .refine(
  86. (val) =>
  87. // Allow the current branch name during edit
  88. val === branch?.name || (branches ?? []).every((b) => b.name !== val),
  89. 'A branch with this name already exists'
  90. ),
  91. gitBranchName: z.string().optional(),
  92. })
  93. const form = useForm<z.infer<typeof FormSchema>>({
  94. mode: 'onChange',
  95. reValidateMode: 'onChange',
  96. resolver: zodResolver(FormSchema as any),
  97. defaultValues: { branchName: '', gitBranchName: '' },
  98. })
  99. const gitBranchName = useWatch({ control: form.control, name: 'gitBranchName' })
  100. const debouncedGitBranchName = useDebounce(gitBranchName, 500)
  101. const isFormValid = form.formState.isValid && (!gitBranchName || isGitBranchValid)
  102. const canSubmit = isFormValid && !isUpdating && !isChecking
  103. const openLinkerPanel = () => {
  104. onClose()
  105. if (projectRef) {
  106. router.push(`/project/${projectRef}/settings/integrations`)
  107. }
  108. }
  109. const onSubmit = (data: z.infer<typeof FormSchema>) => {
  110. if (!projectRef) return console.error('Project ref is required')
  111. if (!branch?.project_ref) return console.error('Branch ref is required')
  112. const payload: {
  113. branchRef: string
  114. projectRef: string
  115. branchName: string
  116. gitBranch?: string
  117. } = {
  118. branchRef: branch.project_ref,
  119. projectRef,
  120. branchName: data.branchName,
  121. }
  122. // Only add gitBranch to the payload if it is present and valid
  123. // If gitBranchName is empty or invalid, gitBranch remains undefined in the payload
  124. if (data.gitBranchName && isGitBranchValid) {
  125. payload.gitBranch = data.gitBranchName
  126. }
  127. updateBranch(payload)
  128. }
  129. const validateGitBranchName = useCallback(
  130. (branchName: string) => {
  131. if (!githubConnection)
  132. return console.error(
  133. '[EditBranchModal > validateGitBranchName] GitHub Connection is missing'
  134. )
  135. const repositoryId = githubConnection.repository.id
  136. const requested = branchName
  137. checkGithubBranchValidity(
  138. { repositoryId, branchName },
  139. {
  140. onSuccess: () => {
  141. if (form.getValues('gitBranchName') !== requested) return
  142. // Check if another branch is already linked to this git branch
  143. const existingBranch = (branches ?? []).find(
  144. (b) => b.git_branch === branchName && b.id !== branch?.id
  145. )
  146. if (existingBranch) {
  147. setIsGitBranchValid(false)
  148. form.setError('gitBranchName', {
  149. message: `Branch "${existingBranch.name}" is already linked to git branch "${branchName}"`,
  150. })
  151. return
  152. }
  153. setIsGitBranchValid(true)
  154. form.clearErrors('gitBranchName')
  155. },
  156. onError: (error) => {
  157. if (form.getValues('gitBranchName') !== requested) return
  158. setIsGitBranchValid(false)
  159. form.setError('gitBranchName', {
  160. ...error,
  161. message: `Unable to find branch "${branchName}" in ${repoOwner}/${repoName}`,
  162. })
  163. },
  164. }
  165. )
  166. },
  167. [githubConnection, form, checkGithubBranchValidity, repoOwner, repoName, branches, branch]
  168. )
  169. // Pre-fill form when the modal becomes visible and branch data is available
  170. useEffect(() => {
  171. if (visible && branch) {
  172. form.reset({
  173. branchName: branch.name ?? '',
  174. gitBranchName: branch.git_branch ?? '',
  175. })
  176. }
  177. }, [branch, visible, form])
  178. useEffect(() => {
  179. if (!githubConnection || !debouncedGitBranchName) {
  180. return form.clearErrors('gitBranchName')
  181. }
  182. form.clearErrors('gitBranchName')
  183. validateGitBranchName(debouncedGitBranchName)
  184. }, [debouncedGitBranchName, validateGitBranchName, form, githubConnection])
  185. return (
  186. <Dialog open={visible} onOpenChange={(open) => !open && onClose()}>
  187. <DialogContent size="large" hideClose>
  188. <DialogHeader padding="small">
  189. <DialogTitle>Edit branch "{branch?.name}"</DialogTitle>
  190. </DialogHeader>
  191. <DialogSectionSeparator />
  192. <Form {...form}>
  193. <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
  194. <DialogSection padding="medium" className="space-y-4">
  195. <FormField
  196. control={form.control}
  197. name="branchName"
  198. render={({ field }) => (
  199. <FormItemLayout label="Preview branch name">
  200. <FormControl>
  201. <Input
  202. {...field}
  203. placeholder="e.g. staging, dev-feature-x"
  204. autoComplete="off"
  205. />
  206. </FormControl>
  207. </FormItemLayout>
  208. )}
  209. />
  210. {isLoadingConnections && (
  211. <div className="flex flex-col gap-y-2">
  212. <ShimmeringLoader />
  213. <ShimmeringLoader className="w-1/2" />
  214. </div>
  215. )}
  216. {isErrorConnections && (
  217. <AlertError
  218. error={connectionsError}
  219. subject="Failed to retrieve GitHub connection information"
  220. />
  221. )}
  222. {isSuccessConnections &&
  223. (githubConnection ? (
  224. <FormField
  225. control={form.control}
  226. name="gitBranchName"
  227. render={({ field }) => (
  228. <FormItemLayout
  229. label={
  230. <div className="flex items-center justify-between w-full gap-4">
  231. <span className="flex-1">Sync with Git branch</span>
  232. <div className="flex items-center gap-2 text-sm">
  233. <Image
  234. className={cn('dark:invert')}
  235. src={`${BASE_PATH}/img/icons/github-icon.svg`}
  236. width={16}
  237. height={16}
  238. alt={`GitHub icon`}
  239. />
  240. <InlineLink href={`https://github.com/${repoOwner}/${repoName}`}>
  241. {repoOwner}/{repoName}
  242. </InlineLink>
  243. </div>
  244. </div>
  245. }
  246. labelOptional="Optional"
  247. description="Automatically deploy changes on every commit"
  248. >
  249. <div className="relative">
  250. <FormControl>
  251. <Input
  252. {...field}
  253. placeholder="e.g. main, feat/some-feature"
  254. autoComplete="off"
  255. onChange={(e) => {
  256. field.onChange(e)
  257. setIsGitBranchValid(false)
  258. }}
  259. />
  260. </FormControl>
  261. <div className="absolute top-2.5 right-3 flex items-center gap-2">
  262. {field.value ? (
  263. isChecking ? (
  264. <Loader2 size={14} className="animate-spin" />
  265. ) : isGitBranchValid ? (
  266. <Check size={14} className="text-brand" strokeWidth={2} />
  267. ) : null
  268. ) : null}
  269. </div>
  270. </div>
  271. </FormItemLayout>
  272. )}
  273. />
  274. ) : (
  275. <div className="flex items-center gap-2 justify-between">
  276. <div className="flex flex-col gap-1">
  277. <div className="flex items-center gap-2">
  278. <Label>Sync with a GitHub branch</Label>
  279. </div>
  280. <p className="text-sm text-foreground-light">
  281. Optionally connect to a GitHub repository to manage migrations automatically
  282. for this branch.
  283. </p>
  284. </div>
  285. <Button type="default" icon={<Github />} onClick={openLinkerPanel}>
  286. Connect to GitHub
  287. </Button>
  288. </div>
  289. ))}
  290. </DialogSection>
  291. <DialogFooter padding="medium">
  292. <Button disabled={isUpdating} type="default" onClick={onClose}>
  293. Cancel
  294. </Button>
  295. <Button
  296. form={formId}
  297. disabled={
  298. (!!gitBranchName && !isSuccessConnections) ||
  299. isUpdating ||
  300. !canSubmit ||
  301. isChecking
  302. }
  303. loading={isUpdating}
  304. type="primary"
  305. htmlType="submit"
  306. >
  307. Update branch
  308. </Button>
  309. </DialogFooter>
  310. </form>
  311. </Form>
  312. </DialogContent>
  313. </Dialog>
  314. )
  315. }