Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

reusable MultiValueInput component

Steven Tey8832f78808ff
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/invite-partner-sheet.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/invite-partner-sheet.tsx
index 869ded4d36..96cdf1ba1c 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/invite-partner-sheet.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/partners/invite-partner-sheet.tsx
@@ -13,6 +13,8 @@ import {
BlurImage,
Button,
InfoTooltip,
+ MultiValueInput,
+ type MultiValueInputRef,
RichTextArea,
RichTextProvider,
RichTextToolbar,
@@ -45,8 +47,6 @@ type EmailContent = {
body: string;
};
-const invitePartnerEmailSchema = z.email().trim().min(1).max(100);
-
function InvitePartnerSheetContent({ setIsOpen }: InvitePartnerSheetProps) {
const { program, mutate } = useProgram<
ProgramProps & { inviteEmailData: ProgramInviteEmailData }
@@ -101,117 +101,9 @@ function InvitePartnerSheetContent({ setIsOpen }: InvitePartnerSheetProps) {
},
});
- const [recipientEmails, setRecipientEmails] = useState<string[]>([]);
- const [emailInput, setEmailInput] = useState("");
- const [selectedRecipientEmail, setSelectedRecipientEmail] = useState<
- string | null
- >(null);
- const emailInputRef = useRef<HTMLInputElement>(null);
- const emailFieldRef = useRef<HTMLDivElement>(null);
- const [isEmailFieldWrapped, setIsEmailFieldWrapped] = useState(false);
- const hasMultipleRecipients = recipientEmails.length > 1;
-
- const handleEmailInputChange = (value: string) => {
- emailInputRef.current?.setCustomValidity("");
- setSelectedRecipientEmail(null);
- setEmailInput(value);
- };
-
- const handleEmailInputKeyDown = (
- e: React.KeyboardEvent<HTMLInputElement>,
- ) => {
- const inputElement = e.currentTarget;
- const selectedIndex = selectedRecipientEmail
- ? recipientEmails.findIndex((email) => email === selectedRecipientEmail)
- : -1;
-
- if (e.key === "," || e.key === "Enter") {
- e.preventDefault();
- commitEmailInput();
- return;
- }
-
- if (e.key === "ArrowLeft" && recipientEmails.length > 0) {
- // Move chip selection left from the input caret, then across chips.
- if (selectedIndex > 0) {
- e.preventDefault();
- setSelectedRecipientEmail(recipientEmails[selectedIndex - 1]);
- return;
- }
-
- if (
- selectedIndex === -1 &&
- inputElement.selectionStart === 0 &&
- inputElement.selectionEnd === 0
- ) {
- e.preventDefault();
- setSelectedRecipientEmail(recipientEmails[recipientEmails.length - 1]);
- return;
- }
- }
-
- if (e.key === "ArrowRight" && selectedIndex !== -1) {
- e.preventDefault();
-
- if (selectedIndex < recipientEmails.length - 1) {
- setSelectedRecipientEmail(recipientEmails[selectedIndex + 1]);
- return;
- }
-
- // Return to regular input cursor mode.
- setSelectedRecipientEmail(null);
- return;
- }
-
- if (
- (e.key === "Backspace" || e.key === "Delete") &&
- !emailInput &&
- recipientEmails.length > 0
- ) {
- e.preventDefault();
-
- if (selectedRecipientEmail) {
- setRecipientEmails((prev) =>
- prev.filter((email) => email !== selectedRecipientEmail),
- );
- setSelectedRecipientEmail(null);
- return;
- }
-
- setSelectedRecipientEmail(recipientEmails[recipientEmails.length - 1]);
- }
-
- if (e.key === "Tab" && selectedRecipientEmail) {
- e.preventDefault();
- setSelectedRecipientEmail(null);
- }
- };
-
- useEffect(() => {
- const container = emailFieldRef.current;
- if (!container) return;
-
- const checkWrappedState = () => {
- const children = Array.from(container.children) as HTMLElement[];
-
- if (children.length <= 1) {
- setIsEmailFieldWrapped(false);
- return;
- }
-
- const tops = children.map((el) => el.offsetTop);
- const firstRowTop = Math.min(...tops);
- const wrapped = tops.some((top) => top - firstRowTop > 2);
- setIsEmailFieldWrapped(wrapped);
- };
-
- checkWrappedState();
-
- const observer = new ResizeObserver(checkWrappedState);
- observer.observe(container);
-
- return () => observer.disconnect();
- }, [recipientEmails, emailInput]);
+ const multiValueInputRef = useRef<MultiValueInputRef>(null);
+ const emails = watch("emails") ?? [];
+ const hasMultipleRecipients = emails.length > 1;
const { executeAsync, isPending } = useAction(invitePartnerAction, {
onSuccess: ({ data }) => {
@@ -262,112 +154,24 @@ function InvitePartnerSheetContent({ setIsOpen }: InvitePartnerSheetProps) {
},
});
- useEffect(() => {
- setValue("emails", recipientEmails, {
- shouldDirty: true,
- shouldValidate: true,
- });
- setValue("email", recipientEmails[0], {
- shouldDirty: true,
- shouldValidate: true,
- });
- }, [recipientEmails, setValue]);
-
- useEffect(() => {
- if (
- selectedRecipientEmail &&
- !recipientEmails.includes(selectedRecipientEmail)
- ) {
- setSelectedRecipientEmail(null);
- }
- }, [recipientEmails, selectedRecipientEmail]);
-
- const addRecipientEmail = (rawValue: string) => {
- const normalizedValue = rawValue.trim().toLowerCase();
-
- if (!normalizedValue) {
- return true;
- }
-
- const parsedEmail = invitePartnerEmailSchema.safeParse(normalizedValue);
-
- if (!parsedEmail.success) {
- emailInputRef.current?.setCustomValidity(
- "Please enter a valid email address.",
- );
- emailInputRef.current?.reportValidity();
- return false;
- }
-
- setRecipientEmails((prev) => {
- if (prev.includes(normalizedValue)) {
- return prev;
- }
-
- return [...prev, normalizedValue];
- });
- emailInputRef.current?.setCustomValidity("");
-
- return true;
- };
-
- const commitEmailInput = () => {
- const emailCandidates = emailInput
- .split(",")
- .map((value) => value.trim())
- .filter(Boolean);
-
- if (emailCandidates.length === 0) {
- setEmailInput("");
- return true;
- }
-
- for (const candidate of emailCandidates) {
- const wasAdded = addRecipientEmail(candidate);
-
- if (!wasAdded) {
- return false;
- }
- }
-
- setEmailInput("");
- return true;
- };
-
const onSubmit = async (data: InvitePartnerFormData) => {
if (!workspaceId || !program?.id) {
return;
}
- const didCommitPendingInput = commitEmailInput();
-
- if (!didCommitPendingInput) {
- return;
- }
+ const finalEmails =
+ multiValueInputRef.current?.commitPendingInput() ?? data.emails ?? [];
- const finalRecipientEmails = Array.from(
- new Set([
- ...recipientEmails,
- ...emailInput
- .split(",")
- .map((value) => value.trim().toLowerCase())
- .filter(Boolean),
- ]),
- );
-
- if (finalRecipientEmails.length === 0) {
- emailInputRef.current?.setCustomValidity(
- "Please enter at least one email address.",
- );
- emailInputRef.current?.reportValidity();
+ if (finalEmails.length === 0) {
+ toast.error("Please enter at least one email address.");
return;
}
await executeAsync({
...data,
- email: finalRecipientEmails[0],
- emails: finalRecipientEmails,
- ...(finalRecipientEmails.length > 1
+ email: finalEmails[0],
+ emails: finalEmails,
+ ...(finalEmails.length > 1
? { name: undefined, username: undefined }
: {}),
workspaceId,
@@ -454,72 +258,30 @@ function InvitePartnerSheetContent({ setIsOpen }: InvitePartnerSheetProps) {
Email
</label>
- <div
- ref={emailFieldRef}
- className={cn(
- "relative mt-2 flex w-full flex-wrap items-center gap-1 rounded-md border border-neutral-300 bg-white px-1.5 shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
- isEmailFieldWrapped ? "py-[4px]" : "h-[38px] py-[3px]",
- )}
- >
- {recipientEmails.map((recipientEmail) => (
- <span
- key={recipientEmail}
- onClick={() => setSelectedRecipientEmail(recipientEmail)}
- className={cn(
- "inline-flex items-center gap-1 rounded-md pl-1.5 pr-1 py-0.5 text-sm leading-6",
- selectedRecipientEmail === recipientEmail
- ? "bg-neutral-300 text-neutral-900"
- : "bg-neutral-100 text-neutral-900",
- )}
- >
- <span>{recipientEmail}</span>
- <Button
- type="button"
- variant="outline"
- icon={<X className="size-3" strokeWidth={2.5} />}
- onClick={(e) => {
- e.stopPropagation();
- setSelectedRecipientEmail((prev) =>
- prev === recipientEmail ? null : prev,
- );
- setRecipientEmails((prev) =>
- prev.filter((email) => email !== recipientEmail),
- );
- }}
- className={cn(
- "h-auto w-fit rounded-md p-0.5 shadow-none",
- selectedRecipientEmail === recipientEmail
- ? "text-neutral-600 hover:text-neutral-800"
- : "text-neutral-500 hover:text-neutral-700",
- )}
- />
- </span>
- ))}
- <div className="min-w-[8rem] flex-[1_1_8rem]">
- <input
- ref={emailInputRef}
- id="partner-email-input"
- value={emailInput}
- onChange={(e) => handleEmailInputChange(e.target.value)}
- onKeyDown={handleEmailInputKeyDown}
- onBlur={() => {
- setSelectedRecipientEmail(null);
- commitEmailInput();
- }}
- className={cn(
- "h-7 w-full border-0 bg-transparent px-1.5 text-sm leading-6 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0",
- selectedRecipientEmail &&
- "caret-transparent text-transparent placeholder:text-transparent",
- )}
- placeholder="[email protected]"
- type="text"
- autoComplete="off"
- autoFocus={!isMobile}
- />
- </div>
+ <div className="mt-2">
+ <MultiValueInput
+ ref={multiValueInputRef}
+ id="partner-email-input"
+ values={emails}
+ onChange={(values) => {
+ setValue("emails", values, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ setValue("email", values[0] ?? "", {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ }}
+ placeholder="[email protected]"
+ normalize={(v) => v.trim().toLowerCase()}
+ maxValues={50}
+ disabled={isEditingEmail || isSavingEmailData}
+ autoFocus={!isMobile}
+ />
</div>
<p className="mt-2 text-xs text-neutral-500">
- Separate multiple emails with commas
+ Separate multiple emails with commas, or paste a list
</p>
</div>
@@ -626,10 +388,7 @@ function InvitePartnerSheetContent({ setIsOpen }: InvitePartnerSheetProps) {
className="w-fit"
loading={isPending || isSubmitting || isSubmitSuccessful}
disabled={
- isPending ||
- (recipientEmails.length === 0 && emailInput.trim().length === 0) ||
- isEditingEmail ||
- isSavingEmailData
+ isPending || isEditingEmail || isSavingEmailData
}
/>
</div>
diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx
index 8a8ddba900..eb468c27f0 100644
--- a/packages/ui/src/index.tsx
+++ b/packages/ui/src/index.tsx
@@ -23,6 +23,7 @@ export * from "./form";
export * from "./grid";
export * from "./input";
export * from "./label";
+export * from "./multi-value-input";
export * from "./menu-item";
export * from "./mini-area-chart";
export * from "./modal";
diff --git a/packages/ui/src/multi-value-input.tsx b/packages/ui/src/multi-value-input.tsx
new file mode 100644
index 0000000000..a0b815a034
--- /dev/null
+++ b/packages/ui/src/multi-value-input.tsx
@@ -0,0 +1,311 @@
+"use client";
+
+import { cn } from "@dub/utils";
+import { X } from "lucide-react";
+import React, {
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+} from "react";
+
+/**
+ * Parses CSV-like pasted text: splits on commas and newlines, and respects
+ * double-quoted fields (commas/newlines inside quotes are kept).
+ */
+function parseCsvLikeValues(raw: string): string[] {
+ const result: string[] = [];
+ let current = "";
+ let inQuotes = false;
+
+ for (let i = 0; i < raw.length; i++) {
+ const c = raw[i];
+
+ if (c === '"') {
+ inQuotes = !inQuotes;
+ continue;
+ }
+
+ if (!inQuotes && (c === "," || c === "\n" || c === "\r")) {
+ // Treat \r\n as single newline
+ if (c === "\r" && raw[i + 1] === "\n") i++;
+ const trimmed = current.trim();
+ if (trimmed) result.push(trimmed);
+ current = "";
+ continue;
+ }
+
+ current += c;
+ }
+
+ const trimmed = current.trim();
+ if (trimmed) result.push(trimmed);
+ return result;
+}
+
+export interface MultiValueInputRef {
+ /** Commits any pending input, updates parent, and returns the full list. */
+ commitPendingInput: () => string[];
+}
+
+export interface MultiValueInputProps {
+ values: string[];
+ onChange: (values: string[]) => void;
+ placeholder?: string;
+ id?: string;
+ className?: string;
+ inputClassName?: string;
+ disabled?: boolean;
+ autoFocus?: boolean;
+ /** Optional normalizer for each value when adding (e.g. trim + lowercase). */
+ normalize?: (value: string) => string;
+ /** Optional max number of values (no limit if omitted). */
+ maxValues?: number;
+}
+
+const MultiValueInput = React.forwardRef<
+ MultiValueInputRef,
+ MultiValueInputProps
+>(function MultiValueInput(
+ {
+ values,
+ onChange,
+ placeholder,
+ id,
+ className,
+ inputClassName,
+ disabled,
+ normalize = (v) => v.trim(),
+ maxValues,
+ autoFocus,
+ },
+ ref,
+) {
+ const [inputValue, setInputValue] = useState("");
+ const [selectedValue, setSelectedValue] = useState<string | null>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [isWrapped, setIsWrapped] = useState(false);
+
+ const addValues = useCallback(
+ (candidates: string[]) => {
+ const normalized = candidates
+ .map(normalize)
+ .filter(Boolean)
+ .filter((v) => !values.includes(v));
+ if (normalized.length === 0) return values;
+ const next = [...values];
+ for (const v of normalized) {
+ if (maxValues != null && next.length >= maxValues) break;
+ next.push(v);
+ }
+ return next;
+ },
+ [values, normalize, maxValues],
+ );
+
+ const commitPendingInput = useCallback((): string[] => {
+ const parsed = parseCsvLikeValues(inputValue);
+ if (parsed.length === 0) {
+ setInputValue("");
+ return values;
+ }
+ const next = addValues(parsed);
+ onChange(next);
+ setInputValue("");
+ return next;
+ }, [inputValue, values, addValues, onChange]);
+
+ useImperativeHandle(
+ ref,
+ () => ({
+ commitPendingInput() {
+ return commitPendingInput();
+ },
+ }),
+ [commitPendingInput],
+ );
+
+ // Clear selection when the selected value is removed from the list
+ useEffect(() => {
+ if (selectedValue && !values.includes(selectedValue)) {
+ setSelectedValue(null);
+ }
+ }, [values, selectedValue]);
+
+ // ResizeObserver for wrapped layout
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ const checkWrapped = () => {
+ const children = Array.from(container.children) as HTMLElement[];
+ if (children.length <= 1) {
+ setIsWrapped(false);
+ return;
+ }
+ const tops = children.map((el) => el.offsetTop);
+ const firstRowTop = Math.min(...tops);
+ setIsWrapped(tops.some((top) => top - firstRowTop > 2));
+ };
+
+ checkWrapped();
+ const observer = new ResizeObserver(checkWrapped);
+ observer.observe(container);
+ return () => observer.disconnect();
+ }, [values, inputValue]);
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ const inputEl = e.currentTarget;
+ const selectedIndex = selectedValue ? values.indexOf(selectedValue) : -1;
+
+ if (e.key === "," || e.key === "Enter") {
+ e.preventDefault();
+ commitPendingInput();
+ return;
+ }
+
+ if (e.key === "ArrowLeft" && values.length > 0) {
+ if (selectedIndex > 0) {
+ e.preventDefault();
+ setSelectedValue(values[selectedIndex - 1]);
+ return;
+ }
+ if (
+ selectedIndex === -1 &&
+ inputEl.selectionStart === 0 &&
+ inputEl.selectionEnd === 0
+ ) {
+ e.preventDefault();
+ setSelectedValue(values[values.length - 1]);
+ return;
+ }
+ }
+
+ if (e.key === "ArrowRight" && selectedIndex !== -1) {
+ e.preventDefault();
+ if (selectedIndex < values.length - 1) {
+ setSelectedValue(values[selectedIndex + 1]);
+ return;
+ }
+ setSelectedValue(null);
+ return;
+ }
+
+ if (
+ (e.key === "Backspace" || e.key === "Delete") &&
+ !inputValue &&
+ values.length > 0
+ ) {
+ e.preventDefault();
+ if (selectedValue) {
+ const next = values.filter((v) => v !== selectedValue);
+ onChange(next);
+ setSelectedValue(null);
+ return;
+ }
+ setSelectedValue(values[values.length - 1]);
+ }
+
+ if (e.key === "Tab" && selectedValue) {
+ e.preventDefault();
+ setSelectedValue(null);
+ }
+ };
+
+ const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
+ const pasted = e.clipboardData.getData("text");
+ const parsed = parseCsvLikeValues(pasted);
+ if (parsed.length === 0) return;
+
+ e.preventDefault();
+ const next = addValues(parsed);
+ onChange(next);
+ setInputValue("");
+ };
+
+ const handleBlur = () => {
+ setSelectedValue(null);
+ const next = commitPendingInput();
+ if (next !== values) onChange(next);
+ };
+
+ const removeValue = (value: string) => {
+ setSelectedValue((prev) => (prev === value ? null : prev));
+ onChange(values.filter((v) => v !== value));
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className={cn(
+ "relative flex w-full flex-wrap items-center gap-1 rounded-md border border-neutral-300 bg-white px-1.5 shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",
+ isWrapped ? "py-[4px]" : "h-[38px] py-[3px]",
+ disabled && "cursor-not-allowed bg-neutral-50 opacity-60",
+ className,
+ )}
+ >
+ {values.map((value) => (
+ <span
+ key={value}
+ onClick={() => setSelectedValue(value)}
+ className={cn(
+ "inline-flex items-center gap-1 rounded-md py-0.5 pl-1.5 pr-1 text-sm leading-6",
+ selectedValue === value
+ ? "bg-neutral-300 text-neutral-900"
+ : "bg-neutral-100 text-neutral-900",
+ )}
+ >
+ <span>{value}</span>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ removeValue(value);
+ }}
+ disabled={disabled}
+ className={cn(
+ "rounded-md p-0.5 outline-none transition hover:bg-neutral-200 focus:ring-1 focus:ring-neutral-400",
+ selectedValue === value
+ ? "text-neutral-600 hover:text-neutral-800"
+ : "text-neutral-500 hover:text-neutral-700",
+ )}
+ aria-label={`Remove ${value}`}
+ >
+ <X className="size-3" strokeWidth={2.5} aria-hidden />
+ </button>
+ </span>
+ ))}
+ <div className="min-w-[8rem] flex-[1_1_8rem]">
+ <input
+ ref={inputRef}
+ id={id}
+ value={inputValue}
+ onChange={(e) => {
+ setSelectedValue(null);
+ setInputValue(e.target.value);
+ }}
+ onKeyDown={handleKeyDown}
+ onBlur={handleBlur}
+ onPaste={handlePaste}
+ disabled={disabled}
+ className={cn(
+ "h-7 w-full border-0 bg-transparent px-1.5 text-sm leading-6 text-neutral-900 placeholder-neutral-400 focus:outline-none focus:ring-0",
+ selectedValue &&
+ "text-transparent caret-transparent placeholder:text-transparent",
+ inputClassName,
+ )}
+ placeholder={placeholder}
+ type="text"
+ autoComplete="off"
+ autoFocus={autoFocus}
+ />
+ </div>
+ </div>
+ );
+});
+
+MultiValueInput.displayName = "MultiValueInput";
+
+export { MultiValueInput };