import { h, Fragment } from 'preact'; import { useRef, useState } from 'preact/hooks'; const KEYS = { ENTER: 'Enter', COMMA: ',', SPACE: ' ', }; // TODO: think about how this may change based on // a different usage. We will most likely want this to be passed in as a prop. const ALLOWED_CHARS_REGEX = /([a-zA-Z0-9@.])/; /** * Component allowing users to add multiple entries for a given input field that get displayed as destructive pills * * @param {Object} props * @param {string} props.placeholder Input placeholder text */ export const MultiInput = ({ placeholder }) => { const inputRef = useRef(null); const [items, setItems] = useState([]); const handleBlur = ({ target: { value } }) => { addItemToList(value); clearSelection(); }; const handleKeyDown = (e) => { switch (e.key) { case KEYS.SPACE: case KEYS.ENTER: case KEYS.COMMA: e.preventDefault(); addItemToList(e.target.value); clearSelection(); break; default: if (!ALLOWED_CHARS_REGEX.test(e.key)) { e.preventDefault(); } } }; const handleDestructiveClick = (clickedItem) => { const newArr = items.filter((item) => item !== clickedItem); setItems(newArr); }; const addItemToList = (value) => { // TODO: we will want to do some validation here based on a prop if (value.trim().length > 0) { setItems([...items, value]); } }; const clearSelection = () => { inputRef.current.value = ''; }; const listItems = items.map((item, index) => (