import React from 'react'; import './styles.css'; import { TInputChips, AllowedKeys } from '../types'; const InputChips = ({ chips, setChips, inputValue, setInputValue, keysToTriggerChipConversion = ['Enter', 'Comma'], validate, disabled = false, placeholder, nextPlaceholder, removeBtnSvg, chipStyles, chipClassName, containerStyles, containerClassName, inputStyle, inputClassName, closeBtnStyle, closeBtnClassName, backspaceToRemoveChip = false, errorMsg, }: TInputChips) => { const inputRef = React.useRef(null); const [isFocused, setIsFocused] = React.useState(false); const handleInputChange = (e: React.ChangeEvent) => { const value = e.target.value; if (keysToTriggerChipConversion.includes('Space')) { setInputValue(value.trim()); } else { setInputValue(value); } }; const handleInputKeyDown = (e: React.KeyboardEvent) => { if ( backspaceToRemoveChip && e.key === 'Backspace' && inputValue.trim() === '' && chips.length > 0 ) { e.preventDefault(); const updatedChips = [...chips]; updatedChips.pop(); setChips(updatedChips); return; } if (e.key === 'ArrowLeft' && inputValue.trim() === '' && chips.length > 0) { // Logic to select last chip could be added here, but for now we are just cleaning up } const isKeyAllowed = (key: string): key is AllowedKeys => { return (keysToTriggerChipConversion as AllowedKeys[]).includes( key as AllowedKeys ); }; if (isKeyAllowed(e.code) && (!validate || validate())) { let chip = inputValue.trim(); if (keysToTriggerChipConversion.some((key) => key.length === 1)) { const regex = React.useMemo(() => { return new RegExp( `[${keysToTriggerChipConversion .filter((key) => key.length === 1) .map((key) => key.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&') ) .join('')}]`, 'g' ); }, [keysToTriggerChipConversion]); chip = chip.replace(regex, ''); } if (chip) { setChips([...chips, chip]); setInputValue(''); } e.preventDefault(); } }; const removeChip = ( e: React.MouseEvent, chipToRemove: string ) => { e.preventDefault(); const filteredChips = chips.filter( (chip, index) => chip + index !== chipToRemove ); setChips(filteredChips); }; return ( <>
inputRef.current?.focus()} > {chips.map((chip, index) => (
{chip}
))} setIsFocused(true)} onBlur={() => setIsFocused(false)} />
{errorMsg?.length && (

{errorMsg}

)} ); }; export default InputChips;