Files
calendar/apps/web/modules/ee/teams/components/MemberInvitationModal.tsx
T
Eunjae LeeGitHubClaude Opus 4.5Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
bf348ee209 refactor: migrate Icon to component icons from @coss/ui/icons (#27458)
* feat: add @coss/ui/icons package and migrate static icon usages

Create a new icon system in @coss/ui/icons that wraps lucide-react icons
with controlled props (size and className only). Migrate 44 component
files from <Icon name="xxx" /> to <XxxIcon /> pattern.

This is Phase 1 of the icon migration, covering only static icon names.
Dynamic icon usages (e.g., name={variable}) are skipped for now.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 2)

Migrated 18 files from <Icon name="xxx" /> to <XxxIcon /> pattern:
- Event meta, insights, shell, user table bulk actions
- Webhooks, blocklist, form-builder, form components

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 3)

Migrated 7 files:
- CancelBooking, AddGuestsDialog, ChargeCardDialog
- ReassignDialog, RescheduleDialog
- Categories, Slider

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 4)

Migrated 6 files:
- Organizations: AboutOrganizationForm, PaymentStatusView, profile
- Workflows: CallDetailsSheet, SkeletonLoaderList, TimeTimeUnitInput

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 5)

Migrated 4 files:
- TwoFactorModalHeader
- App setups: alby, make, btcpayserver

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 6)

- confirmDialog.tsx: clock icon
- ics-feedcalendar/Setup.tsx: trash, plus icons
- hitpay/Setup.tsx: info icon
- paypal/Setup.tsx: circle-alert icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 7)

- webhook-edit-view.tsx: external-link icon
- webhook-new-view.tsx: external-link icon
- UserDropdown.tsx: chevron-down, user, settings, moon, map, circle-help, download, blocks, log-out icons
- TopNav.tsx: settings icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 8)

- EmailInviteForm.tsx: x icon
- InviteOptions.tsx: mail, upload, link icons
- SkeletonLoader.tsx: search, clock, user icons
- Embed.tsx: sun, arrow-left icons
- CalendarSwitch.tsx: arrow-left, rotate-cw icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 9)

- apps-view.tsx: search icon
- categories-view.tsx: arrow-left, arrow-right icons
- DatePicker.tsx: calendar icon
- EditLocationDialog.tsx: map-pin icon
- AppPage.tsx: circle-alert, book-open, external-link, mail, file, shield, flag icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 10)

- LicenseSelection.tsx: loader, check icons
- AppConnectionItem.tsx: circle-alert, arrow-right icons
- oauth-client-form/index.tsx: info icons (x2)
- auth/error/page.tsx: x icon
- troubleshoot/layout.tsx: loader icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 11)

- UpgradeTipWrapper.tsx: users, refresh-ccw, user-plus icons
- PbacOptInModal.tsx: shield-check, lock, users, shield icons
- AdvancedPermissionGroup.tsx: chevron-right, info icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 12)

- AdminAppsList.tsx: pencil icon
- AvailableTimes.tsx: calendar-x-2 icon
- BookingDetailsSheet.tsx: external-link (x2), repeat icons
- BookingCalendarContainer.tsx: chevron-left, chevron-right icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 13)

- videos-single-view.tsx: chevron-right icon
- TroubleshooterSidebar.tsx: arrow-left icon
- RuleBuilder.tsx: filter icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 14)

- FieldMappingBuilder.tsx: arrow-right, link icons
- IntegrationAttributeSyncCard.tsx: key icon
- onboarding-view.tsx: loader icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 15)

- team-profile-view.tsx: copy icon
- DateRangeFilter.tsx: check icon
- ColumnVisibilityButton.tsx: check icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 16)

- EventWorkflowsTab.tsx: lock
- event-types-listing-view.tsx: search
- onboarding-migrate-members-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, user-plus
- onboarding-migrate-teams-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, arrow-right, users
- EventAvailabilityTab.tsx: globe, user
- onboarding-teams-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, arrow-right, users
- FormBuilder.tsx: mail, phone, arrow-up, arrow-down
- AIEventController.tsx: info
- EventTeamAssignmentTab.tsx: x

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 17)

