"use client"
/**
* EmailComposerSheet — the shared "email people" rail, laid out like a mail client.
*
* Built on {@link FloatingSheetPanel}, so the hub behind it stays live. A page never renders
* this directly: it hands an `EmailComposerContext` to `useEmailComposer()` and the provider
* mounts the sheet once.
*
* Top to bottom: toolbar (Preview ⇄ Edit toggle) · From / Reply to · To (badges) · Cc · Bcc ·
* Template · Subject · body (merge fields as inline badges) · attachments · footer
* (Send test email, Send ▾ Schedule). "Edit recipients" opens a second panel for the full
* list, skip-already-emailed, individual-emails and copy-me options.
*/
import * as React from "react"
import { cn } from "../../lib/utils"
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "../ui/alert-dialog"
import {
Attachment,
AttachmentAction,
AttachmentActions,
AttachmentTrigger,
AttachmentContent,
AttachmentDescription,
AttachmentMedia,
AttachmentTitle,
} from "../ui/attachment"
import { Badge } from "../ui/badge"
import { LocalBanner } from "../ui/banner"
import { Button } from "../ui/button"
import { Checkbox } from "../ui/checkbox"
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../ui/dialog"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "../ui/dropdown-menu"
import {
FloatingSheetPanel,
FloatingSheetPanelBody,
FloatingSheetPanelContent,
FloatingSheetPanelFooter,
FloatingSheetPanelHeader,
FloatingSheetPanelToolbar,
} from "../ui/floating-sheet-panel"
import { Input } from "../ui/input"
import { Label } from "../ui/label"
import { MergeTagText } from "../ui/merge-tag"
import { MergeTagInput } from "../ui/merge-tag-input"
import { RichTextEditor } from "../ui/rich-text-editor"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select"
import { SheetTitle } from "../ui/sheet"
import { Textarea } from "../ui/textarea"
import { Tip } from "../ui/tip"
import { ToggleSwitch } from "../ui/toggle-switch"
import { EmailAttachmentPreviewDialog } from "./email-attachment-preview"
import { EmailChipField, type EmailChip } from "./email-chip-field"
import {
CheckMenuItem,
EMAIL_FOOTER_OPTIONS,
EMAIL_HEADER_OPTIONS,
EmailFooterBlock,
EmailHeaderBlock,
EmailHeaderFooterPicker,
type EmailFooterKind,
type EmailHeaderKind,
} from "./email-header-footer"
import { EmailRecipientsReview } from "./email-recipients-review"
import { EmailMessagePreview } from "./email-message-preview"
import {
BLANK_EMAIL_TEMPLATE,
DEFAULT_MERGE_FIELDS,
DEFAULT_TEMPLATE_FOOTER,
DEFAULT_TEMPLATE_HEADER,
audienceNoun,
emailProblem,
formatFileSize,
resolveMergeFields,
type EmailAttachmentFile,
type EmailComposerContext,
type EmailContact,
type EmailRecipient,
type EmailSendPayload,
type EmailTemplateDefinition,
} from "./email-composer-types"
export interface EmailComposerSheetProps {
open: boolean
onOpenChange: (open: boolean) => void
context: EmailComposerContext
/** Called after the sender confirms. The page owns delivery. */
onSend: (payload: EmailSendPayload) => void
/** Adds "Send test email". Receives the message as one recipient would see it. */
onSendTest?: (payload: EmailSendPayload, toEmail: string) => void
/** Called when the sender saves the current letter as a template. */
onSaveTemplate?: (audience: string, template: EmailTemplateDefinition) => void
}
/** Rails sit at z-[80]; menus and dialogs opened from one must clear it. */
const MENU_Z = "z-properties-sheet-portal"
const DIALOG_Z = "z-[90]"
const toAttachments = (template: EmailTemplateDefinition): EmailAttachmentFile[] =>
(template.attachments ?? []).map(file => ({
id: `tpl-${template.id}-${file.name}`,
name: file.name,
size: file.size,
fromTemplate: true,
url: file.url,
}))
/** The template a composer opens with: the one marked default, else the first. */
const pickFirst = (list: EmailTemplateDefinition[]) => list.find(t => t.isDefault) ?? list[0]
/** No usable address, or the page says this person cannot be emailed yet. */
const isUnsendable = (p: EmailRecipient) => Boolean(emailProblem(p)) || Boolean(p.blockedReason)
const hasText = (html: string) => html.replace(/<[^>]*>/g, "").replace(/ /g, " ").trim().length > 0
function formatWhen(date: string, time: string): string {
const parsed = new Date(`${date}T${time || "09:00"}`)
return Number.isNaN(parsed.getTime())
? `${date} ${time}`
: parsed.toLocaleString("en-US", { weekday: "short", month: "short", day: "numeric", hour: "numeric", minute: "2-digit" })
}
function FieldRow({
label,
children,
action,
className,
}: {
label: string
children: React.ReactNode
action?: React.ReactNode
className?: string
}) {
return (
{label}
{children}
{action ?
{action}
: null}
)
}
export function EmailComposerSheet({
open,
onOpenChange,
context,
onSend,
onSendTest,
onSaveTemplate,
}: EmailComposerSheetProps) {
const dirtyRef = React.useRef(false)
const [discardOpen, setDiscardOpen] = React.useState(false)
const closeNow = () => {
dirtyRef.current = false
setDiscardOpen(false)
onOpenChange(false)
}
const requestClose = () => (dirtyRef.current ? setDiscardOpen(true) : closeNow())
return (
<>
(next ? onOpenChange(true) : requestClose())}>
{/* Mounted only while open, so every open starts from the context's defaults. */}
{
dirtyRef.current = dirty
}}
onSend={onSend}
onSendTest={onSendTest}
onSaveTemplate={onSaveTemplate}
/>
Discard this email?
Closing the email discards the draft. Keep editing to go back.
Keep editing
Discard
>
)
}
interface BodyProps {
context: EmailComposerContext
onClose: () => void
onCancel: () => void
onDirtyChange: (dirty: boolean) => void
onSend: EmailComposerSheetProps["onSend"]
onSendTest?: EmailComposerSheetProps["onSendTest"]
onSaveTemplate?: EmailComposerSheetProps["onSaveTemplate"]
}
function ComposerBody({
context,
onClose,
onCancel,
onDirtyChange,
onSend,
onSendTest,
onSaveTemplate,
}: BodyProps) {
const { audiences, sender, prefill } = context
const [emailFix, setEmailFix] = React.useState>({})
const recipients = React.useMemo(
() => context.recipients.map(r => (emailFix[r.id] ? { ...r, email: emailFix[r.id] } : r)),
[context.recipients, emailFix],
)
const recordNoun = context.recordNoun ?? "record"
const mergeFields = React.useMemo(() => context.mergeFields ?? DEFAULT_MERGE_FIELDS, [context.mergeFields])
const meEmail = sender.me ?? sender.email
const availableAudiences = React.useMemo(
() => audiences.filter(a => recipients.some(r => r.audience === a.id)),
[audiences, recipients],
)
// With several groups (placements and schedules reach students, preceptors, faculty…),
// the sender chooses one on the Recipients page first. Nothing is picked by default.
const multi = availableAudiences.length > 1
const initialAudience = prefill?.audience ?? (multi ? "" : availableAudiences[0]?.id ?? "")
const templatesFor = React.useCallback(
(audienceId: string) => {
const list = context.templates?.[audienceId]
return list && list.length > 0 ? list : [BLANK_EMAIL_TEMPLATE]
},
[context.templates],
)
const firstTemplate = pickFirst(templatesFor(initialAudience))
const [stage, setStage] = React.useState<"compose" | "review">(multi && !prefill ? "review" : "compose")
const [composeVisited, setComposeVisited] = React.useState(!(multi && !prefill))
const [view, setView] = React.useState<"edit" | "preview">("edit")
const [audienceId, setAudienceId] = React.useState(initialAudience)
const [templates, setTemplates] = React.useState(() => templatesFor(initialAudience))
const [header, setHeader] = React.useState(
firstTemplate.header ?? DEFAULT_TEMPLATE_HEADER,
)
const [footer, setFooter] = React.useState(
firstTemplate.footer ?? DEFAULT_TEMPLATE_FOOTER,
)
const [templateQuery, setTemplateQuery] = React.useState("")
const [templateId, setTemplateId] = React.useState(prefill ? "" : firstTemplate.id)
const [subject, setSubject] = React.useState(prefill?.subject ?? firstTemplate.subject)
const [body, setBody] = React.useState(prefill?.body ?? firstTemplate.body)
const [attachments, setAttachments] = React.useState(() =>
prefill ? [] : toAttachments(firstTemplate),
)
const [excluded, setExcluded] = React.useState>(() => new Set())
const [separate, setSeparate] = React.useState(
() => audiences.find(a => a.id === initialAudience)?.separateByDefault ?? false,
)
const [previewFile, setPreviewFile] = React.useState(null)
const [extraTo, setExtraTo] = React.useState([])
const [cc, setCc] = React.useState([])
const [bcc, setBcc] = React.useState([])
const [showCc, setShowCc] = React.useState(false)
const [showBcc, setShowBcc] = React.useState(false)
const [senderOpen, setSenderOpen] = React.useState(false)
const [fromEmail, setFromEmail] = React.useState(sender.email)
const [replyTo, setReplyTo] = React.useState(sender.replyTo ?? sender.email)
const [previewId, setPreviewId] = React.useState(null)
const [dialog, setDialog] = React.useState(null)
const [date, setDate] = React.useState("")
const [time, setTime] = React.useState("09:00")
const [saveName, setSaveName] = React.useState("")
const [saveDescription, setSaveDescription] = React.useState("")
const [notice, setNotice] = React.useState(null)
const fileInputRef = React.useRef(null)
const audience = audiences.find(a => a.id === audienceId)
const template = templates.find(t => t.id === templateId)
const people = React.useMemo(() => recipients.filter(r => r.audience === audienceId), [recipients, audienceId])
const isHidden = React.useCallback(
(p: EmailRecipient) => excluded.has(p.id),
[excluded],
)
const listed = people.filter(p => !isHidden(p))
const eligible = listed.filter(p => !isUnsendable(p))
const validExtras = extraTo.filter(e => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e))
const total = eligible.length + validExtras.length
const noun = audience ? audienceNoun(audience, total) : "recipients"
// Separate emails send one per record; otherwise one per person.
const emailCount = separate
? eligible.reduce((sum, p) => sum + Math.max(1, p.records ?? 1), 0) + validExtras.length
: total
const copyMe = bcc.includes(meEmail)
const contacts: EmailContact[] = React.useMemo(
() => [
...recipients.map(r => ({
name: r.name,
email: r.email,
tag: audiences.find(a => a.id === r.audience)?.noun ?? audiences.find(a => a.id === r.audience)?.label,
})),
{ name: sender.name, email: sender.email, tag: "Sender" },
...(context.senders ?? []),
],
[recipients, audiences, sender, context.senders],
)
const senderOptions: EmailContact[] = React.useMemo(
() => [{ name: sender.name, email: sender.email, tag: "Sender" }, ...(context.senders ?? [])],
[sender, context.senders],
)
const fromName = senderOptions.find(s => s.email === fromEmail)?.name ?? fromEmail
const previewPerson = eligible.find(p => p.id === previewId) ?? eligible[0] ?? people[0]
const scheduledFor = date ? `${date}T${time || "09:00"}` : null
const baseSubject = prefill?.subject ?? template?.subject ?? ""
const baseBody = prefill?.body ?? template?.body ?? ""
const dirty =
subject !== baseSubject ||
body !== baseBody ||
extraTo.length > 0 ||
cc.length > 0 ||
bcc.length > 0 ||
attachments.some(a => !a.fromTemplate)
React.useEffect(() => onDirtyChange(dirty), [dirty, onDirtyChange])
const problems: string[] = []
if (!subject.trim()) problems.push("Add a subject.")
if (!hasText(body)) problems.push("Write a message.")
if (total === 0) problems.push("Add at least one recipient.")
const canSend = problems.length === 0
const applyTemplate = (next: EmailTemplateDefinition) => {
setTemplateId(next.id)
setSubject(next.subject)
setBody(next.body)
// A template always brings its header and footer.
setHeader(next.header ?? DEFAULT_TEMPLATE_HEADER)
setFooter(next.footer ?? DEFAULT_TEMPLATE_FOOTER)
// Keep files the sender added; swap only the ones the previous template brought in.
setAttachments(prev => [...prev.filter(f => !f.fromTemplate), ...toAttachments(next)])
}
const changeAudience = (next: string) => {
const list = templatesFor(next)
setAudienceId(next)
setTemplates(list)
setExcluded(new Set())
setPreviewId(null)
setSeparate(audiences.find(a => a.id === next)?.separateByDefault ?? false)
applyTemplate(pickFirst(list))
}
const setCopyMe = (on: boolean) => {
setBcc(prev => (on ? (prev.includes(meEmail) ? prev : [...prev, meEmail]) : prev.filter(e => e !== meEmail)))
if (on) setShowBcc(true)
}
const addFiles = (files: FileList | null) => {
if (!files) return
setAttachments(prev => [
...prev,
...Array.from(files).map((file, i) => ({
id: `file-${Date.now()}-${prev.length + i}`,
name: file.name,
size: file.size,
file,
})),
])
if (fileInputRef.current) fileInputRef.current.value = ""
}
const payloadFor = (recipientList: EmailRecipient[], when: string | null): EmailSendPayload => ({
audience: audienceId,
subject,
body,
recipients: recipientList,
extraTo: validExtras,
cc,
bcc,
from: fromEmail,
replyTo,
separateEmails: separate,
header,
footer,
attachments,
copyToSender: copyMe,
scheduledFor: when,
})
const send = (when: string | null) => {
onSend(payloadFor(eligible, when))
onClose()
}
const sendTest = () => {
if (!onSendTest || !previewPerson) return
onSendTest(payloadFor([previewPerson], null), meEmail)
setNotice(`Test email sent to ${meEmail}. It shows ${previewPerson.name}'s details.`)
}
const openSave = () => {
setSaveName("")
setSaveDescription("")
setDialog("save")
}
const confirmSave = () => {
const saved: EmailTemplateDefinition = {
id: `custom-${Date.now()}`,
label: saveName.trim(),
description: saveDescription.trim(),
subject,
body,
header,
footer,
}
setTemplates(prev => [...prev, saved])
setTemplateId(saved.id)
onSaveTemplate?.(audienceId, saved)
setDialog(null)
setNotice(`Saved “${saved.label}” to the template list.`)
}
const describeField = (key: string) => {
if (!previewPerson) return null
const value = resolveMergeFields(`{{${key}}}`, previewPerson, sender.name)
return { person: previewPerson.name, value: value === `{{${key}}}` ? "No value for this person" : value }
}
const toChips: EmailChip[] = listed.map(p => ({
id: p.id,
label: p.name,
title: emailProblem(p) || p.blockedReason || p.email,
invalid: isUnsendable(p),
}))
/* ── Review stage: full recipient list and options ─────────────────────── */
if (stage === "review") {
return (
<>
Recipients}
onBack={composeVisited ? () => setStage("compose") : undefined}
backLabel="Back to email"
/>
!isUnsendable(p) && !excluded.has(p.id)}
onToggle={(id, on) =>
setExcluded(prev => {
const next = new Set(prev)
if (on) next.delete(id)
else next.add(id)
return next
})
}
onSetMany={(ids, on) =>
setExcluded(prev => {
const next = new Set(prev)
ids.forEach(id => (on ? next.delete(id) : next.add(id)))
return next
})
}
onFixEmail={(id, email) => setEmailFix(prev => ({ ...prev, [id]: email }))}
separate={separate}
onSeparate={setSeparate}
copyMe={copyMe}
onCopyMe={setCopyMe}
meEmail={meEmail}
recipientCount={total}
emailCount={emailCount}
/>
Cancel
{
setComposeVisited(true)
setStage("compose")
}}
>
{composeVisited ? "Done" : "Compose"}
>
)
}
/** The Template row: a full-width menu above Subject, with a clear button. */
const templateRow = (
Template
{template?.label ?? "Select a template"}
{templates.filter(t => t.id !== BLANK_EMAIL_TEMPLATE.id).length >= 7 ? (
setTemplateQuery(event.target.value)}
// Keep the menu's own type-ahead out of the search box.
onKeyDown={event => event.stopPropagation()}
placeholder="Search templates"
aria-label="Search templates"
/>
) : null}
{templates
.filter(t => t.id !== BLANK_EMAIL_TEMPLATE.id)
.filter(t => {
const q = templateQuery.trim().toLowerCase()
return !q || `${t.label} ${t.description ?? ""} ${t.subject}`.toLowerCase().includes(q)
})
.map(t => (
applyTemplate(t)} className="items-start">
{t.label}
{t.isDefault ? Default : null}
{t.description ? {t.description} : null}
{t.subject ? (
) : null}
))}
{template && template.id !== BLANK_EMAIL_TEMPLATE.id ? (
{
setTemplateId("")
setSubject("")
setBody(BLANK_EMAIL_TEMPLATE.body)
setHeader("none")
setFooter("none")
setAttachments(prev => prev.filter(f => !f.fromTemplate))
}}
>
) : null}
)
const sendLabel =
total === 0 ? "Send" : emailCount !== total ? `Send ${emailCount} ${emailCount === 1 ? "email" : "emails"}` : `Send to ${total}`
return (
<>
New email}
onBack={multi ? () => setStage("review") : undefined}
backLabel="Back to recipients"
actions={
<>
setView(view === "edit" ? "preview" : "edit")}>
{view === "edit" ? "Preview" : "Edit"}
>
}
/>
{notice ? (
setNotice(null)}>
{notice}
) : null}
{view === "preview" ? (
{previewPerson ? (
<>
{eligible.length > 1 ? (
Preview as
{eligible.map(p => (
{p.name}
))}
) : null}
>
) : (
No recipients to preview.
)}
) : (
{/* From / Reply to */}
{senderOpen ? (
From
v[0] && setFromEmail(v[0])}
suggestions={senderOptions}
/>
setSenderOpen(false)}>
Reply to
v[0] && setReplyTo(v[0])}
suggestions={contacts}
/>
) : (
setSenderOpen(true)}
className="flex w-full items-center gap-2 rounded py-1 text-start hover:bg-interactive-hover"
>
From
{fromName}
· Reply to
{replyTo}
)}
{/* To */}
setStage("review")}>
{!showCc ? (
setShowCc(true)}>
Cc
) : null}
{!showBcc ? (
setShowBcc(true)}>
Bcc
) : null}
>
}
>
setExcluded(prev => new Set(prev).add(id))}
values={extraTo}
onChange={setExtraTo}
suggestions={contacts}
/>
{showCc ? (
{
setCc([])
setShowCc(false)
}}
>
}
>
) : null}
{showBcc ? (
{
setBcc([])
setShowBcc(false)
}}
>
}
>
) : null}
{templateRow}
{/* Subject */}
{/* Message: full width, no box. Header and footer sit inside it. */}
)}
{dirty ? (
Save as template
) : null}
{onSendTest ? (
Send test email
) : null}
setDialog("now")}>
{sendLabel}
setDialog("now")}>
Send now
Starts sending immediately
setDialog("later")}>
Schedule for later
Pick a date and time
!open && setPreviewFile(null)}
from={sender.brand.name}
className={DIALOG_Z}
overlayClassName={DIALOG_Z}
/>
{/* Send now */}
!open && setDialog(null)}>
Send this email?
{emailCount > 1
? `${emailCount} emails go to ${total} ${noun}, each with their details filled in.`
: `Your email goes to ${total} ${noun}.`}{" "}
This can’t be unsent.
Keep editing
send(null)}>Send
{/* Schedule */}
!open && setDialog(null)}>
Schedule this email
Times use your time zone.
{date ? Goes out {formatWhen(date, time)}.
: null}
setDialog(null)}>
Cancel
send(scheduledFor)}>
Schedule
{/* Save as template */}
!open && setDialog(null)}>
Save as template
Name this letter and say what it is for. It joins the template list.
setDialog(null)}>
Cancel
Save
>
)
}
function SendSummary({ rows }: { rows: [string, string][] }) {
return (
{rows.map(([term, detail]) => (
{term}
{detail}
))}
)
}