Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(ui): shared EmailInput chip field and email validation (#8663)

Andrew Huangb1e667f41b11
diff --git a/DESIGN.md b/DESIGN.md
index 40adc35eb2..f6741323dd 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -223,6 +223,7 @@ specialized primitives not listed here (for example `CodeBlock`, `CopyButton`,
| [`DateRangeFilter`](frontend/src/components/v3/platform/DateRangeFilter/DateRangeFilter.tsx) | Platform date-range filter with presets — for filter bars. |
| [`SecretInput`](frontend/src/components/v3/platform/SecretInput/SecretInput.tsx) | Platform secret-value editor with mask toggle and `${var}` highlighting. |
| [`PasswordGenerator`](frontend/src/components/v3/platform/PasswordGenerator/PasswordGenerator.tsx) | Platform password generator against project secret-validation rules. |
+| [`EmailInput`](frontend/src/components/v3/platform/EmailInput/EmailInput.tsx) | Platform chip field for one or more free-text email addresses. Validate it with `emailListSchema` from `@app/helpers/email`; check single addresses or picker-created invitees with `isValidEmail` rather than a local regex or `z.string().email()`. |
#### Containers & overlays
diff --git a/frontend/src/components/auth/InitialSignupStep.tsx b/frontend/src/components/auth/InitialSignupStep.tsx
index daf8ab96dd..9114368644 100644
--- a/frontend/src/components/auth/InitialSignupStep.tsx
+++ b/frontend/src/components/auth/InitialSignupStep.tsx
@@ -4,7 +4,6 @@ import { faGithub, faGitlab, faGoogle } from "@fortawesome/free-brands-svg-icons
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import HCaptcha from "@hcaptcha/react-hcaptcha";
import { Link } from "@tanstack/react-router";
-import { z } from "zod";
import { RegionSelect } from "@app/components/navigation/RegionSelect";
import { createNotification } from "@app/components/notifications";
@@ -21,6 +20,7 @@ import {
} from "@app/components/v3";
import { envConfig } from "@app/config/env";
import { useServerConfig } from "@app/context";
+import { isValidEmail } from "@app/helpers/email";
import { preserveHubSpotUtk } from "@app/helpers/utmTracking";
import { useSendVerificationEmail } from "@app/hooks/api";
import { LoginMethod } from "@app/hooks/api/admin/types";
@@ -52,7 +52,7 @@ export default function InitialSignupStep({
const [isCaptchaReady, setIsCaptchaReady] = useState(!requiresCaptcha);
const [isCaptchaPending, setIsCaptchaPending] = useState(false);
const captchaRef = useRef<HCaptcha>(null);
- const isEmailValid = z.string().email().safeParse(email).success;
+ const isEmailValid = isValidEmail(email);
const shouldDisplaySignupMethod = (method: LoginMethod) =>
!config.enabledLoginMethods || config.enabledLoginMethods.includes(method);
@@ -63,9 +63,7 @@ export default function InitialSignupStep({
shouldDisplaySignupMethod(LoginMethod.GITLAB);
const handleEmailSignup = async () => {
- const isValid = z.string().email().safeParse(email);
-
- if (!isValid.success) {
+ if (!isEmailValid) {
setEmailError(true);
return;
}
diff --git a/frontend/src/components/auth/TeamInviteStep.tsx b/frontend/src/components/auth/TeamInviteStep.tsx
index 7eaaa5ae76..a263c65f94 100644
--- a/frontend/src/components/auth/TeamInviteStep.tsx
+++ b/frontend/src/components/auth/TeamInviteStep.tsx
@@ -8,11 +8,11 @@ import {
CardDescription,
CardHeader,
CardTitle,
+ EmailInput,
Field,
- FieldFeedback,
- TextArea
+ FieldFeedback
} from "@app/components/v3";
-import { emailListSchema, parseEmailList } from "@app/helpers/email";
+import { emailListSchema, MAX_INVITE_EMAILS } from "@app/helpers/email";
import { useAddUsersToOrg } from "@app/hooks/api";
import { useFetchServerStatus } from "@app/hooks/api/serverDetails";
import { usePopUp } from "@app/hooks/usePopUp";
@@ -22,8 +22,8 @@ import { AuthPagePanel } from "./AuthPagePanel";
import { EmailServiceSetupModal } from "./EmailServiceSetupModal";
interface TeamInviteStepProps {
- emails: string;
- onEmailsChange: (emails: string) => void;
+ emails: string[];
+ onEmailsChange: (emails: string[]) => void;
onBack: () => void;
productName?: string;
/** Signup-created projects the invitees get member access to. */
@@ -46,6 +46,7 @@ export default function TeamInviteStep({
}: TeamInviteStepProps): JSX.Element {
const { t } = useTranslation();
const [validationError, setValidationError] = useState("");
+ const [draft, setDraft] = useState("");
const [isSending, setIsSending] = useState(false);
const { data: serverDetails } = useFetchServerStatus();
@@ -58,13 +59,13 @@ export default function TeamInviteStep({
const inviteUsersAndContinue = async () => {
if (isSending) return;
- const result = emailListSchema.safeParse(emails);
+ const result = emailListSchema({ max: MAX_INVITE_EMAILS, isRequired: true }).safeParse(emails);
if (!result.success) {
setValidationError(result.error.issues[0].message);
return;
}
- const parsed = Array.from(new Set(parseEmailList(result.data)));
+ const parsed = result.data;
setValidationError("");
const startedAt = Date.now();
setIsSending(true);
@@ -100,7 +101,7 @@ export default function TeamInviteStep({
return;
}
- onEmailsChange("");
+ onEmailsChange([]);
onComplete();
};
@@ -117,16 +118,17 @@ export default function TeamInviteStep({
</CardHeader>
<CardContent className="flex flex-col gap-4">
<Field data-invalid={Boolean(validationError)}>
- <TextArea
+ <EmailInput
+ aria-label="Teammate emails"
aria-describedby="signup-invite-feedback"
- variant="outlined"
- className="min-h-20"
value={emails}
- disabled={isSending}
- onChange={(e) => {
- onEmailsChange(e.target.value);
+ isDisabled={isSending}
+ onValueChange={(next) => {
+ onEmailsChange(next);
if (validationError) setValidationError("");
}}
+ inputValue={draft}
+ onInputValueChange={setDraft}
isError={Boolean(validationError)}
/>
@@ -161,7 +163,7 @@ export default function TeamInviteStep({
}}
variant="project"
isPending={isSending}
- isDisabled={!emails.trim()}
+ isDisabled={!emails.length && !draft.trim()}
>
Send invites
</Button>
diff --git a/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
index 6da0681423..715140d3cf 100644
--- a/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
+++ b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
@@ -1,6 +1,6 @@
import * as React from "react";
import { Combobox as ComboboxPrimitive } from "@base-ui/react/combobox";
-import { XIcon } from "lucide-react";
+import { TriangleAlertIcon, XIcon } from "lucide-react";
import { cn } from "../../utils";
import { useScrollEdges } from "../../utils/useScrollEdges";
@@ -12,10 +12,12 @@ import {
COMBOBOX_CHIPS_INPUT_CLASS,
comboboxChipsViewportClass
} from "../Combobox/combobox-chips";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../Tooltip";
import "../../utils/ScrollEdgeFade.css";
const NO_ITEMS: string[] = [];
+const DEFAULT_PASTE_DELIMITER = /[\n\r, ]/;
type TagsInputProps = Omit<
React.ComponentPropsWithoutRef<"input">,
@@ -29,6 +31,10 @@ type TagsInputProps = Omit<
/** Returning a reason refuses the commit. `existing` never contains the value being checked. */
validateTag?: (tag: string, existing: string[]) => string | null;
onValidationError?: (reason: string | null) => void;
+ /** Returning a reason flags a committed tag as invalid without refusing it, so it stays visible and removable. */
+ getTagError?: (tag: string) => string | null;
+ /** What splits a pasted list into separate tags. Defaults to commas, spaces and newlines. */
+ pasteDelimiter?: RegExp;
inputValue?: string;
onInputValueChange?: (draft: string) => void;
className?: string;
@@ -43,6 +49,8 @@ const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(
isError,
validateTag,
onValidationError,
+ getTagError,
+ pasteDelimiter = DEFAULT_PASTE_DELIMITER,
inputValue,
onInputValueChange,
className,
@@ -97,13 +105,17 @@ const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(
const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
const pasted = event.clipboardData.getData("text");
- const splitOn = /[\n\r, ]/;
- if (!splitOn.test(pasted)) return;
+ if (!pasteDelimiter.test(pasted)) return;
event.preventDefault();
- const parts = pasted
- .split(splitOn)
+ const { selectionStart, selectionEnd } = event.currentTarget;
+ const parts = [
+ draft.slice(0, selectionStart ?? draft.length),
+ pasted,
+ draft.slice(selectionEnd ?? draft.length)
+ ]
+ .flatMap((chunk) => chunk.split(pasteDelimiter))
.map((part) => part.trim())
.filter(Boolean);
@@ -162,22 +174,43 @@ const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(
data-scrollable-start={scrollEdges.start}
data-scrollable-end={scrollEdges.end}
>
- {tags.map((tag) => (
- <ComboboxPrimitive.Chip key={tag} className={COMBOBOX_CHIP_CLASS}>
- <span className={COMBOBOX_CHIP_LABEL_CLASS}>{tag}</span>
- {!isDisabled && (
- <ComboboxPrimitive.ChipRemove
- aria-label={`Remove ${tag}`}
- // Removal is Base UI's, through the controlled Root. Doing it here too would fire the
- // caller's handler twice. Adding is ours, in `commit`, since there is no options list.
- onClick={() => onValidationError?.(null)}
- className={COMBOBOX_CHIP_REMOVE_CLASS}
- >
- <XIcon className="size-3" />
- </ComboboxPrimitive.ChipRemove>
- )}
- </ComboboxPrimitive.Chip>
- ))}
+ {tags.map((tag) => {
+ const tagError = getTagError?.(tag) ?? null;
+ const isInvalid = tagError !== null;
+ const chip = (
+ <ComboboxPrimitive.Chip
+ key={tag}
+ data-invalid={isInvalid || undefined}
+ className={cn(COMBOBOX_CHIP_CLASS, isInvalid && "bg-danger/15 text-danger")}
+ >
+ {isInvalid && <TriangleAlertIcon aria-hidden className="size-3 shrink-0" />}
+ <span className={COMBOBOX_CHIP_LABEL_CLASS}>{tag}</span>
+ {isInvalid && <span className="sr-only">({tagError})</span>}
+ {!isDisabled && (
+ <ComboboxPrimitive.ChipRemove
+ aria-label={`Remove ${tag}`}
+ // Removal is Base UI's, through the controlled Root. Doing it here too would fire the
+ // caller's handler twice. Adding is ours, in `commit`, since there is no options list.
+ onClick={() => onValidationError?.(null)}
+ className={cn(
+ COMBOBOX_CHIP_REMOVE_CLASS,
+ isInvalid &&
+ "text-danger hover:bg-danger/20 hover:text-danger focus-visible:ring-danger"
+ )}
+ >
+ <XIcon className="size-3" />
+ </ComboboxPrimitive.ChipRemove>
+ )}
+ </ComboboxPrimitive.Chip>
+ );
+ if (!isInvalid) return chip;
+ return (
+ <Tooltip key={tag}>
+ <TooltipTrigger asChild>{chip}</TooltipTrigger>
+ <TooltipContent>{tagError}</TooltipContent>
+ </Tooltip>
+ );
+ })}
<ComboboxPrimitive.Input
ref={forwardedRef}
aria-invalid={isError || undefined}
@@ -185,7 +218,10 @@ const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onBlur={() => commit(draft)}
- className={COMBOBOX_CHIPS_INPUT_CLASS}
+ className={cn(
+ COMBOBOX_CHIPS_INPUT_CLASS,
+ tags.length > 0 && !draft && "min-w-0 focus:min-w-24"
+ )}
{...inputProps}
/>
</div>
diff --git a/frontend/src/components/v3/platform/EmailInput/EmailInput.stories.tsx b/frontend/src/components/v3/platform/EmailInput/EmailInput.stories.tsx
new file mode 100644
index 0000000000..2d442665d2
--- /dev/null
+++ b/frontend/src/components/v3/platform/EmailInput/EmailInput.stories.tsx
@@ -0,0 +1,96 @@
+import { useState } from "react";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+import { expect, userEvent, within } from "storybook/test";
+
+import { emailListSchema } from "@app/helpers/email";
+
+import { Field, FieldDescription, FieldError, FieldLabel } from "../../generic/Field";
+import { EmailInput } from "./EmailInput";
+
+/**
+ * `EmailInput` is the one field for entering email addresses. It builds on `TagsInput`: Enter, a
+ * comma, a space or blur turns the draft into a chip, and a pasted list is split on commas,
+ * semicolons and whitespace. Addresses are lowercased and deduplicated as they arrive.
+ *
+ * A malformed address is kept as a flagged chip rather than refused, so a pasted list never loses
+ * entries silently. The form decides whether that blocks submission: validate the value with
+ * `emailListSchema` from `@app/helpers/email`, which uses the same `isValidEmail` check, and render
+ * its message in `FieldError`.
+ */
+const meta = {
+ title: "Platform/EmailInput",
+ component: EmailInput,
+ parameters: {
+ layout: "centered"
+ },
+ tags: ["autodocs"],
+ args: {
+ onValueChange: () => undefined
+ },
+ decorators: [
+ (Story) => (
+ <div className="w-96">
+ <Story />
+ </div>
+ )
+ ],
+ globals: {
+ backgrounds: { value: "card" }
+ }
+} satisfies Meta<typeof EmailInput>;
+
+export default meta;
+type Story = StoryObj;
+
+const schema = emailListSchema({ max: 100, isRequired: true });
+
+const DefaultRender = ({ initial }: { initial: string[] }) => {
+ const [value, setValue] = useState<string[]>(initial);
+ const result = schema.safeParse(value);
+ const error = result.success ? undefined : result.error.issues[0].message;
+
+ return (
+ <Field data-invalid={error ? "true" : undefined}>
+ <FieldLabel htmlFor="email-input-default">Emails</FieldLabel>
+ <EmailInput
+ id="email-input-default"
+ value={value}
+ onValueChange={setValue}
+ isError={Boolean(error)}
+ />
+ {error ? (
+ <FieldError>{error}</FieldError>
+ ) : (
+ <FieldDescription>Paste a list or press Enter after each address.</FieldDescription>
+ )}
+ </Field>
+ );
+};
+
+export const Default: Story = {
+ render: () => <DefaultRender initial={["[email protected]", "[email protected]"]} />
+};
+
+/** Invalid addresses stay visible as flagged chips, and the schema message names them. */
+export const InvalidAddresses: Story = {
+ name: "Example: Invalid Addresses",
+ render: () => <DefaultRender initial={["[email protected]", "not-an-email", "sam@example"]} />
+};
+
+/** A pasted list is split, lowercased and deduplicated, and a half-typed address next to it is kept. */
+export const PasteList: Story = {
+ name: "Example: Paste a List",
+ render: () => <DefaultRender initial={[]} />,
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const input = canvas.getByRole("combobox");
+
+ await userEvent.type(input, "[email protected]");
+
+ await expect(canvas.getByText("[email protected]")).toBeVisible();
+ await expect(canvas.getByText("[email protected]")).toBeVisible();
+ await expect(canvas.getByText("[email protected]")).toBeVisible();
+ }
+};
diff --git a/frontend/src/components/v3/platform/EmailInput/EmailInput.tsx b/frontend/src/components/v3/platform/EmailInput/EmailInput.tsx
new file mode 100644
index 0000000000..c5cce06243
--- /dev/null
+++ b/frontend/src/components/v3/platform/EmailInput/EmailInput.tsx
@@ -0,0 +1,36 @@
+import * as React from "react";
+
+import { EMAIL_LIST_DELIMITER, isValidEmail, parseEmailList } from "@app/helpers/email";
+
+import { TagsInput, type TagsInputProps } from "../../generic/TagsInput";
+
+type EmailInputProps = Omit<
+ TagsInputProps,
+ "value" | "onValueChange" | "validateTag" | "onValidationError" | "getTagError" | "onBlur"
+> & {
+ value?: readonly string[];
+ onValueChange: (emails: string[]) => void;
+};
+
+/**
+ * The shared multi-address email field. Addresses become chips on Enter, comma, space or blur, and a
+ * pasted list is split on commas, semicolons and whitespace. Every value is lowercased and
+ * deduplicated, and a malformed address stays as a flagged chip so it can be read and removed.
+ * Pair it with `emailListSchema` for the form error; this component only flags.
+ */
+const EmailInput = React.forwardRef<HTMLInputElement, EmailInputProps>(
+ ({ onValueChange, autoComplete = "off", ...props }, ref) => (
+ <TagsInput
+ ref={ref}
+ autoComplete={autoComplete}
+ onValueChange={(next) => onValueChange(parseEmailList(next))}
+ getTagError={(email) => (isValidEmail(email) ? null : "Not a valid email address")}
+ pasteDelimiter={EMAIL_LIST_DELIMITER}
+ {...props}
+ />
+ )
+);
+
+EmailInput.displayName = "EmailInput";
+
+export { EmailInput, type EmailInputProps };
diff --git a/frontend/src/components/v3/platform/EmailInput/index.ts b/frontend/src/components/v3/platform/EmailInput/index.ts
new file mode 100644
index 0000000000..ae70e4738b
--- /dev/null
+++ b/frontend/src/components/v3/platform/EmailInput/index.ts
@@ -0,0 +1 @@
+export { EmailInput, type EmailInputProps } from "./EmailInput";
diff --git a/frontend/src/components/v3/platform/index.ts b/frontend/src/components/v3/platform/index.ts
index 134f7a1eb2..e90b2cf47f 100644
--- a/frontend/src/components/v3/platform/index.ts
+++ b/frontend/src/components/v3/platform/index.ts
@@ -2,6 +2,7 @@ export * from "./AccessRestricted";
export * from "./DateRangeFilter";
export * from "./DeleteConfirmDialog";
export * from "./DocumentationLinkBadge";
+export * from "./EmailInput";
export * from "./GatewayPicker";
export * from "./IdentityRoleBadges";
export * from "./LookingForOrgPageLink";
diff --git a/frontend/src/helpers/email.test.ts b/frontend/src/helpers/email.test.ts
new file mode 100644
index 0000000000..d94a79ed80
--- /dev/null
+++ b/frontend/src/helpers/email.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from "vitest";
+
+import { emailListSchema, isValidEmail, parseEmailList } from "./email";
+
+describe("isValidEmail", () => {
+ it.each(["[email protected]", "[email protected]"])("accepts %s", (email) => {
+ expect(isValidEmail(email)).toBe(true);
+ });
+
+ it.each([
+ "",
+ " ",
+ "plainaddress",
+ "a@example",
+ `a@${"x".repeat(64)}.com`,
+ `${"a".repeat(250)}@example.com`
+ ])("rejects %j", (email) => {
+ expect(isValidEmail(email)).toBe(false);
+ });
+});
+
+describe("parseEmailList", () => {
+ it("splits on commas, semicolons and whitespace, lowercases and dedupes in order", () => {
+ ]);
+ });
+});
+
+describe("emailListSchema", () => {
+ it("requires an address only when asked", () => {
+ expect(emailListSchema().safeParse([]).success).toBe(true);
+ expect(emailListSchema({ isRequired: true }).safeParse([]).success).toBe(false);
+ });
+
+ it("enforces the cap and names invalid addresses", () => {
+ expect(emailListSchema({ max: 1 }).safeParse(["[email protected]", "[email protected]"]).success).toBe(false);
+
+ const result = emailListSchema().safeParse(["[email protected]", "nope"]);
+ expect(result.success).toBe(false);
+ expect(result.error?.issues[0].message).toBe("Invalid email address: nope.");
+ });
+});
diff --git a/frontend/src/helpers/email.ts b/frontend/src/helpers/email.ts
index 5125ceeb13..b1cd289154 100644
--- a/frontend/src/helpers/email.ts
+++ b/frontend/src/helpers/email.ts
@@ -74,6 +74,8 @@ export const allowedEmailDomainsSchema = z
})
.transform(normalizeAllowedEmailDomains);
+// The authoritative frontend email-shape check. It answers whether an address is well formed and
+// fits what the backend stores; it never claims the mailbox or domain exists.
export const isValidEmail = (email: string) =>
email.length <= MAX_EMAIL_LENGTH &&
EmailSchema.safeParse(email).success &&
@@ -83,33 +85,46 @@ export const isValidEmail = (email: string) =>
// before hitting the API.
export const MAX_INVITE_EMAILS = 100;
-export const parseEmailList = (value: string) =>
- value
- .split(",")
- .map((email) => email.trim())
- .filter(Boolean);
-
-// Shared validation for a comma-separated email list entered in a textarea. Embed it directly as an
-// object field in a react-hook-form schema: z.object({ emails: emailListSchema, ... }).
-export const emailListSchema = z
- .string()
- .trim()
- .toLowerCase()
- .superRefine((value, ctx) => {
- const emails = parseEmailList(value);
+export const normalizeEmail = (email: string) => email.trim().toLowerCase();
+
+// Splits pasted or typed text on commas, semicolons and whitespace, normalizes each address, and
+// drops duplicates while keeping the first occurrence's order. EmailInput runs every change through
+// this, so a value held by a form is always a clean, deduplicated list.
+export const EMAIL_LIST_DELIMITER = /[\s,;]+/;
+
+export const parseEmailList = (values: string[]) =>
+ Array.from(
+ new Set(
+ values
+ .flatMap((value) => value.split(EMAIL_LIST_DELIMITER))
+ .map(normalizeEmail)
+ .filter(Boolean)
+ )
+ );
- if (!emails.length) {
+// Shared validation for an EmailInput value. Embed it directly as an object field in a
+// react-hook-form schema: z.object({ emails: emailListSchema({ max: MAX_INVITE_EMAILS }) }).
+// Shape validation only: an address that passes is well formed, not known to exist.
+export const emailListSchema = ({
+ max,
+ isRequired = false
+}: {
+ max?: number;
+ isRequired?: boolean;
+} = {}) =>
+ z.array(z.string()).superRefine((emails, ctx) => {
+ if (isRequired && !emails.length) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
- message: "Please enter at least one email address."
+ message: "Enter at least one email address."
});
return;
}
- if (emails.length > MAX_INVITE_EMAILS) {
+ if (max !== undefined && emails.length > max) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
- message: `You can invite up to ${MAX_INVITE_EMAILS} users at a time.`
+ message: `Enter up to ${max} email address${max === 1 ? "" : "es"}.`
});
}
diff --git a/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx b/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx
index e69c5fee50..4f06d9932c 100644
--- a/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx
+++ b/frontend/src/pages/admin/ResourceOverviewPage/components/AddOrganizationModal.tsx
@@ -18,6 +18,7 @@ import {
FieldLabel,
Input
} from "@app/components/v3";
+import { isValidEmail } from "@app/helpers/email";
import { useDebounce } from "@app/hooks";
import { useAdminGetUsers, useServerAdminCreateOrganization } from "@app/hooks/api";
import { GenericResourceNameSchema } from "@app/lib/schemas";
@@ -130,15 +131,11 @@ const Content = ({ onClose }: ContentProps) => {
/>
<Controller
render={({ field, fieldState: { error } }) => {
- const email = searchUserFilter.trim();
- const isNewEmail =
- z.string().email().safeParse(email).success &&
- ![...users, ...field.value].some(
- (user) => (user.email || user.username)?.toLowerCase() === email.toLowerCase()
- );
- const inviteOption: Invitee | null = isNewEmail
- ? { id: `invite:${email.toLowerCase()}`, email }
- : null;
+ const isKnownEmail = (email: string, user: Invitee) =>
+ (user.email || user.username)?.toLowerCase() === email.toLowerCase();
+ const isSearching = searchUserFilter !== debouncedSearchTerm || isPending;
+ // Results for an earlier query would sit above the Invite row and take Enter.
+ const isStaleForEmail = isSearching && isValidEmail(searchUserFilter.trim());
return (
<Field>
@@ -146,23 +143,31 @@ const Content = ({ onClose }: ContentProps) => {
<Combobox<Invitee>
id={adminSelectId}
multiple
- options={inviteOption ? [inviteOption, ...users] : users}
+ options={isStaleForEmail ? [] : users}
value={field.value}
onValueChange={field.onChange}
onClear={() => field.onChange([])}
getOptionLabel={getUserLabel}
getOptionValue={(user) => user.id}
- renderOption={(user) =>
- user.id.startsWith("invite:") ? `Invite "${user.email}"` : getUserLabel(user)
- }
+ creation={{
+ isValid: (email) => isValidEmail(email),
+ isDuplicate: isKnownEmail,
+ formatLabel: (email) => `Invite "${email}"`,
+ emptyLabel: "Type an email to invite",
+ onCreate: (email) =>
+ field.onChange([
+ ...field.value,
+ { id: `invite:${email.toLowerCase()}`, email: email.toLowerCase() }
+ ])
+ }}
placeholder="Search users or invite by email..."
searchPlaceholder="Search users or enter an email..."
searchAriaLabel="Search users or enter an email to invite"
emptyMessage="No users found. Enter a valid email address to invite a new user."
- isLoading={searchUserFilter !== debouncedSearchTerm || isPending}
+ isLoading={isSearching}
isError={Boolean(error)}
shouldFilter={false}
- includeMissingSelectedOptions
+ includeMissingSelectedOptions={false}
modal
onInputValueChange={(value) => {
setSearchUserFilter(value);
diff --git a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
index 93d2e55661..1264f43bb1 100644
--- a/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
+++ b/frontend/src/pages/auth/SignUpPage/SignUpPage.tsx
@@ -61,7 +61,7 @@ export const SignUpPage = ({ invite }: SignUpPageProps) => {
isInvite ? SignupSection.UserInfo : SignupSection.Email
);
const [orgId, setOrgId] = useState("");
- const [inviteEmails, setInviteEmails] = useState("");
+ const [inviteEmails, setInviteEmails] = useState<string[]>([]);
const projectCache = useRef<Partial<Record<SignupProductType, Project>>>({});
// An empty selection means "just exploring".
const [selectedProducts, setSelectedProducts] = useState<SignupProductType[]>([]);
diff --git a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
index dfb96b8fa1..bf2f0f0e72 100644
--- a/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
+++ b/frontend/src/pages/organization/AccessManagementPage/components/OrgMembersTab/components/OrgMembersSection/AddOrgMemberModal.tsx
@@ -4,9 +4,9 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
-import { Button, Field, FieldError, FieldLabel, SheetClose, TextArea } from "@app/components/v3";
+import { Button, EmailInput, Field, FieldError, FieldLabel, SheetClose } from "@app/components/v3";
import { useOrganization } from "@app/context";
-import { emailListSchema, parseEmailList } from "@app/helpers/email";
+import { emailListSchema, MAX_INVITE_EMAILS } from "@app/helpers/email";
import { findOrgMembershipRole } from "@app/helpers/roles";
import { useScopeVariant } from "@app/hooks";
import {
@@ -34,7 +34,7 @@ import {
import { DEFAULT_PROJECT_ROLE } from "./ProjectRoleSelect";
const addMemberFormSchema = projectAssignmentSchema.extend({
- emails: emailListSchema,
+ emails: emailListSchema({ max: MAX_INVITE_EMAILS, isRequired: true }),
organizationRole: z.object({
name: z.string(),
slug: z.string(),
@@ -74,7 +74,8 @@ export const AddOrgMemberModal = ({
});
const methods = useForm<TAddMemberForm>({
- resolver: zodResolver(addMemberFormSchema)
+ resolver: zodResolver(addMemberFormSchema),
+ defaultValues: { emails: [] }
});
const {
control,
@@ -87,6 +88,7 @@ export const AddOrgMemberModal = ({
useEffect(() => {
if (organizationRoles) {
reset({
+ emails: [],
organizationRole: findOrgMembershipRole(
organizationRoles,
currentOrg.defaultMembershipRole
@@ -108,10 +110,9 @@ export const AddOrgMemberModal = ({
const targetProjects = resolveTargetProjects(product, projectsToInvite, rawProjects);
if (!targetProjects) return;
- const usernames = parseEmailList(emails);
const { data } = await addUsersMutateAsync({
organizationId: currentOrg?.id,
- inviteeEmails: usernames,
+ inviteeEmails: emails,
organizationRoleSlug: organizationRole.slug
});
@@ -122,7 +123,7 @@ export const AddOrgMemberModal = ({
projectId: el.id,
projectType: el.type,
roleSlugs: [projectRole.slug],
- usernames
+ usernames: emails
})
)
);
@@ -136,7 +137,7 @@ export const AddOrgMemberModal = ({
if (!data.completeInviteLinks?.length) {
createNotification({
- text: `Successfully invited user${usernames.length > 1 ? "s" : ""} to the organization.`,
+ text: `Successfully invited user${emails.length > 1 ? "s" : ""} to the organization.`,
type: "success"
});
}
@@ -146,7 +147,7 @@ export const AddOrgMemberModal = ({
}
reset({
- emails: "",
+ emails: [],
product: undefined,
projects: [],
projectRole: DEFAULT_PROJECT_ROLE,
@@ -181,15 +182,16 @@ export const AddOrgMemberModal = ({
<Controller
control={control}
name="emails"
- render={({ field, fieldState: { error } }) => (
+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (
<Field>
<FieldLabel htmlFor="add-org-member-emails">Emails</FieldLabel>
- <TextArea
+ <EmailInput
+ ref={ref}
id="add-org-member-emails"
- className="h-24"
+ value={value}
+ onValueChange={onChange}
isError={Boolean(error)}
- {...field}
/>
<FieldError>{error?.message}</FieldError>
</Field>
diff --git a/frontend/src/pages/organization/SecretInsightsPage/components/RequestOrgAuditReportModal.tsx b/frontend/src/pages/organization/SecretInsightsPage/components/RequestOrgAuditReportModal.tsx
index 58476f56c9..315b07356a 100644
--- a/frontend/src/pages/organization/SecretInsightsPage/components/RequestOrgAuditReportModal.tsx
+++ b/frontend/src/pages/organization/SecretInsightsPage/components/RequestOrgAuditReportModal.tsx
@@ -12,13 +12,14 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
+ EmailInput,
Field,
FieldContent,
FieldDescription,
FieldError,
- FieldLabel,
- TextArea
+ FieldLabel
} from "@app/components/v3";
+import { emailListSchema } from "@app/helpers/email";
import { OrgAuditReportType, useRequestOrgAuditReport } from "@app/hooks/api/auditReports";
import {
@@ -28,23 +29,11 @@ import {
ORG_AUDIT_REPORT_TYPES_REQUIRING_AUDIT_LOG
} from "./orgAuditReportMeta";
-const parseEmails = (raw?: string): string[] =>
- (raw ?? "")
- .split(/[\s,]+/)
- .map((email) => email.trim())
- .filter(Boolean);
+const MAX_AUDIT_REPORT_RECIPIENTS = 20;
const formSchema = z.object({
reportTypes: z.nativeEnum(OrgAuditReportType).array().min(1, "Select at least one report type"),
- emailRecipients: z
- .string()
- .optional()
- .refine(
- (value) => parseEmails(value).every((email) => z.string().email().safeParse(email).success),
- {
- message: "Enter valid, comma-separated email addresses"
- }
- )
+ emailRecipients: emailListSchema({ max: MAX_AUDIT_REPORT_RECIPIENTS })
});
type TFormSchema = z.infer<typeof formSchema>;
@@ -73,7 +62,7 @@ export const RequestOrgAuditReportModal = ({
formState: { isSubmitting }
} = useForm<TFormSchema>({
resolver: zodResolver(formSchema),
- defaultValues: { reportTypes: [], emailRecipients: "" }
+ defaultValues: { reportTypes: [], emailRecipients: [] }
});
const handleClose = (open: boolean) => {
@@ -82,7 +71,7 @@ export const RequestOrgAuditReportModal = ({
};
const onSubmit = async (data: TFormSchema) => {
- const recipients = parseEmails(data.emailRecipients);
+ const recipients = data.emailRecipients;
try {
await requestOrgAuditReport.mutateAsync({
reports: data.reportTypes.map((type) => ({ type })),
@@ -170,14 +159,15 @@ export const RequestOrgAuditReportModal = ({
<Field>
<FieldLabel>Email recipients</FieldLabel>
<FieldContent>
- <TextArea
- {...field}
+ <EmailInput
+ ref={field.ref}
+ value={field.value}
+ onValueChange={field.onChange}
+ aria-label="Email recipients"
isError={Boolean(error)}
/>
- <FieldDescription>
- Comma-separated emails. Defaults to your own email when left blank.
- </FieldDescription>
+ <FieldDescription>Defaults to your own email when left blank.</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
diff --git a/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx b/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
index f5c5bd3587..12fdf757f1 100644
--- a/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
+++ b/frontend/src/pages/organization/SignupOnboardingPage/SignupOnboardingPage.tsx
@@ -41,7 +41,7 @@ export const SignupOnboardingPage = () => {
const [section, setSection] = useState<OnboardingSection>(OnboardingSection.Loading);
const [orgId, setOrgId] = useState("");
- const [inviteEmails, setInviteEmails] = useState("");
+ const [inviteEmails, setInviteEmails] = useState<string[]>([]);
const projectCache = useRef<Partial<Record<SignupProductType, Project>>>({});
// An empty selection means "just exploring".
const [selectedProducts, setSelectedProducts] = useState<SignupProductType[]>([]);
diff --git a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
index 1b43a9f285..42d10daab3 100644
--- a/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
+++ b/frontend/src/pages/project/AccessControlPage/components/MembersTab/components/AddMemberModal.tsx
@@ -36,6 +36,7 @@ import {
useProject,
useProjectPermission
} from "@app/context";
+import { isValidEmail } from "@app/helpers/email";
import { getProjectLabel, hidesProjects } from "@app/helpers/project";
import {
useAddUserToWsNonE2EE,
@@ -331,7 +332,7 @@ export const AddMemberModal = ({ popUp, handlePopUpToggle }: Props) => {
formatCreateLabel={(inputValue) => `Invite "${inputValue}"`}
isValidNewOption={(input) =>
Boolean(input) &&
- z.string().email().safeParse(input).success &&
+ isValidEmail(input) &&
!orgUsers
?.flatMap(({ user }) => {
const emails: string[] = [];
diff --git a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
index cf5f7a9447..cd62bbc5c2 100644
--- a/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
+++ b/frontend/src/pages/public/ShareSecretPage/components/ShareSecretForm.tsx
@@ -24,6 +24,7 @@ import {
Badge,
Button,
CopyButton,
+ EmailInput,
Field,
FieldDescription,
FieldError,
@@ -47,6 +48,7 @@ import {
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
+import { emailListSchema } from "@app/helpers/email";
import { useToggle } from "@app/hooks";
import { useCreatePublicSharedSecret, useCreateSharedSecret } from "@app/hooks/api";
import { SecretSharingAccessType } from "@app/hooks/api/secretSharing";
@@ -65,14 +67,6 @@ const expiresInOptions = [
const MAX_RECIPIENTS = 100;
const ABSOLUTE_VIEW_CEILING = 1000;
-const parseRecipients = (emails?: string) =>
- emails
- ? emails
- .split(",")
- .map((email) => email.trim())
- .filter(Boolean)
- : [];
-
const baseSchema = z.object({
name: z.string().max(50, "Name must be 50 characters or fewer.").optional(),
password: z.string().optional(),
@@ -81,19 +75,7 @@ const baseSchema = z.object({
viewLimit: z.string(),
shouldLimitView: z.boolean(),
accessType: z.nativeEnum(SecretSharingAccessType).optional(),
- emails: z
- .string()
- .optional()
- .refine(
- (val) => {
- const recipients = parseRecipients(val);
- if (recipients.length > MAX_RECIPIENTS) return false;
- return recipients.every((email) => z.string().email().safeParse(email).success);
- },
- {
- message: `Enter up to ${MAX_RECIPIENTS} valid emails, separated by commas.`
- }
- ),
+ emails: emailListSchema({ max: MAX_RECIPIENTS }).optional(),
allowExternalEmails: z.boolean().optional()
});
@@ -120,7 +102,7 @@ const buildSchema = (maxSharedSecretViewLimit?: number | null) =>
}
}
- if (data.allowExternalEmails && parseRecipients(data.emails).length > 0 && !data.password) {
+ if (data.allowExternalEmails && data.emails?.length && !data.password) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["password"],
@@ -225,7 +207,7 @@ export const ShareSecretForm = ({
isLimitingView,
Boolean(watch("password")),
!isPublic && isOrgAccess,
- !isPublic && !isAllowingExternalEmails && parseRecipients(watch("emails")).length > 0
+ !isPublic && !isAllowingExternalEmails && Boolean(watch("emails")?.length)
].filter(Boolean).length;
const onFormSubmit = async ({
@@ -239,7 +221,7 @@ export const ShareSecretForm = ({
shouldLimitView,
allowExternalEmails
}: FormData) => {
- const recipients = parseRecipients(emails);
+ const recipients = emails ?? [];
const { id } = await createSharedSecret.mutateAsync({
name,
@@ -664,11 +646,12 @@ export const ShareSecretForm = ({
</TooltipContent>
</Tooltip>
</FieldLabel>
- <Input
- {...field}
+ <EmailInput
+ ref={field.ref}
id="share-secret-emails"
+ value={field.value}
+ onValueChange={field.onChange}
- autoComplete="off"
isError={Boolean(error)}
/>
<FieldDescription>
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx
index 18bdc77993..2715514180 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/RequestAuditReportModal.tsx
@@ -12,13 +12,14 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
+ EmailInput,
Field,
FieldContent,
FieldDescription,
FieldError,
- FieldLabel,
- TextArea
+ FieldLabel
} from "@app/components/v3";
+import { emailListSchema } from "@app/helpers/email";
import { AuditReportType, useRequestAuditReport } from "@app/hooks/api/auditReports";
import {
@@ -27,23 +28,9 @@ import {
AUDIT_REPORT_TYPES_ORDERED
} from "./auditReportMeta";
-const parseEmails = (raw?: string): string[] =>
- (raw ?? "")
- .split(/[\s,]+/)
- .map((email) => email.trim())
- .filter(Boolean);
-
const formSchema = z.object({
reportTypes: z.nativeEnum(AuditReportType).array().min(1, "Select at least one report type"),
- emailRecipients: z
- .string()
- .optional()
- .refine(
- (value) => parseEmails(value).every((email) => z.string().email().safeParse(email).success),
- {
- message: "Enter valid, comma-separated email addresses"
- }
- )
+ emailRecipients: emailListSchema()
});
type TFormSchema = z.infer<typeof formSchema>;
@@ -64,7 +51,7 @@ export const RequestAuditReportModal = ({ isOpen, onOpenChange, projectId }: Pro
formState: { isSubmitting }
} = useForm<TFormSchema>({
resolver: zodResolver(formSchema),
- defaultValues: { reportTypes: [], emailRecipients: "" }
+ defaultValues: { reportTypes: [], emailRecipients: [] }
});
const handleClose = (open: boolean) => {
@@ -73,7 +60,7 @@ export const RequestAuditReportModal = ({ isOpen, onOpenChange, projectId }: Pro
};
const onSubmit = async (data: TFormSchema) => {
- const recipients = parseEmails(data.emailRecipients);
+ const recipients = data.emailRecipients;
try {
await requestAuditReport.mutateAsync({
projectId,
@@ -163,14 +150,15 @@ export const RequestAuditReportModal = ({ isOpen, onOpenChange, projectId }: Pro
<Field>
<FieldLabel>Email recipients</FieldLabel>
<FieldContent>
- <TextArea
- {...field}
+ <EmailInput
+ ref={field.ref}
+ value={field.value}
+ onValueChange={field.onChange}
+ aria-label="Email recipients"
isError={Boolean(error)}
/>
- <FieldDescription>
- Comma-separated emails. Defaults to your own email when left blank.
- </FieldDescription>
+ <FieldDescription>Defaults to your own email when left blank.</FieldDescription>
<FieldError errors={[error]} />
</FieldContent>
</Field>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx
index 87c97028b6..0a0f23fc36 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersModal/InviteMembersModal.tsx
@@ -14,17 +14,17 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
+ EmailInput,
Field,
FieldError,
FieldLabel,
FilterableSelect,
- TextArea,
Tooltip,
TooltipContent,
TooltipTrigger
} from "@app/components/v3";
import { useOrganization, useProject, useProjectPermission } from "@app/context";
-import { emailListSchema, parseEmailList } from "@app/helpers/email";
+import { emailListSchema, MAX_INVITE_EMAILS } from "@app/helpers/email";
import { useAddUserToWsNonE2EE, useGetProjectRoles } from "@app/hooks/api";
import { ProjectVersion } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -35,7 +35,7 @@ import { filterByGrantConditions, getMemberAssignRoleConditions } from "@app/lib
const DEFAULT_PROJECT_ROLE = { slug: "member", name: "Member" };
const inviteMembersFormSchema = z.object({
- emails: emailListSchema,
+ emails: emailListSchema({ max: MAX_INVITE_EMAILS, isRequired: true }),
projectRole: z
.object({
slug: z.string().min(1),
@@ -87,7 +87,7 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle, experimentVariant
formState: { isSubmitting }
} = useForm<TInviteMembersForm>({
resolver: zodResolver(inviteMembersFormSchema),
- defaultValues: { emails: "", projectRole: DEFAULT_PROJECT_ROLE }
+ defaultValues: { emails: [], projectRole: DEFAULT_PROJECT_ROLE }
});
const { mutateAsync: addUserToProject } = useAddUserToWsNonE2EE();
@@ -126,10 +126,9 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle, experimentVariant
return;
}
- const usernames = parseEmailList(emails);
- if (usernames.length) {
+ if (emails.length) {
await addUserToProject({
- usernames,
+ usernames: emails,
orgId: currentOrg.id,
projectId: currentProject.id,
projectType: currentProject.type,
@@ -139,7 +138,7 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle, experimentVariant
analytics.captureForOrganization(AnalyticsEvent.SecretsActivationModalMembersInvited, orgId, {
...baseEventProps,
- invitedCount: usernames.length
+ invitedCount: emails.length
});
createNotification({
@@ -175,16 +174,16 @@ export const InviteMembersModal = ({ popUp, handlePopUpToggle, experimentVariant
<Controller
control={control}
name="emails"
- render={({ field, fieldState: { error } }) => (
+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (
<Field>
<FieldLabel htmlFor="invite-members-emails">Emails</FieldLabel>
- <TextArea
+ <EmailInput
+ ref={ref}
id="invite-members-emails"
- rows={1}
- className="min-h-8"
+ value={value}
+ onValueChange={onChange}
isError={Boolean(error)}
- {...field}
/>
<FieldError>{error?.message}</FieldError>
</Field>
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersNudge/InviteMembersNudge.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersNudge/InviteMembersNudge.tsx
index 639d9939ce..ff1de0d50d 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersNudge/InviteMembersNudge.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/InviteMembersNudge/InviteMembersNudge.tsx
@@ -11,15 +11,15 @@ import {
Card,
CardDescription,
CardTitle,
+ EmailInput,
Field,
FieldDescription,
FieldError,
FieldLabel,
- IconButton,
- Input
+ IconButton
} from "@app/components/v3";
import { useOrganization, useProject, useProjectPermission } from "@app/context";
-import { emailListSchema, parseEmailList } from "@app/helpers/email";
+import { emailListSchema, MAX_INVITE_EMAILS } from "@app/helpers/email";
import { useAddUserToWsNonE2EE, useGetProjectRoles } from "@app/hooks/api";
import { ProjectVersion } from "@app/hooks/api/projects/types";
import { UsePopUpState } from "@app/hooks/usePopUp";
@@ -32,7 +32,7 @@ import { useFloatingBarClearance } from "./useFloatingBarClearance";
const SUCCESS_AUTO_DISMISS_MS = 3000;
const inviteMembersNudgeFormSchema = z.object({
- emails: emailListSchema
+ emails: emailListSchema({ max: MAX_INVITE_EMAILS, isRequired: true })
});
export const InviteMembersNudge = ({ popUp, handlePopUpToggle, isLifted = false }: Props) => {
@@ -73,7 +73,7 @@ export const InviteMembersNudge = ({ popUp, handlePopUpToggle, isLifted = false
formState: { isSubmitting }
} = useForm<TInviteMembersNudgeForm>({
resolver: zodResolver(inviteMembersNudgeFormSchema),
- defaultValues: { emails: "" }
+ defaultValues: { emails: [] }
});
const { mutateAsync: addUserToProject } = useAddUserToWsNonE2EE();
@@ -137,10 +137,9 @@ export const InviteMembersNudge = ({ popUp, handlePopUpToggle, isLifted = false
return;
}
- const usernames = parseEmailList(emails);
- if (usernames.length) {
+ if (emails.length) {
await addUserToProject({
- usernames,
+ usernames: emails,
orgId: currentOrg.id,
projectId: currentProject.id,
projectType: currentProject.type,
@@ -150,7 +149,7 @@ export const InviteMembersNudge = ({ popUp, handlePopUpToggle, isLifted = false
analytics.captureForOrganization(AnalyticsEvent.SecretsActivationModalMembersInvited, orgId, {
...baseEventProps,
- invitedCount: usernames.length
+ invitedCount: emails.length
});
createNotification({
@@ -242,17 +241,17 @@ export const InviteMembersNudge = ({ popUp, handlePopUpToggle, isLifted = false
<Controller
control={control}
name="emails"
- render={({ field, fieldState: { error } }) => (
+ render={({ field: { value, onChange, ref }, fieldState: { error } }) => (
<Field>
<FieldLabel htmlFor="invite-members-nudge-emails">Emails</FieldLabel>
- <Input
+ <EmailInput
+ ref={ref}
id="invite-members-nudge-emails"
- type="text"
- autoComplete="off"
+ value={value}
+ onValueChange={onChange}
isError={Boolean(error)}
- disabled={!canSubmit}
+ isDisabled={!canSubmit}
- {...field}
/>
<FieldDescription>{roleDescription}</FieldDescription>
<FieldError>{error?.message}</FieldError>