- EventAdvancedTab.tsx: pencil, info
- HostLocations.tsx: triangle-alert, loader
- EventTypeLayout.tsx: loader
- Locations.tsx: x, corner-down-right, check
- EditWeightsForAllTeamMembers.tsx: upload, search, info, chevron-down
- WorkflowPage.tsx: pencil

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 18)

- TestPhoneCallDialog.tsx: phone
- WorkflowListPage.tsx: link
- UsersTable.tsx: building, lock
- TeamList.tsx: building, paintbrush, chart-line, user-plus, users, pencil
- bookings-single-view.tsx: chevron-left, check, calendar, x, external-link

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 19)

- TeamsListing.tsx: users, refresh-ccw, user-plus, mail, video, eye-off, info
- ConnectionInfo.tsx: clipboard
- IntercomContactForm.tsx: message-circle, loader, send

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in teams components

- EventTypesList.tsx: check → CheckIcon
- MemberInvitationModal.tsx: user, users, building → UserIcon, UsersIcon, BuildingIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in workflow components

- ImportNumberDialog.tsx: info → InfoIcon
- VoiceSelector.tsx: user → UserIcon
- IncomingCallsTab.tsx: info, phone-incoming → InfoIcon, PhoneIncomingIcon
- PhoneNumberTab.tsx: loader, phone → LoaderIcon, PhoneIcon
- VoiceSelectionDialog.tsx: pause, play, user → PauseIcon, PlayIcon, UserIcon
- WebCallDialog.tsx: loader, phone, phone-off, triangle-alert, trash, message-circle → new icons (kept Icon import for dynamic mic icon)
- WorkflowDetailsPage.tsx: zap, arrow-right → ZapIcon, ArrowRightIcon
- AddActionDialog.tsx: info → InfoIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in WorkflowStepContainer

- info → InfoIcon (2 instances)
- phone → PhoneIcon (2 instances)
- circle-help → CircleHelpIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in data-table and org components

- attributes-list-view.tsx: tags → TagsIcon
- AddFilterButton.tsx: plus, eye-off → PlusIcon, EyeOffIcon
- BaseSelectFilterOptions.tsx: check → CheckIcon
- DataTable.tsx: arrow-up, arrow-down, check, chevrons-up-down, eye-off → new icons
- booking-dry-run-success-view.tsx: check → CheckIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in username and routing components

- UsernameTextfield.tsx: check → CheckIcon
- PremiumTextfield.tsx: check, external-link → CheckIcon, ExternalLinkIcon (kept Icon for star with fill prop)
- Header.tsx (routing-forms): pencil, menu, waypoints → PencilIcon, MenuIcon, WaypointsIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in routing-forms pages

Batch 25: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- Forms.tsx: file-text, shuffle, chart-bar, circle-check, mail, download → FileTextIcon, ShuffleIcon, ChartBarIcon, CircleCheckIcon, MailIcon, DownloadIcon
- FormEdit.tsx: chevron-down, menu → ChevronDownIcon, MenuIcon
- IncompleteBooking.tsx: globe → GlobeIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI package

Batch 26: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- ProgressToast.tsx: file-down, x → FileDownIcon, XIcon
- showToast.tsx: check, info, x → CheckIcon, InfoIcon, XIcon
- InfoBadge.tsx: info → InfoIcon
- MeetingTimeInTimezones.tsx: globe → GlobeIcon
- InputError.tsx: info → InfoIcon
- ConfirmationDialogContent.tsx: circle-alert, check → CircleAlertIcon, CheckIcon
- CalendarSwitch.tsx: arrow-left, rotate-cw → ArrowLeftIcon, RotateCwIcon
- ArrowButton.tsx: arrow-up, arrow-down → ArrowUpIcon, ArrowDownIcon
- FileUploader.tsx: upload → UploadIcon (kept Icon for dynamic)
- Checkbox.tsx: check → CheckIcon
- EditableHeading.tsx: pencil → PencilIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI and app-store packages

