import { zodResolver } from "@hookform/resolvers/zod"; import { t } from "@lingui/core/macro"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { useEffect, useState } from "react"; import { useForm } from "react-hook-form"; import { HiInformationCircle, HiMiniCheck, HiOutlineDocumentDuplicate, HiXMark, } from "react-icons/hi2"; import { z } from "zod"; import { authClient } from "@kan/auth/client"; import Button from "~/components/Button"; import Input from "~/components/Input"; import { useClipboard } from "~/hooks/useClipboard"; import { useModal } from "~/providers/modal"; const newApiKeySchema = z.object({ name: z .string() .min(1, { message: t`API key name is required` }) .max(30, { message: t`API key name cannot exceed 30 characters` }), }); export default function NewApiKeyModal() { const { closeModal } = useModal(); const { copied, copy } = useClipboard({ timeout: 2000 }); const [createdApiKey, setCreatedApiKey] = useState<{ key: string; name: string; } | null>(null); const { register, handleSubmit, reset, formState: { errors }, } = useForm>({ resolver: zodResolver(newApiKeySchema), defaultValues: { name: "", }, }); const qc = useQueryClient(); const createApiKeyMutation = useMutation({ mutationFn: ({ name }: { name: string }) => authClient.apiKey.create({ name, prefix: "kan_" }), onSuccess: ({ data: apiKey }) => { void qc.invalidateQueries({ queryKey: ["apiKeys"], }); if (apiKey && apiKey.key && apiKey.name) { setCreatedApiKey({ key: apiKey.key, name: apiKey.name, }); } }, onError: () => { // Handle error if needed }, }); const onSubmit = (data: z.infer) => { createApiKeyMutation.mutate({ name: data.name }); }; useEffect(() => { // Reset state and form when modal opens setCreatedApiKey(null); reset(); }, [reset]); useEffect(() => { if (!createdApiKey) { const nameElement = document.querySelector("#name"); if (nameElement) nameElement.focus(); } }, [createdApiKey]); if (createdApiKey) { return (

{t`API key created`}

{t`This API key will only be shown once. Please save it in a secure location.`}

); } return (

{t`New API key`}

{ if (e.key === "Enter") { e.preventDefault(); await handleSubmit(onSubmit)(); } }} />
); }