Files
cal.diy/packages/features/ee/teams/components/MemberInvitationModal.tsx
T
5d709cf63c feat: v3 of UI components (#19136)
* ui playground

* add types to ui

* push avatar ignore ts and eslint errors

* feat: V3 UI avatar  (#18997)

* avatar playground

* add overflow-hidden back for loading indicator

* update lock

* feat: v3/badge  (#18999)

* badge intro

* fix text on small badge

* add dark mode warning

* feat: v3/button (#19014)

* TOC

* wip buttons

* shadows

* secondary

* semantic colours

* minimal buttons

* update disabled states

* checkbox

* dropdown v3

* load icons

* fix design sections

* fix icon gap

* fix

* remove client component from rsc

* use peer as avatar

* gif

* fix button gap - dropdown iocn

* support start icon in dropdowns

* add alert demo + v3 component + darken semantic text

* base inputs and text field

* wip input

* input field addon/suffix

* toast page

* wip select

* match designs for input and select rounded

* fix

* fix select isloading transform

* fix multi icons transition rotation

* fix group heading

* range slider demo + range slider

* range slider popover design

* v3 dialog

* fix slider thumb size

* wrap in suspense for useSearchParam difference in next14+

* base of tabs + horizontal tabs

* fix select sizing to match input 36px

* fix dark mode hover on button

* target domState class for light/dark so we work on portal elements

* fix default bg on popover

* lightmode toasts + eleveation token

* empty screen

* intro to split button concept

* mass colour updates

* intro to themes

* remove i18n from label with name

* bouncy buttons

* feat: small select

* nav item dumb component

* full demo

* settings demo

* fix tabs

* fix mt

* fix dropdown feedback from loom

* alert fixes mentioned in loom

* push font-cal

* move to fumadocs

* fix avatar

* colors table

* add typeography

* icon + spacing guide

* add border radius and shadow tables

* fix colours and border radius

* remove prose undline via fumas fork

* fix icon buttons sizes

* button group component

* fix horizontal tabs

* tab fixes

* switches

* pagination component

* show toasts components raw

* sync with airtable

* add use client

* 10px on input again

* 10px in select also

* fix input height

* fix files merge

* fix loading state for icon buttons

* fix button fab

* Enable addon to now overflow to next line in DS

* use cal font for dialog text

* add avatar square variant

* fix select padding and menu size

* fix type errors

* fix type errors

* add switch small size and fix type errors

* fix ref types on input

* update web styles

* remove addonFilled to fix type errors

* push dialog fixes

* fix checkbox display

* remove prose from alert examples

* remove prose from all our component examples

* badge rounded-lg on lg size

* update colors

* force w/h on icon buttons instead of inheriting

* remove border-focus

* remove border-focus from tailwind config

* update tokens to match new colours

* add new border subtle tokens and add to toasts

* fix lg button padding

* fix and drastically improve rtl rests

* multi select use badges

* use badge design for select pills

* fix avatar alignment

* fix tests and remove redudant ones

* fix tests and remove redudant ones

* update atoms globals css

* extract tokens.css

* extract app.css

* force flex for atoms

* add @calcom/ui/css

* revert ui playground styles abstraction

* fix input focus states

* fix focus states for buttons

* feat: v3/app work (#19233)

* globals.css for app + event types listing search

* few app wide NITS

* fix select foucs within styling

* fix formbuilder switch styles

* fix disabled state of nested inputs

* workflow fixes

* webhook form fixes

* i18n on tabs info

* booking filters + tab

* fix filters spacing

* make first item so we get correct border radius if not default

* round radio group in create event types + make button small

* profile page

* update editor br

* button nits in existing places in the app

* fix timezone select and multilist in guest form

* fix text area on public booking page

* size small event types create

* margin on routing filter

* filters improvments

* routing insights fixes

* fix date filter range

* ooo fixes

* fix teams/members bulk actions

* create team UI

* i18n in useTabs instead of in tab component now

* Add event type setup border to availability

* fix bulk actions on org members table

* onboarding fixes

* fix input types with ref stripe comparision

* i18n fixes for platform

* update globals of atoms

* fix form builder firstname/lastname switch + correct footer useage

* fix select

* Revert "add @calcom/ui/css"

This reverts commit 0dd8f9012907a278cfede4a98f289cb0744c9244.

* revert tokens css

* Revert "extract app.css"

This reverts commit 10b998604816ad3310c24b36a02a638dabc5be24.

* linear nits

* workflow dropdown

* fix page theme heading sizes to match cards

* fix stepper for team creation

* adjust margin to FilterSearchField

* fix ooo icon

* fix booker and dark mode due to darkgray 50

* more dark mode fixes

* add size prop

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Morgan Vernay <morgan@cal.com>

* remove ui-playground

* fix grow missing from merge

* add search icon data-test-id back to search

* fix FormAction style

* fix datatestid for apps and tabs

* change selector for team invitation e2e

* fix use data-testid from item instaed of using names

* rename upper case O

* fix unit tests data-testid

* fix unit tests data-testid

* more data-testid changes

* add data-testid to apps tab

* data-testid to installed appPage

* fix embed tests

* fix filter-popover-trigger

* use text-error and use dataId for locator

* more e2e improvment

* pass in single testId as button is now duplicate

* show field-error instead

* add test to eventtype tabs

* Add css vars to embed too\

* add scrollbar and change dialog overlay colour

* fix type

* use attribute instead of class for tab detection

* await promise

* use new tokens for sprite generation

* add correct testing Ids to e2e instead of button:text

* use testIds for creation of orgs

* Webhook receiver wait for 10 seconds

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Morgan Vernay <morgan@cal.com>
Co-authored-by: Hariom <hariombalhara@gmail.com>
Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
2025-02-14 16:31:21 -05:00

555 lines
19 KiB
TypeScript

import { useSession } from "next-auth/react";
import { Trans } from "next-i18next";
import type { FormEvent } from "react";
import { useMemo, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import TeamInviteFromOrg from "@calcom/ee/organizations/components/TeamInviteFromOrg";
import { classNames } from "@calcom/lib";
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";
import { trpc } from "@calcom/trpc";
import { isEmail } from "@calcom/trpc/server/routers/viewer/teams/util";
import {
Button,
Dialog,
DialogContent,
DialogFooter,
Form,
Icon,
Label,
Select,
showToast,
TextAreaField,
TextField,
ToggleGroup,
} from "@calcom/ui";
import type { PendingMember } from "../lib/types";
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 &&
(currentOrg.user.role === MembershipRole.OWNER || currentOrg.user.role === MembershipRole.ADMIN);
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({ inviteLink }) {
trpcContext.viewer.teams.get.invalidate();
trpcContext.viewer.teams.list.invalidate();
},
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: <Icon name="user" />,
},
{ value: "BULK", label: t("invite_team_bulk_segment"), iconLeft: <Icon name="users" /> },
];
if (canSeeOrganization) {
array.unshift({
value: "ORGANIZATION",
label: t("organization"),
iconLeft: <Icon name="building" />,
});
}
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">
<Trans i18nKey="invite_new_member_description">
Note: This will <span className="text-emphasis font-medium">cost an extra seat ($15/m)</span>{" "}
on your subscription.
</Trans>
</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)}>
<div className="mb-10 mt-6 space-y-6">
{/* Indivdual 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-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={() => {
props.onSettingsOpen && props.onSettingsOpen();
newMemberFormMethods.reset();
}}
data-testid="edit-invite-link-button">
{t("edit_invite_link")}
</Button>
</div>
)}
</div>
<DialogFooter showDivider>
{!disableCopyLink && (
<div className="flex-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({
"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();
}}
/>
);
};