import {useState, useRef} from '@wordpress/element'; import {__} from '@wordpress/i18n'; import './TokenInput.scss'; const TokenInput = ( {tokens, onChange, placeholder, className = ''} ) => { const [inputValue, setInputValue] = useState( '' ); const containerRef = useRef( null ); const handleRemoveTag = ( tagToRemove ) => { onChange( tokens.filter( tag => tag !== tagToRemove ) ); }; const handleAddTag = ( newTag ) => { const trimmedTag = newTag.trim(); // Only add the tag if it's empty and doesn't already exist if ( trimmedTag && !tokens.includes( trimmedTag ) ) { onChange( [...tokens, trimmedTag] ); } setInputValue( '' ); // Reset the input field after adding a new tag. }; const handleKeyDown = ( e ) => { if ( e.key === 'Enter' ) { e.preventDefault(); handleAddTag( inputValue ); } }; return (
{tokens.map( tag => ( {tag} ) )} setInputValue( e.target.value )} onKeyDown={handleKeyDown} placeholder={tokens.length === 0 ? placeholder : ''} />
{inputValue && ( )}
); }; export default TokenInput;