import React, { useCallback, useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import toast from 'react-hot-toast'; import { EnvironmentVariable } from 'gql-client'; import { IconButton, Input, Typography } from '@material-tailwind/react'; import { useGQLClient } from 'context/GQLClientContext'; import { DeleteVariableDialog } from 'components/projects/Dialog/DeleteVariableDialog'; const ShowPasswordIcon = ({ handler, isVisible, }: { handler: () => void; isVisible: boolean; }) => { return ( { handler(); }} className="cursor-pointer" > {isVisible ? '-' : '+'} ); }; const EditEnvironmentVariableRow = ({ variable, onUpdate, }: { variable: EnvironmentVariable; onUpdate: () => Promise; }) => { const client = useGQLClient(); const { handleSubmit, register, reset } = useForm({ defaultValues: { key: variable.key, value: variable.value, }, }); const [showPassword, setShowPassword] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [edit, setEdit] = useState(false); const removeEnvironmentVariableHandler = useCallback(async () => { const { removeEnvironmentVariable: isEnvironmentVariableRemoved } = await client.removeEnvironmentVariable(variable.id); if (isEnvironmentVariableRemoved) { await onUpdate(); setDeleteDialogOpen((preVal) => !preVal); toast.success('Variable deleted'); } else { toast.error('Variable not deleted'); } }, [variable, onUpdate]); const updateEnvironmentVariableHandler = useCallback( async (data: { key: string; value: string }) => { const { updateEnvironmentVariable: isEnvironmentVariableUpdated } = await client.updateEnvironmentVariable(variable.id, data); if (isEnvironmentVariableUpdated) { await onUpdate(); toast.success('Variable edited'); setEdit((preVal) => !preVal); } else { toast.error('Variable not edited'); } }, [variable, onUpdate], ); useEffect(() => { reset({ key: variable.key, value: variable.value }); }, [variable]); return ( <>
Key
Value { setShowPassword((prevShowPassword) => !prevShowPassword); }} isVisible={showPassword} /> } {...register(`value`)} />
{edit ? ( <>
{'S'}
{ reset(); setEdit((preVal) => !preVal); }} placeholder={''} > {'C'}
) : ( <>
{ setEdit((preVal) => !preVal); }} placeholder={''} > {'E'}
setDeleteDialogOpen((preVal) => !preVal)} placeholder={''} > {'D'}
)}
setDeleteDialogOpen((preVal) => !preVal)} open={deleteDialogOpen} handleConfirm={removeEnvironmentVariableHandler} variableKey={variable.key} /> ); }; export default EditEnvironmentVariableRow;