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"; import { Listbox, Transition } from "@headlessui/react"; // icons import { Check, ChevronDown, Plus, XCircle } from "lucide-react"; // ui import { Button, Input, TOAST_TYPE, setToast } from "@plane/ui"; // components import { OnboardingStepIndicator } from "components/onboarding/step-indicator"; // constants import { MEMBER_INVITED } from "constants/event-tracker"; import { EUserWorkspaceRoles, ROLE } from "constants/workspace"; // helpers import { getUserRole } from "helpers/user.helper"; // hooks import { useEventTracker } from "hooks/store"; import useDynamicDropdownPosition from "hooks/use-dynamic-dropdown"; // assets import userDark from "public/onboarding/user-dark.svg"; import userLight from "public/onboarding/user-light.svg"; import user1 from "public/users/user-1.png"; import user2 from "public/users/user-2.png"; // services import { WorkspaceService } from "services/workspace.service"; // types import { IUser, IWorkspace, TOnboardingSteps } from "@plane/types"; type Props = { finishOnboarding: () => Promise; stepChange: (steps: Partial) => Promise; 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 InviteMemberForm: 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="h-12 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 h-11 w-full items-center justify-between gap-1 rounded-md px-2.5 py-2 text-xs duration-300" > {ROLE[value]}
{Object.entries(ROLE).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}
{selected && }
)}
))}
)} />
{fields.length > 1 && ( )}
{email && !emailRegex.test(email) && (
🤥{" "} That doesn{"'"}t look like an email address.
)}
); }; export const InviteMembers: React.FC = (props) => { const { finishOnboarding, stepChange, 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 () => { const payload: Partial = { workspace_invite: true, }; await stepChange(payload); 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 (