import { useEffect, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { faCheck, faCopy } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider"; import { Button, FormControl, IconButton, Input, Modal, ModalContent, Select, SelectItem } from "@app/components/v2"; import { useToggle } from "@app/hooks"; import { useCreateAPIKey } from "@app/hooks/api"; import { UsePopUpState } from "@app/hooks/usePopUp"; const expirations = [ { label: "1 day", value: "1d" }, { label: "7 days", value: "7d" }, { label: "1 month", value: "1mo" }, { label: "6 months", value: "6mo" }, { label: "12 months", value: "12mo" } ]; const expirationMapping: { [key: string]: number } = { "1d": 86400, "7d": 604800, "1mo": 2592000, "6mo": 15552000, "12mo": 31104000 } const schema = yup.object({ name: yup.string().required("API Key name is required"), expiresIn: yup.string().required("API Key expiration window is required") }).required(); export type FormData = yup.InferType; type Props = { popUp: UsePopUpState<["addAPIKey"]>; handlePopUpToggle: (popUpName: keyof UsePopUpState<["addAPIKey"]>, state?: boolean) => void; }; export const AddAPIKeyModal = ({ popUp, handlePopUpToggle }: Props) => { const [newAPIKey, setNewAPIKey] = useState(""); const [isAPIKeyCopied, setIsAPIKeyCopied] = useToggle(false); const { createNotification } = useNotificationContext(); const { mutateAsync, isLoading } = useCreateAPIKey(); const { control, handleSubmit, reset } = useForm({ resolver: yupResolver(schema) }); useEffect(() => { let timer: NodeJS.Timeout; if (isAPIKeyCopied) { timer = setTimeout(() => setIsAPIKeyCopied.off(), 2000); } return () => clearTimeout(timer); }, [setIsAPIKeyCopied]); const copyTokenToClipboard = () => { navigator.clipboard.writeText(newAPIKey); setIsAPIKeyCopied.on(); }; const onFormSubmit = async ({ name, expiresIn }: FormData) => { try { const { apiKey } = await mutateAsync({ name, expiresIn: expirationMapping[expiresIn] }); setNewAPIKey(apiKey); createNotification({ text: "Successfully created API key", type: "success" }); reset(); } catch (err) { console.error(err); createNotification({ text: "Failed to create API key", type: "error" }); } } const hasAPIKey = Boolean(newAPIKey); return ( { handlePopUpToggle("addAPIKey", isOpen); reset(); setNewAPIKey(""); }} > {!hasAPIKey ? (
( )} /> ( )} />
) : (

{newAPIKey}

Click to copy
)}
); }