Skip to content

add multi-email input component and refactor compose email form #386

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions apps/web/app/(app)/compose/ComposeEmailForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ import { isActionError } from "@/utils/error";
import { Tiptap, type TiptapHandle } from "@/components/editor/Tiptap";
import { sendEmailAction } from "@/utils/actions/mail";
import type { ContactsResponse } from "@/app/api/google/contacts/route";
import type { SendEmailBody } from "@/utils/gmail/mail";
import { CommandShortcut } from "@/components/ui/command";
import { useModifierKey } from "@/hooks/useModifierKey";
import ComposeMailBox from "@/app/(app)/compose/ComposeMailBox";
import { SendEmailBody } from "@/utils/gmail/mail";

export type ReplyingToEmail = {
threadId: string;
Expand Down Expand Up @@ -66,7 +67,8 @@ export const ComposeEmailForm = ({
replyToEmail: replyingToEmail,
subject: replyingToEmail?.subject,
to: replyingToEmail?.to,
cc: replyingToEmail?.cc,
cc: "",
bcc: "",
messageHtml: replyingToEmail?.draftHtml,
},
});
Expand All @@ -75,6 +77,9 @@ export const ComposeEmailForm = ({
async (data) => {
const enrichedData = {
...data,
to: Array.isArray(data.to) ? data.to.join(",") : data.to,
cc: Array.isArray(data.cc) ? data.cc.join(",") : data.cc,
bcc: Array.isArray(data.bcc) ? data.bcc.join(",") : data.bcc,
messageHtml: showFullContent
? data.messageHtml || ""
: `${data.messageHtml || ""}<br>${replyingToEmail?.quotedContentHtml || ""}`,
Expand Down Expand Up @@ -126,7 +131,10 @@ export const ComposeEmailForm = ({
);

// TODO not in love with how this was implemented
const selectedEmailAddressses = watch("to", "").split(",").filter(Boolean);
const toField = watch("to", "");
const selectedEmailAddressses = (
Array.isArray(toField) ? toField : toField.split(",")
).filter(Boolean);

const onRemoveSelectedEmail = (emailAddress: string) => {
const filteredEmailAddresses = selectedEmailAddressses.filter(
Expand Down Expand Up @@ -304,12 +312,12 @@ export const ComposeEmailForm = ({
</Combobox>
</div>
) : (
<Input
type="text"
name="to"
label="To"
registerProps={register("to", { required: true })}
error={errors.to}
<ComposeMailBox
to={watch("to")}
cc={watch("cc")}
bcc={watch("bcc")}
register={register}
errors={errors}
/>
)}

Expand Down
141 changes: 141 additions & 0 deletions apps/web/app/(app)/compose/ComposeMailBox.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import MultiEmailInput from "@/app/(app)/compose/MultiEmailInput";
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/utils";

enum CarbonCopyType {
CC = "cc",
BCC = "bcc",
}

type ComposeMailBoxProps = {
to: string;
cc?: string;
bcc?: string;
register: any;
errors?: any;
};

export default function ComposeMailBox(props: ComposeMailBoxProps) {
const { register, to, cc, bcc, errors } = props;

const [carbonCopy, setCarbonCopy] = useState({
cc: false,
bcc: false,
});

const showCC = carbonCopy.cc;
const showBCC = carbonCopy.bcc;

const toggleCarbonCopy = (type: CarbonCopyType) => {
setCarbonCopy((prev) => ({
...prev,
[type]: !prev[type],
}));
};

const moveToggleButtonsToNewLine =
carbonCopy.cc || carbonCopy.bcc || (to && to.length > 0);

return (
<div className={`relative flex flex-col gap-2 rounded-md border p-2`}>
<div className="flex items-center justify-between">
<MultiEmailInput
register={register}
name="to"
label="To"
className="flex-1"
error={errors?.to}
/>
{
// when no email is present, show the toggle buttons in-line.
!moveToggleButtonsToNewLine && (
<ToggleButtonsWrapper
toggleCarbonCopy={toggleCarbonCopy}
showCC={carbonCopy.cc}
showBCC={carbonCopy.bcc}
/>
)
}
</div>
{showCC && (
<MultiEmailInput
name="cc"
label="Cc"
register={register}
error={errors?.cc}
/>
)}
{showBCC && (
<MultiEmailInput
name="bcc"
label="Bcc"
register={register}
error={errors?.bcc}
/>
)}
{/* Moved ToggleButtonsWrapper to a new line below if email is present */}
{moveToggleButtonsToNewLine && (
<ToggleButtonsWrapper
toggleCarbonCopy={toggleCarbonCopy}
showCC={carbonCopy.cc}
showBCC={carbonCopy.bcc}
/>
)}
</div>
);
}

const ToggleButtonsWrapper = ({
toggleCarbonCopy,
showCC,
showBCC,
}: {
toggleCarbonCopy: (type: CarbonCopyType) => void;
showCC: boolean;
showBCC: boolean;
}) => {
return (
<div className="flex justify-end">
<div className="flex gap-1">
{[
!showCC && { type: CarbonCopyType.CC, width: "w-8" },
!showBCC && { type: CarbonCopyType.BCC, width: "w-10" },
]
.filter(Boolean)
.map(
(button) =>
button && (
<ToggleButton
key={button.type}
label={button.type}
className={button.width}
onClick={() => toggleCarbonCopy(button.type)}
/>
),
)}
</div>
</div>
);
};

const ToggleButton = ({
label,
className,
onClick,
}: {
label: string;
className?: string;
onClick: () => void;
}) => {
return (
<Button
size="sm"
variant={"outline"}
className={cn(`h-6 w-8 text-[10px]`, className)}
onClick={onClick}
>
{label}
</Button>
);
};
136 changes: 136 additions & 0 deletions apps/web/app/(app)/compose/MultiEmailInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
"use client";

import {
useState,
useRef,
useEffect,
type KeyboardEvent,
type ChangeEvent,
} from "react";
import { X } from "lucide-react";
import { Label } from "@/components/ui/label";
import { cn } from "@/utils";

interface MultiEmailInputProps {
name: string;
label: string;
placeholder?: string;
className?: string;
register?: any;
error?: any;
}

export default function MultiEmailInput({
name,
label = "To",
placeholder = "",
className = "",
register,
error,
}: MultiEmailInputProps) {
const [emails, setEmails] = useState<string[]>([]);
const [inputValue, setInputValue] = useState("");
const inputRef = useRef<HTMLInputElement>(null);

// Email validation regex
const isValidEmail = (email: string) => {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
};

const addEmail = (email: string) => {
const trimmedEmail = email.trim();
if (
trimmedEmail &&
isValidEmail(trimmedEmail) &&
!emails.includes(trimmedEmail)
) {
const newEmails = [...emails, trimmedEmail];
setEmails(newEmails);
if (register) {
register(name).onChange({
target: { name, value: newEmails },
});
}
}
setInputValue("");
};

const removeEmail = (index: number) => {
const newEmails = emails.filter((_, i) => i !== index);
setEmails(newEmails);
if (register) {
register(name).onChange({
target: { name, value: newEmails },
});
}
};

const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if ((e.key === " " || e.key === "Tab") && inputValue) {
console.log("came here,", e.key);
e.preventDefault();
addEmail(inputValue);
} else if (e.key === "Backspace" && !inputValue && emails.length > 0) {
removeEmail(emails.length - 1);
}
};

const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};

const handleBlur = () => {
if (inputValue) {
addEmail(inputValue);
}
};

return (
<div
className={cn(
"flex flex-wrap items-center gap-2",
error && "text-destructive",
className,
)}
>
<Label
className={cn(
"text-sm font-normal text-muted-foreground",
error && "text-destructive",
)}
>
{label}
</Label>
{emails.map((email, index) => (
<div
key={index}
className="flex w-fit items-center gap-1 rounded-md bg-primary/10 px-2 py-1 text-sm text-primary"
>
<span>{email}</span>
<button
type="button"
onClick={() => removeEmail(index)}
className="flex h-4 w-4 items-center justify-center rounded-full hover:bg-primary/20"
aria-label={`Remove ${email}`}
>
<X className="h-3 w-3" />
</button>
</div>
))}
<input
ref={inputRef}
type="text"
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
onBlur={handleBlur}
className="min-w-[120px] flex-1 border-none bg-transparent p-0 text-sm outline-none focus:ring-0"
placeholder={emails.length === 0 ? placeholder : ""}
/>
<input type="hidden" {...register?.(name)} value={emails.join(",")} />
{error && (
<span className="text-xs text-destructive">{error.message}</span>
)}
</div>
);
}