"use client"; import { useState, useEffect } from "react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Badge } from "@/components/ui/badge"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Separator } from "@/components/ui/separator"; import { X, Plus, Save, Trash2 } from "lucide-react"; import { Prompt, PromptFormData } from "./types"; interface PromptEditorProps { prompt?: Prompt; onSave: (prompt: PromptFormData) => void; onCancel: () => void; onDelete?: (promptId: string) => void; error?: string | null; } export function PromptEditor({ prompt, onSave, onCancel, onDelete, error, }: PromptEditorProps) { const [formData, setFormData] = useState({ prompt: "", variables: [], }); const [newVariable, setNewVariable] = useState(""); const [variableValues, setVariableValues] = useState>( {} ); useEffect(() => { if (prompt) { setFormData({ prompt: prompt.prompt || "", variables: prompt.variables || [], }); } }, [prompt]); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!formData.prompt.trim()) { return; } onSave(formData); }; const addVariable = () => { if ( newVariable.trim() && !formData.variables.includes(newVariable.trim()) ) { setFormData(prev => ({ ...prev, variables: [...prev.variables, newVariable.trim()], })); setNewVariable(""); } }; const removeVariable = (variableToRemove: string) => { setFormData(prev => ({ ...prev, variables: prev.variables.filter( variable => variable !== variableToRemove ), })); }; const renderPreview = () => { const text = formData.prompt; if (!text) return text; // Split text by variable patterns and process each part const parts = text.split(/(\{\{\s*\w+\s*\}\})/g); return parts.map((part, index) => { const variableMatch = part.match(/\{\{\s*(\w+)\s*\}\}/); if (variableMatch) { const variableName = variableMatch[1]; const isDefined = formData.variables.includes(variableName); const value = variableValues[variableName]; if (!isDefined) { // Variable not in variables list - likely a typo/bug (RED) return ( {part} ); } else if (value && value.trim()) { // Variable defined and has value - show the value (GREEN) return ( {value} ); } else { // Variable defined but empty (YELLOW) return ( {part} ); } } return part; }); }; const updateVariableValue = (variable: string, value: string) => { setVariableValues(prev => ({ ...prev, [variable]: value, })); }; return (
{error && (

{error}

)}
{/* Form Section */}