All files / shared / components YamlEditor.tsx

84.9% Statements 45/53
64.7% Branches 22/34
91.66% Functions 11/12
90.47% Lines 38/42

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    57x   57x   15x 1x 1x 1x   14x 9x 9x 9x   82x 82x 82x 1x 1x 1x 13x 82x 22x   5x 5x 5x         13x 3x             60x     10x                                    
import { useState, useCallback } from 'react'
import { load } from 'js-yaml'
 
interface YamlEditorProps {
  value: string
  onChange: (val: string) => void
  disabled?: boolean
  'data-testid'?: string
}
 
function validateYaml(raw: string): string | null {
  if (raw.trim() === '') return null
  try {
    load(raw)
    return null
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : String(err)
    return `Invalid YAML: ${message}`
  }
}
 
export function YamlEditor({ value, onChange, disabled = false, 'data-testid': dataTestId }: YamlEditorProps) {
  const [error, setError] = useState<string | null>(() => validateYaml(value))
 
  const handleChange = useCallback(
    (e: React.ChangeEvent<HTMLTextAreaElement>) => {
      const raw = e.target.value
      onChange(raw)
      setError(validateYaml(raw))
    },
    [onChange],
  )
 
  if (disabled) {
    return (
      <div
        data-testid={dataTestId}
        className="font-mono text-sm whitespace-pre-wrap rounded-md border border-input bg-muted/30 px-3 py-2 min-h-[5rem] text-muted-foreground"
      >
        {value || <span className="italic">—</span>}
      </div>
    )
  }
 
  return (
    <div className="flex flex-col gap-1">
      <textarea
        value={value}
        onChange={handleChange}
        disabled={disabled}
        data-testid={dataTestId}
        className="flex min-h-[12rem] w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50"
        spellCheck={false}
      />
      {error && (
        <p className="text-xs text-destructive" data-testid="yaml-error">
          {error}
        </p>
      )}
    </div>
  )
}