Email for professionals and teams
feat(mail): conversation view, forwarding with attachments, rich-text composer
Oday Bakkourc6a38ae8e50d
diff --git a/CLAUDE.md b/CLAUDE.mdindex 5864745..5a1b6e7 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -46,7 +46,9 @@ Inbound: `email` handler → R2 → queue → `processInboundMessage` (`src/lib/Outbound: `src/lib/email/send.ts` / `sender.ts`, composing with mimetext and sending through the `EMAIL` send_email binding, with `outbound_jobs` rows tracking queued sends. `to`, `cc` and `bcc` accept a header string or an array; `toAddr`/`ccAddr`/`bccAddr` on `messages` store the full comma-joined lists (use `splitEmailAddressList` from `src/lib/email/address.ts`, not `getEmailAddress`, when a value may be a list).-Threading: `resolveThreadId` in `src/lib/email/threading.ts` files an inbound or imported message under the thread of the stored message its `In-Reply-To`/`References` name (matched against `providerMessageId` in the same mailbox); otherwise its own Message-ID seeds a new thread. Outbound replies carry `inReplyTo`/`references`/`threadId` from the draft, and a fresh send is keyed by the Message-ID Cloudflare returns. `/api/messages/[id]/thread` returns the conversation.+Composer: `src/components/compose/rich-text-editor.tsx` is a contentEditable HTML editor; the body is one HTML string and the text/plain part is derived with `htmlToPlainText` (`rich-text-utils.ts`). Quoted/forwarded content is wrapped by `wrapQuotedHtml` and folded by both the composer and the reader (`splitQuotedHtml`). Forward copies the source's attachments onto the draft (`copyMessageAttachments`); `/api/send` with `draftId` sends them.++Threading: `resolveThreadId` in `src/lib/email/threading.ts` files an inbound or imported message under the thread of the stored message its `In-Reply-To`/`References` name (matched against `providerMessageId` in the same mailbox); otherwise its own Message-ID seeds a new thread. Outbound replies carry `inReplyTo`/`references`/`threadId` from the draft, and a fresh send is keyed by the Message-ID Cloudflare returns. `/api/messages/[id]/thread` returns the conversation. Lists pass `group=thread` (the "conversation view" toggle, `use-conversation-view.ts`) to get one row per thread plus `threadMessageIds`, which row actions and bulk actions expand to.### Routing rules have two scopesdiff --git a/docs/api.md b/docs/api.mdindex 76aa3d2..eeccbd8 100644--- a/docs/api.md+++ b/docs/api.md@@ -51,7 +51,9 @@ To send a reply that threads correctly in the recipient's client, pass the paren}```-`GET /api/messages/{id}/thread` (session auth) returns every stored message in the same conversation, oldest first, excluding drafts and trash.+`GET /api/messages/{id}/thread` (session auth) returns every stored message in the same conversation, oldest first, excluding drafts and trash. `GET /api/messages?group=thread` collapses a list to one row per conversation (its newest message matching the filter) and adds `threadCount`, `threadUnread` and `threadMessageIds`, the ids that row stands for within the current filter, so bulk actions can act on the whole conversation.++Messages composed in Mailflare are sent as HTML with a plain-text alternative derived from it. Quoted or forwarded content is wrapped in `<div class="mailflare-quote" data-mailflare-quote="1">` so the reader can fold it. `POST /api/drafts` accepts `forwardOfMessageId`, which copies that message's attachments onto the new draft; `DELETE /api/drafts/{id}/attachments/{attachmentId}` removes one, and `POST /api/send` with `draftId` sends the draft's stored files along with any uploaded in the request.The dashboard composer accepts up to 10 attachments, with a 10 MB limit per file and a 20 MB combined limit. Attachment metadata is stored in D1 and file content is stored in R2. Downloads require access to the mailbox containing the message.diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsxindex 07367e1..ffbcf4f 100644--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx@@ -3,7 +3,7 @@import Link from "next/link";import { useParams } from "next/navigation";import { useEffect, useState } from "react";-import { ArrowLeft, Cloud, ExternalLink } from "lucide-react";+import { ArrowLeft, ChevronRight, Cloud, ExternalLink } from "lucide-react";import dayjs from "dayjs";import { MarkAsRead } from "@/components/mark-read";import { useSelectedMailbox } from "@/components/mailbox-provider";@@ -112,6 +112,9 @@ export default function MessageDetailPage() {const htmlBody = sanitizeEmailHtml(resolveInlineAttachmentUrls(bodyDisplay.htmlBody, message.id, attachments),);+ const quotedHtml = sanitizeEmailHtml(+ resolveInlineAttachmentUrls(bodyDisplay.quotedHtml, message.id, attachments),+ );const cloudAttachmentResult = extractCloudAttachments(bodyDisplay.latestContent,);@@ -144,6 +147,8 @@ export default function MessageDetailPage() {ownAddress={ownAddress}ownAddresses={ownAddresses}message={message}+ messageMeta={message}+ bodyHtml={body?.htmlBody}/></div><ConversationThread@@ -203,12 +208,24 @@ export default function MessageDetailPage() {</div><div className="prose max-w-none text-neutral-900">{htmlBody ? (- <div className="mx-auto" dangerouslySetInnerHTML={{ __html: htmlBody }} />+ <div className="email-body mx-auto" dangerouslySetInnerHTML={{ __html: htmlBody }} />) : (<pre className="whitespace-pre-wrap text-sm text mx-auto">{cloudAttachmentResult.content}</pre>)}+ {quotedHtml && (+ <details className="group mt-4 border-l-2 border-neutral-200 pl-4">+ <summary className="flex cursor-pointer list-none items-center gap-2 rounded-md py-2 text-xs font-medium text-neutral-500 hover:text-neutral-800">+ <ChevronRight className="h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90" />+ <span>Quoted text</span>+ </summary>+ <div+ className="email-body max-w-none pb-2 text-sm text-neutral-600"+ dangerouslySetInnerHTML={{ __html: quotedHtml }}+ />+ </details>+ )}{bodyDisplay.quotedContent.map((quotedContent) => (<PreviousMessagekey={`${quotedContent.dateLine}-${quotedContent.content.slice(0, 24)}`}diff --git a/src/app/(dashboard)/inbox/[messageId]/types.d.ts b/src/app/(dashboard)/inbox/[messageId]/types.d.tsindex caa501a..ed098ff 100644--- a/src/app/(dashboard)/inbox/[messageId]/types.d.ts+++ b/src/app/(dashboard)/inbox/[messageId]/types.d.ts@@ -24,5 +24,7 @@ export type MessageAttachment = {export type MessageBodyDisplay = ReplyContentParts & {htmlBody: string | null;+ /** Quoted/forwarded HTML a Mailflare composer folded under the message, shown collapsed. */+ quotedHtml: string | null;hasQuotedContent: boolean;};diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.tsindex 862c6d4..cfbbb85 100644--- a/src/app/(dashboard)/inbox/[messageId]/utils.ts+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts@@ -3,6 +3,7 @@ import { fetchCachedMessageDetail, getCachedMessageDetail } from "@/lib/messagesimport { getEmailAddress, getEmailAddressList, normalizeEmailAddress } from "@/lib/email/address";import { getDisplayNameForAddress } from "@/lib/contacts/utils";import { htmlToReadableText, splitRepliedEmailContent } from "@/lib/email/reply-content-utils";+import { splitQuotedHtml } from "@/components/compose/rich-text-utils";import type { Message } from "@/hooks/types";import type { MessageAttachment, MessageBodyDisplay, MessageDetailResponse } from "./types";@@ -50,12 +51,28 @@ export function getMessageBodyDisplay(fallback: string | null | undefined,ownAddress?: string,): MessageBodyDisplay {+ // A message composed in Mailflare marks its quoted part, so the rich body can+ // stay rich and the quote fold on its own. Other mail falls back to the+ // text heuristics, which can only render the result as text.+ const marked = splitQuotedHtml(htmlBody);+ if (marked.quoted !== null) {+ const parts = splitRepliedEmailContent(htmlToReadableText(marked.body), { ownAddress });+ return {+ latestContent: parts.latestContent,+ quotedContent: [],+ htmlBody: marked.body,+ quotedHtml: marked.quoted,+ hasQuotedContent: true,+ };+ }+const textSource = textBody ?? (htmlToReadableText(htmlBody) || fallback || "");const parts = splitRepliedEmailContent(textSource, { ownAddress });return {...parts,htmlBody: parts.quotedContent.length > 0 ? null : htmlBody ?? null,+ quotedHtml: null,hasQuotedContent: parts.quotedContent.length > 0,};}diff --git a/src/app/api/drafts/[id]/attachments/[attachmentId]/route.ts b/src/app/api/drafts/[id]/attachments/[attachmentId]/route.tsnew file mode 100644index 0000000..10ccdec--- /dev/null+++ b/src/app/api/drafts/[id]/attachments/[attachmentId]/route.ts@@ -0,0 +1,31 @@+import { NextResponse } from "next/server";+import { eq } from "drizzle-orm";+import { getEnv } from "@/lib/cloudflare";+import { getDb } from "@/db";+import { messages } from "@/db/schema";+import { requireUser } from "@/lib/auth/cookies";+import { deleteMessageAttachment } from "@/lib/email/attachments";+import { userOwnsDraft } from "../../../utils";++type DraftAttachmentRouteParams = {+ params: Promise<{ id: string; attachmentId: string }>;+};++/** Drop one file from a draft, e.g. an attachment carried over by Forward the user does not want to send. */+export async function DELETE(request: Request, { params }: DraftAttachmentRouteParams) {+ const { id, attachmentId } = await params;+ const env = getEnv();+ const user = await requireUser(env, request);+ const db = getDb(env);+ const [draft] = await db.select().from(messages).where(eq(messages.id, id)).limit(1);++ if (!userOwnsDraft(draft, user.id)) {+ return NextResponse.json({ error: "Draft not found" }, { status: 404 });+ }++ const removed = await deleteMessageAttachment(env, id, attachmentId);+ if (!removed) {+ return NextResponse.json({ error: "Attachment not found" }, { status: 404 });+ }+ return NextResponse.json({ ok: true });+}diff --git a/src/app/api/drafts/[id]/route.ts b/src/app/api/drafts/[id]/route.tsindex b1730dd..38cf592 100644--- a/src/app/api/drafts/[id]/route.ts+++ b/src/app/api/drafts/[id]/route.ts@@ -10,6 +10,7 @@ import { selectDraftWithBody } from "./utils";import { readJsonBody } from "@/lib/http/request";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { getDraftSender, userOwnsDraft } from "../utils";+import { deleteMessageAttachmentObjects, listMessageAttachments } from "@/lib/email/attachments";export async function GET(request: Request, { params }: DraftRouteParams) {const { id } = await params;@@ -22,7 +23,8 @@ export async function GET(request: Request, { params }: DraftRouteParams) {return NextResponse.json({ error: "Draft not found" }, { status: 404 });}- return NextResponse.json({ draft });+ const attachments = await listMessageAttachments(env, id);+ return NextResponse.json({ draft: { ...draft, attachments } });}export async function PATCH(request: Request, { params }: DraftRouteParams) {@@ -78,6 +80,8 @@ export async function DELETE(request: Request, { params }: DraftRouteParams) {return NextResponse.json({ error: "Draft not found" }, { status: 404 });}+ // Rows cascade with the draft; the R2 objects do not.+ await deleteMessageAttachmentObjects(env, id);await db.delete(messages).where(eq(messages.id, id));return NextResponse.json({ ok: true });}diff --git a/src/app/api/drafts/route.ts b/src/app/api/drafts/route.tsindex 7c1f5b3..58f557e 100644--- a/src/app/api/drafts/route.ts+++ b/src/app/api/drafts/route.ts@@ -7,6 +7,8 @@ import { requireUser } from "@/lib/auth/cookies";import { newId } from "@/lib/ids";import { buildSnippet } from "@/lib/email/parse";import { readJsonBody } from "@/lib/http/request";+import { copyMessageAttachments } from "@/lib/email/attachments";+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";import { RequestBodyTooLargeError } from "@/lib/http/errors";import type { DraftPayload } from "./types";import { getDraftSender } from "./utils";@@ -49,6 +51,21 @@ export async function POST(request: Request) {if ("error" in sender) {return NextResponse.json({ error: sender.error }, { status: 403 });}+ // Forwarding: the source must be readable by this user before its files are copied.+ let forwardSourceId: string | null = null;+ if (input.forwardOfMessageId) {+ const [source] = await db+ .select({ id: messages.id, mailboxId: messages.mailboxId })+ .from(messages)+ .where(eq(messages.id, input.forwardOfMessageId))+ .limit(1);+ const sourceAccess = source?.mailboxId ? await getMailboxAccessLevel(db, user, source.mailboxId) : null;+ if (!source || !sourceAccess?.canRead) {+ return NextResponse.json({ error: "Message not found" }, { status: 404 });+ }+ forwardSourceId = source.id;+ }+const draftId = newId("msg");const text = input.text ?? "";const html = input.html ?? "";@@ -73,5 +90,6 @@ export async function POST(request: Request) {threadId: input.threadId || null,});- return NextResponse.json({ draft: { id: draftId } });+ const attachments = forwardSourceId ? await copyMessageAttachments(env, forwardSourceId, draftId) : [];+ return NextResponse.json({ draft: { id: draftId, attachments } });}diff --git a/src/app/api/drafts/types.d.ts b/src/app/api/drafts/types.d.tsindex 4bbf9ab..6e2f8ee 100644--- a/src/app/api/drafts/types.d.ts+++ b/src/app/api/drafts/types.d.ts@@ -11,4 +11,6 @@ export type DraftPayload = {inReplyTo?: string | null;references?: string | null;threadId?: string | null;+ /** Copy this message's attachments onto the new draft (forwarding). */+ forwardOfMessageId?: string | null;};diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.tsindex 3df4d35..2227626 100644--- a/src/app/api/messages/route.ts+++ b/src/app/api/messages/route.ts@@ -1,5 +1,5 @@import { NextResponse } from "next/server";-import { eq, desc, and, like, or, count, isNull, isNotNull, inArray, lte, gt, notInArray } from "drizzle-orm";+import { eq, desc, and, like, or, count, countDistinct, isNull, isNotNull, inArray, lte, gt, max, notInArray, sql, sum } from "drizzle-orm";import type { SQL } from "drizzle-orm";import { getEnv } from "@/lib/cloudflare";import { getCurrentUser } from "@/lib/auth/cookies";@@ -29,6 +29,9 @@ export async function GET(request: Request) {const snoozed = url.searchParams.get("snoozed");const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 100);const offset = Math.max(Number(url.searchParams.get("offset") ?? 0), 0);+ // Conversation view: one row per thread, represented by its newest message+ // that matches the filter. Drafts are never grouped.+ const groupByThread = url.searchParams.get("group") === "thread" && status !== "draft";const db = getDb(env);const accessibleMailboxes = await listAccessibleMailboxes(db, user);@@ -86,22 +89,70 @@ export async function GET(request: Request) {conditions.push(like(messages.subject, `%${title}%`));}const where = and(...conditions);+ // Messages that were never threaded (older rows, drafts) stand alone.+ const threadKey = sql<string>`coalesce(${messages.threadId}, ${messages.id})`;- const [totalRow] = await db- .select({ total: count() })- .from(messages)- .where(where);- const rows = await db- .select()- .from(messages)- .where(where)- .orderBy(desc(messages.createdAt))- .limit(limit)- .offset(offset);+ let total = 0;+ let rows: (typeof messages.$inferSelect)[];+ // Which stored messages each visible row stands for, so acting on a+ // conversation row acts on the whole conversation within this folder.+ const threadMessageIds = new Map<string, string[]>();+ if (groupByThread) {+ const [totalRow] = await db.select({ total: countDistinct(threadKey) }).from(messages).where(where);+ total = totalRow?.total ?? 0;+ const latestPerThread = db+ .select({ tid: threadKey.as("tid"), latest: max(messages.createdAt).as("latest") })+ .from(messages)+ .where(where)+ .groupBy(threadKey)+ .as("latest_per_thread");+ const joined = await db+ .select({ message: messages })+ .from(messages)+ .innerJoin(+ latestPerThread,+ and(eq(threadKey, latestPerThread.tid), eq(messages.createdAt, latestPerThread.latest)),+ )+ .where(where)+ .orderBy(desc(messages.createdAt))+ .limit(limit)+ .offset(offset);+ // Two messages in one thread can share a timestamp to the second; keep one row.+ const seen = new Set<string>();+ rows = [];+ for (const { message } of joined) {+ const key = message.threadId ?? message.id;+ if (seen.has(key)) continue;+ seen.add(key);+ rows.push(message);+ }+ const keys = rows.map((row) => row.threadId ?? row.id);+ if (keys.length > 0) {+ const members = await db+ .select({ id: messages.id, key: threadKey })+ .from(messages)+ .where(and(where, inArray(threadKey, keys)));+ for (const member of members) {+ const list = threadMessageIds.get(member.key) ?? [];+ list.push(member.id);+ threadMessageIds.set(member.key, list);+ }+ }+ } else {+ const [totalRow] = await db.select({ total: count() }).from(messages).where(where);+ total = totalRow?.total ?? 0;+ rows = await db+ .select()+ .from(messages)+ .where(where)+ .orderBy(desc(messages.createdAt))+ .limit(limit)+ .offset(offset);+ }// Conversation sizes for the rows on this page, so the list can show "(3)"// next to a subject the way threaded clients do.const threadIds = Array.from(new Set(rows.map((row) => row.threadId).filter((id): id is string => !!id)));- const threadCounts = new Map<string, number>();+ const threadCounts = new Map<string, { total: number; unread: number }>();if (threadIds.length > 0) {const scope = mailboxId? eq(messages.mailboxId, mailboxId)@@ -109,12 +160,16 @@ export async function GET(request: Request) {? inArray(messages.mailboxId, accessibleMailboxIds): eq(messages.userId, user.id);const countRows = await db- .select({ threadId: messages.threadId, total: count() })+ .select({+ threadId: messages.threadId,+ total: count(),+ unread: sum(sql`case when ${messages.read} = 0 and ${messages.direction} = 'inbound' then 1 else 0 end`),+ }).from(messages).where(and(scope, inArray(messages.threadId, threadIds), isNotNull(messages.threadId), notInArray(messages.status, ["draft", "trash"]))).groupBy(messages.threadId);for (const row of countRows) {- if (row.threadId) threadCounts.set(row.threadId, row.total);+ if (row.threadId) threadCounts.set(row.threadId, { total: row.total, unread: Number(row.unread ?? 0) });}}const mailboxNameMap = new Map(@@ -148,9 +203,13 @@ export async function GET(request: Request) {contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??null,toContactName: contactMap?.get(normalizeEmailAddress(getFirstEmailAddressEntry(message.toAddr))) ?? null,- threadCount: message.threadId ? threadCounts.get(message.threadId) ?? 1 : 1,+ threadCount: (message.threadId && threadCounts.get(message.threadId)?.total) || 1,+ threadUnread: (message.threadId && threadCounts.get(message.threadId)?.unread) || 0,+ ...(groupByThread+ ? { threadMessageIds: threadMessageIds.get(message.threadId ?? message.id) ?? [message.id] }+ : {}),};});- return NextResponse.json({ messages: enrichedRows, total: totalRow?.total ?? 0, limit, offset });+ return NextResponse.json({ messages: enrichedRows, total, limit, offset, grouped: groupByThread });}diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.tsindex 4742552..fff692d 100644--- a/src/app/api/send/route.ts+++ b/src/app/api/send/route.ts@@ -6,6 +6,11 @@ import { sendEmail } from "@/lib/email/send";import { parseSendRequest } from "./utils";import { RequestBodyTooLargeError } from "@/lib/http/errors";import { getSendErrorStatus } from "./error-utils";+import { getDb } from "@/db";+import { messages } from "@/db/schema";+import { eq } from "drizzle-orm";+import { loadMessageAttachmentContents } from "@/lib/email/attachments";+import { userOwnsDraft } from "@/app/api/drafts/utils";export async function POST(request: Request) {const env = getEnv();@@ -17,12 +22,23 @@ export async function POST(request: Request) {const status = error instanceof RequestBodyTooLargeError ? 413 : 400;return NextResponse.json({ error: "Invalid send request" }, { status });}- const { attachments, ...fields } = input;+ const { attachments = [], draftId, ...fields } = input;const parsed = sendEmailSchema.omit({ attachments: true }).safeParse(fields);if (!parsed.success) {return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });}+ // Files already stored on the draft (a forwarded message's attachments) ride+ // along with whatever the composer uploaded in this request.+ if (draftId) {+ const db = getDb(env);+ const [draft] = await db.select().from(messages).where(eq(messages.id, draftId)).limit(1);+ if (!userOwnsDraft(draft, user.id)) {+ return NextResponse.json({ error: "Draft not found" }, { status: 404 });+ }+ attachments.push(...(await loadMessageAttachmentContents(env, draftId)));+ }+try {const result = await sendEmail(env, {userId: user.id,diff --git a/src/app/api/send/types.d.ts b/src/app/api/send/types.d.tsindex 6b7ea24..4492e4e 100644--- a/src/app/api/send/types.d.ts+++ b/src/app/api/send/types.d.ts@@ -13,4 +13,6 @@ export interface SendRequestPayload {inReplyTo?: string;references?: string;threadId?: string;+ /** Draft whose stored attachments (e.g. forwarded files) should be sent along. */+ draftId?: string;}diff --git a/src/app/api/send/utils.ts b/src/app/api/send/utils.tsindex dc09007..41e63de 100644--- a/src/app/api/send/utils.ts+++ b/src/app/api/send/utils.ts@@ -34,6 +34,7 @@ export async function parseSendRequest(request: Request): Promise<SendRequestPayinReplyTo: getOptionalFormValue(form, "inReplyTo"),references: getOptionalFormValue(form, "references"),threadId: getOptionalFormValue(form, "threadId"),+ draftId: getOptionalFormValue(form, "draftId"),subject: String(form.get("subject") ?? ""),text: getOptionalFormValue(form, "text"),html: getOptionalFormValue(form, "html"),diff --git a/src/app/globals.css b/src/app/globals.cssindex ea2d695..0e95a64 100644--- a/src/app/globals.css+++ b/src/app/globals.css@@ -89,3 +89,30 @@ pre {animation-duration: 1ms !important;}}++/* Rendered email bodies (reader, conversation cards, composer). Tailwind's+ preflight strips list markers and blockquote styling, which both incoming+ mail and the composer's own lists rely on. */+.email-body ul {+ list-style: disc;+ padding-left: 1.5rem;+ margin: 0.25rem 0;+}+.email-body ol {+ list-style: decimal;+ padding-left: 1.5rem;+ margin: 0.25rem 0;+}+.email-body blockquote {+ border-left: 2px solid #d4d4d4;+ margin: 0.25rem 0;+ padding-left: 0.75rem;+ color: #525252;+}+.email-body a {+ color: #2563eb;+ text-decoration: underline;+}+.email-body p {+ margin: 0 0 0.5rem;+}diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsxindex f2eab4c..c73cc2b 100644--- a/src/components/compose/compose-form.tsx+++ b/src/components/compose/compose-form.tsx@@ -1,20 +1,28 @@"use client";import { useEffect, useMemo, useRef, useState } from "react";-import { FileText, Minimize2, Paperclip, Reply, Send, X } from "lucide-react";+import { FileText, Forward, Minimize2, Paperclip, Reply, Send, X } from "lucide-react";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Select } from "@/components/ui/select";-import { Textarea } from "@/components/ui/textarea";import { useSelectedMailbox } from "@/components/mailbox-provider";import { authFetch } from "@/lib/auth/client";import { formatEmailAddress, getEmailAddress } from "@/lib/email/address";import { cn } from "@/lib/utils";-import { applyMailboxSignature, buildSendFormData, fetchDraft, formatAttachmentSize } from "./utils";+import { buildSendFormData, fetchDraft, formatAttachmentSize } from "./utils";import { RecipientInput } from "./recipient-input";+import { RichTextEditor } from "./rich-text-editor";+import {+ applyMailboxSignatureHtml,+ hasMeaningfulHtml,+ htmlToPlainText,+ joinQuotedHtml,+ splitQuotedHtml,+ textToHtml,+} from "./rich-text-utils";import { headerToRecipients, isValidRecipient, recipientsToHeader } from "./recipient-utils";-import type { ComposeAttachment, ComposeThreading } from "./types";+import type { ComposeAttachment, ComposeStoredAttachment, ComposeThreading } from "./types";type Toast = { type: "success" | "error"; message: string } | null;@@ -36,8 +44,12 @@ export function ComposeForm({const [showBcc, setShowBcc] = useState(false);const [threading, setThreading] = useState<ComposeThreading | null>(null);const [subject, setSubject] = useState("");- const [text, setText] = useState("");+ // The body is HTML; quoted/forwarded content is kept aside and folded.+ const [html, setHtml] = useState("");+ const [quotedHtml, setQuotedHtml] = useState<string | null>(null);const [attachments, setAttachments] = useState<ComposeAttachment[]>([]);+ // Attachments the draft already holds server-side (a forwarded message's files).+ const [storedAttachments, setStoredAttachments] = useState<ComposeStoredAttachment[]>([]);const [toast, setToast] = useState<Toast>(null);const [loading, setLoading] = useState(false);const [loadingDraft, setLoadingDraft] = useState(false);@@ -112,7 +124,10 @@ export function ComposeForm({: null,);setSubject(draft.subject ?? "");- setText(draft.textBody ?? "");+ const stored = splitQuotedHtml(draft.htmlBody || textToHtml(draft.textBody));+ setHtml(stored.body);+ setQuotedHtml(stored.quoted);+ setStoredAttachments(draft.attachments?.filter((item) => item.disposition === "attachment") ?? []);setLoadedDraftMailboxId(draft.mailboxId);setLoadedDraftFrom(getEmailAddress(draft.fromAddr).toLowerCase());})@@ -146,14 +161,15 @@ export function ComposeForm({useEffect(() => {if (loadingDraft) return;const nextSignature = selectedMailbox?.signature ?? "";- setText((current) => applyMailboxSignature(current, previousSignature.current, nextSignature));+ setHtml((current) => applyMailboxSignatureHtml(current, previousSignature.current, nextSignature));previousSignature.current = nextSignature;}, [loadingDraft, selectedMailbox?.id, selectedMailbox?.signature]);useEffect(() => {- const bodyContent = text.trim();+ const bodyContent = htmlToPlainText(html).trim();const signatureOnly = bodyContent === (selectedMailbox?.signature?.trim() ?? "");- const hasContent = to.length > 0 || cc.length > 0 || bcc.length > 0 || subject.trim() || (bodyContent && !signatureOnly);+ const hasContent =+ to.length > 0 || cc.length > 0 || bcc.length > 0 || subject.trim() || quotedHtml || (bodyContent && !signatureOnly);if (!fromAddr || !hasContent || loadingDraft) return;if (saveTimer.current) clearTimeout(saveTimer.current);@@ -165,7 +181,8 @@ export function ComposeForm({cc: recipientsToHeader(cc),bcc: recipientsToHeader(bcc),subject,- text,+ html: joinQuotedHtml(html, quotedHtml),+ text: htmlToPlainText(joinQuotedHtml(html, quotedHtml)),inReplyTo: threading?.inReplyTo ?? null,references: threading?.references ?? null,threadId: threading?.threadId ?? null,@@ -182,7 +199,7 @@ export function ComposeForm({return () => {if (saveTimer.current) clearTimeout(saveTimer.current);};- }, [bcc, cc, draftId, fromAddr, loadingDraft, selectedMailbox?.id, selectedMailbox?.signature, subject, text, threading, to]);+ }, [bcc, cc, draftId, fromAddr, html, loadingDraft, quotedHtml, selectedMailbox?.id, selectedMailbox?.signature, subject, threading, to]);async function onSubmit(event: React.FormEvent<HTMLFormElement>) {event.preventDefault();@@ -195,7 +212,12 @@ export function ComposeForm({setToast({ type: "error", message: `"${invalid}" is not a valid email address` });return;}+ if (!hasMeaningfulHtml(html) && !quotedHtml) {+ setToast({ type: "error", message: "Write a message before sending" });+ return;+ }setLoading(true);+ const fullHtml = joinQuotedHtml(html, quotedHtml);const res = await authFetch("/api/send", {method: "POST",body: buildSendFormData({@@ -205,9 +227,11 @@ export function ComposeForm({cc: recipientsToHeader(cc),bcc: recipientsToHeader(bcc),subject,- text,+ text: htmlToPlainText(fullHtml),+ html: fullHtml,mailboxId: selectedMailbox?.id,threading: threading ?? undefined,+ draftId: storedAttachments.length > 0 ? draftId : null,}),});const data = (await res.json()) as { messageId?: string; error?: string };@@ -230,21 +254,35 @@ export function ComposeForm({setShowCc(false);setShowBcc(false);setThreading(null);+ setStoredAttachments([]);setSubject("");- setText(applyMailboxSignature("", "", selectedMailbox?.signature));+ setHtml(applyMailboxSignatureHtml("", "", selectedMailbox?.signature));+ setQuotedHtml(null);setAttachments([]);setToast({ type: "success", message: "Message sent" });window.dispatchEvent(new Event("mailflare:messages-changed"));}+ async function removeStoredAttachment(attachmentId: string) {+ if (!draftId) return;+ const res = await authFetch(`/api/drafts/${draftId}/attachments/${attachmentId}`, { method: "DELETE" });+ if (!res.ok) {+ setToast({ type: "error", message: "Could not remove attachment" });+ return;+ }+ setStoredAttachments((current) => current.filter((item) => item.id !== attachmentId));+ }+function addAttachments(files: FileList | null) {if (!files) return;const nextFiles = Array.from(files);- const nextCount = attachments.length + nextFiles.length;- const totalSize = [...attachments.map((attachment) => attachment.file), ...nextFiles].reduce(- (total, file) => total + file.size,- 0,- );+ const nextCount = storedAttachments.length + attachments.length + nextFiles.length;+ const totalSize =+ storedAttachments.reduce((total, item) => total + item.size, 0) ++ [...attachments.map((attachment) => attachment.file), ...nextFiles].reduce(+ (total, file) => total + file.size,+ 0,+ );if (nextCount > 10) {setToast({ type: "error", message: "A message can include at most 10 attachments" });@@ -294,7 +332,16 @@ export function ComposeForm({<div className="flex h-9 items-center justify-between bg-neutral-800 px-4 text-sm font-medium text-white"><span className="flex items-center gap-2">{threading?.inReplyTo && <Reply className="h-3.5 w-3.5 text-neutral-300" />}- {loadingDraft ? "Loading draft" : threading?.inReplyTo ? "Reply" : draftId ? "Draft saved" : "New Message"}+ {!threading?.inReplyTo && /^fwd?:/i.test(subject) && <Forward className="h-3.5 w-3.5 text-neutral-300" />}+ {loadingDraft+ ? "Loading draft"+ : threading?.inReplyTo+ ? "Reply"+ : /^fwd?:/i.test(subject)+ ? "Forward"+ : draftId+ ? "Draft saved"+ : "New Message"}</span>{mode === "popup" && (<div className="flex items-center gap-3 text-neutral-300">@@ -379,18 +426,36 @@ export function ComposeForm({className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"/></div>- <div className="min-h-0 flex-1 px-4 py-2">- <Label htmlFor={`${mode}-text`} className="sr-only">Body</Label>- <Textarea- id={`${mode}-text`}- value={text}- onChange={(event) => setText(event.target.value)}- disabled={loadingDraft}- className="h-full min-h-full resize-none border-0 px-0 shadow-none focus-visible:ring-0"- />- </div>- {attachments.length > 0 && (+ <Label htmlFor={`${mode}-text`} className="sr-only">Body</Label>+ <RichTextEditor+ id={`${mode}-text`}+ value={html}+ onChange={setHtml}+ quotedHtml={quotedHtml}+ disabled={loadingDraft}+ placeholder="Write your message"+ />+ {(attachments.length > 0 || storedAttachments.length > 0) && (<div className="flex flex-wrap gap-2 border-t border-neutral-100 px-4 py-3">+ {storedAttachments.map((attachment) => (+ <div+ key={attachment.id}+ className="flex max-w-full items-center gap-2 rounded-lg border border-neutral-200 bg-neutral-50 px-3 py-2 text-sm"+ title="Carried over from the forwarded message"+ >+ <FileText className="h-4 w-4 shrink-0 text-neutral-500" />+ <span className="max-w-48 truncate">{attachment.filename}</span>+ <span className="text-xs text-neutral-400">{formatAttachmentSize(attachment.size)}</span>+ <button+ type="button"+ onClick={() => void removeStoredAttachment(attachment.id)}+ className="rounded-full p-1 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700"+ >+ <X className="h-3.5 w-3.5" />+ <span className="sr-only">Remove attachment</span>+ </button>+ </div>+ ))}{attachments.map((attachment) => (<divkey={attachment.id}diff --git a/src/components/compose/rich-text-editor-types.d.ts b/src/components/compose/rich-text-editor-types.d.tsnew file mode 100644index 0000000..fbf041e--- /dev/null+++ b/src/components/compose/rich-text-editor-types.d.ts@@ -0,0 +1,18 @@+export type RichTextEditorProps = {+ id: string;+ /** Editable HTML. */+ value: string;+ onChange: (html: string) => void;+ /** Quoted or forwarded HTML shown folded under the editable area. */+ quotedHtml?: string | null;+ disabled?: boolean;+ placeholder?: string;+ className?: string;+};++export type ToolbarCommand = {+ command: string;+ label: string;+ icon: React.ComponentType<{ className?: string }>;+ value?: string;+};diff --git a/src/components/compose/rich-text-editor.tsx b/src/components/compose/rich-text-editor.tsxnew file mode 100644index 0000000..98353b9--- /dev/null+++ b/src/components/compose/rich-text-editor.tsx@@ -0,0 +1,231 @@+"use client";++import { useEffect, useRef, useState } from "react";+import type { ClipboardEvent, KeyboardEvent } from "react";+import {+ Bold,+ Italic,+ Link2,+ List,+ ListOrdered,+ Quote,+ RemoveFormatting,+ Strikethrough,+ Underline,+} from "lucide-react";+import { Tooltip } from "@/components/ui/tooltip";+import { cn } from "@/lib/utils";+import type { RichTextEditorProps, ToolbarCommand } from "./rich-text-editor-types";++const COMMANDS: ToolbarCommand[] = [+ { command: "bold", label: "Bold (⌘B)", icon: Bold },+ { command: "italic", label: "Italic (⌘I)", icon: Italic },+ { command: "underline", label: "Underline (⌘U)", icon: Underline },+ { command: "strikeThrough", label: "Strikethrough", icon: Strikethrough },+ { command: "insertUnorderedList", label: "Bulleted list", icon: List },+ { command: "insertOrderedList", label: "Numbered list", icon: ListOrdered },+ { command: "formatBlock", label: "Quote", icon: Quote, value: "blockquote" },+];++/**+ * A small HTML editor built on contentEditable. It stays deliberately light:+ * inline styles, lists, quotes and links, with pasted content flattened to+ * text so a message never carries another site's markup.+ */+export function RichTextEditor({ id, value, onChange, quotedHtml, disabled, placeholder, className }: RichTextEditorProps) {+ const editorRef = useRef<HTMLDivElement | null>(null);+ const [active, setActive] = useState<Record<string, boolean>>({});+ const [linkOpen, setLinkOpen] = useState(false);+ const [linkUrl, setLinkUrl] = useState("");+ const [showQuoted, setShowQuoted] = useState(false);+ const savedRange = useRef<Range | null>(null);++ // Keep the DOM in step with the value without resetting the caret on every keystroke.+ useEffect(() => {+ const element = editorRef.current;+ if (element && element.innerHTML !== value) element.innerHTML = value;+ }, [value]);++ useEffect(() => {+ function refresh() {+ const element = editorRef.current;+ if (!element || !element.contains(document.activeElement)) return;+ const next: Record<string, boolean> = {};+ for (const item of COMMANDS) {+ if (item.command === "formatBlock") {+ next[item.command] = document.queryCommandValue("formatBlock").toLowerCase() === "blockquote";+ } else {+ next[item.command] = document.queryCommandState(item.command);+ }+ }+ setActive(next);+ }+ document.addEventListener("selectionchange", refresh);+ return () => document.removeEventListener("selectionchange", refresh);+ }, []);++ function emit() {+ onChange(editorRef.current?.innerHTML ?? "");+ }++ function run(command: string, commandValue?: string) {+ editorRef.current?.focus();+ if (command === "formatBlock" && active.formatBlock) {+ document.execCommand("formatBlock", false, "div");+ } else {+ document.execCommand(command, false, commandValue);+ }+ emit();+ }++ function openLink() {+ const selection = window.getSelection();+ savedRange.current = selection && selection.rangeCount > 0 ? selection.getRangeAt(0).cloneRange() : null;+ setLinkUrl("");+ setLinkOpen(true);+ }++ function applyLink() {+ const url = linkUrl.trim();+ setLinkOpen(false);+ if (!url) return;+ const href = /^(https?:|mailto:)/i.test(url) ? url : `https://${url}`;+ editorRef.current?.focus();+ const selection = window.getSelection();+ if (savedRange.current && selection) {+ selection.removeAllRanges();+ selection.addRange(savedRange.current);+ }+ if (selection && selection.isCollapsed) {+ document.execCommand("insertHTML", false, `<a href="${href.replace(/"/g, """)}">${href}</a>`);+ } else {+ document.execCommand("createLink", false, href);+ }+ emit();+ }++ function onPaste(event: ClipboardEvent<HTMLDivElement>) {+ event.preventDefault();+ const text = event.clipboardData.getData("text/plain");+ document.execCommand("insertText", false, text);+ }++ function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ openLink();+ }+ }++ return (+ <div className={cn("flex min-h-0 flex-1 flex-col", className)}>+ <div className="relative min-h-0 flex-1 overflow-y-auto">+ <div+ ref={editorRef}+ id={id}+ role="textbox"+ aria-multiline="true"+ aria-label="Message body"+ contentEditable={!disabled}+ suppressContentEditableWarning+ data-placeholder={placeholder}+ onInput={emit}+ onBlur={emit}+ onPaste={onPaste}+ onKeyDown={onKeyDown}+ className={cn(+ "email-body max-w-none px-4 py-3 text-sm text-neutral-900 outline-none",+ "min-h-32 empty:before:pointer-events-none empty:before:text-neutral-400 empty:before:content-[attr(data-placeholder)]",+ disabled && "cursor-not-allowed opacity-60",+ )}+ />+ {quotedHtml && (+ <div className="px-4 pb-3">+ <button+ type="button"+ onClick={() => setShowQuoted((open) => !open)}+ aria-expanded={showQuoted}+ className="rounded-full border border-neutral-200 bg-neutral-100 px-2 text-xs leading-5 text-neutral-500 hover:bg-neutral-200"+ title={showQuoted ? "Hide quoted text" : "Show quoted text"}+ >+ •••+ </button>+ {showQuoted && (+ <div+ className="email-body mt-2 max-w-none border-l-2 border-neutral-200 pl-3 text-sm text-neutral-600"+ dangerouslySetInnerHTML={{ __html: quotedHtml }}+ />+ )}+ </div>+ )}+ </div>+ <div className="relative flex items-center gap-0.5 border-t border-neutral-100 px-2 py-1">+ {COMMANDS.map((item) => (+ <Tooltip key={item.command} label={item.label}>+ <button+ type="button"+ aria-label={item.label}+ aria-pressed={!!active[item.command]}+ disabled={disabled}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => run(item.command, item.value)}+ className={cn(+ "rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900",+ active[item.command] && "bg-neutral-200 text-neutral-900",+ )}+ >+ <item.icon className="h-4 w-4" />+ </button>+ </Tooltip>+ ))}+ <Tooltip label="Insert link (⌘K)">+ <button+ type="button"+ aria-label="Insert link"+ disabled={disabled}+ onMouseDown={(event) => event.preventDefault()}+ onClick={openLink}+ className="rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900"+ >+ <Link2 className="h-4 w-4" />+ </button>+ </Tooltip>+ <Tooltip label="Clear formatting">+ <button+ type="button"+ aria-label="Clear formatting"+ disabled={disabled}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => run("removeFormat")}+ className="rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900"+ >+ <RemoveFormatting className="h-4 w-4" />+ </button>+ </Tooltip>+ {linkOpen && (+ <form+ className="absolute bottom-full left-2 z-10 mb-1 flex items-center gap-2 rounded-lg border border-neutral-200 bg-white p-2 shadow-lg"+ onSubmit={(event) => {+ event.preventDefault();+ applyLink();+ }}+ >+ <input+ autoFocus+ value={linkUrl}+ onChange={(event) => setLinkUrl(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape") setLinkOpen(false);+ }}+ placeholder="https://example.com"+ className="h-8 w-64 rounded-md border border-neutral-200 px-2 text-sm outline-none focus:border-blue-400"+ />+ <button type="submit" className="rounded-md bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700">+ Apply+ </button>+ </form>+ )}+ </div>+ </div>+ );+}diff --git a/src/components/compose/rich-text-utils.ts b/src/components/compose/rich-text-utils.tsnew file mode 100644index 0000000..00f0171--- /dev/null+++ b/src/components/compose/rich-text-utils.ts@@ -0,0 +1,129 @@+/**+ * Helpers for the HTML composer. The editor owns one HTML string; the plain-text+ * alternative and the draft/send payloads are all derived from it, so there is+ * a single source of truth for what the message says.+ */++export const QUOTE_ATTRIBUTE = "data-mailflare-quote";+const QUOTE_OPEN = `<div class="mailflare-quote" ${QUOTE_ATTRIBUTE}="1">`;+const SIGNATURE_ATTRIBUTE = "data-mailflare-signature";++export function escapeHtml(value: string): string {+ return value+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """);+}++/** Plain text as HTML: escaped, with line breaks preserved. */+export function textToHtml(text: string | null | undefined): string {+ const value = (text ?? "").replace(/\r\n?/g, "\n");+ if (!value) return "";+ return `<div>${escapeHtml(value).replace(/\n/g, "<br>")}</div>`;+}++/** Wrap quoted or forwarded content so the composer and reader can fold it. */+export function wrapQuotedHtml(inner: string): string {+ return `${QUOTE_OPEN}${inner}</div>`;+}++/** Split a stored HTML body into the editable part and the folded quote, if any. */+export function splitQuotedHtml(html: string | null | undefined): { body: string; quoted: string | null } {+ const value = html ?? "";+ const index = value.indexOf(QUOTE_OPEN);+ if (index < 0) return { body: value, quoted: null };+ const inner = value.slice(index + QUOTE_OPEN.length).replace(/<\/div>\s*$/, "");+ return { body: value.slice(0, index), quoted: inner };+}++export function joinQuotedHtml(body: string, quoted: string | null): string {+ return quoted ? `${body}${wrapQuotedHtml(quoted)}` : body;+}++/** True when the HTML carries something other than empty blocks and whitespace. */+export function hasMeaningfulHtml(html: string): boolean {+ return htmlToPlainText(html).trim().length > 0 || /<img\b/i.test(html);+}++function signatureBlock(signature: string | null | undefined): string {+ const value = signature?.trim() ?? "";+ return value ? `<div ${SIGNATURE_ATTRIBUTE}="1"><br><br>${textToHtml(value).replace(/^<div>|<\/div>$/g, "")}</div>` : "";+}++/** Swap or append the mailbox signature, mirroring the plain-text behaviour. */+export function applyMailboxSignatureHtml(+ html: string,+ previousSignature: string | null | undefined,+ nextSignature: string | null | undefined,+): string {+ const previousBlock = signatureBlock(previousSignature);+ const nextBlock = signatureBlock(nextSignature);+ if (previousBlock && html.includes(previousBlock)) return html.replace(previousBlock, nextBlock);+ if (!nextBlock || html.includes(nextBlock)) return html;+ return `${html}${nextBlock}`;+}++const BLOCK_TAGS = new Set(["p", "div", "li", "tr", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "blockquote", "ul", "ol", "table"]);++/**+ * The text/plain alternative of a composed message. Blocks become lines, lists+ * get bullets or numbers, blockquotes get the classic "> " prefix so reply+ * chains stay readable in text-only clients and in Mailflare's own reader.+ */+export function htmlToPlainText(html: string | null | undefined): string {+ if (!html) return "";+ if (typeof DOMParser === "undefined") {+ return html.replace(/<br\s*\/?>/gi, "\n").replace(/<\/(p|div|li)>/gi, "\n").replace(/<[^>]+>/g, "");+ }+ const doc = new DOMParser().parseFromString(`<body>${html}</body>`, "text/html");+ const text = renderNode(doc.body, { listDepth: 0, ordered: [] });+ return text.replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();+}++type RenderState = { listDepth: number; ordered: Array<number | null> };++function renderNode(node: Node, state: RenderState): string {+ if (node.nodeType === Node.TEXT_NODE) return (node.textContent ?? "").replace(/\s+/g, " ");+ if (node.nodeType !== Node.ELEMENT_NODE) return "";+ const element = node as HTMLElement;+ const tag = element.tagName.toLowerCase();+ if (tag === "br") return "\n";+ if (tag === "style" || tag === "script" || tag === "head") return "";++ if (tag === "ul" || tag === "ol") {+ const next: RenderState = { listDepth: state.listDepth + 1, ordered: [...state.ordered, tag === "ol" ? 0 : null] };+ const items = Array.from(element.children)+ .map((child) => {+ const index = next.ordered.length - 1;+ if (next.ordered[index] !== null) next.ordered[index] = (next.ordered[index] ?? 0) + 1;+ const marker = next.ordered[index] !== null ? `${next.ordered[index]}. ` : "- ";+ const indent = " ".repeat(state.listDepth);+ return `${indent}${marker}${renderChildren(child, next).trim()}`;+ })+ .join("\n");+ return `\n${items}\n`;+ }++ let inner = renderChildren(element, state);+ if (tag === "a") {+ const href = element.getAttribute("href") ?? "";+ if (href && href !== inner.trim() && !href.startsWith("mailto:")) inner = `${inner} (${href})`;+ }+ if (tag === "blockquote") {+ const quoted = inner+ .trim()+ .split("\n")+ .map((line) => `> ${line}`)+ .join("\n");+ return `\n${quoted}\n`;+ }+ if (BLOCK_TAGS.has(tag)) return `\n${inner}\n`;+ return inner;+}++function renderChildren(element: Element, state: RenderState): string {+ return Array.from(element.childNodes)+ .map((child) => renderNode(child, state))+ .join("");+}diff --git a/src/components/compose/types.d.ts b/src/components/compose/types.d.tsindex e8c03f8..b0c01ad 100644--- a/src/components/compose/types.d.ts+++ b/src/components/compose/types.d.ts@@ -11,6 +11,16 @@ export type ComposeDraft = {inReplyTo?: string | null;references?: string | null;threadId?: string | null;+ /** Files already stored on the draft, e.g. carried over by Forward. */+ attachments?: ComposeStoredAttachment[];+};++export type ComposeStoredAttachment = {+ id: string;+ filename: string;+ size: number;+ type: string;+ disposition: "attachment" | "inline";};/** Headers a reply draft carries so the sent message joins its conversation. */diff --git a/src/components/compose/utils.ts b/src/components/compose/utils.tsindex 47fec37..7030c0b 100644--- a/src/components/compose/utils.ts+++ b/src/components/compose/utils.ts@@ -18,10 +18,13 @@ export function buildSendFormData(input: {mailboxId?: string;subject: string;text: string;+ html?: string;to: string;cc?: string;bcc?: string;threading?: ComposeThreading;+ /** Draft whose stored attachments should be sent with the message. */+ draftId?: string | null;}): FormData {const form = new FormData();form.set("from", input.from);@@ -30,10 +33,12 @@ export function buildSendFormData(input: {if (input.bcc) form.set("bcc", input.bcc);form.set("subject", input.subject);form.set("text", input.text);+ if (input.html) form.set("html", input.html);if (input.mailboxId) form.set("mailboxId", input.mailboxId);if (input.threading?.inReplyTo) form.set("inReplyTo", input.threading.inReplyTo);if (input.threading?.references) form.set("references", input.threading.references);if (input.threading?.threadId) form.set("threadId", input.threading.threadId);+ if (input.draftId) form.set("draftId", input.draftId);for (const attachment of input.attachments) {form.append("attachments", attachment.file);}diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsxindex 48f7523..75b535c 100644--- a/src/components/message-actions/message-actions.tsx+++ b/src/components/message-actions/message-actions.tsx@@ -2,7 +2,7 @@import { createElement, useState } from "react";import { useRouter } from "next/navigation";-import { Archive, Ban, BellOff, Mail, MailOpen, MoreVertical, Reply, ReplyAll, ShieldAlert, Trash2 } from "lucide-react";+import { Archive, Ban, BellOff, Forward, Mail, MailOpen, MoreVertical, Reply, ReplyAll, ShieldAlert, Trash2 } from "lucide-react";import { useCompose } from "@/components/compose/compose-context";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";@@ -11,6 +11,7 @@ import type { MessageActionsProps, ReplyMode } from "./types";import {confirmTrashWithoutUnsubscribe,blockMessageContact,+ createForwardDraft,createReplyDraft,createTrashSenderRule,getMessageActionRedirect,@@ -35,11 +36,13 @@ export function MessageActions({ownAddress,ownAddresses = [],message,+ messageMeta,+ bodyHtml,}: MessageActionsProps) {const router = useRouter();const { openDraftComposer } = useCompose();const [pendingAction, setPendingAction] = useState<- BulkMessageAction | "unsubscribe" | ReplyMode | "block" | null+ BulkMessageAction | "unsubscribe" | ReplyMode | "forward" | "block" | null>(null);const [error, setError] = useState<string | null>(null);const [moreOpen, setMoreOpen] = useState(false);@@ -106,6 +109,8 @@ export function MessageActions({ownAddress,subject,bodyText,+ bodyHtml,+ sentAt: messageMeta?.createdAt,recipients: getReplyRecipients(replyable, ownAddresses, mode),threading: getReplyThreading(replyable),});@@ -117,6 +122,26 @@ export function MessageActions({}}+ async function handleForward() {+ if (!message || !messageMeta) return;+ setPendingAction("forward");+ setError(null);+ try {+ const draftId = await createForwardDraft({+ mailboxId,+ ownAddress,+ message: { ...message, ...messageMeta },+ bodyText,+ bodyHtml,+ });+ openDraftComposer(draftId);+ } catch (forwardError) {+ setError(forwardError instanceof Error ? forwardError.message : "Could not start forward");+ } finally {+ setPendingAction(null);+ }+ }+async function onBlockContact() {setMoreOpen(false);setError(null);@@ -172,6 +197,20 @@ export function MessageActions({</Button></Tooltip>)}+ {message && messageMeta && (+ <Tooltip label="Forward">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ aria-label="Forward"+ disabled={disabled}+ onClick={() => void handleForward()}+ >+ <Forward className="h-5 w-5" />+ </Button>+ </Tooltip>+ )}<Tooltip label="Archive"><Buttonvariant="ghost"diff --git a/src/components/message-actions/types.d.ts b/src/components/message-actions/types.d.tsindex 92e439d..5092dc5 100644--- a/src/components/message-actions/types.d.ts+++ b/src/components/message-actions/types.d.ts@@ -17,9 +17,20 @@ export type MessageActionsProps = {ownAddresses?: string[];/** Recipient and threading headers of the message being acted on. */message?: ReplyableMessage;+ /** Needed by Forward, which quotes the original header block. */+ messageMeta?: Pick<Message, "id" | "subject" | "createdAt">;+ bodyHtml?: string | null;};-export type SingleMessageAction = BulkMessageAction | "reply" | "replyAll";+export type ForwardDraftInput = {+ mailboxId: string | null;+ ownAddress?: string | null;+ message: ReplyableMessage & Pick<Message, "id" | "subject" | "createdAt">;+ bodyText?: string | null;+ bodyHtml?: string | null;+};++export type SingleMessageAction = BulkMessageAction | "reply" | "replyAll" | "forward";export type ReplyMode = "reply" | "replyAll";@@ -39,6 +50,8 @@ export type ReplyDraftInput = {ownAddress?: string | null;subject?: string | null;bodyText?: string | null;+ bodyHtml?: string | null;+ sentAt?: string | null;recipients: ReplyRecipients;threading?: {inReplyTo: string | null;diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.tsindex a3241fd..f8d86d5 100644--- a/src/components/message-actions/utils.ts+++ b/src/components/message-actions/utils.ts@@ -2,8 +2,12 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";import { authFetch } from "@/lib/auth/client";import { getEmailAddress, normalizeEmailAddress, splitEmailAddressList } from "@/lib/email/address";import { getLatestEmailContent } from "@/lib/email/reply-content-utils";+import dayjs from "dayjs";+import { sanitizeEmailHtml } from "@/app/(dashboard)/inbox/[messageId]/email-html-sanitizer";+import { escapeHtml, htmlToPlainText, textToHtml, wrapQuotedHtml } from "@/components/compose/rich-text-utils";import type {BlockMessageContactInput,+ ForwardDraftInput,MoveMessageActionItem,ReplyableMessage,ReplyDraftInput,@@ -143,6 +147,26 @@ export function buildReplyQuote(return `\n\n${getEmailAddress(senderAddress)} wrote:\n${quoted}\n`;}+const QUOTE_STYLE = "margin:0 0 0 .8ex;border-left:1px solid #ccc;padding-left:1ex";++/**+ * The folded quote under a reply: the "On <date>, <sender> wrote:" line every+ * client recognises, then the original as HTML (sanitised) or as text.+ */+export function buildReplyQuoteHtml(+ senderAddress: string,+ sentAt: string | null | undefined,+ bodyText: string | null | undefined,+ bodyHtml: string | null | undefined,+) {+ const original = bodyHtml ? sanitizeEmailHtml(bodyHtml) : textToHtml(bodyText);+ if (!original) return null;+ const when = sentAt ? dayjs(sentAt).format("ddd, MMM D, YYYY [at] h:mm A") : "an earlier date";+ return wrapQuotedHtml(+ `<div>On ${escapeHtml(when)}, ${escapeHtml(senderAddress)} wrote:</div><blockquote style="${QUOTE_STYLE}">${original}</blockquote>`,+ );+}+/*** Who a reply goes to. A plain reply answers the sender; reply-all also keeps* everyone else on the To and Cc lines, minus the mailbox's own addresses so@@ -198,16 +222,69 @@ export function getReplyThreading(message: ReplyableMessage) {};}+export function buildForwardSubject(subject: string | null | undefined) {+ const trimmed = (subject ?? "").trim();+ if (!trimmed) return "Fwd:";+ return /^fwd?:/i.test(trimmed) ? trimmed : `Fwd: ${trimmed}`;+}++/** The header block mail clients put above a forwarded message, as folded HTML. */+export function buildForwardHtml(+ message: ForwardDraftInput["message"],+ bodyText: string | null | undefined,+ bodyHtml: string | null | undefined,+) {+ const lines = [+ `From: ${message.fromAddr}`,+ `Date: ${dayjs(message.createdAt).format("ddd, MMM D, YYYY [at] h:mm A")}`,+ `Subject: ${message.subject ?? "(no subject)"}`,+ `To: ${message.toAddr}`,+ ];+ if (message.ccAddr) lines.push(`Cc: ${message.ccAddr}`);+ const header = `<div>---------- Forwarded message ---------<br>${lines.map(escapeHtml).join("<br>")}</div><br>`;+ const original = bodyHtml ? sanitizeEmailHtml(bodyHtml) : textToHtml(bodyText);+ return wrapQuotedHtml(`${header}${original ?? ""}`);+}++/**+ * A forward keeps the original's attachments (copied onto the draft server-side)+ * and references its Message-ID so recipients who already have it see the link.+ */+export async function createForwardDraft({ mailboxId, ownAddress, message, bodyText, bodyHtml }: ForwardDraftInput) {+ const html = buildForwardHtml(message, bodyText, bodyHtml);+ const response = await authFetch("/api/drafts", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ mailboxId,+ from: getEmailAddress(ownAddress ?? ""),+ to: "",+ subject: buildForwardSubject(message.subject),+ html,+ text: htmlToPlainText(html),+ references: getReplyThreading(message).references,+ threadId: message.threadId,+ forwardOfMessageId: message.id,+ }),+ });+ const data = (await response.json()) as { draft?: { id: string }; error?: string };+ if (!response.ok || !data.draft) throw new Error(data.error ?? "Unable to start forward");+ return data.draft.id;+}+export async function createReplyDraft({mailboxId,senderAddress,ownAddress,subject,bodyText,+ bodyHtml,+ sentAt,recipients,threading,}: ReplyDraftInput) {if (recipients.to.length === 0) throw new Error("Sender address is required");+ const html = buildReplyQuoteHtml(senderAddress, sentAt, bodyText, bodyHtml) ?? "";const response = await authFetch("/api/drafts", {method: "POST",@@ -219,7 +296,8 @@ export async function createReplyDraft({to: recipients.to.join(", "),cc: recipients.cc.join(", "),subject: buildReplySubject(subject),- text: buildReplyQuote(senderAddress, bodyText),+ html,+ text: htmlToPlainText(html),...threading,}),});diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsxindex d103628..e9fb16c 100644--- a/src/components/messages/conversation-thread.tsx+++ b/src/components/messages/conversation-thread.tsx@@ -131,7 +131,7 @@ export function ConversationMessageCard({<{getEmailAddress(message.fromAddr)}></p>{body.html ? (- <div className="prose max-w-none text-sm text-neutral-900" dangerouslySetInnerHTML={{ __html: body.html }} />+ <div className="email-body max-w-none text-sm text-neutral-900" dangerouslySetInnerHTML={{ __html: body.html }} />) : (<pre className="whitespace-pre-wrap font-sans text-sm text-neutral-900">{body.text}</pre>)}diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsxindex 90e5b7b..bd89da6 100644--- a/src/components/messages/message-folder-page.tsx+++ b/src/components/messages/message-folder-page.tsx@@ -3,7 +3,7 @@import Link from "next/link";import { useEffect, useMemo, useState } from "react";import type { MouseEvent } from "react";-import { ChevronLeft, ChevronRight, ListFilter } from "lucide-react";+import { ChevronLeft, ChevronRight, ListFilter, MessagesSquare } from "lucide-react";import { Button } from "@/components/ui/button";import { Checkbox } from "@/components/ui/checkbox";import { Tooltip } from "@/components/ui/tooltip";@@ -14,11 +14,13 @@ import { usePageLoading } from "@/components/page-loading";import { useMessageCounts } from "@/hooks/use-message-counts";import { useMessages } from "@/hooks/use-messages";import type { BulkMessageAction } from "@/app/api/messages/bulk/types";+import type { Message } from "@/hooks/types";import { setMessageDragData } from "@/lib/messages/drag-utils";import { BulkMessageToolbar } from "./bulk-message-toolbar";import { MessageListRowActions } from "./message-list-row-actions";import { dispatchMessageCountsDelta, toggleMessageStar } from "./message-list-row-actions-utils";import { MessageNavigationProgress, useMessageNavigation } from "./message-navigation";+import { useConversationView } from "./use-conversation-view";import type { MessageFolderPageProps, MessageListRowProps } from "./types";import {formatMessageListTimestamp,@@ -51,7 +53,8 @@ function MessageListRow({useEffect(() => setRead(message.read), [message.read]);useEffect(() => setStarred(message.starred), [message.starred]);const rowMessage = { ...message, read, starred };- const unread = rowMessage.direction === "inbound" && !rowMessage.read;+ // A conversation row is unread when any message in it still is.+ const unread = (rowMessage.direction === "inbound" && !rowMessage.read) || (message.threadUnread ?? 0) > 0;const draggable = config.folder === "inbox" && message.direction === "inbound";const party = getMessageParty(rowMessage, config.folder, currentAccountName);const preview = getMessagePreview(rowMessage, config.folder);@@ -243,11 +246,14 @@ export function MessageFolderPage({>([]);const [pendingBulkAction, setPendingBulkAction] = useState(false);const [unreadOnly, setUnreadOnly] = useState(false);+ const [conversationView, setConversationView] = useConversationView();+ const grouped = conversationView && config.folder !== "drafts";const { messages, isLoading, total, limit, updateMessages } = useMessages(config.folder, selectedMailbox?.id, {query,limit: pageSize,offset,read: unreadOnly ? "unread" : "all",+ group: grouped ? "thread" : undefined,}, !mailboxesLoading, config.folderId);const { counts } = useMessageCounts(selectedMailbox?.id, !mailboxesLoading);usePageLoading(mailboxesLoading || isLoading);@@ -270,11 +276,16 @@ export function MessageFolderPage({);const hasUnreadSelection = selectedMessages.some((message) => !message.read);const allVisibleSelected = messages.length > 0 && messages.every((message) => selectedIds.includes(message.id));+ // In conversation view a row stands for every message of its thread in this+ // folder, so actions and drags carry all of them.+ const rowMessageIds = (message: Message) => message.threadMessageIds ?? [message.id];+ const expandSelectedIds = (ids: string[]) =>+ ids.flatMap((id) => rowMessageIds(messages.find((message) => message.id === id) ?? { id } as Message));useEffect(() => {setOffset(0);setSelectedMessages([]);- }, [query, selectedMailbox?.id, config.folder, config.folderId, unreadOnly]);+ }, [query, selectedMailbox?.id, config.folder, config.folderId, unreadOnly, grouped]);useEffect(() => {setSelectedMessages([]);@@ -297,7 +308,7 @@ export function MessageFolderPage({setSelectedMessages((current) => {if (!selected) return current.filter((item) => item.id !== messageId);if (current.some((item) => item.id === messageId)) return current;- return [...current, { id: message.id, read: message.read }];+ return [...current, { id: message.id, read: message.read && !(message.threadUnread ?? 0) }];});}@@ -310,7 +321,7 @@ export function MessageFolderPage({const next = new Map(current.map((message) => [message.id, message]));for (const message of messages) {- next.set(message.id, { id: message.id, read: message.read });+ next.set(message.id, { id: message.id, read: message.read && !(message.threadUnread ?? 0) });}return Array.from(next.values());});@@ -336,7 +347,7 @@ export function MessageFolderPage({if (inboxUnreadDelta) dispatchMessageCountsDelta({ inboxUnreadDelta });}try {- await runBulkMessageAction(selectedIds, action);+ await runBulkMessageAction(expandSelectedIds(selectedIds), action);setSelectedMessages([]);} catch (error) {if (readValue !== null) {@@ -411,6 +422,21 @@ export function MessageFolderPage({<ChevronRight className="h-4 w-4" /></Button></Tooltip>+ {config.folder !== "drafts" && (+ <Tooltip label={conversationView ? "Conversation view on" : "Conversation view off"}>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ aria-label="Toggle conversation view"+ aria-pressed={conversationView}+ onClick={() => setConversationView(!conversationView)}+ className={conversationView ? "bg-blue-100 text-blue-700 hover:bg-blue-100" : undefined}+ >+ <MessagesSquare className="h-4 w-4" />+ </Button>+ </Tooltip>+ )}{config.folder === "inbox" && (<Tooltip label={unreadOnly ? "Showing unread emails" : "Show unread emails only"}><Button@@ -444,8 +470,10 @@ export function MessageFolderPage({compact={compact}currentAccountName={currentAccountName}onSelectedChange={updateSelectedMessage}- onMessageAction={(messageId, action) => runBulkMessageAction([messageId], action, action !== "read" && action !== "unread")}- dragMessageIds={selectedIds.includes(message.id) ? selectedIds : [message.id]}+ onMessageAction={(messageId, action) =>+ runBulkMessageAction(expandSelectedIds([messageId]), action, action !== "read" && action !== "unread")+ }+ dragMessageIds={expandSelectedIds(selectedIds.includes(message.id) ? selectedIds : [message.id])}/>))}{!isLoading && messages.length === 0 && (diff --git a/src/components/messages/use-conversation-view.ts b/src/components/messages/use-conversation-view.tsnew file mode 100644index 0000000..6dc7e0b--- /dev/null+++ b/src/components/messages/use-conversation-view.ts@@ -0,0 +1,43 @@+import { useCallback, useEffect, useState } from "react";++const STORAGE_KEY = "mailflare-conversation-view";+const CHANGE_EVENT = "mailflare:conversation-view-changed";++function readStored(): boolean {+ try {+ return localStorage.getItem(STORAGE_KEY) !== "off";+ } catch {+ return true;+ }+}++/**+ * Whether lists collapse each conversation to one row. On by default and+ * remembered per browser; every open list follows a change immediately.+ */+export function useConversationView(): [boolean, (next: boolean) => void] {+ const [enabled, setEnabled] = useState(true);++ useEffect(() => {+ const sync = () => setEnabled(readStored());+ sync();+ window.addEventListener(CHANGE_EVENT, sync);+ window.addEventListener("storage", sync);+ return () => {+ window.removeEventListener(CHANGE_EVENT, sync);+ window.removeEventListener("storage", sync);+ };+ }, []);++ const update = useCallback((next: boolean) => {+ try {+ localStorage.setItem(STORAGE_KEY, next ? "on" : "off");+ } catch {+ // Private mode or blocked storage: the toggle still applies for this page.+ }+ setEnabled(next);+ window.dispatchEvent(new Event(CHANGE_EVENT));+ }, []);++ return [enabled, update];+}diff --git a/src/hooks/types.d.ts b/src/hooks/types.d.tsindex b8eb0a6..436defc 100644--- a/src/hooks/types.d.ts+++ b/src/hooks/types.d.ts@@ -31,6 +31,10 @@ export type Message = {references?: string | null;/** Messages in the same conversation (excluding drafts and trash), when the list API computed it. */threadCount?: number;+ /** Unread inbound messages in the conversation. */+ threadUnread?: number;+ /** In conversation view: every message this row stands for within the current folder. */+ threadMessageIds?: string[];createdAt: string;};@@ -62,6 +66,8 @@ export type MessageFilterOptions = {title?: string;limit?: number;offset?: number;+ /** "thread" collapses each conversation to its newest matching message. */+ group?: "thread";};export type MessageListResponse = {diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.tsindex 928111e..4e2fffa 100644--- a/src/hooks/use-messages.ts+++ b/src/hooks/use-messages.ts@@ -56,7 +56,7 @@ export function useMessages(window.removeEventListener("mailflare:messages-changed", onMessagesChanged);window.clearInterval(refreshInterval);};- }, [enabled, filters?.limit, filters?.offset, filters?.query, filters?.read, filters?.title, folder, folderId, mailboxId]);+ }, [enabled, filters?.group, filters?.limit, filters?.offset, filters?.query, filters?.read, filters?.title, folder, folderId, mailboxId]);return { messages, unreadCount, isLoading, total, limit, offset, updateMessages: setMessages };}diff --git a/src/hooks/utils.ts b/src/hooks/utils.tsindex 5fc3d20..c87be29 100644--- a/src/hooks/utils.ts+++ b/src/hooks/utils.ts@@ -68,6 +68,7 @@ export function getMessageQueryParams(if (parsedFilters?.read && parsedFilters.read !== "all") params.set("read", parsedFilters.read);if (filters?.limit) params.set("limit", String(filters.limit));if (filters?.offset) params.set("offset", String(filters.offset));+ if (filters?.group) params.set("group", filters.group);return params;}diff --git a/src/lib/email/attachments.ts b/src/lib/email/attachments.tsindex 9b3a797..29db1b2 100644--- a/src/lib/email/attachments.ts+++ b/src/lib/email/attachments.ts@@ -109,6 +109,101 @@ export async function storeMessageAttachments(return stored;}+/**+ * Duplicate a message's attachments onto another message (a forward draft).+ * R2 keys are unique per row, so the objects are copied rather than shared,+ * which keeps deleting the draft from touching the original.+ */+export async function copyMessageAttachments(+ env: CloudflareEnv,+ fromMessageId: string,+ toMessageId: string,+): Promise<AttachmentMetadata[]> {+ const db = getDb(env);+ const rows = await db.select().from(messageAttachments).where(eq(messageAttachments.messageId, fromMessageId));+ const copied: AttachmentMetadata[] = [];+ for (const row of rows) {+ const object = await env.BUCKET.get(row.r2Key);+ if (!object) continue;+ const id = newId("att");+ const r2Key = `attachments/${toMessageId}/${id}/${row.filename}`;+ await env.BUCKET.put(r2Key, await object.arrayBuffer(), {+ httpMetadata: { contentType: row.contentType },+ customMetadata: { filename: row.filename, messageId: toMessageId },+ });+ await db.insert(messageAttachments).values({+ id,+ messageId: toMessageId,+ filename: row.filename,+ contentType: row.contentType,+ size: row.size,+ disposition: row.disposition,+ contentId: row.contentId,+ r2Key,+ });+ copied.push({+ id,+ messageId: toMessageId,+ filename: row.filename,+ type: row.contentType,+ size: row.size,+ disposition: row.disposition as "attachment" | "inline",+ contentId: row.contentId,+ });+ }+ return copied;+}++/** Attachments with their bytes, for handing a draft's files to the send path. */+export async function loadMessageAttachmentContents(+ env: CloudflareEnv,+ messageId: string,+): Promise<AttachmentContent[]> {+ const db = getDb(env);+ const rows = await db.select().from(messageAttachments).where(eq(messageAttachments.messageId, messageId));+ const result: AttachmentContent[] = [];+ for (const row of rows) {+ const object = await env.BUCKET.get(row.r2Key);+ if (!object) continue;+ result.push({+ filename: row.filename,+ type: row.contentType,+ content: await object.arrayBuffer(),+ disposition: row.disposition as "attachment" | "inline",+ contentId: row.contentId,+ });+ }+ return result;+}++/** Remove one attachment (row and object). Returns false when it is not on that message. */+export async function deleteMessageAttachment(+ env: CloudflareEnv,+ messageId: string,+ attachmentId: string,+): Promise<boolean> {+ const db = getDb(env);+ const [row] = await db+ .select({ r2Key: messageAttachments.r2Key })+ .from(messageAttachments)+ .where(and(eq(messageAttachments.id, attachmentId), eq(messageAttachments.messageId, messageId)))+ .limit(1);+ if (!row) return false;+ await db.delete(messageAttachments).where(eq(messageAttachments.id, attachmentId));+ await env.BUCKET.delete(row.r2Key);+ return true;+}++/** Remove every attachment object of a message; the rows cascade with the message row. */+export async function deleteMessageAttachmentObjects(env: CloudflareEnv, messageId: string): Promise<void> {+ const db = getDb(env);+ const rows = await db+ .select({ r2Key: messageAttachments.r2Key })+ .from(messageAttachments)+ .where(eq(messageAttachments.messageId, messageId));+ await Promise.all(rows.map((row) => env.BUCKET.delete(row.r2Key)));+}+export async function listMessageAttachments(env: CloudflareEnv,messageId: string,