All files / src/shared/components AllergiesTagInput.tsx

100% Statements 15/15
100% Branches 13/13
100% Functions 7/7
100% Lines 14/14

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                      65x     6x 6x 3x   6x       44x 4x 4x 40x 1x       65x     31x             2x                       38x                  
import { useState, type KeyboardEvent } from 'react'
 
interface AllergiesTagInputProps {
  id?: string
  value: string[]
  onChange: (value: string[]) => void
  placeholder?: string
  removeLabel: (item: string) => string
}
 
export function AllergiesTagInput({ id, value, onChange, placeholder, removeLabel }: AllergiesTagInputProps) {
  const [draft, setDraft] = useState('')
 
  function commitDraft() {
    const trimmed = draft.trim()
    if (trimmed && !value.includes(trimmed)) {
      onChange([...value, trimmed])
    }
    setDraft('')
  }
 
  function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === 'Enter' || event.key === ',') {
      event.preventDefault()
      commitDraft()
    } else if (event.key === 'Backspace' && draft === '' && value.length > 0) {
      onChange(value.slice(0, -1))
    }
  }
 
  return (
    <div className="focus-within:border-primary focus-within:ring-primary/10 mt-2 flex flex-wrap items-center gap-2 rounded-2xl border border-border bg-muted px-3 py-2 focus-within:bg-card focus-within:ring-4">
      {value.map((item) => (
        <span
          key={item}
          className="bg-primary/10 text-primary inline-flex items-center gap-1 rounded-full px-3 py-1 text-sm font-medium"
        >
          {item}
          <button
            type="button"
            onClick={() => onChange(value.filter((existing) => existing !== item))}
            aria-label={removeLabel(item)}
            className="text-primary/70 hover:text-primary"
          >
            ×
          </button>
        </span>
      ))}
      <input
        id={id}
        type="text"
        value={draft}
        onChange={(event) => setDraft(event.target.value)}
        onKeyDown={handleKeyDown}
        onBlur={commitDraft}
        placeholder={placeholder}
        className="min-w-[120px] flex-1 bg-transparent text-sm outline-none placeholder:text-ink-faint"
      />
    </div>
  )
}