All files / features / runs / components RunForm.tsx

22.05% Statements 15/68
11.62% Branches 5/43
13.63% Functions 3/22
26.31% Lines 15/57

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            69x   69x             69x                                                                                                                                                                                                                                                                                                  
import { useState, forwardRef, useImperativeHandle, useEffect } from 'react'
import { EntitySelect } from '@/shared/components/EntitySelect'
import { KeyValueEditor } from '@/shared/components/KeyValueEditor'
import { useProjects } from '@/features/projects/projectsApi'
import { usePipelines } from '@/features/pipelines/pipelinesApi'
import { useCreateRun } from '@/features/runs/runsApi'
import type { SelectionOption } from '@/shared/components/EntitySelect'
 
export interface CrudFormRef {
  submit: () => Promise<void>
}
 
export interface RunFormProps {
  id?: string
  defaults?: { project_id?: string }
  onSuccess: () => void
  onClose: () => void
  onDirtyChange?: (dirty: boolean) => void
  onPendingChange?: (pending: boolean) => void
}
 
interface FormState {
  project_id: string
  pipeline_id: string
  issue_key: string
  additional_data: Record<string, string>
}

function toSelectionOptions(
  items: Array<{ id: string; name: string }> | undefined,
): SelectionOption[] {
  return (items ?? []).map((item) => ({
    value: item.id,
    label: item.name,
  }))
}

export const RunForm = forwardRef<CrudFormRef, RunFormProps>(function RunForm(
  { id: _id, defaults, onSuccess, onClose: _onClose, onDirtyChange, onPendingChange },
  ref,
) {
  const [form, setForm] = useState<FormState>({
    project_id: defaults?.project_id ?? '',
    pipeline_id: '',
    issue_key: '',
    additional_data: {},
  })
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [submitted, setSubmitted] = useState(false)

  const { data: projectsData, isLoading: projectsLoading } = useProjects()
  const { data: pipelinesData, isLoading: pipelinesLoading } = usePipelines(form.project_id)
 
  const { mutateAsync: createRun, isPending } = useCreateRun()
 
  const isDirty =
    !submitted && (
      form.project_id !== (defaults?.project_id ?? '') ||
      form.pipeline_id !== '' ||
      form.issue_key !== '' ||
      Object.keys(form.additional_data).length > 0
    )

  useEffect(() => { onDirtyChange?.(isDirty) }, [isDirty, onDirtyChange])
  useEffect(() => { onPendingChange?.(isPending) }, [isPending, onPendingChange])
 
  function validate(): Record<string, string> {
    const errs: Record<string, string> = {}
    if (!form.pipeline_id) {
      errs.pipeline_id = 'Pipeline is required'
    }
    return errs
  }
 
  async function handleSubmit() {
    if (isPending) return
    const errs = validate()
    setErrors(errs)
    if (Object.keys(errs).length > 0) return
 
    setSubmitted(true)
    try {
      const sourceMetadata: Record<string, string> = {}
      if (form.issue_key) sourceMetadata.issue_key = form.issue_key
 
      await createRun({
        pipeline_id: form.pipeline_id,
        source_type: 'manual',
        source_metadata: Object.keys(sourceMetadata).length > 0 ? sourceMetadata : null,
      })
      onSuccess()
    } catch {
      setSubmitted(false)
    }
  }
 
  useImperativeHandle(ref, () => ({
    submit: handleSubmit,
  }))
 
  const projectOptions = toSelectionOptions(projectsData?.data)
  const pipelineOptions = toSelectionOptions(pipelinesData?.data)
 
  return (
    <fieldset disabled={isPending} className="flex flex-col gap-4">
      <div className="flex flex-col gap-1">
        <label className="text-sm font-medium">Project</label>
        <EntitySelect
          options={projectOptions}
          value={form.project_id}
          onChange={(val) => {
            setForm((prev) => ({
              ...prev,
              project_id: (val as string) ?? '',
              pipeline_id: '',
            }))
          }}
          placeholder="Select project..."
          isLoading={projectsLoading}
        />
      </div>
      <div className="flex flex-col gap-1">
        <label className="text-sm font-medium">Pipeline</label>
        <EntitySelect
          options={pipelineOptions}
          value={form.pipeline_id}
          onChange={(val) => {
            setForm((prev) => ({ ...prev, pipeline_id: (val as string) ?? '' }))
          }}
          placeholder={
            form.project_id ? 'Select pipeline...' : 'Select a project first...'
          }
          isLoading={pipelinesLoading}
          disabled={!form.project_id}
        />
        {errors.pipeline_id && (
          <p className="text-sm text-destructive">{errors.pipeline_id}</p>
        )}
      </div>
      <label className="flex flex-col gap-1 text-sm font-medium">
        Issue Key
        <input
          className="rounded-md border border-input bg-background px-3 py-2 text-sm"
          value={form.issue_key}
          onChange={(e) =>
            setForm((prev) => ({ ...prev, issue_key: e.target.value }))
          }
          placeholder="e.g. PROJ-123"
        />
      </label>
      <KeyValueEditor
        label="Additional Data"
        value={form.additional_data}
        onChange={(val) =>
          setForm((prev) => ({ ...prev, additional_data: val ?? {} }))
        }
      />
    </fieldset>
  )
})