import { useState, type KeyboardEvent } from 'react'; import { Controller, useFormContext } from 'react-hook-form'; import { FieldError } from './FieldError'; type Props = { name: string; label: string; hint?: string; placeholder?: string; }; export function ChipsField({ name, label, hint, placeholder = 'Ajouter puis Entrée…' }: Props) { const { control } = useFormContext(); const [draft, setDraft] = useState(''); return ( { const items: string[] = Array.isArray(field.value) ? field.value : []; const add = () => { const value = draft.trim(); if (!value) return; if (items.includes(value)) { setDraft(''); return; } field.onChange([...items, value]); setDraft(''); }; const remove = (idx: number) => { field.onChange(items.filter((_, i) => i !== idx)); }; const onKey = (e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ',') { e.preventDefault(); add(); } else if (e.key === 'Backspace' && draft === '' && items.length > 0) { field.onChange(items.slice(0, -1)); } }; return (
{label} {hint && ( {hint} )}
{items.map((item, idx) => ( remove(idx)} title="Cliquer pour retirer" > {item} × ))}
setDraft(e.target.value)} onKeyDown={onKey} placeholder={placeholder} className="flex-1 bg-[color:var(--color-surface-2)] border border-[color:var(--color-border)] focus:border-[color:var(--color-cyan)] focus:outline-none p-2 rounded text-sm font-mono text-[color:var(--color-text)] transition-colors" />
); }} /> ); }