import React, { useEffect } from "react"; // swr import { mutate } from "swr"; // react-hook-form import { Controller, useFieldArray, useForm } from "react-hook-form"; // headless import { Dialog, Transition } from "@headlessui/react"; // services import workspaceService from "services/workspace.service"; // hooks import useToast from "hooks/use-toast"; // ui import { CustomSelect, Input, PrimaryButton, SecondaryButton } from "components/ui"; // icons import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; // types import { ICurrentUserResponse } from "types"; // constants import { ROLE } from "constants/workspace"; import { WORKSPACE_INVITATIONS } from "constants/fetch-keys"; type Props = { isOpen: boolean; setIsOpen: React.Dispatch>; workspace_slug: string; user: ICurrentUserResponse | undefined; onSuccess: () => void; }; type EmailRole = { email: string; role: 5 | 10 | 15 | 20; }; type FormValues = { emails: EmailRole[]; }; const defaultValues: FormValues = { emails: [ { email: "", role: 15, }, ], }; const SendWorkspaceInvitationModal: React.FC = (props) => { const { isOpen, setIsOpen, workspace_slug, user, onSuccess } = props; const { control, reset, handleSubmit, formState: { isSubmitting, errors }, } = useForm(); const { fields, append, remove } = useFieldArray({ control, name: "emails", }); const { setToastAlert } = useToast(); const handleClose = () => { setIsOpen(false); const timeout = setTimeout(() => { reset(defaultValues); clearTimeout(timeout); }, 500); }; const onSubmit = async (formData: FormValues) => { if (!workspace_slug) return; const payload = { ...formData }; await workspaceService .inviteWorkspace(workspace_slug, payload, user) .then(async (res) => { setIsOpen(false); handleClose(); setToastAlert({ type: "success", title: "Success!", message: "Invitations sent successfully.", }); onSuccess(); }) .catch((err) => { setToastAlert({ type: "error", title: "Error!", message: `${err.error}`, }); console.log(err); }) .finally(() => { reset(defaultValues); mutate(WORKSPACE_INVITATIONS); }); }; const appendField = () => { append({ email: "", role: 15 }); }; useEffect(() => { if (fields.length === 0) { append([{ email: "", role: 15 }]); } }, [fields, append]); return (
{ if (e.code === "Enter") e.preventDefault(); }} >
Invite people to collaborate

Invite members to work on your workspace.

{fields.map((field, index) => (
( <> {errors.emails?.[index]?.email && ( {errors.emails?.[index]?.email?.message} )} )} />
( {ROLE[value]}} onChange={onChange} width="w-full" input > {Object.entries(ROLE).map(([key, value]) => ( {value} ))} )} />
{fields.length > 1 && ( )}
))}
Cancel {isSubmitting ? "Sending Invitation..." : "Send Invitation"}
); }; export default SendWorkspaceInvitationModal;