Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement AddContactModal #2040

Merged
merged 2 commits into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions apps/web/src/components/AddContactModal/AddContactModal.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { mockImplicitContact } from "@umami/core";
import { getNetworksForContracts } from "@umami/multisig";
import { type UmamiStore, contactsActions, makeStore, mockToast } from "@umami/state";
import { mockContractAddress, mockImplicitAddress } from "@umami/tezos";

import { AddContactModal } from "./AddContactModal";
import { act, renderInModal, screen, userEvent, waitFor } from "../../testUtils";

jest.mock("@umami/multisig", () => ({
...jest.requireActual("@umami/multisig"),
getNetworksForContracts: jest.fn(),
}));

const contact1 = mockImplicitContact(1);
const contact2 = mockImplicitContact(2);

let store: UmamiStore;

beforeEach(() => {
store = makeStore();
});

describe("<AddContactModal />", () => {
const contractPkh = mockContractAddress(0).pkh;

it("has pre-filled address field", async () => {
await renderInModal(<AddContactModal pkh={mockImplicitAddress(0).pkh} />, store);

expect(screen.getByLabelText("Address")).toHaveValue(mockImplicitAddress(0).pkh);
});

it("validates initial address field", async () => {
const user = userEvent.setup();
await renderInModal(<AddContactModal pkh="invalid pkh" />, store);

await act(() => user.click(screen.getByLabelText("Address")));
// click outside of address input to trigger blur event
await act(() => user.click(screen.getByTestId("confirmation-button")));

await waitFor(() =>
expect(screen.getByTestId("address-error")).toHaveTextContent("Invalid address")
);
});

it("adds contact to address book with pre-filled address", async () => {
const user = userEvent.setup();
store.dispatch(contactsActions.upsert(contact2));
await renderInModal(<AddContactModal pkh={contact1.pkh} />, store);

// Set name
const nameInput = screen.getByLabelText("Name");
await act(() => user.clear(nameInput));
await act(() => user.type(nameInput, "Test Contact"));
// Submit
await act(() => user.click(screen.getByTestId("confirmation-button")));

await waitFor(() =>
expect(store.getState().contacts).toEqual({
[contact2.pkh]: contact2,
[contact1.pkh]: {
name: "Test Contact",
pkh: contact1.pkh,
},
})
);
});

it("fetches network for contract addresses", async () => {
jest.mocked(getNetworksForContracts).mockResolvedValue(new Map([[contractPkh, "ghostnet"]]));
const user = userEvent.setup();
await renderInModal(<AddContactModal pkh={contractPkh} />, store);

// Set name
const nameInput = screen.getByLabelText("Name");
await act(() => user.clear(nameInput));
await act(() => user.type(nameInput, "Test Contact"));
// Submit
await act(() => user.click(screen.getByTestId("confirmation-button")));

await waitFor(() =>
expect(store.getState().contacts).toEqual({
[contractPkh]: {
name: "Test Contact",
pkh: contractPkh,
network: "ghostnet",
},
})
);
});

it("shows error toast on unknown network for contract addresses", async () => {
jest.mocked(getNetworksForContracts).mockResolvedValue(new Map());
const user = userEvent.setup();
await renderInModal(<AddContactModal pkh={contractPkh} />, store);

// Set name
const nameInput = screen.getByLabelText("Name");
await act(() => user.clear(nameInput));
await act(() => user.type(nameInput, "Test Contact"));
// Submit
await act(() => user.click(screen.getByTestId("confirmation-button")));

expect(mockToast).toHaveBeenCalledWith({
description: `Network not found for contract ${contractPkh}`,
status: "error",
isClosable: true,
});
expect(store.getState().contacts).toEqual({});
});
});
131 changes: 131 additions & 0 deletions apps/web/src/components/AddContactModal/AddContactModal.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import {
Button,
FormControl,
FormErrorMessage,
FormLabel,
Heading,
Input,
ModalBody,
ModalContent,
ModalFooter,
ModalHeader,
} from "@chakra-ui/react";
import { useDynamicModalContext } from "@umami/components";
import { type Contact } from "@umami/core";
import { getNetworksForContracts } from "@umami/multisig";
import {
contactsActions,
useAppDispatch,
useAsyncActionHandler,
useAvailableNetworks,
useValidateName,
useValidateNewContactPkh,
} from "@umami/state";
import { isValidContractPkh } from "@umami/tezos";
import { type FC } from "react";
import { useForm } from "react-hook-form";

