import { FC, KeyboardEvent, useEffect, useRef, useState } from 'react'; import { Prompt } from '@/types/prompt'; interface Props { prompt: Prompt; variables: string[]; onSubmit: (updatedVariables: string[]) => void; onClose: () => void; } export const VariableModal: FC = ({ prompt, variables, onSubmit, onClose, }) => { const [updatedVariables, setUpdatedVariables] = useState< { key: string; value: string }[] >( variables .map((variable) => ({ key: variable, value: '' })) .filter( (item, index, array) => array.findIndex((t) => t.key === item.key) === index, ), ); const modalRef = useRef(null); const nameInputRef = useRef(null); const handleChange = (index: number, value: string) => { setUpdatedVariables((prev) => { const updated = [...prev]; updated[index].value = value; return updated; }); }; const handleSubmit = () => { if (updatedVariables.some((variable) => variable.value === '')) { alert('Please fill out all variables'); return; } onSubmit(updatedVariables.map((variable) => variable.value)); onClose(); }; const handleKeyDown = (e: KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(); } else if (e.key === 'Escape') { onClose(); } }; useEffect(() => { const handleOutsideClick = (e: MouseEvent) => { if (modalRef.current && !modalRef.current.contains(e.target as Node)) { onClose(); } }; window.addEventListener('click', handleOutsideClick); return () => { window.removeEventListener('click', handleOutsideClick); }; }, [onClose]); useEffect(() => { if (nameInputRef.current) { nameInputRef.current.focus(); } }, []); return (
{prompt.name}
{prompt.description}
{updatedVariables.map((variable, index) => (
{variable.key}