Files
explore/ui/apiKey/ApiKeyModal/ApiKeyForm.tsx
T
48b39022d3 Account v2 (#2262)
* simple profile button and auth modal layout

* connect email and code screens to API

* add screens to modal for wallet authentication

* migrate to pin input

* user profile menu

* refactor otp field

* fix passing set-cookie from api response

* add wallet info into profile menu

* add mobile menu

* show connected wallet address in button

* my profile page re-design

* custom behaviour of connect button on dapp page

* style pin input

* add logout

* handle case when account is disabled

* handle case when wc is disabled

* remove old components

* refactoring

* workflow to link wallet or email to account

* link wallet from profile

* show better OTP code errors

* add email alert on watchlist and verified addresses pages

* deprecate env and remove old code

* remove code for unverified email page

* add auth guard to address action items

* move useRedirectForInvalidAuthToken hook

* add mixpanel events

* refetch csrf token after login and fix connect wallet from contract page

* Add NEXT_PUBLIC_RE_CAPTCHA_V3_APP_SITE_KEY env

* migrate to reCAPTCHA v3

* resend code and change email from profile page

* better wallet sign-in message error

* fix demo envs

* update some screenshots

* profile button design fixes

* fix behaviour "connect wallet" button on contract page

* fix linking email and wallet to existing account

* bug fixes

* restore the login page

* update screenshots

* tests for auth modal and user profile

* add name field to profile page and write some tests

* [skip ci] clean up and more tests

* update texts

* change text once more

* fix verified email checkmark behaviour

* pass api error to the toast while signing in with wallet

* [skip ci] disable email field on profile page

* bug fixes

* update screenshot

* Blockscout account V2

Fixes #2029

* fix texts and button paddings

* Form fields refactoring (#2320)

* text and address fields for watchlist form

* checkbox field component

* refactor private tags form

* refactor api keys and custom abi

* refactor verifiy address and token info forms (pt. 1)

* refactor token info forms (pt. 2)

* refactor token info forms (pt. 3)

* refactor public tags form

* refactor contract verification form

* refactor contract audit form

* refactor auth, profile and csv export forms

* renaming and moving

* more refactoring and test fixes

---------

Co-authored-by: aagaev <[email protected]>
2024-10-30 12:56:57 +01:00

133 lines
3.6 KiB
TypeScript

import {
Box,
Button,
} from '@chakra-ui/react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import React, { useCallback } from 'react';
import type { SubmitHandler } from 'react-hook-form';
import { useForm, FormProvider } from 'react-hook-form';
import type { ApiKey, ApiKeys, ApiKeyErrors } from 'types/api/account';
import type { ResourceErrorAccount } from 'lib/api/resources';
import { resourceKey } from 'lib/api/resources';
import useApiFetch from 'lib/api/useApiFetch';
import getErrorMessage from 'lib/getErrorMessage';
import FormFieldText from 'ui/shared/forms/fields/FormFieldText';
type Props = {
data?: ApiKey;
onClose: () => void;
setAlertVisible: (isAlertVisible: boolean) => void;
}
type Inputs = {
token: string;
name: string;
}
const NAME_MAX_LENGTH = 255;
const ApiKeyForm: React.FC<Props> = ({ data, onClose, setAlertVisible }) => {
const formApi = useForm<Inputs>({
mode: 'onTouched',
defaultValues: {
token: data?.api_key || '',
name: data?.name || '',
},
});
const apiFetch = useApiFetch();
const queryClient = useQueryClient();
const updateApiKey = (data: Inputs) => {
const body = { name: data.name };
if (!data.token) {
return apiFetch('api_keys', { fetchParams: { method: 'POST', body } });
}
return apiFetch('api_keys', {
pathParams: { id: data.token },
fetchParams: { method: 'PUT', body },
});
};
const mutation = useMutation({
mutationFn: updateApiKey,
onSuccess: async(data) => {
const response = data as unknown as ApiKey;
queryClient.setQueryData([ resourceKey('api_keys') ], (prevData: ApiKeys | undefined) => {
const isExisting = prevData && prevData.some((item) => item.api_key === response.api_key);
if (isExisting) {
return prevData.map((item) => {
if (item.api_key === response.api_key) {
return response;
}
return item;
});
}
return [ response, ...(prevData || []) ];
});
onClose();
},
onError: (error: ResourceErrorAccount<ApiKeyErrors>) => {
const errorMap = error.payload?.errors;
if (errorMap?.name) {
formApi.setError('name', { type: 'custom', message: getErrorMessage(errorMap, 'name') });
} else if (errorMap?.identity_id) {
formApi.setError('name', { type: 'custom', message: getErrorMessage(errorMap, 'identity_id') });
} else {
setAlertVisible(true);
}
},
});
const onSubmit: SubmitHandler<Inputs> = useCallback(async(data) => {
setAlertVisible(false);
await mutation.mutateAsync(data);
}, [ mutation, setAlertVisible ]);
return (
<FormProvider { ...formApi }>
<form noValidate onSubmit={ formApi.handleSubmit(onSubmit) }>
{ data && (
<FormFieldText<Inputs>
name="token"
placeholder="Auto-generated API key token"
isReadOnly
bgColor="dialog_bg"
mb={ 5 }
/>
) }
<FormFieldText<Inputs>
name="name"
placeholder="Application name for API key (e.g Web3 project)"
isRequired
rules={{
maxLength: NAME_MAX_LENGTH,
}}
bgColor="dialog_bg"
mb={ 8 }
/>
<Box marginTop={ 8 }>
<Button
size="lg"
type="submit"
isDisabled={ !formApi.formState.isDirty }
isLoading={ mutation.isPending }
>
{ data ? 'Save' : 'Generate API key' }
</Button>
</Box>
</form>
</FormProvider>
);
};
export default ApiKeyForm;