All files / features / repositories RepositoryFormPage.tsx

0% Statements 0/43
0% Branches 0/52
0% Functions 0/14
0% Lines 0/40

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186                                                                                                                                                                                                                                                                                                                                                                                   
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Loader2 } from 'lucide-react'
import { useRepository, useCreateRepository, useUpdateRepository, useDeleteRepository } from './repositoriesApi'
import { Button } from '@/components/ui/button'
import { Card, CardContent } from '@/components/ui/card'
import { Breadcrumb } from '@/shared/components/Breadcrumb'
import { ConfirmDialog } from '@/shared/components/ConfirmDialog'
 
export function RepositoryFormPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const isEdit = !!id
  const { data: repo } = useRepository(id ?? '')
  const updateRepository = useUpdateRepository(id ?? '')
  const createRepository = useCreateRepository()
  const deleteRepository = useDeleteRepository()
 
  const [name, setName] = useState('')
  const [url, setUrl] = useState('')
  const [description, setDescription] = useState('')
  const [authToken, setAuthToken] = useState('')
  const [showDelete, setShowDelete] = useState(false)
 
  useEffect(() => {
    if (repo) {
      setName(repo.name)
      setUrl(repo.url)
      setDescription(repo.description ?? '')
      setAuthToken(repo.auth_token_encrypted ?? '')
    }
  }, [repo])
 
  const gitUrlPattern = /^[a-zA-Z0-9]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}:[a-zA-Z0-9._/-]+\.git$|^https?:\/\/[a-zA-Z0-9.-]+\/[a-zA-Z0-9._/-]+\.git$|^git@[a-zA-Z0-9.-]+:[a-zA-Z0-9._/-]+$/
 
  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!name || !url) return
    if (!gitUrlPattern.test(url)) return
 
    const payload = {
      name,
      url,
      description: description || null,
      auth_token_encrypted: authToken || null,
    }
 
    if (isEdit) {
      updateRepository.mutate(payload, {
        onSuccess: () => navigate('/repositories', { replace: true }),
      })
    } else {
      createRepository.mutate(payload, {
        onSuccess: () => navigate('/repositories', { replace: true }),
      })
    }
  }
 
  return (
    <div className="mx-auto max-w-lg">
      <Breadcrumb items={
        isEdit
          ? [
              { label: 'Dashboard', href: '/' },
              { label: 'Repositories', href: '/repositories' },
              { label: repo?.name ?? '...', href: `/repositories/${id}` },
              { label: 'Edit' },
            ]
          : [
              { label: 'Dashboard', href: '/' },
              { label: 'Repositories', href: '/repositories' },
              { label: 'New Repository' },
            ]
      } />
 
      <h1 className="mb-6 text-2xl font-bold">
        {isEdit ? 'Edit Repository' : 'New Repository'}
      </h1>
 
      <Card>
        <CardContent className="p-4">
          <form onSubmit={handleSubmit} className="flex flex-col gap-4">
            <label className="flex flex-col gap-1 text-sm font-medium">
              Name *
              <input
                className="rounded-md border border-input bg-background px-3 py-2"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="org/myapp"
                required
              />
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Git URL *
              <input
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={url}
                onChange={(e) => setUrl(e.target.value)}
                placeholder="git@github.com:org/repo.git"
                required
              />
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Description
              <textarea
                className="rounded-md border border-input bg-background px-3 py-2 text-sm"
                value={description}
                onChange={(e) => {
                  if (e.target.value.length <= 500) setDescription(e.target.value)
                }}
                rows={2}
                maxLength={500}
                placeholder="Optional description"
              />
              <p className="text-xs text-muted-foreground">
                {description.length}/500
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Auth Token / PAT
              <input
                type="password"
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={authToken}
                onChange={(e) => setAuthToken(e.target.value)}
                placeholder="Optional personal access token"
              />
              <p className="text-xs text-muted-foreground">
                Create a dedicated bot/user with minimal permissions — read-only is sufficient for most repos. Read+write only if the pipeline needs to push output branches. The same repo can be added twice with different tokens (e.g. read-only for CI, read+write for release). Stored encrypted.
              </p>
            </label>
 
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <Button type="submit" disabled={!name || !url || !gitUrlPattern.test(url) || createRepository.isPending || updateRepository.isPending}>
                  {(createRepository.isPending || updateRepository.isPending) && (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  )}
                  {createRepository.isPending || updateRepository.isPending
                    ? (isEdit ? 'Saving...' : 'Creating...')
                    : (isEdit ? 'Save Changes' : 'Create Repository')
                  }
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => navigate('/repositories')}
                >
                  Cancel
                </Button>
              </div>
              {isEdit && (
                <Button
                  type="button"
                  variant="destructive"
                  onClick={() => setShowDelete(true)}
                >
                  Delete
                </Button>
              )}
            </div>
          </form>
        </CardContent>
      </Card>
 
      <ConfirmDialog
        open={showDelete}
        title="Delete repository"
        message={`Are you sure you want to delete '${repo?.name ?? 'this repository'}'?`}
        onConfirm={() => {
          if (id) {
            deleteRepository.mutate(id, {
              onSuccess: () => navigate('/repositories', { replace: true }),
            })
          }
          setShowDelete(false)
        }}
        onCancel={() => setShowDelete(false)}
      />
    </div>
  )
}