All files / features / projects ProjectFormPage.tsx

25.62% Statements 41/160
17.5% Branches 28/160
24.44% Functions 11/45
37.03% Lines 40/108

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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232                37x 1x 37x 37x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x             4x 4x                                                                         4x                                                                                                                                                                                                                                                                                   4x                    
import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Loader2 } from 'lucide-react'
import { useCreateProject, useUpdateProject, useProject, useDeleteProject } from './projectsApi'
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'
 
const namePattern = /^[a-zA-Z0-9][a-zA-Z0-9 ._-]{2,99}$/
 
export function ProjectFormPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const isEdit = !!id
  const { data } = useProject(id ?? '')
  const createProject = useCreateProject()
  const updateProject = useUpdateProject(id ?? '')
  const deleteProject = useDeleteProject()
 
  const [name, setName] = useState('')
  const [repoUrl, setRepoUrl] = useState('')
  const [description, setDescription] = useState('')
  const [deployKeySecret, setDeployKeySecret] = useState('')
  const [repoToken, setRepoToken] = useState('')
  const [showDelete, setShowDelete] = useState(false)
  const [nameError, setNameError] = useState<string | null>(null)
  const [submitted, setSubmitted] = useState(false)
 
  useEffect(() => {
  I  if (data?.project) {
      setName(data.project.name)
      setRepoUrl(data.project.repo_url ?? '')
      setDescription(data.project.description ?? '')
      setDeployKeySecret(data.project.deploy_key_secret ?? '')
      setRepoToken(data.project.repo_token_encrypted ?? '')
    }
  }, [data])
 
  useEffect(() => {
    function handleBeforeUnload(e: BeforeUnloadEvent) {
      const isDirty = name !== (data?.project?.name ?? '')
        || description !== (data?.project?.description ?? '')
      if (isDirty && !submitted) {
        e.preventDefault()
      }
    }
    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => window.removeEventListener('beforeunload', handleBeforeUnload)
  }, [name, description, submitted, data])
 
  function validateName(value: string): string | null {
    if (!value) return 'Name is required'
    if (value.length < 3) return 'Must be at least 3 characters'
    if (value.length > 100) return 'Must be 100 characters or fewer'
    if (!namePattern.test(value)) return 'Must start with alphanumeric and contain only letters, numbers, spaces, dots, hyphens, or underscores'
    return null
  }

  function handleNameChange(value: string) {
    setName(value)
    setNameError(validateName(value))
  }
 
  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    const nameErr = validateName(name)
    setNameError(nameErr)
    if (nameErr) return

    setSubmitted(true)
    const payload = {
      name,
      repo_url: repoUrl,
      description: description || null,
      deploy_key_secret: deployKeySecret || null,
      repo_token_encrypted: repoToken || null,
    }

    if (isEdit) {
      updateProject.mutate(payload, {
        onSuccess: () => navigate(`/projects/${id}`, { replace: true }),
      })
    } else {
      createProject.mutate(payload, {
        onSuccess: (project) => navigate(`/projects/${project.id}`, { replace: true }),
      })
    }
  }
 
  return (
    <div className="mx-auto max-w-lg">
      <Breadcrumb items={
        isEdit
          ? [
              { label: 'Dashboard', href: '/' },
              { label: 'Projects', href: '/projects' },
              { label: data?.project?.name ?? '...', href: `/projects/${id}` },
              { label: 'Edit' },
            ]
          : [
              { label: 'Dashboard', href: '/' },
              { label: 'Projects', href: '/projects' },
              { label: 'New Project' },
            ]
      } />
 
      <h1 className="mb-6 text-2xl font-bold">
        {isEdit ? 'Edit Project' : 'New Project'}
      </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) => handleNameChange(e.target.value)}
                required
              />
              {nameError && (
                <p className="text-xs text-destructive">{nameError}</p>
              )}
            </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={repoUrl}
                onChange={(e) => setRepoUrl(e.target.value)}
                placeholder="git@github.com:org/repo.git"
                required={!isEdit}
              />
            </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={3}
                maxLength={500}
              />
              <p className="text-xs text-muted-foreground">
                {description.length}/500 characters
              </p>
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Deploy Key Secret
              <input
                type="password"
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={deployKeySecret}
                onChange={(e) => setDeployKeySecret(e.target.value)}
                placeholder="Optional deploy key secret"
              />
            </label>
 
            <label className="flex flex-col gap-1 text-sm font-medium">
              Repo Token
              <input
                type="password"
                className="rounded-md border border-input bg-background px-3 py-2 font-mono text-sm"
                value={repoToken}
                onChange={(e) => setRepoToken(e.target.value)}
                placeholder="Optional repository token"
              />
            </label>
 
            <div className="flex items-center justify-between">
              <div className="flex gap-2">
                <Button type="submit" disabled={!name || createProject.isPending || updateProject.isPending}>
                  {(createProject.isPending || updateProject.isPending) && (
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  )}
                  {createProject.isPending || updateProject.isPending
                    ? (isEdit ? 'Saving...' : 'Creating...')
                    : (isEdit ? 'Save Changes' : 'Create Project')
                  }
                </Button>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => {
                    if (isEdit) {
                      navigate(`/projects/${id}`)
                    } else {
                      navigate('/projects')
                    }
                  }}
                >
                  Cancel
                </Button>
              </div>
              {isEdit && (
                <Button
                  type="button"
                  variant="destructive"
                  onClick={() => setShowDelete(true)}
                >
                  Delete
                </Button>
              )}
            </div>
          </form>
        </CardContent>
      </Card>
 
      <ConfirmDialog
        open={showDelete}
        title="Delete project"
        message={`Are you sure you want to delete '${data?.project?.name ?? 'this project'}'? This will also delete all associated pipelines.`}
        onConfirm={() => {
          if (id) {
            deleteProject.mutate(id, { onSuccess: () => navigate('/projects', { replace: true }) })
          }
          setShowDelete(false)
        }}
        onCancel={() => setShowDelete(false)}
      />
 
    </div>
  )
}