import React, { useEffect, useRef, useState } from "react"; import Image from "next/image"; import { useTheme } from "next-themes"; import { Control, Controller, FieldArrayWithId, UseFieldArrayRemove, UseFormGetValues, UseFormSetValue, UseFormWatch, useFieldArray, useForm, } from "react-hook-form"; // icons import { Check, ChevronDown, Plus, XCircle } from "lucide-react"; import { Listbox, Transition } from "@headlessui/react"; // types import { IUser, IWorkspace } from "@plane/types"; // ui import { Button, Input, TOAST_TYPE, setToast } from "@plane/ui"; // constants import { MEMBER_INVITED } from "@/constants/event-tracker"; import { EUserWorkspaceRoles, ROLE, ROLE_DETAILS } from "@/constants/workspace"; // helpers import { getUserRole } from "@/helpers/user.helper"; // hooks import { useEventTracker } from "@/hooks/store"; import useDynamicDropdownPosition from "@/hooks/use-dynamic-dropdown"; // services import { WorkspaceService } from "@/services/workspace.service"; // assets import InviteMembersDark from "public/onboarding/invite-members-dark.svg"; import InviteMembersLight from "public/onboarding/invite-members-light.svg"; // components import { OnboardingHeader } from "./header"; import { SwitchOrDeleteAccountDropdown } from "./switch-or-delete-account-dropdown"; type Props = { finishOnboarding: () => Promise; totalSteps: number; user: IUser | undefined; workspace: IWorkspace | undefined; }; type EmailRole = { email: string; role: EUserWorkspaceRoles; role_active: boolean; }; type FormValues = { emails: EmailRole[]; }; type InviteMemberFormProps = { index: number; remove: UseFieldArrayRemove; control: Control; setValue: UseFormSetValue; getValues: UseFormGetValues; watch: UseFormWatch; field: FieldArrayWithId; fields: FieldArrayWithId[]; errors: any; isInvitationDisabled: boolean; setIsInvitationDisabled: (value: boolean) => void; }; // services const workspaceService = new WorkspaceService(); const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i; const placeholderEmails = [ "charlie.taylor@frstflt.com", "octave.chanute@frstflt.com", "george.spratt@frstflt.com", "frank.coffyn@frstflt.com", "amos.root@frstflt.com", "edward.deeds@frstflt.com", "charles.m.manly@frstflt.com", "glenn.curtiss@frstflt.com", "thomas.selfridge@frstflt.com", "albert.zahm@frstflt.com", ]; const InviteMemberInput: React.FC = (props) => { const { control, index, fields, remove, errors, isInvitationDisabled, setIsInvitationDisabled, setValue, getValues, watch, } = props; const buttonRef = useRef(null); const dropdownRef = useRef(null); const [isDropdownOpen, setIsDropdownOpen] = useState(false); useDynamicDropdownPosition(isDropdownOpen, () => setIsDropdownOpen(false), buttonRef, dropdownRef); const email = watch(`emails.${index}.email`); const emailOnChange = (event: React.ChangeEvent) => { if (event.target.value === "") { const validEmail = fields.map((_, i) => emailRegex.test(getValues(`emails.${i}.email`))).includes(true); if (validEmail) { setIsInvitationDisabled(false); } else { setIsInvitationDisabled(true); } if (getValues(`emails.${index}.role_active`)) { setValue(`emails.${index}.role_active`, false); } } else { if (!getValues(`emails.${index}.role_active`)) { setValue(`emails.${index}.role_active`, true); } if (isInvitationDisabled && emailRegex.test(event.target.value)) { setIsInvitationDisabled(false); } else if (!isInvitationDisabled && !emailRegex.test(event.target.value)) { setIsInvitationDisabled(true); } } }; return (
( { emailOnChange(event); onChange(event); }} ref={ref} hasError={Boolean(errors.emails?.[index]?.email)} placeholder={placeholderEmails[index % placeholderEmails.length]} className="w-full border-onboarding-border-100 text-xs placeholder:text-onboarding-text-400 sm:text-sm" /> )} />
( { onChange(val); setIsDropdownOpen(false); setValue(`emails.${index}.role_active`, true); }} className="w-full flex-shrink-0 text-left" > setIsDropdownOpen((prev) => !prev)} className="flex w-full items-center justify-between gap-1 rounded-md px-2.5 py-2 text-sm border-[0.5px] border-onboarding-border-100" > {ROLE[value]}
{Object.entries(ROLE_DETAILS).map(([key, value]) => ( `cursor-pointer select-none truncate rounded px-1 py-1.5 ${ active || selected ? "bg-onboarding-background-400/40" : "" } ${selected ? "text-onboarding-text-100" : "text-custom-text-200"}` } > {({ selected }) => (
{value.title}
{value.description}
{selected && }
)}
))}
)} />
{fields.length > 1 && ( )}
{email && !emailRegex.test(email) && (
🤥{" "} That doesn{"'"}t look like an email address.
)}
); }; export const InviteMembers: React.FC = (props) => { const { finishOnboarding, totalSteps, workspace } = props; const [isInvitationDisabled, setIsInvitationDisabled] = useState(true); const { resolvedTheme } = useTheme(); // store hooks const { captureEvent } = useEventTracker(); const { control, watch, getValues, setValue, handleSubmit, formState: { isSubmitting, errors, isValid }, } = useForm(); const { fields, append, remove } = useFieldArray({ control, name: "emails", }); const nextStep = async () => { await finishOnboarding(); }; const onSubmit = async (formData: FormValues) => { if (!workspace) return; let payload = { ...formData }; payload = { emails: payload.emails.filter((email) => email.email !== "") }; await workspaceService .inviteWorkspace(workspace.slug, { emails: payload.emails.map((email) => ({ email: email.email, role: email.role, })), }) .then(async () => { captureEvent(MEMBER_INVITED, { emails: [ ...payload.emails.map((email) => ({ email: email.email, role: getUserRole(email.role), })), ], project_id: undefined, state: "SUCCESS", element: "Onboarding", }); setToast({ type: TOAST_TYPE.SUCCESS, title: "Success!", message: "Invitations sent successfully.", }); await nextStep(); }) .catch((err) => { captureEvent(MEMBER_INVITED, { project_id: undefined, state: "FAILED", element: "Onboarding", }); setToast({ type: TOAST_TYPE.ERROR, title: "Error!", message: err?.error, }); }); }; const appendField = () => { append({ email: "", role: 15, role_active: false }); }; useEffect(() => { if (fields.length === 0) { append( [ { email: "", role: 15, role_active: false }, { email: "", role: 15, role_active: false }, { email: "", role: 15, role_active: false }, ], { focusIndex: 0, } ); } }, [fields, append]); return (
{/* Since this will always be the last step */}

Invite your teammates

Work in plane happens best with your team. Invite them now to use Plane to its potential.

{ if (e.code === "Enter") e.preventDefault(); }} >
Email
Role
{fields.map((field, index) => ( setIsInvitationDisabled(value)} control={control} errors={errors} field={field} fields={fields} index={index} remove={remove} key={field.id} /> ))}
Profile setup
); };