"use client"; import { Button } from "@unsend/ui/src/button"; import { Input } from "@unsend/ui/src/input"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger, } from "@unsend/ui/src/dialog"; import { api } from "~/trpc/react"; import { useState } from "react"; import { CheckIcon, ClipboardCopy, Eye, EyeOff, Plus } from "lucide-react"; import { toast } from "@unsend/ui/src/toaster"; import { z } from "zod"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, } from "@unsend/ui/src/form"; const apiKeySchema = z.object({ name: z.string({ required_error: "Name is required" }).min(1, { message: "Name is required", }), }); export default function AddApiKey() { const [open, setOpen] = useState(false); const [apiKey, setApiKey] = useState(""); const createApiKeyMutation = api.apiKey.createToken.useMutation(); const [isCopied, setIsCopied] = useState(false); const [showApiKey, setShowApiKey] = useState(false); const utils = api.useUtils(); const apiKeyForm = useForm>({ resolver: zodResolver(apiKeySchema), defaultValues: { name: "", }, }); function handleSave(values: z.infer) { createApiKeyMutation.mutate( { name: values.name, permission: "FULL", }, { onSuccess: (data) => { utils.apiKey.invalidate(); setApiKey(data); apiKeyForm.reset(); }, } ); } function handleCopy() { navigator.clipboard.writeText(apiKey); setIsCopied(true); setTimeout(() => { setIsCopied(false); }, 2000); } function copyAndClose() { handleCopy(); setApiKey(""); setOpen(false); setShowApiKey(false); toast.success("API key copied to clipboard"); } return ( (_open !== open ? setOpen(_open) : null)} > {apiKey ? ( Copy API key
{showApiKey ? (

{apiKey}

) : (
{Array.from({ length: 40 }).map((_, index) => (
))}
)}
) : ( Create a new API key
( API key name {formState.errors.name ? ( ) : ( Use a name to easily identify this API key. )} )} />
)}
); }