Batch 27: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- MultiEmail.tsx: x → XIcon (converted width to size)
- AppListCard.tsx: circle-alert → CircleAlertIcon
- SplitButton.tsx: chevron-down → ChevronDownIcon (kept Icon for dynamic)
- Calendar.tsx: chevron-left, chevron-right → ChevronLeftIcon, ChevronRightIcon
- AppDependencyComponent.tsx: check, circle-x, arrow-right → CheckIcon, CircleXIcon, ArrowRightIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in form input components

Batch 28: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- TextField.tsx: info → InfoIcon (kept Icon for x with onClick)
- Input.tsx: eye, eye-off, search → EyeIcon, EyeOffIcon, SearchIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: use @coss/ui/src/icons in packages with legacy moduleResolution

Packages like packages/ui and packages/app-store use a legacy moduleResolution
setting that doesn't support subpath exports. This changes the import path from
@coss/ui/icons to @coss/ui/src/icons for these packages.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI form and editor components

Migrates static Icon usages:
- MultiOptionInput: x (2x), arrow-up, arrow-down
- components (select): check
- AddVariablesDropdown: chevron-down (3x)
- ToolbarPlugin: chevron-down

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in settings and platform atoms

Migrates static Icon usages:
- SettingsLayoutAppDirClient: chevron-down (2x), chevron-right (2x), arrow-left
- platform/atoms dialog: x
- platform/atoms toast: x

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve @coss/ui/icons module resolution for legacy moduleResolution

Add typesVersions to @coss/ui package.json to help TypeScript resolve
subpath exports even with legacy moduleResolution: "node" setting.

Change imports from @coss/ui/src/icons to @coss/ui/icons to avoid
double-src path issue when Next.js applies import maps.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: localize 'Select field type' fallback label in FormEdit

Address Cubic AI review feedback (confidence 9/10) by using t() for
the hardcoded 'Select field type' string to ensure proper i18n support.

Co-Authored-By: unknown <>

* fix: add typesVersions wildcards for @coss/ui subpath imports

