import React, { useState } from "react"; import { useRouter } from "next/router"; import { mutate } from "swr"; import { Dialog, Transition } from "@headlessui/react"; // services import { TOAST_TYPE, setToast } from "@plane/ui"; import { CreateApiTokenForm, GeneratedTokenDetails } from "components/api-token"; import { API_TOKENS_LIST } from "constants/fetch-keys"; import { renderFormattedDate } from "helpers/date-time.helper"; import { csvDownload } from "helpers/download.helper"; import { APITokenService } from "services/api_token.service"; // ui // components // helpers // types import { IApiToken } from "@plane/types"; // fetch-keys type Props = { isOpen: boolean; onClose: () => void; }; // services const apiTokenService = new APITokenService(); export const CreateApiTokenModal: React.FC = (props) => { const { isOpen, onClose } = props; // states const [neverExpires, setNeverExpires] = useState(false); const [generatedToken, setGeneratedToken] = useState(null); // router const router = useRouter(); const { workspaceSlug } = router.query; const handleClose = () => { onClose(); setTimeout(() => { setNeverExpires(false); setGeneratedToken(null); }, 350); }; const downloadSecretKey = (data: IApiToken) => { const csvData = { Title: data.label, Description: data.description, Expiry: data.expired_at ? renderFormattedDate(data.expired_at)?.replace(",", " ") ?? "" : "Never expires", "Secret key": data.token ?? "", }; csvDownload(csvData, `secret-key-${Date.now()}`); }; const handleCreateToken = async (data: Partial) => { if (!workspaceSlug) return; // make the request to generate the token await apiTokenService .createApiToken(workspaceSlug.toString(), data) .then((res) => { setGeneratedToken(res); downloadSecretKey(res); mutate( API_TOKENS_LIST(workspaceSlug.toString()), (prevData) => { if (!prevData) return; return [res, ...prevData]; }, false ); }) .catch((err) => { setToast({ type: TOAST_TYPE.ERROR, title: "Error", message: err.message, }); throw err; }); }; return ( {}}>
{generatedToken ? ( ) : ( setNeverExpires((prevData) => !prevData)} onSubmit={handleCreateToken} /> )}
); };