|
| 1 | +import { useCallback, useState, type KeyboardEvent } from "react"; |
| 2 | +import { Input } from "~/components/primitives/Input"; |
| 3 | +import { RunTag } from "./RunTag"; |
| 4 | + |
| 5 | +interface TagInputProps { |
| 6 | + id?: string; // used for the hidden input for form submission |
| 7 | + name?: string; // used for the hidden input for form submission |
| 8 | + defaultTags?: string[]; |
| 9 | + placeholder?: string; |
| 10 | + variant?: "small" | "medium"; |
| 11 | + onTagsChange?: (tags: string[]) => void; |
| 12 | +} |
| 13 | + |
| 14 | +export function RunTagInput({ |
| 15 | + id, |
| 16 | + name, |
| 17 | + defaultTags = [], |
| 18 | + placeholder = "Type and press Enter to add tags", |
| 19 | + variant = "small", |
| 20 | + onTagsChange, |
| 21 | +}: TagInputProps) { |
| 22 | + const [tags, setTags] = useState<string[]>(defaultTags); |
| 23 | + const [inputValue, setInputValue] = useState(""); |
| 24 | + |
| 25 | + const addTag = useCallback( |
| 26 | + (tagText: string) => { |
| 27 | + const trimmedTag = tagText.trim(); |
| 28 | + if (trimmedTag && !tags.includes(trimmedTag)) { |
| 29 | + const newTags = [...tags, trimmedTag]; |
| 30 | + setTags(newTags); |
| 31 | + onTagsChange?.(newTags); |
| 32 | + } |
| 33 | + setInputValue(""); |
| 34 | + }, |
| 35 | + [tags, onTagsChange] |
| 36 | + ); |
| 37 | + |
| 38 | + const removeTag = useCallback( |
| 39 | + (tagToRemove: string) => { |
| 40 | + const newTags = tags.filter((tag) => tag !== tagToRemove); |
| 41 | + setTags(newTags); |
| 42 | + onTagsChange?.(newTags); |
| 43 | + }, |
| 44 | + [tags, onTagsChange] |
| 45 | + ); |
| 46 | + |
| 47 | + const handleKeyDown = useCallback( |
| 48 | + (e: KeyboardEvent<HTMLInputElement>) => { |
| 49 | + if (e.key === "Enter") { |
| 50 | + e.preventDefault(); |
| 51 | + addTag(inputValue); |
| 52 | + } else if (e.key === "Backspace" && inputValue === "" && tags.length > 0) { |
| 53 | + removeTag(tags[tags.length - 1]); |
| 54 | + } |
| 55 | + }, |
| 56 | + [inputValue, addTag, removeTag, tags] |
| 57 | + ); |
| 58 | + |
| 59 | + return ( |
| 60 | + <div className="flex flex-col gap-2"> |
| 61 | + <input type="hidden" name={name} id={id} value={tags.join(",")} /> |
| 62 | + |
| 63 | + <Input |
| 64 | + type="text" |
| 65 | + value={inputValue} |
| 66 | + onChange={(e) => setInputValue(e.target.value)} |
| 67 | + onKeyDown={handleKeyDown} |
| 68 | + placeholder={placeholder} |
| 69 | + variant={variant} |
| 70 | + /> |
| 71 | + |
| 72 | + {tags.length > 0 && ( |
| 73 | + <div className="mt-1 flex flex-wrap items-center gap-1 text-xs"> |
| 74 | + {tags.map((tag, i) => ( |
| 75 | + <RunTag key={tag} tag={tag} action={{ type: "delete", onDelete: removeTag }} /> |
| 76 | + ))} |
| 77 | + </div> |
| 78 | + )} |
| 79 | + </div> |
| 80 | + ); |
| 81 | +} |
0 commit comments