Add lib/*, components/*, and hooks/* to typesVersions to support
legacy moduleResolution with all package subpath patterns.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve missing Icon references in settings and workflows

- Add Icon import for dynamic icon usages in SettingsLayoutAppDirClient
- Replace static Icon usages with component icons (InfoIcon, PhoneIcon)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve icon component type errors

- Add onClick prop support to IconProps
- Fix size prop type (use number instead of string)
- Rename local MailOpenIcon to MailOpenIconWrapper to avoid shadowing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: add data-testid to icon components for test compatibility

- Add testId parameter to createIcon function
- Auto-generate data-testid for all icons (e.g., "check-icon", "search-icon")
- Remove outdated mock for @calcom/ui/components/icon in tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update package.json

* Update package.json

* fix: migrate Icon to CalendarDaysIcon in videos-single-view.tsx

Co-Authored-By: unknown <>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 14:30:27 +01:00

567 lines
20 KiB
TypeScript

import { useSession } from "next-auth/react";
import posthog from "posthog-js";
import type { FormEvent } from "react";
import { useMemo, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import TeamInviteFromOrg from "~/ee/organizations/components/TeamInviteFromOrg";
import { checkAdminOrOwner } from "@calcom/features/auth/lib/checkAdminOrOwner";
import { Dialog } from "@calcom/features/components/controlled-dialog";
import type { PendingMember } from "@calcom/features/ee/teams/lib/types";
import ServerTrans from "@calcom/lib/components/ServerTrans";
import { IS_TEAM_BILLING_ENABLED_CLIENT, MAX_NB_INVITES } from "@calcom/lib/constants";
import { useCompatSearchParams } from "@calcom/lib/hooks/useCompatSearchParams";
import { useLocale } from "@calcom/lib/hooks/useLocale";
import { MembershipRole } from "@calcom/prisma/enums";
import { CreationSource } from "@calcom/prisma/enums";
import type { RouterOutputs } from "@calcom/trpc/react";
import { trpc } from "@calcom/trpc/react";
import { isEmail } from "@calcom/trpc/server/routers/viewer/teams/util";
import classNames from "@calcom/ui/classNames";
import { Button } from "@calcom/ui/components/button";
import { DialogContent, DialogFooter } from "@calcom/ui/components/dialog";
import { TextAreaField } from "@calcom/ui/components/form";
import { Form } from "@calcom/ui/components/form";
import { Label } from "@calcom/ui/components/form";
import { TextField } from "@calcom/ui/components/form";
import { Select } from "@calcom/ui/components/form";
import { ToggleGroup } from "@calcom/ui/components/form";
import { BuildingIcon, UserIcon, UsersIcon } from "@coss/ui/icons";
import { showToast } from "@calcom/ui/components/toast";
import { revalidateTeamsList } from "@calcom/web/app/(use-page-wrapper)/(main-nav)/teams/actions";
import { GoogleWorkspaceInviteButton } from "./GoogleWorkspaceInviteButton";
type MemberInvitationModalProps = {
isOpen: boolean;
onExit: () => void;
orgMembers?: RouterOutputs["viewer"]["organizations"]["getMembers"];
onSubmit: (values: NewMemberForm, resetFields: () => void) => void;
onSettingsOpen?: () => void;
teamId: number;
members?: PendingMember[];
token?: string;
isPending?: boolean;
disableCopyLink?: boolean;
isOrg?: boolean;
checkMembershipMutation?: boolean;
};
type MembershipRoleOption = {
value: MembershipRole;
label: string;
};
export interface NewMemberForm {
emailOrUsername: string | string[];
role: MembershipRole;
}
type ModalMode = "INDIVIDUAL" | "BULK" | "ORGANIZATION";
interface FileEvent<T = Element> extends FormEvent<T> {
target: EventTarget & T;
}
function toggleElementInArray(value: string[] | string | undefined, element: string): string[] {
const array = value ? (Array.isArray(value) ? value : [value]) : [];
return array.includes(element) ? array.filter((item) => item !== element) : [...array, element];
}
export default function MemberInvitationModal(props: MemberInvitationModalProps) {
const { t } = useLocale();
const { disableCopyLink = false, isOrg = false } = props;
const trpcContext = trpc.useUtils();
const session = useSession();
const { data: currentOrg } = trpc.viewer.organizations.listCurrent.useQuery(undefined, {
enabled: !!session.data?.user?.org,
});
const checkIfMembershipExistsMutation = trpc.viewer.teams.checkIfMembershipExists.useMutation();
// Check current org role and not team role
const isOrgAdminOrOwner = currentOrg && checkAdminOrOwner(currentOrg.user.role);
const canSeeOrganization = currentOrg?.isPrivate
? isOrgAdminOrOwner
: !!(props?.orgMembers && props.orgMembers?.length > 0 && isOrgAdminOrOwner);
const [modalImportMode, setModalInputMode] = useState<ModalMode>(
canSeeOrganization ? "ORGANIZATION" : "INDIVIDUAL"
);
const createInviteMutation = trpc.viewer.teams.createInvite.useMutation({
async onSuccess() {
trpcContext.viewer.teams.get.invalidate();
trpcContext.viewer.teams.list.invalidate();
revalidateTeamsList();
},
onError: (error) => {
showToast(error.message, "error");
},
});
const options: MembershipRoleOption[] = useMemo(() => {
const options: MembershipRoleOption[] = [
{ value: MembershipRole.MEMBER, label: t("member") },
{ value: MembershipRole.ADMIN, label: t("admin") },
{ value: MembershipRole.OWNER, label: t("owner") },
];
// Adjust options for organizations where the user isn't the owner
if (isOrg && !isOrgAdminOrOwner) {
return options.filter((option) => option.value !== MembershipRole.OWNER);
}
return options;
}, [t, isOrgAdminOrOwner, isOrg]);
const toggleGroupOptions = useMemo(() => {
const array = [
{
value: "INDIVIDUAL",
label: t("invite_team_individual_segment"),
iconLeft: <UserIcon />,
},
{ value: "BULK", label: t("invite_team_bulk_segment"), iconLeft: <UsersIcon /> },
];
if (canSeeOrganization) {
array.unshift({
value: "ORGANIZATION",
label: t("organization"),
iconLeft: <BuildingIcon />,
});
}
return array;
}, [t, canSeeOrganization]);
const newMemberFormMethods = useForm<NewMemberForm>();
const checkIfMembershipExists = (value: string) => {
if (props.checkMembershipMutation) {
return checkIfMembershipExistsMutation.mutateAsync({
teamId: props.teamId,
value,
});
} else {
if (!props?.members?.length) return false;
return (
props?.members.some((member) => member?.username === value) ||
props?.members.some((member) => member?.email === value)
);
}
};
const handleFileUpload = (e: FileEvent<HTMLInputElement>) => {
if (!e.target.files?.length) {
return;
}
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
const emailRegex = /^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i;
reader.onload = (e) => {
const contents = e?.target?.result as string;
const lines = contents.split("\n");
const validEmails = [];
for (const line of lines) {
const columns = line.split(/,|;|\|| /);
for (const column of columns) {
const email = column.trim().toLowerCase();
if (emailRegex.test(email)) {
validEmails.push(email);
break; // Stop checking columns if a valid email is found in this line
}
}
}
newMemberFormMethods.setValue("emailOrUsername", validEmails);
};
reader.readAsText(file);
}
};
const resetFields = () => {
newMemberFormMethods.reset();
newMemberFormMethods.setValue("emailOrUsername", "");
newMemberFormMethods.setValue("role", options[0].value);
setModalInputMode("INDIVIDUAL");
};
const importRef = useRef<HTMLInputElement | null>(null);
return (
<Dialog
name="inviteModal"
open={props.isOpen}
onOpenChange={() => {
props.onExit();
newMemberFormMethods.reset();
}}>
<DialogContent
enableOverflow
type="creation"
title={t("invite_team_member")}
description={
IS_TEAM_BILLING_ENABLED_CLIENT && !currentOrg ? (
<span className="text-subtle text-sm leading-tight">
<ServerTrans
t={t}
i18nKey="invite_new_member_description"
components={[
<span key="invite_new_member_description" className="text-emphasis font-medium">
cost an extra seat ($15/m)
</span>,
]}
/>
</span>
) : null
}>
<div className="sm:max-h-9">
<Label className="sr-only" htmlFor="role">
{t("import_mode")}
</Label>
<ToggleGroup
isFullWidth={true}
className="flex-col sm:flex-row"
onValueChange={(val) => {
setModalInputMode(val as ModalMode);
newMemberFormMethods.clearErrors();
}}
defaultValue={modalImportMode}
options={toggleGroupOptions}
/>
</div>
<Form
form={newMemberFormMethods}
handleSubmit={(values) => {
props.onSubmit(values, resetFields);
posthog.capture("teams_modal_invite_members_button_clicked");
}}>
<div className="mb-10 mt-6 space-y-6">
{/* Individual Invite */}
{modalImportMode === "INDIVIDUAL" && (
<Controller
name="emailOrUsername"
control={newMemberFormMethods.control}
rules={{
required: t("enter_email"),
validate: async (value) => {
// orgs can only invite members by email
if (typeof value === "string" && !isEmail(value)) return t("enter_email");
if (typeof value === "string") {
const doesInviteExists = await checkIfMembershipExists(value);
return !doesInviteExists || t("member_already_invited");
}
},
}}
render={({ field: { onChange }, fieldState: { error } }) => (
<>
<TextField
label={t("email")}
id="inviteUser"
name="inviteUser"
placeholder="email@example.com"
required
onChange={(e) => onChange(e.target.value.trim().toLowerCase())}
/>
{error && <span className="text-sm text-red-800">{error.message}</span>}
</>
)}
/>
)}
{/* Bulk Invite */}
{modalImportMode === "BULK" && (
<div className="bg-cal-muted flex flex-col rounded-md p-4">
<Controller
name="emailOrUsername"
control={newMemberFormMethods.control}
rules={{
required: t("enter_email"),
validate: (value) => {
if (Array.isArray(value) && value.some((email) => !isEmail(email)))
return t("enter_emails");
if (Array.isArray(value) && value.length > MAX_NB_INVITES)
return t("too_many_invites", { nbUsers: MAX_NB_INVITES });
if (typeof value === "string" && !isEmail(value)) return t("enter_email");
},
}}
render={({ field: { onChange, value }, fieldState: { error } }) => (
<>
{/* TODO: Make this a fancy email input that styles on a successful email. */}
<TextAreaField
name="emails"
label={t("invite_via_email")}
rows={4}
autoCorrect="off"
placeholder="john@doe.com, alex@smith.com"
required
value={value}
onChange={(e) => {
const targetValues = e.target.value.split(/[\n,]/);
const emails =
targetValues.length === 1
? targetValues[0].trim().toLocaleLowerCase()
: targetValues.map((email) => email.trim().toLocaleLowerCase());
return onChange(emails);
}}
/>
{error && <span className="text-sm text-red-800">{error.message}</span>}
</>
)}
/>
<GoogleWorkspaceInviteButton
onSuccess={(data) => {
newMemberFormMethods.setValue("emailOrUsername", data);
}}
/>
<Button
type="button"
color="secondary"
onClick={() => {
if (importRef.current) {
importRef.current.click();
}
}}
StartIcon="paperclip"
className="mt-3 justify-center stroke-2">
{t("upload_csv_file")}
</Button>
<input
ref={importRef}
hidden
id="bulkInvite"
type="file"
accept=".csv"
style={{ display: "none" }}
onChange={handleFileUpload}
/>
</div>
)}
{modalImportMode === "ORGANIZATION" && (
<Controller
name="emailOrUsername"
control={newMemberFormMethods.control}
rules={{
required: t("enter_email_or_username"),
}}
render={({ field: { onChange, value } }) => (
<>
<TeamInviteFromOrg
selectedEmails={value}
handleOnChecked={(userEmail) => {
// If 'value' is not an array, create a new array with 'userEmail' to allow future updates to the array.
// If 'value' is an array, update the array by either adding or removing 'userEmail'.
const newValue = toggleElementInArray(value, userEmail);
onChange(newValue);
}}
orgMembers={props.orgMembers}
/>
</>
)}
/>
)}
<Controller
name="role"
control={newMemberFormMethods.control}
defaultValue={options[0].value}
render={({ field: { onChange } }) => (
<div>
<Label className="text-emphasis font-medium" htmlFor="role">
{t("invite_as")}
</Label>
<Select
id="role"
defaultValue={options[0]}
options={options}
onChange={(val) => {
if (val) onChange(val.value);
}}
/>
</div>
)}
/>
{props.token && (
<div className="flex">
<Button
type="button"
color="minimal"
className="me-2 ms-2"
onClick={() => {
if (props.onSettingsOpen) {
props.onSettingsOpen();
}
newMemberFormMethods.reset();
}}
data-testid="edit-invite-link-button">
{t("edit_invite_link")}
</Button>
</div>
)}
</div>
<DialogFooter showDivider>
{!disableCopyLink && (
<div className="grow">
<Button
type="button"
color="minimal"
variant="icon"
onClick={async function () {
try {
// Required for Safari but also works on Chrome
// Credits to https://wolfgangrittner.dev/how-to-use-clipboard-api-in-firefox/
if (typeof ClipboardItem !== "undefined") {
const inviteLinkClipbardItem = new ClipboardItem({
//eslint-disable-next-line no-async-promise-executor
"text/plain": new Promise(async (resolve) => {
// Instead of doing async work and then writing to clipboard, do async work in clipboard API itself
const { inviteLink } = await createInviteMutation.mutateAsync({
teamId: props.teamId,
token: props.token,
});
showToast(t("invite_link_copied"), "success");
resolve(new Blob([inviteLink], { type: "text/plain" }));
}),
});
await navigator.clipboard.write([inviteLinkClipbardItem]);
} else {
// Fallback for browsers that don't support ClipboardItem e.g. Firefox
const { inviteLink } = await createInviteMutation.mutateAsync({
teamId: props.teamId,
token: props.token,
});
await navigator.clipboard.writeText(inviteLink);
showToast(t("invite_link_copied"), "success");
}
} catch (e) {
showToast(t("something_went_wrong_on_our_end"), "error");
console.error(e);
}
}}
className={classNames("gap-2", props.token && "opacity-50")}
StartIcon="link"
data-testid="copy-invite-link-button">
<span className="hidden sm:inline">{t("copy_invite_link")}</span>
</Button>
</div>
)}
<Button
type="button"
color="minimal"
onClick={() => {
props.onExit();
resetFields();
}}>
{t("cancel")}
</Button>
<Button
loading={
props.isPending || createInviteMutation.isPending || checkIfMembershipExistsMutation.isPending
}
type="submit"
color="primary"
className="me-2 ms-2"
data-testid="invite-new-member-button">
{t("send_invite")}
</Button>
</DialogFooter>
</Form>
</DialogContent>
</Dialog>
);
}
export const MemberInvitationModalWithoutMembers = ({
hideInvitationModal,
showMemberInvitationModal,
teamId,
token,
onSettingsOpen,
...props
}: Partial<MemberInvitationModalProps> & {
hideInvitationModal: () => void;
showMemberInvitationModal: boolean;
teamId: number;
token?: string;
onSettingsOpen: () => void;
}) => {
const searchParams = useCompatSearchParams();
const { t, i18n } = useLocale();
const utils = trpc.useUtils();
const inviteMemberMutation = trpc.viewer.teams.inviteMember.useMutation();
const { data: orgMembersNotInThisTeam, isPending: isOrgListLoading } =
trpc.viewer.organizations.getMembers.useQuery(
{
teamIdToExclude: teamId,
distinctUser: true,
},
{
enabled: searchParams !== null && !!teamId && !!showMemberInvitationModal,
}
);
return (
<MemberInvitationModal
{...props}
isPending={inviteMemberMutation.isPending || isOrgListLoading}
isOpen={showMemberInvitationModal}
orgMembers={orgMembersNotInThisTeam}
teamId={teamId}
token={token}
onExit={hideInvitationModal}
checkMembershipMutation={true}
onSubmit={(values, resetFields) => {
inviteMemberMutation.mutate(
{
teamId,
language: i18n.language,
role: values.role,
usernameOrEmail: values.emailOrUsername,
creationSource: CreationSource.WEBAPP,
},
{
onSuccess: async (data) => {
await utils.viewer.teams.get.invalidate();
await utils.viewer.teams.listMembers.invalidate();
await utils.viewer.organizations.getMembers.invalidate();
hideInvitationModal();
if (Array.isArray(data.usernameOrEmail)) {
showToast(
t("email_invite_team_bulk", {
userCount: data.numUsersInvited,
}),
"success"
);
resetFields();
} else {
showToast(
t("email_invite_team", {
email: data.usernameOrEmail,
}),
"success"
);
}
},
onError: (error) => {
showToast(error.message, "error");
},
}
);
}}
onSettingsOpen={() => {
hideInvitationModal();
onSettingsOpen();
}}
/>
);
};