import { Flex, FlexBlock, FlexItem, TextControl, Text } from "../wp"; import { closeSmall, plus } from "@wordpress/icons"; import { __, sprintf } from "@wordpress/i18n"; import { useState, type KeyboardEvent } from "react"; import { AdminButton } from "./AdminButton"; interface StringListInputProps { addLabel?: string; help?: string; label: string; onChange: (values: string[]) => void; placeholder?: string; splitPattern?: RegExp; values: string[]; } const normalizeValues = (values: string[]): string[] => { const seen = new Set(); return values .map((value) => value.trim()) .filter(Boolean) .filter((value) => { const key = value.toLowerCase(); if (seen.has(key)) { return false; } seen.add(key); return true; }); }; export const StringListInput = ({ addLabel = __("Add", "market-sync"), help, label, onChange, placeholder, splitPattern, values, }: StringListInputProps) => { const [inputValue, setInputValue] = useState(""); const addValues = () => { const nextValues = splitPattern ? inputValue.split(splitPattern) : [inputValue]; const normalized = normalizeValues([...values, ...nextValues]); if (normalized.length === values.length && inputValue.trim() === "") { return; } onChange(normalized); setInputValue(""); }; const removeValue = (valueToRemove: string) => { onChange(values.filter((value) => value !== valueToRemove)); }; const handleKeyDown = (event: KeyboardEvent) => { if (event.key !== "Enter") { return; } event.preventDefault(); addValues(); }; return ( {help ? ( {help} ) : null} {values.length > 0 ? ( {values.map((value) => ( {value} removeValue(value)} size="small" style={{ minWidth: "24px", height: "24px", padding: 0 }} variant="tertiary" /> ))} ) : null} ); };