import { ModalCloseButton } from "../CloseButton";

export const AddContactModal: FC<{
pkh: string;
}> = ({ pkh }) => {
const { handleAsyncAction } = useAsyncActionHandler();
const dispatch = useAppDispatch();
const { onClose } = useDynamicModalContext();
const availableNetworks = useAvailableNetworks();

const onSubmitContact = async (newContact: Contact) => {
if (isValidContractPkh(newContact.pkh)) {
await handleAsyncAction(async () => {
const contractsWithNetworks = await getNetworksForContracts(availableNetworks, [
newContact.pkh,
]);
if (!contractsWithNetworks.has(newContact.pkh)) {
throw new Error(`Network not found for contract ${newContact.pkh}`);
}
dispatch(
contactsActions.upsert({
...newContact,
network: contractsWithNetworks.get(newContact.pkh),
})
);
});
} else {
dispatch(contactsActions.upsert({ ...newContact, network: undefined }));
}
onClose();
reset();
};

const {
handleSubmit,
formState: { isValid, errors },
register,
reset,
} = useForm<Contact>({
mode: "onBlur",
defaultValues: { pkh },
});

const onSubmit = ({ name, pkh }: Contact) => {
void onSubmitContact({ name: name.trim(), pkh });
};

const validatePkh = useValidateNewContactPkh();
const validateName = useValidateName();

return (
<ModalContent>
<form onSubmit={handleSubmit(onSubmit)}>
<ModalHeader>
<Heading size="xl">Add Contact</Heading>
<ModalCloseButton />
</ModalHeader>
<ModalBody gap="24px">
<FormControl isInvalid={!!errors.name}>
<FormLabel>Name</FormLabel>
<Input
type="text"
{...register("name", {
required: "Name is required",
validate: validateName,
})}
placeholder="Enter contact's name"
/>
{errors.name && (
<FormErrorMessage data-testid="name-error">{errors.name.message}</FormErrorMessage>
)}
</FormControl>
<FormControl isInvalid={!!errors.pkh}>
<FormLabel>Address</FormLabel>
<Input
type="text"
{...register("pkh", {
required: "Address is required",
validate: validatePkh,
})}
placeholder="Enter contact's tz address"
/>
{errors.pkh && (
<FormErrorMessage data-testid="address-error">{errors.pkh.message}</FormErrorMessage>
)}
</FormControl>
</ModalBody>
<ModalFooter>
<Button
width="100%"
fontWeight="600"
data-testid="confirmation-button"
isDisabled={!isValid}
size="lg"
type="submit"
variant="primary"
>
Add to Address Book
</Button>
</ModalFooter>
</form>
</ModalContent>
);
};
1 change: 1 addition & 0 deletions apps/web/src/components/AddContactModal/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./AddContactModal";
5 changes: 3 additions & 2 deletions apps/web/src/components/AddressPill/RightIcon.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { Icon, type IconProps, ModalContent } from "@chakra-ui/react";
import { Icon, type IconProps } from "@chakra-ui/react";
import { type AddressKind, KNOWN_ADDRESS_TYPES, useDynamicModalContext } from "@umami/components";
import { useAddressExistsInContacts } from "@umami/state";
import { memo } from "react";

import { AddContactIcon } from "../../assets/icons";
import { AddContactModal } from "../AddContactModal";

export const RightIcon = memo(
({ addressKind: { type, pkh }, ...rest }: { addressKind: AddressKind } & IconProps) => {
Expand All @@ -18,7 +19,7 @@ export const RightIcon = memo(
<Icon
as={AddContactIcon}
data-testid="add-contact-icon"
onClick={() => openWith(<ModalContent>NOT IMPLEMENTED</ModalContent>)} // TODO: add
onClick={() => openWith(<AddContactModal pkh={pkh} />)}
{...rest}
/>
);
Expand Down
Loading