Skip to content

Email for professionals and teams

Improve UI

Hieu Nguyen (Jack)8a3c1d27fdd8
diff --git a/README.md b/README.md
index d734325..b2f6daa 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,20 @@ TypeScript email service on **Cloudflare Workers** (OpenNext + Next.js), **Drizz
- **First visit:** register → **onboarding** (add domain + first mailbox) → inbox.
- **Domains:** added via **Cloudflare API** (zone must exist on your account).
+### Features
+
+[x] Domain onboarding through Cloudflare, including inbound Email Routing DNS and sending DNS setup.
+[x] Domain removal cleanup for linked Cloudflare routing rules and sending subdomain resources.
+[x] Mailbox creation with automatic Cloudflare Email Routing rules.
+[x] Mailbox management with a grid view, mailbox detail page, and editable display name.
+[x] Inbox, sent, drafts, spam, and trash folders backed by a shared mail list component.
+[x] Popup composer with autosaved drafts and draft resume from the drafts folder.
+[x] Outbound send API, API keys, message read status, spam/trash moves, and seeded demo data.
+[] Advanced routing rules for catch-all addresses, forwarding, reject/block rules, and priorities.
+[] Webhook management UI and delivery retry visibility.
+[] Search, filtering, and richer mailbox/folder counts.
+[] Attachment support and richer compose formatting.
+
## Domain API (yes, programmatic)
Domains are **not** dashboard-only. This app calls Cloudflare when you add/remove a domain:
diff --git a/src/app/(dashboard)/admin/page.tsx b/src/app/(admin)/admin/page.tsx
similarity index 87%
rename from src/app/(dashboard)/admin/page.tsx
rename to src/app/(admin)/admin/page.tsx
index 8b5a38b..a6c2600 100644
--- a/src/app/(dashboard)/admin/page.tsx
+++ b/src/app/(admin)/admin/page.tsx
@@ -1,5 +1,5 @@
import Link from "next/link";
-import { Globe2, KeyRound, Mail, Route, Settings, Webhook } from "lucide-react";
+import { Globe2, KeyRound, Mail, Settings, Webhook } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
const sections = [
@@ -15,12 +15,6 @@ const sections = [
description: "Add Cloudflare domains and inspect DNS state.",
icon: Globe2,
},
- {
- href: "/routing",
- title: "Routing",
- description: "Configure inbound handling and forwarding rules.",
- icon: Route,
- },
{
href: "/api-keys",
title: "API Keys",
@@ -43,7 +37,7 @@ const sections = [
export default function AdminSettingsPage() {
return (
- <div className="h-full overflow-auto px-8 py-8">
+ <div className="h-full overflow-auto">
<div className="mb-8">
<h1 className="text-2xl font-normal text-neutral-900">Admin settings</h1>
<p className="mt-2 text-sm text-neutral-500">
diff --git a/src/app/(admin)/api-keys/page.tsx b/src/app/(admin)/api-keys/page.tsx
new file mode 100644
index 0000000..77cdb2f
--- /dev/null
+++ b/src/app/(admin)/api-keys/page.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { KeyRound, Plus } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Badge } from "@/components/ui/badge";
+import { Card, CardContent } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { ApiKey } from "./types";
+import { parseApiKeyScopes } from "./utils";
+
+export default function ApiKeysPage() {
+ const qc = useQueryClient();
+ const [name, setName] = useState("");
+ const [newKey, setNewKey] = useState<string | null>(null);
+ const [createOpen, setCreateOpen] = useState(false);
+
+ const { data, isLoading } = useQuery({
+ queryKey: ["api-keys"],
+ queryFn: async () => {
+ const res = await fetch("/api/api-keys");
+ return (await res.json()) as { apiKeys: ApiKey[] };
+ },
+ });
+
+ const create = useMutation({
+ mutationFn: async () => {
+ const res = await fetch("/api/api-keys", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name, scopes: ["send", "read"] }),
+ });
+ const json = (await res.json()) as { key?: string };
+ if (!res.ok) throw new Error("Failed");
+ setNewKey(json.key ?? null);
+ setName("");
+ },
+ onSuccess: () => {
+ setCreateOpen(false);
+ qc.invalidateQueries({ queryKey: ["api-keys"] });
+ },
+ });
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between gap-4">
+ <h1 className="text-2xl font-semibold">API Keys</h1>
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
+ <DialogTrigger asChild>
+ <Button>
+ <Plus className="h-4 w-4" />
+ New API key
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Create API key</DialogTitle>
+ <DialogDescription>Create a key with send and read permissions.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label>Name</Label>
+ <Input value={name} onChange={(e) => setName(e.target.value)} placeholder="Production app" />
+ </div>
+ {create.isError && (
+ <p className="text-sm text-red-600">{(create.error as Error).message}</p>
+ )}
+ <Button onClick={() => create.mutate()} disabled={!name || create.isPending}>
+ {create.isPending ? "Creating..." : "Create key"}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ {newKey && (
+ <Card className="border-blue-600/10 bg-blue-400/10">
+ <CardContent className="pt-6">
+ <p className="text-sm font-medium text-blue-600">Copy your key now:</p>
+ <code className="block mt-2 text-xs break-all font-bold">{newKey}</code>
+ </CardContent>
+ </Card>
+ )}
+ <section className="space-y-3">
+ <div className="flex items-center justify-between">
+ <span className="text-sm text-neutral-500">{(data?.apiKeys ?? []).length} total</span>
+ </div>
+ {isLoading && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ Loading API keys...
+ </p>
+ )}
+ {!isLoading && (data?.apiKeys ?? []).length === 0 && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ No API keys yet
+ </p>
+ )}
+ <div className="grid gap-3 md:grid-cols-2">
+ {(data?.apiKeys ?? []).map((key) => (
+ <div
+ key={key.id}
+ className="flex min-h-24 items-start gap-3 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm shadow-neutral-100"
+ >
+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600">
+ <KeyRound className="h-5 w-5" />
+ </span>
+ <span className="min-w-0 flex-1 space-y-2">
+ <span className="block truncate text-sm font-semibold text-neutral-900">{key.name}</span>
+ <span className="block truncate font-mono text-sm text-neutral-500">{key.prefix}...</span>
+ <span className="flex flex-wrap gap-1">
+ {parseApiKeyScopes(key.scopes).map((scope) => (
+ <Badge key={scope} variant="outline">
+ {scope}
+ </Badge>
+ ))}
+ </span>
+ </span>
+ </div>
+ ))}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/src/app/(admin)/api-keys/types.d.ts b/src/app/(admin)/api-keys/types.d.ts
new file mode 100644
index 0000000..8b2d235
--- /dev/null
+++ b/src/app/(admin)/api-keys/types.d.ts
@@ -0,0 +1,8 @@
+export type ApiKey = {
+ id: string;
+ name: string;
+ prefix: string;
+ scopes: string;
+ createdAt?: string;
+ lastUsedAt?: string | null;
+};
diff --git a/src/app/(admin)/api-keys/utils.ts b/src/app/(admin)/api-keys/utils.ts
new file mode 100644
index 0000000..9ec9fd2
--- /dev/null
+++ b/src/app/(admin)/api-keys/utils.ts
@@ -0,0 +1,8 @@
+export function parseApiKeyScopes(scopes: string): string[] {
+ try {
+ const parsed = JSON.parse(scopes);
+ return Array.isArray(parsed) ? parsed.filter((scope) => typeof scope === "string") : [];
+ } catch {
+ return [];
+ }
+}
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
new file mode 100644
index 0000000..541ad2d
--- /dev/null
+++ b/src/app/(admin)/domains/page.tsx
@@ -0,0 +1,279 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useState } from "react";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Badge } from "@/components/ui/badge";
+import {
+ Check,
+ X,
+ AlertTriangle,
+ ArrowRight,
+ Globe2,
+ Plus,
+ Trash2,
+} from "lucide-react";
+import type { DnsRecord, DnsStatusSummary, Domain } from "./types";
+
+export default function DomainsPage() {
+ const qc = useQueryClient();
+ const [hostname, setHostname] = useState("");
+ const [createOpen, setCreateOpen] = useState(false);
+ const [dnsView, setDnsView] = useState<{
+ domain: Domain;
+ dns: unknown;
+ } | null>(null);
+
+ const { data, isLoading } = useQuery({
+ queryKey: ["domains"],
+ queryFn: async () => {
+ const res = await fetch("/api/domains?includeDns=true");
+ return (await res.json()) as {
+ domains: Domain[];
+ dns: Record<string, DnsStatusSummary>;
+ };
+ },
+ });
+
+ const create = useMutation({
+ mutationFn: async () => {
+ const res = await fetch("/api/domains", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ hostname,
+ enableRouting: true,
+ enableSending: true,
+ }),
+ });
+ const json = (await res.json()) as { error?: string };
+ if (!res.ok) throw new Error(json.error ?? "Failed");
+ return json;
+ },
+ onSuccess: () => {
+ setHostname("");
+ setCreateOpen(false);
+ qc.invalidateQueries({ queryKey: ["domains"] });
+ },
+ });
+
+ const remove = useMutation({
+ mutationFn: async (id: string) => {
+ const res = await fetch(`/api/domains/${id}`, { method: "DELETE" });
+ if (!res.ok) throw new Error("Failed to remove");
+ },
+ onSuccess: () => qc.invalidateQueries({ queryKey: ["domains"] }),
+ });
+
+ const loadDns = async (id: string) => {
+ const res = await fetch(`/api/domains/${id}/dns`);
+ const json = (await res.json()) as { domain: Domain; dns: unknown };
+ if (res.ok) setDnsView(json);
+ };
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between gap-4">
+ <div>
+ <h1 className="text-2xl font-semibold">Domains</h1>
+ <p className="mt-1 text-sm text-neutral-500">
+ Domains must be on your Cloudflare account. Adding a domain enables
+ Email Routing and Email Sending DNS automatically.
+ </p>
+ </div>
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
+ <DialogTrigger asChild>
+ <Button>
+ <Plus className="h-4 w-4" />
+ New domain
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Add domain</DialogTitle>
+ <DialogDescription>
+ Provision Cloudflare routing and sending DNS for a zone in your
+ account.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="hostname">Hostname</Label>
+ <Input
+ id="hostname"
+ value={hostname}
+ onChange={(e) => setHostname(e.target.value)}
+ placeholder="example.com"
+ />
+ </div>
+ {create.isError && (
+ <p className="text-sm text-red-600">
+ {(create.error as Error).message}
+ </p>
+ )}
+ <Button
+ onClick={() => create.mutate()}
+ disabled={!hostname || create.isPending}
+ >
+ {create.isPending ? "Adding..." : "Add domain"}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ <section className="space-y-3">
+ {/* <div className="flex items-center justify-between">
+ <span className="text-sm text-neutral-500">{(data?.domains ?? []).length} total</span>
+ </div> */}
+ {isLoading && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ Loading DNS status...
+ </p>
+ )}
+ {!isLoading && (data?.domains ?? []).length === 0 && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ No domains yet
+ </p>
+ )}
+ <div className="grid gap-3 md:grid-cols-2">
+ {(data?.domains ?? []).map((d) => {
+ const dns = data?.dns?.[d.id];
+ return (
+ <div
+ key={d.id}
+ className="flex min-h-36 flex-col gap-3 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm shadow-neutral-100"
+ >
+ <div className="flex items-start gap-3">
+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600">
+ <Globe2 className="h-5 w-5" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <span className="block truncate font-mono text-sm font-semibold text-neutral-900">
+ {d.hostname}
+ </span>
+ <div className="mt-2 flex flex-wrap gap-2">
+ <Badge
+ variant={
+ d.status === "active" ? "success" : "secondary"
+ }
+ >
+ {d.status}
+ </Badge>
+ {d.routingEnabled && (
+ <Badge variant="outline">routing</Badge>
+ )}
+ {d.sendingEnabled && (
+ <Badge variant="outline">sending</Badge>
+ )}
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => loadDns(d.id)}
+ >
+ DNS
+ </Button>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => remove.mutate(d.id)}
+ disabled={remove.isPending}
+ aria-label={`Remove ${d.hostname}`}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ </div>
+ {dns && (
+ <div className="flex flex-wrap items-center gap-3 text-xs">
+ <span className="flex items-center gap-1 text-neutral-500">
+ Routing{" "}
+ {dns.routing.configured ? (
+ <Check className="h-3.5 w-3.5 text-green-600" />
+ ) : (
+ <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
+ )}
+ </span>
+ {dns.routing.missing.length > 0 && (
+ <span className="text-red-600 flex items-center gap-1">
+ <X className="h-3 w-3" />
+ Missing: {dns.routing.missing.join(", ")}
+ </span>
+ )}
+ <span className="text-neutral-300">|</span>
+ <span className="flex items-center gap-1 text-neutral-500">
+ Sending{" "}
+ {dns.sending.configured ? (
+ <Check className="h-3.5 w-3.5 text-green-600" />
+ ) : (
+ <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
+ )}
+ </span>
+ {dns.sending.records.length > 0 && (
+ <span className="text-neutral-500">
+ {dns.sending.records.join(", ")}
+ </span>
+ )}
+ <button
+ onClick={() => loadDns(d.id)}
+ className="flex items-center gap-0.5 text-blue-600 hover:text-blue-800"
+ >
+ <ArrowRight className="h-3 w-3" />
+ details
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </section>
+ {dnsView && (
+ <Card>
+ <CardHeader>
+ <CardTitle>DNS — {dnsView.domain.hostname}</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4 text-xs font-mono">
+ <div>
+ <p className="font-sans font-medium text-sm mb-2">
+ Email Routing
+ </p>
+ <pre className="overflow-auto bg-neutral-50 dark:bg-neutral-900 p-3 rounded-md">
+ {JSON.stringify(
+ (dnsView.dns as { routing: unknown }).routing,
+ null,
+ 2,
+ )}
+ </pre>
+ </div>
+ <div>
+ <p className="font-sans font-medium text-sm mb-2">
+ Email Sending
+ </p>
+ <pre className="overflow-auto bg-neutral-50 dark:bg-neutral-900 p-3 rounded-md">
+ {JSON.stringify(
+ (dnsView.dns as { sending: DnsRecord[] }).sending,
+ null,
+ 2,
+ )}
+ </pre>
+ </div>
+ </CardContent>
+ </Card>
+ )}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/domains/types.d.ts b/src/app/(admin)/domains/types.d.ts
new file mode 100644
index 0000000..8ba5db2
--- /dev/null
+++ b/src/app/(admin)/domains/types.d.ts
@@ -0,0 +1,20 @@
+export type Domain = {
+ id: string;
+ hostname: string;
+ status: string;
+ routingEnabled: boolean;
+ sendingEnabled: boolean;
+ zoneId: string;
+};
+
+export type DnsRecord = {
+ type?: string;
+ name?: string;
+ content?: string;
+ priority?: number;
+};
+
+export type DnsStatusSummary = {
+ routing: { configured: boolean; missing: string[] };
+ sending: { configured: boolean; records: string[] };
+};
diff --git a/src/app/(admin)/layout.tsx b/src/app/(admin)/layout.tsx
new file mode 100644
index 0000000..a53e836
--- /dev/null
+++ b/src/app/(admin)/layout.tsx
@@ -0,0 +1,54 @@
+import Link from "next/link";
+import { redirect } from "next/navigation";
+import { HelpCircle, Search } from "lucide-react";
+
+export const dynamic = "force-dynamic";
+import { ComposeProvider } from "@/components/compose/compose-context";
+import { FloatingComposer } from "@/components/compose/floating-composer";
+import { DashboardShellNav } from "@/components/dashboard-shell";
+import { MailboxProvider } from "@/components/mailbox-provider";
+import { MailboxSelector } from "@/components/mailbox-selector";
+import { getEnv } from "@/lib/cloudflare";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { AdminNav } from "@/components/admin-nav";
+
+export default async function DashboardLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ const env = getEnv();
+ const user = await getCurrentUser(env);
+ if (!user) redirect("/login");
+
+ return (
+ <MailboxProvider>
+ <ComposeProvider>
+ <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
+ <aside className="flex flex-col gap-4 px-3 py-4">
+ <AdminNav />
+ </aside>
+ <div className="flex min-h-screen flex-col">
+ <header className="flex h-16 items-center gap-4 pr-4 text-sm">
+ <div className="flex h-12 flex-1 max-w-3xl items-center gap-3 rounded-full bg-[#eaf1fb] px-4 text-neutral-600">
+ <Search className="h-5 w-5" />
+ <span className="text-[15px]">Search mail</span>
+ </div>
+ <Link
+ href="/settings"
+ className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
+ >
+ <HelpCircle className="h-5 w-5" />
+ </Link>
+ <MailboxSelector />
+ </header>
+ <main className="flex-1 overflow-hidden rounded-t-3xl bg-white px-12 py-8 w-fit min-w-172">
+ {children}
+ </main>
+ </div>
+ <FloatingComposer />
+ </div>
+ </ComposeProvider>
+ </MailboxProvider>
+ );
+}
diff --git a/src/app/(admin)/mailboxes/[id]/page.tsx b/src/app/(admin)/mailboxes/[id]/page.tsx
new file mode 100644
index 0000000..5d526b1
--- /dev/null
+++ b/src/app/(admin)/mailboxes/[id]/page.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { ArrowLeft, Mail, Save } from "lucide-react";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useEffect, useState } from "react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { fetchMailbox, getMailboxAddress, updateMailboxName } from "./utils";
+
+export default function MailboxSettingsPage() {
+ const params = useParams<{ id: string }>();
+ const mailboxId = params.id;
+ const qc = useQueryClient();
+ const [displayName, setDisplayName] = useState("");
+
+ const mailbox = useQuery({
+ queryKey: ["mailbox", mailboxId],
+ queryFn: () => fetchMailbox(mailboxId),
+ enabled: !!mailboxId,
+ });
+
+ useEffect(() => {
+ if (mailbox.data) setDisplayName(mailbox.data.displayName ?? "");
+ }, [mailbox.data]);
+
+ const updateName = useMutation({
+ mutationFn: () => updateMailboxName(mailboxId, displayName),
+ onSuccess: (updatedMailbox) => {
+ qc.setQueryData(["mailbox", mailboxId], updatedMailbox);
+ qc.invalidateQueries({ queryKey: ["mailboxes"] });
+ },
+ });
+
+ const address = mailbox.data ? getMailboxAddress(mailbox.data) : "";
+
+ return (
+ <div className="max-w-3xl space-y-6">
+ <div className="flex items-center gap-3">
+ <Button asChild variant="ghost" size="sm">
+ <Link href="/mailboxes">
+ <ArrowLeft className="h-4 w-4" />
+ Mailboxes
+ </Link>
+ </Button>
+ </div>
+
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h1 className="truncate text-2xl font-semibold text-neutral-900">
+ {mailbox.data?.displayName || mailbox.data?.localPart || "Mailbox"}
+ </h1>
+ <p className="mt-1 truncate font-mono text-sm text-neutral-500">
+ {address || "Loading mailbox..."}
+ </p>
+ </div>
+ {mailbox.data?.isPrimary && <Badge variant="secondary">Primary</Badge>}
+ </div>
+
+ {mailbox.isError && (
+ <p className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
+ {mailbox.error instanceof Error ? mailbox.error.message : "Failed to load mailbox"}
+ </p>
+ )}
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Settings</CardTitle>
+ <CardDescription>
+ Update the mailbox label shown in selectors and mailbox lists.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <div className="space-y-2">
+ <Label htmlFor="displayName">Name</Label>
+ <Input
+ id="displayName"
+ value={displayName}
+ onChange={(event) => setDisplayName(event.target.value)}
+ placeholder={mailbox.data?.localPart ?? "Mailbox name"}
+ disabled={mailbox.isLoading || updateName.isPending}
+ />
+ </div>
+ {updateName.isError && (
+ <p className="text-sm text-red-600">
+ {updateName.error instanceof Error
+ ? updateName.error.message
+ : "Failed to update mailbox"}
+ </p>
+ )}
+ {updateName.isSuccess && (
+ <p className="text-sm text-green-700">Mailbox settings saved</p>
+ )}
+ <Button
+ onClick={() => updateName.mutate()}
+ disabled={mailbox.isLoading || updateName.isPending}
+ >
+ <Save className="h-4 w-4" />
+ {updateName.isPending ? "Saving..." : "Save changes"}
+ </Button>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Address</CardTitle>
+ <CardDescription>
+ The email address, username, and domain are managed as routing resources.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="grid gap-4 sm:grid-cols-2">
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Email</p>
+ <p className="truncate font-mono text-sm text-neutral-900">{address || "-"}</p>
+ </div>
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Username</p>
+ <p className="truncate font-mono text-sm text-neutral-900">
+ {mailbox.data?.localPart ?? "-"}
+ </p>
+ </div>
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Domain</p>
+ <p className="truncate font-mono text-sm text-neutral-900">
+ {mailbox.data?.hostname ?? "-"}
+ </p>
+ </div>
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">Routing</p>
+ <p className="flex items-center gap-2 text-sm text-neutral-900">
+ <Mail className="h-4 w-4 text-neutral-400" />
+ Cloudflare Email Routing
+ </p>
+ </div>
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
diff --git a/src/app/(admin)/mailboxes/[id]/types.d.ts b/src/app/(admin)/mailboxes/[id]/types.d.ts
new file mode 100644
index 0000000..c040c00
--- /dev/null
+++ b/src/app/(admin)/mailboxes/[id]/types.d.ts
@@ -0,0 +1,15 @@
+export type MailboxDetail = {
+ id: string;
+ userId: string;
+ domainId: string;
+ localPart: string;
+ displayName: string | null;
+ createdAt: string;
+ hostname: string;
+ isPrimary?: boolean;
+};
+
+export type MailboxDetailResponse = {
+ mailbox?: MailboxDetail;
+ error?: string;
+};
diff --git a/src/app/(admin)/mailboxes/[id]/utils.ts b/src/app/(admin)/mailboxes/[id]/utils.ts
new file mode 100644
index 0000000..715efb8
--- /dev/null
+++ b/src/app/(admin)/mailboxes/[id]/utils.ts
@@ -0,0 +1,31 @@
+import type { MailboxDetail, MailboxDetailResponse } from "./types";
+
+export function getMailboxAddress(mailbox: Pick<MailboxDetail, "localPart" | "hostname">): string {
+ return `${mailbox.localPart}@${mailbox.hostname}`;
+}
+
+export async function fetchMailbox(id: string): Promise<MailboxDetail> {
+ const res = await fetch(`/api/mailboxes/${id}`);
+ const json = (await res.json()) as MailboxDetailResponse;
+
+ if (!res.ok || !json.mailbox) {
+ throw new Error(json.error ?? "Failed to load mailbox");
+ }
+
+ return json.mailbox;
+}
+
+export async function updateMailboxName(id: string, displayName: string): Promise<MailboxDetail> {
+ const res = await fetch(`/api/mailboxes/${id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ displayName }),
+ });
+ const json = (await res.json()) as MailboxDetailResponse;
+
+ if (!res.ok || !json.mailbox) {
+ throw new Error(json.error ?? "Failed to update mailbox");
+ }
+
+ return json.mailbox;
+}
diff --git a/src/app/(admin)/mailboxes/page.tsx b/src/app/(admin)/mailboxes/page.tsx
new file mode 100644
index 0000000..08b8d4a
--- /dev/null
+++ b/src/app/(admin)/mailboxes/page.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import Link from "next/link";
+import { useState } from "react";
+import { Mail, Plus } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { Domain, Mailbox } from "./types";
+import { getMailboxAddress, getMailboxName } from "./utils";
+
+export default function MailboxesPage() {
+ const qc = useQueryClient();
+ const [localPart, setLocalPart] = useState("");
+ const [domainId, setDomainId] = useState("");
+ const [createOpen, setCreateOpen] = useState(false);
+
+ const domains = useQuery({
+ queryKey: ["domains"],
+ queryFn: async () => {
+ const res = await fetch("/api/domains");
+ return (await res.json()) as { domains: Domain[] };
+ },
+ });
+
+ const mailboxes = useQuery({
+ queryKey: ["mailboxes"],
+ queryFn: async () => {
+ const res = await fetch("/api/mailboxes");
+ return (await res.json()) as { mailboxes: Mailbox[] };
+ },
+ });
+
+ const create = useMutation({
+ mutationFn: async () => {
+ const res = await fetch("/api/mailboxes", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ domainId, localPart, displayName: localPart }),
+ });
+ const json = (await res.json()) as { error?: string };
+ if (!res.ok) throw new Error(json.error ?? "Failed");
+ setLocalPart("");
+ setDomainId("");
+ },
+ onSuccess: () => {
+ setCreateOpen(false);
+ qc.invalidateQueries({ queryKey: ["mailboxes"] });
+ },
+ });
+
+ const domainMap = new Map(
+ (domains.data?.domains ?? []).map((d) => [d.id, d.hostname]),
+ );
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-center justify-between gap-4">
+ <h1 className="text-2xl font-semibold">Mailboxes</h1>
+ <Dialog open={createOpen} onOpenChange={setCreateOpen}>
+ <DialogTrigger asChild>
+ <Button>
+ <Plus className="h-4 w-4" />
+ New mailbox
+ </Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Create mailbox</DialogTitle>
+ <DialogDescription>Add a mailbox and provision its routing rule automatically.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label>Domain</Label>
+ <select
+ className="w-full h-10 rounded-md border border-neutral-200 px-3 text-sm shadow-sm shadow-neutral-200/50 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:border-blue-600 disabled:cursor-not-allowed disabled:opacity-50"
+ value={domainId}
+ onChange={(event) => setDomainId(event.target.value)}
+ >
+ <option value="">Select domain</option>
+ {(domains.data?.domains ?? []).map((domain) => (
+ <option key={domain.id} value={domain.id}>
+ {domain.hostname}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="space-y-2 relative">
+ <Label>Username</Label>
+ <Input
+ value={localPart}
+ onChange={(event) => setLocalPart(event.target.value)}
+ placeholder="support"
+ />
+ {domainId && (
+ <span className="absolute bottom-2.5 right-4 text-sm text-neutral-400">
+ @{domainMap.get(domainId)}
+ </span>
+ )}
+ </div>
+ {create.isError && (
+ <p className="text-sm text-red-600">{(create.error as Error).message}</p>
+ )}
+ <Button
+ onClick={() => create.mutate()}
+ disabled={!domainId || !localPart || create.isPending}
+ >
+ {create.isPending ? "Creating..." : "Create mailbox"}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </div>
+ <section className="space-y-3">
+ {/* <div className="flex items-center justify-between">
+ <span className="text-sm text-neutral-500">
+ {(mailboxes.data?.mailboxes ?? []).length} total
+ </span>
+ </div> */}
+ {mailboxes.isLoading && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ Loading mailboxes...
+ </p>
+ )}
+ {!mailboxes.isLoading && (mailboxes.data?.mailboxes ?? []).length === 0 && (
+ <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ No mailboxes yet
+ </p>
+ )}
+ <div className="grid gap-3 md:grid-cols-2">
+ {(mailboxes.data?.mailboxes ?? []).map((mailbox) => {
+ const mailboxWithHostname = {
+ ...mailbox,
+ hostname: mailbox.hostname ?? domainMap.get(mailbox.domainId) ?? "?",
+ };
+
+ return (
+ <Link
+ key={mailbox.id}
+ href={`/mailboxes/${mailbox.id}`}
+ className="group flex min-h-24 items-start gap-3 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm shadow-neutral-100 transition hover:border-blue-200 hover:bg-[#f8fbff] hover:shadow-md"
+ >
+ <span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-neutral-100 text-neutral-600 group-hover:bg-blue-50 group-hover:text-blue-700">
+ <Mail className="h-5 w-5" />
+ </span>
+ <span className="min-w-0 space-y-1">
+ <span className="block truncate text-sm font-semibold text-neutral-900">
+ {getMailboxName(mailboxWithHostname)}
+ </span>
+ <span className="block truncate font-mono text-sm text-neutral-500">
+ {getMailboxAddress(mailboxWithHostname)}
+ </span>
+ </span>
+ </Link>
+ );
+ })}
+ </div>
+ </section>
+ </div>
+ );
+}
diff --git a/src/app/(admin)/mailboxes/types.d.ts b/src/app/(admin)/mailboxes/types.d.ts
new file mode 100644
index 0000000..576e4a1
--- /dev/null
+++ b/src/app/(admin)/mailboxes/types.d.ts
@@ -0,0 +1,13 @@
+export type Mailbox = {
+ id: string;
+ localPart: string;
+ displayName: string | null;
+ domainId: string;
+ hostname: string;
+ isPrimary?: boolean;
+};
+
+export type Domain = {
+ id: string;
+ hostname: string;
+};
diff --git a/src/app/(admin)/mailboxes/utils.ts b/src/app/(admin)/mailboxes/utils.ts
new file mode 100644
index 0000000..1c7ddfb
--- /dev/null
+++ b/src/app/(admin)/mailboxes/utils.ts
@@ -0,0 +1,9 @@
+import type { Mailbox } from "./types";
+
+export function getMailboxAddress(mailbox: Pick<Mailbox, "localPart" | "hostname">): string {
+ return `${mailbox.localPart}@${mailbox.hostname}`;
+}
+
+export function getMailboxName(mailbox: Pick<Mailbox, "displayName" | "localPart">): string {
+ return mailbox.displayName?.trim() || mailbox.localPart;
+}
diff --git a/src/app/(dashboard)/routing/page.tsx b/src/app/(admin)/routing/page.tsx
similarity index 98%
rename from src/app/(dashboard)/routing/page.tsx
rename to src/app/(admin)/routing/page.tsx
index 3650669..10dd2d4 100644
--- a/src/app/(dashboard)/routing/page.tsx
+++ b/src/app/(admin)/routing/page.tsx
@@ -51,7 +51,7 @@ export default function RoutingPage() {
<div className="space-y-2">
<Label>Domain</Label>
<select
- className="w-full h-10 rounded-md border border-neutral-200 dark:border-neutral-800 px-3 text-sm"
+ className="w-full h-10 rounded-md border border-neutral-200 px-3 text-sm"
value={domainId}
onChange={(e) => setDomainId(e.target.value)}
>
diff --git a/src/app/(dashboard)/settings/page.tsx b/src/app/(admin)/settings/page.tsx
similarity index 100%
rename from src/app/(dashboard)/settings/page.tsx
rename to src/app/(admin)/settings/page.tsx
diff --git a/src/app/(dashboard)/webhooks/page.tsx b/src/app/(admin)/webhooks/page.tsx
similarity index 100%
rename from src/app/(dashboard)/webhooks/page.tsx
rename to src/app/(admin)/webhooks/page.tsx
diff --git a/src/app/(dashboard)/api-keys/page.tsx b/src/app/(dashboard)/api-keys/page.tsx
deleted file mode 100644
index 5146257..0000000
--- a/src/app/(dashboard)/api-keys/page.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-"use client";
-
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useState } from "react";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-
-type ApiKey = { id: string; name: string; prefix: string; scopes: string };
-
-export default function ApiKeysPage() {
- const qc = useQueryClient();
- const [name, setName] = useState("");
- const [newKey, setNewKey] = useState<string | null>(null);
-
- const { data } = useQuery({
- queryKey: ["api-keys"],
- queryFn: async () => {
- const res = await fetch("/api/api-keys");
- return (await res.json()) as { apiKeys: ApiKey[] };
- },
- });
-
- const create = useMutation({
- mutationFn: async () => {
- const res = await fetch("/api/api-keys", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ name, scopes: ["send", "read"] }),
- });
- const json = (await res.json()) as { key?: string };
- if (!res.ok) throw new Error("Failed");
- setNewKey(json.key ?? null);
- setName("");
- },
- onSuccess: () => qc.invalidateQueries({ queryKey: ["api-keys"] }),
- });
-
- return (
- <div className="space-y-6 max-w-2xl">
- <h1 className="text-2xl font-semibold">API Keys</h1>
- {newKey && (
- <Card className="border-amber-300 bg-amber-50 dark:bg-amber-950">
- <CardContent className="pt-6">
- <p className="text-sm font-medium">Copy your key now:</p>
- <code className="block mt-2 text-xs break-all">{newKey}</code>
- </CardContent>
- </Card>
- )}
- <Card>
- <CardHeader>
- <CardTitle>Create key</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="space-y-2">
- <Label>Name</Label>
- <Input value={name} onChange={(e) => setName(e.target.value)} />
- </div>
- <Button onClick={() => create.mutate()} disabled={!name || create.isPending}>
- Create
- </Button>
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle>Keys</CardTitle>
- </CardHeader>
- <CardContent className="space-y-2 text-sm">
- {(data?.apiKeys ?? []).map((k) => (
- <div key={k.id} className="flex justify-between">
- <span>
- {k.name} · <code>{k.prefix}…</code>
- </span>
- <span className="text-neutral-500">{k.scopes}</span>
- </div>
- ))}
- </CardContent>
- </Card>
- </div>
- );
-}
diff --git a/src/app/(dashboard)/domains/page.tsx b/src/app/(dashboard)/domains/page.tsx
deleted file mode 100644
index 4ceb55c..0000000
--- a/src/app/(dashboard)/domains/page.tsx
+++ /dev/null
@@ -1,211 +0,0 @@
-"use client";
-
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useState } from "react";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-import { Badge } from "@/components/ui/badge";
-import { Check, X, AlertTriangle, ArrowRight } from "lucide-react";
-
-type Domain = {
- id: string;
- hostname: string;
- status: string;
- routingEnabled: boolean;
- sendingEnabled: boolean;
- zoneId: string;
-};
-
-type DnsRecord = { type?: string; name?: string; content?: string; priority?: number };
-
-type DnsStatusSummary = {
- routing: { configured: boolean; missing: string[] };
- sending: { configured: boolean; records: string[] };
-};
-
-export default function DomainsPage() {
- const qc = useQueryClient();
- const [hostname, setHostname] = useState("");
- const [dnsView, setDnsView] = useState<{ domain: Domain; dns: unknown } | null>(null);
-
- const { data, isLoading } = useQuery({
- queryKey: ["domains"],
- queryFn: async () => {
- const res = await fetch("/api/domains?includeDns=true");
- return (await res.json()) as {
- domains: Domain[];
- dns: Record<string, DnsStatusSummary>;
- };
- },
- });
-
- const create = useMutation({
- mutationFn: async () => {
- const res = await fetch("/api/domains", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ hostname, enableRouting: true, enableSending: true }),
- });
- const json = (await res.json()) as { error?: string };
- if (!res.ok) throw new Error(json.error ?? "Failed");
- return json;
- },
- onSuccess: () => {
- setHostname("");
- qc.invalidateQueries({ queryKey: ["domains"] });
- },
- });
-
- const remove = useMutation({
- mutationFn: async (id: string) => {
- const res = await fetch(`/api/domains/${id}`, { method: "DELETE" });
- if (!res.ok) throw new Error("Failed to remove");
- },
- onSuccess: () => qc.invalidateQueries({ queryKey: ["domains"] }),
- });
-
- const loadDns = async (id: string) => {
- const res = await fetch(`/api/domains/${id}/dns`);
- const json = (await res.json()) as { domain: Domain; dns: unknown };
- if (res.ok) setDnsView(json);
- };
-
- return (
- <div className="space-y-6 max-w-3xl">
- <h1 className="text-2xl font-semibold">Domains</h1>
- <p className="text-sm text-neutral-500">
- Domains must be on your Cloudflare account. Adding a domain calls the Cloudflare API to enable Email
- Routing (inbound MX/SPF/DKIM) and Email Sending DNS automatically.
- </p>
- <Card>
- <CardHeader>
- <CardTitle>Add domain</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="space-y-2">
- <Label htmlFor="hostname">Hostname</Label>
- <Input
- id="hostname"
- value={hostname}
- onChange={(e) => setHostname(e.target.value)}
- placeholder="example.com"
- />
- </div>
- <Button onClick={() => create.mutate()} disabled={!hostname || create.isPending}>
- {create.isPending ? "Adding..." : "Add via Cloudflare API"}
- </Button>
- {create.isError && (
- <p className="text-sm text-red-600">{(create.error as Error).message}</p>
- )}
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle>Your domains</CardTitle>
- </CardHeader>
- <CardContent className="space-y-3">
- {isLoading && (
- <p className="text-sm text-neutral-500">Loading DNS status...</p>
- )}
- {(data?.domains ?? []).map((d) => {
- const dns = data?.dns?.[d.id];
- return (
- <div
- key={d.id}
- className="flex flex-col gap-2 border-b border-neutral-100 dark:border-neutral-800 pb-3"
- >
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div>
- <span className="font-mono text-sm">{d.hostname}</span>
- <div className="flex gap-2 mt-1">
- <Badge variant={d.status === "active" ? "default" : "secondary"}>
- {d.status}
- </Badge>
- {d.routingEnabled && <Badge variant="outline">routing</Badge>}
- {d.sendingEnabled && <Badge variant="outline">sending</Badge>}
- </div>
- </div>
- <div className="flex gap-2">
- <Button variant="outline" size="sm" onClick={() => loadDns(d.id)}>
- DNS
- </Button>
- <Button
- variant="destructive"
- size="sm"
- onClick={() => remove.mutate(d.id)}
- disabled={remove.isPending}
- >
- Remove
- </Button>
- </div>
- </div>
- {dns && (
- <div className="flex flex-wrap items-center gap-3 text-xs">
- <span className="flex items-center gap-1 text-neutral-500">
- Routing{" "}
- {dns.routing.configured ? (
- <Check className="h-3.5 w-3.5 text-green-600" />
- ) : (
- <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
- )}
- </span>
- {dns.routing.missing.length > 0 && (
- <span className="text-red-600 flex items-center gap-1">
- <X className="h-3 w-3" />
- Missing: {dns.routing.missing.join(", ")}
- </span>
- )}
- <span className="text-neutral-300">|</span>
- <span className="flex items-center gap-1 text-neutral-500">
- Sending{" "}
- {dns.sending.configured ? (
- <Check className="h-3.5 w-3.5 text-green-600" />
- ) : (
- <AlertTriangle className="h-3.5 w-3.5 text-amber-500" />
- )}
- </span>
- {dns.sending.records.length > 0 && (
- <span className="text-neutral-500">
- {dns.sending.records.join(", ")}
- </span>
- )}
- <button
- onClick={() => loadDns(d.id)}
- className="flex items-center gap-0.5 text-blue-600 hover:text-blue-800"
- >
- <ArrowRight className="h-3 w-3" />
- details
- </button>
- </div>
- )}
- </div>
- );
- })}
- </CardContent>
- </Card>
- {dnsView && (
- <Card>
- <CardHeader>
- <CardTitle>DNS — {dnsView.domain.hostname}</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4 text-xs font-mono">
- <div>
- <p className="font-sans font-medium text-sm mb-2">Email Routing</p>
- <pre className="overflow-auto bg-neutral-50 dark:bg-neutral-900 p-3 rounded-md">
- {JSON.stringify((dnsView.dns as { routing: unknown }).routing, null, 2)}
- </pre>
- </div>
- <div>
- <p className="font-sans font-medium text-sm mb-2">Email Sending</p>
- <pre className="overflow-auto bg-neutral-50 dark:bg-neutral-900 p-3 rounded-md">
- {JSON.stringify((dnsView.dns as { sending: DnsRecord[] }).sending, null, 2)}
- </pre>
- </div>
- </CardContent>
- </Card>
- )}
- </div>
- );
-}
diff --git a/src/app/(dashboard)/layout.tsx b/src/app/(dashboard)/layout.tsx
index f7ce244..68c3597 100644
--- a/src/app/(dashboard)/layout.tsx
+++ b/src/app/(dashboard)/layout.tsx
@@ -1,15 +1,17 @@
import Link from "next/link";
import { redirect } from "next/navigation";
-import { HelpCircle, Search } from "lucide-react";
+import { HelpCircle } from "lucide-react";
export const dynamic = "force-dynamic";
import { ComposeProvider } from "@/components/compose/compose-context";
import { FloatingComposer } from "@/components/compose/floating-composer";
-import { DashboardShellNav } from "@/components/dashboard-shell";
+import { MailSearchInput } from "@/components/mail-search/mail-search-input";
+import { MailSearchProvider } from "@/components/mail-search/mail-search-context";
import { MailboxProvider } from "@/components/mailbox-provider";
import { MailboxSelector } from "@/components/mailbox-selector";
import { getEnv } from "@/lib/cloudflare";
import { getCurrentUser } from "@/lib/auth/cookies";
+import { DashboardNav } from "@/components/dashboard-nav";
export default async function DashboardLayout({ children }: { children: React.ReactNode }) {
const env = getEnv();
@@ -19,28 +21,27 @@ export default async function DashboardLayout({ children }: { children: React.Re
return (
<MailboxProvider>
<ComposeProvider>
- <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
- <aside className="flex flex-col gap-4 px-3 py-4">
- <DashboardShellNav />
- </aside>
- <div className="flex min-h-screen flex-col">
- <header className="flex h-16 items-center gap-4 pr-4 text-sm">
- <div className="flex h-12 flex-1 max-w-3xl items-center gap-3 rounded-full bg-[#eaf1fb] px-4 text-neutral-600">
- <Search className="h-5 w-5" />
- <span className="text-[15px]">Search mail</span>
- </div>
- <Link
- href="/settings"
- className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
- >
- <HelpCircle className="h-5 w-5" />
- </Link>
- <MailboxSelector />
- </header>
- <main className="flex-1 overflow-hidden rounded-tl-3xl bg-white">{children}</main>
+ <MailSearchProvider>
+ <div className="grid min-h-screen grid-cols-[256px_1fr] bg-[#f6f8fc]">
+ <aside className="flex flex-col gap-4 px-3 py-4">
+ <DashboardNav />
+ </aside>
+ <div className="flex min-h-screen flex-col">
+ <header className="flex h-16 items-center gap-4 pr-4 text-sm">
+ <MailSearchInput />
+ <Link
+ href="/settings"
+ className="flex h-10 w-10 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200"
+ >
+ <HelpCircle className="h-5 w-5" />
+ </Link>
+ <MailboxSelector />
+ </header>
+ <main className="flex-1 overflow-hidden rounded-tl-3xl bg-white">{children}</main>
+ </div>
+ <FloatingComposer />
</div>
- <FloatingComposer />
- </div>
+ </MailSearchProvider>
</ComposeProvider>
</MailboxProvider>
);
diff --git a/src/app/(dashboard)/mailboxes/page.tsx b/src/app/(dashboard)/mailboxes/page.tsx
deleted file mode 100644
index 7b5c87e..0000000
--- a/src/app/(dashboard)/mailboxes/page.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-"use client";
-
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useState } from "react";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
-import { Input } from "@/components/ui/input";
-import { Label } from "@/components/ui/label";
-
-type Mailbox = { id: string; localPart: string; displayName: string | null; domainId: string };
-type Domain = { id: string; hostname: string };
-
-export default function MailboxesPage() {
- const qc = useQueryClient();
- const [localPart, setLocalPart] = useState("");
- const [domainId, setDomainId] = useState("");
-
- const domains = useQuery({
- queryKey: ["domains"],
- queryFn: async () => {
- const res = await fetch("/api/domains");
- return (await res.json()) as { domains: Domain[] };
- },
- });
-
- const mailboxes = useQuery({
- queryKey: ["mailboxes"],
- queryFn: async () => {
- const res = await fetch("/api/mailboxes");
- return (await res.json()) as { mailboxes: Mailbox[] };
- },
- });
-
- const create = useMutation({
- mutationFn: async () => {
- const res = await fetch("/api/mailboxes", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ domainId, localPart, displayName: localPart }),
- });
- const json = (await res.json()) as { error?: string };
- if (!res.ok) throw new Error(json.error ?? "Failed");
- setLocalPart("");
- },
- onSuccess: () => qc.invalidateQueries({ queryKey: ["mailboxes"] }),
- });
-
- const domainMap = new Map((domains.data?.domains ?? []).map((d) => [d.id, d.hostname]));
-
- return (
- <div className="space-y-6 max-w-2xl">
- <h1 className="text-2xl font-semibold">Mailboxes</h1>
- <Card>
- <CardHeader>
- <CardTitle>Create mailbox</CardTitle>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="space-y-2">
- <Label>Domain</Label>
- <select
- className="w-full h-10 rounded-md border border-neutral-200 dark:border-neutral-800 px-3 text-sm"
- value={domainId}
- onChange={(e) => setDomainId(e.target.value)}
- >
- <option value="">Select domain</option>
- {(domains.data?.domains ?? []).map((d) => (
- <option key={d.id} value={d.id}>
- {d.hostname}
- </option>
- ))}
- </select>
- </div>
- <div className="space-y-2">
- <Label>Local part</Label>
- <Input value={localPart} onChange={(e) => setLocalPart(e.target.value)} placeholder="support" />
- </div>
- <Button onClick={() => create.mutate()} disabled={!domainId || !localPart || create.isPending}>
- Create mailbox
- </Button>
- </CardContent>
- </Card>
- <Card>
- <CardHeader>
- <CardTitle>Addresses</CardTitle>
- </CardHeader>
- <CardContent className="space-y-2 font-mono text-sm">
- {(mailboxes.data?.mailboxes ?? []).map((m) => (
- <p key={m.id}>
- {m.localPart}@{domainMap.get(m.domainId) ?? "?"}
- </p>
- ))}
- </CardContent>
- </Card>
- </div>
- );
-}
diff --git a/src/app/api/drafts/[id]/route.ts b/src/app/api/drafts/[id]/route.ts
index 5ee8381..d7b921e 100644
--- a/src/app/api/drafts/[id]/route.ts
+++ b/src/app/api/drafts/[id]/route.ts
@@ -5,19 +5,24 @@ import { getDb } from "@/db";
import { messageBodies, messages } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
import { buildSnippet } from "@/lib/email/parse";
+import type { DraftPayload, DraftRouteParams } from "./types";
+import { selectDraftWithBody } from "./utils";
-type Params = { params: Promise<{ id: string }> };
+export async function GET(_request: Request, { params }: DraftRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env);
+ const db = getDb(env);
+ const draft = await selectDraftWithBody(db, user.id, id);
-type DraftPayload = {
- mailboxId?: string | null;
- from?: string;
- to?: string;
- subject?: string;
- text?: string;
- html?: string;
-};
+ if (!draft) {
+ return NextResponse.json({ error: "Draft not found" }, { status: 404 });
+ }
+
+ return NextResponse.json({ draft });
+}
-export async function PATCH(request: Request, { params }: Params) {
+export async function PATCH(request: Request, { params }: DraftRouteParams) {
const { id } = await params;
const env = getEnv();
const user = await requireUser(env);
@@ -53,7 +58,7 @@ export async function PATCH(request: Request, { params }: Params) {
return NextResponse.json({ draft: { id } });
}
-export async function DELETE(_request: Request, { params }: Params) {
+export async function DELETE(_request: Request, { params }: DraftRouteParams) {
const { id } = await params;
const env = getEnv();
const user = await requireUser(env);
diff --git a/src/app/api/drafts/[id]/types.d.ts b/src/app/api/drafts/[id]/types.d.ts
new file mode 100644
index 0000000..612176f
--- /dev/null
+++ b/src/app/api/drafts/[id]/types.d.ts
@@ -0,0 +1,12 @@
+export type DraftRouteParams = {
+ params: Promise<{ id: string }>;
+};
+
+export type DraftPayload = {
+ mailboxId?: string | null;
+ from?: string;
+ to?: string;
+ subject?: string;
+ text?: string;
+ html?: string;
+};
diff --git a/src/app/api/drafts/[id]/utils.ts b/src/app/api/drafts/[id]/utils.ts
new file mode 100644
index 0000000..0541092
--- /dev/null
+++ b/src/app/api/drafts/[id]/utils.ts
@@ -0,0 +1,25 @@
+import { eq } from "drizzle-orm";
+import type { getDb } from "@/db";
+import { messageBodies, messages } from "@/db/schema";
+
+type Db = ReturnType<typeof getDb>;
+
+export function selectDraftWithBody(db: Db, userId: string, draftId: string) {
+ return db
+ .select({
+ id: messages.id,
+ userId: messages.userId,
+ mailboxId: messages.mailboxId,
+ fromAddr: messages.fromAddr,
+ toAddr: messages.toAddr,
+ subject: messages.subject,
+ status: messages.status,
+ textBody: messageBodies.textBody,
+ htmlBody: messageBodies.htmlBody,
+ })
+ .from(messages)
+ .leftJoin(messageBodies, eq(messageBodies.messageId, messages.id))
+ .where(eq(messages.id, draftId))
+ .limit(1)
+ .then(([draft]) => (draft && draft.userId === userId && draft.status === "draft" ? draft : null));
+}
diff --git a/src/app/api/mailboxes/[id]/route.ts b/src/app/api/mailboxes/[id]/route.ts
new file mode 100644
index 0000000..57b3763
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/route.ts
@@ -0,0 +1,63 @@
+import { eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { mailboxes } from "@/db/schema";
+import { requireUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { updateMailboxSchema } from "@/lib/validators";
+import type { MailboxRouteParams } from "./types";
+import { getMailboxUpdateValues, selectMailboxForUser } from "./utils";
+
+export async function GET(_request: Request, { params }: MailboxRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env);
+ const db = getDb(env);
+ const [mailbox] = await selectMailboxForUser(db, user.id, id);
+
+ if (!mailbox) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+
+ return NextResponse.json({
+ mailbox: {
+ ...mailbox,
+ isPrimary: `${mailbox.localPart}@${mailbox.hostname}` === user.email,
+ },
+ });
+}
+
+export async function PATCH(request: Request, { params }: MailboxRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env);
+ const parsed = updateMailboxSchema.safeParse(await request.json());
+
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const [existing] = await selectMailboxForUser(db, user.id, id);
+
+ if (!existing) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+
+ const updateValues = getMailboxUpdateValues(parsed.data);
+ if (Object.keys(updateValues).length > 0) {
+ await db
+ .update(mailboxes)
+ .set(updateValues)
+ .where(eq(mailboxes.id, id));
+ }
+
+ const [mailbox] = await selectMailboxForUser(db, user.id, id);
+
+ return NextResponse.json({
+ mailbox: {
+ ...mailbox,
+ isPrimary: `${mailbox!.localPart}@${mailbox!.hostname}` === user.email,
+ },
+ });
+}
diff --git a/src/app/api/mailboxes/[id]/types.d.ts b/src/app/api/mailboxes/[id]/types.d.ts
new file mode 100644
index 0000000..ea6ee90
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/types.d.ts
@@ -0,0 +1,7 @@
+export type MailboxRouteParams = {
+ params: Promise<{ id: string }>;
+};
+
+export type MailboxUpdateValues = {
+ displayName?: string | null;
+};
diff --git a/src/app/api/mailboxes/[id]/utils.ts b/src/app/api/mailboxes/[id]/utils.ts
new file mode 100644
index 0000000..de4ed64
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/utils.ts
@@ -0,0 +1,30 @@
+import { and, eq } from "drizzle-orm";
+import { domains, mailboxes } from "@/db/schema";
+import type { getDb } from "@/db";
+import type { MailboxUpdateValues } from "./types";
+
+type Db = ReturnType<typeof getDb>;
+
+export function selectMailboxForUser(db: Db, userId: string, mailboxId: string) {
+ return db
+ .select({
+ id: mailboxes.id,
+ userId: mailboxes.userId,
+ domainId: mailboxes.domainId,
+ localPart: mailboxes.localPart,
+ displayName: mailboxes.displayName,
+ createdAt: mailboxes.createdAt,
+ hostname: domains.hostname,
+ })
+ .from(mailboxes)
+ .innerJoin(domains, eq(mailboxes.domainId, domains.id))
+ .where(and(eq(mailboxes.id, mailboxId), eq(mailboxes.userId, userId)))
+ .limit(1);
+}
+
+export function getMailboxUpdateValues(input: MailboxUpdateValues): MailboxUpdateValues {
+ if (!("displayName" in input)) return {};
+
+ const displayName = input.displayName?.trim() || null;
+ return { displayName };
+}
diff --git a/src/app/api/messages/counts/route.ts b/src/app/api/messages/counts/route.ts
new file mode 100644
index 0000000..df6a44e
--- /dev/null
+++ b/src/app/api/messages/counts/route.ts
@@ -0,0 +1,36 @@
+import { and, eq } from "drizzle-orm";
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { messages } from "@/db/schema";
+import { getCurrentUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { buildMessageCounts } from "./utils";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const user = await getCurrentUser(env);
+ if (!user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const url = new URL(request.url);
+ const mailboxId = url.searchParams.get("mailboxId");
+ const db = getDb(env);
+ const conditions = [eq(messages.userId, user.id)];
+
+ if (mailboxId) {
+ conditions.push(eq(messages.mailboxId, mailboxId));
+ }
+
+ const rows = await db
+ .select({
+ mailboxId: messages.mailboxId,
+ direction: messages.direction,
+ status: messages.status,
+ read: messages.read,
+ })
+ .from(messages)
+ .where(and(...conditions));
+
+ return NextResponse.json({ counts: buildMessageCounts(rows) });
+}
diff --git a/src/app/api/messages/counts/types.d.ts b/src/app/api/messages/counts/types.d.ts
new file mode 100644
index 0000000..5329222
--- /dev/null
+++ b/src/app/api/messages/counts/types.d.ts
@@ -0,0 +1,11 @@
+import type { MessageCounts, MessageFolder } from "@/hooks/types";
+import type { messages } from "@/db/schema";
+
+export type MessageCountRow = Pick<
+ typeof messages.$inferSelect,
+ "mailboxId" | "direction" | "status" | "read"
+>;
+
+export type FolderAccumulator = MessageCounts["folders"];
+
+export type CountableFolder = MessageFolder | null;
diff --git a/src/app/api/messages/counts/utils.ts b/src/app/api/messages/counts/utils.ts
new file mode 100644
index 0000000..48e066c
--- /dev/null
+++ b/src/app/api/messages/counts/utils.ts
@@ -0,0 +1,58 @@
+import type { MessageCounts, MessageFolder } from "@/hooks/types";
+import type { CountableFolder, MessageCountRow } from "./types";
+
+export function getMessageFolder(row: MessageCountRow): CountableFolder {
+ if (row.status === "trash") return "trash";
+ if (row.status === "spam") return "spam";
+ if (row.direction === "inbound" && row.status === "received") return "inbox";
+ if (row.direction === "outbound" && row.status === "sent") return "sent";
+ if (row.direction === "outbound" && row.status === "draft") return "drafts";
+ return null;
+}
+
+export function createEmptyFolderCounts(): MessageCounts["folders"] {
+ return {
+ inbox: { total: 0, unread: 0 },
+ sent: { total: 0, unread: 0 },
+ drafts: { total: 0, unread: 0 },
+ spam: { total: 0, unread: 0 },
+ trash: { total: 0, unread: 0 },
+ };
+}
+
+export function buildMessageCounts(rows: MessageCountRow[]): MessageCounts {
+ const folders = createEmptyFolderCounts();
+ const mailboxMap = new Map<string, { mailboxId: string; total: number; unread: number; inbox: number }>();
+
+ for (const row of rows) {
+ const folder = getMessageFolder(row);
+ if (folder) {
+ folders[folder].total += 1;
+ if (!row.read) folders[folder].unread += 1;
+ }
+
+ if (!row.mailboxId) continue;
+
+ const mailboxCount = mailboxMap.get(row.mailboxId) ?? {
+ mailboxId: row.mailboxId,
+ total: 0,
+ unread: 0,
+ inbox: 0,
+ };
+ mailboxCount.total += 1;
+ if (!row.read) mailboxCount.unread += 1;
+ if (folder === "inbox") mailboxCount.inbox += 1;
+ mailboxMap.set(row.mailboxId, mailboxCount);
+ }
+
+ return {
+ folders,
+ mailboxes: [...mailboxMap.values()],
+ };
+}
+
+export function getFolderLabelCount(folder: MessageFolder, counts: MessageCounts["folders"]) {
+ const count = counts[folder];
+ if (folder === "inbox" || folder === "spam") return count.unread || count.total;
+ return count.total;
+}
diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.ts
index 59c8d9f..b9b36e6 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 } from "drizzle-orm";
+import { eq, desc, and, like, or } from "drizzle-orm";
import { getEnv } from "@/lib/cloudflare";
import { getCurrentUser } from "@/lib/auth/cookies";
import { getDb } from "@/db";
@@ -16,6 +16,9 @@ export async function GET(request: Request) {
const direction = url.searchParams.get("direction");
const mailboxId = url.searchParams.get("mailboxId");
const status = url.searchParams.get("status");
+ const query = url.searchParams.get("q")?.trim();
+ const title = url.searchParams.get("title")?.trim();
+ const read = url.searchParams.get("read");
const limit = Math.min(Number(url.searchParams.get("limit") ?? 50), 100);
const db = getDb(env);
@@ -29,6 +32,25 @@ export async function GET(request: Request) {
if (status) {
conditions.push(eq(messages.status, status));
}
+ if (read === "read") {
+ conditions.push(eq(messages.read, true));
+ }
+ if (read === "unread") {
+ conditions.push(eq(messages.read, false));
+ }
+ if (query) {
+ const pattern = `%${query}%`;
+ const queryCondition = or(
+ like(messages.fromAddr, pattern),
+ like(messages.toAddr, pattern),
+ like(messages.subject, pattern),
+ like(messages.snippet, pattern),
+ );
+ if (queryCondition) conditions.push(queryCondition);
+ }
+ if (title) {
+ conditions.push(like(messages.subject, `%${title}%`));
+ }
const rows = await db
.select()
diff --git a/src/app/globals.css b/src/app/globals.css
index 014448d..7866116 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -1,5 +1,7 @@
@import "tailwindcss";
+@custom-variant dark (&:where(.dark, .dark *));
+
:root {
--background: #f6f8fc;
--foreground: #202124;
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index ae60383..722496b 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -24,7 +24,7 @@ export default function RootLayout({ children }: Readonly<{ children: React.Reac
<head>
<link rel="icon" type="image/x-icon" href="/favicon.ico"></link>
</head>
- <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
+ <body className={`${geistSans.variable} ${geistMono.variable} antialiased light`}>
<Providers>{children}</Providers>
</body>
</html>
diff --git a/src/components/admin-nav.tsx b/src/components/admin-nav.tsx
index 5659483..64d2caf 100644
--- a/src/components/admin-nav.tsx
+++ b/src/components/admin-nav.tsx
@@ -6,21 +6,17 @@ import {
Globe2,
KeyRound,
Mail,
- PanelLeft,
- Route,
Settings,
- Webhook,
} from "lucide-react";
import { cn } from "@/lib/utils";
+import { NavItem } from "./components-nav";
const links = [
{ href: "/admin", label: "Overview", icon: Settings },
{ href: "/mailboxes", label: "Mailboxes", icon: Mail },
{ href: "/domains", label: "Domains", icon: Globe2 },
- { href: "/routing", label: "Routing", icon: Route },
{ href: "/api-keys", label: "API Keys", icon: KeyRound },
- { href: "/webhooks", label: "Webhooks", icon: Webhook },
- { href: "/settings", label: "Account", icon: Settings },
+ // { href: "/webhooks", label: "Webhooks", icon: Webhook }
];
export function AdminNav({ className }: { className?: string }) {
@@ -35,26 +31,7 @@ export function AdminNav({ className }: { className?: string }) {
<img src="/icon-96.png" height={28} width={28} />
<span className="text-lg font-semibold text-neutral-800">Admin</span>
</Link>
- {links.map((link) => {
- const Icon = link.icon;
- const active =
- pathname === link.href ||
- (link.href !== "/admin" && pathname.startsWith(`${link.href}/`));
-
- return (
- <Link
- key={link.href}
- href={link.href}
- className={cn(
- "flex h-9 items-center gap-3 rounded-r-full px-3 text-sm font-medium text-neutral-700 transition-colors hover:bg-blue-50",
- active && "bg-blue-100 text-blue-900",
- )}
- >
- <Icon className="h-4 w-4" />
- {link.label}
- </Link>
- );
- })}
+ {links.map((link) => <NavItem link={link} key={link.href} />)}
</nav>
);
}
diff --git a/src/components/components-nav.tsx b/src/components/components-nav.tsx
index 67e07de..2c8bc5b 100644
--- a/src/components/components-nav.tsx
+++ b/src/components/components-nav.tsx
@@ -30,7 +30,12 @@ export function NavItem({ link }:{ link: any }) {
className={classes}
>
<Icon className="h-4 w-4" />
- {link.label}
+ <span className="flex-1">{link.label}</span>
+ {typeof link.count === "number" && link.count > 0 && (
+ <span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">
+ {link.count > 99 ? "99+" : link.count}
+ </span>
+ )}
</button>
);
}
@@ -41,7 +46,12 @@ export function NavItem({ link }:{ link: any }) {
className={cn("-ml-3 pl-6", classes)}
>
<Icon className="h-4 w-4" />
- {link.label}
+ <span className="flex-1">{link.label}</span>
+ {typeof link.count === "number" && link.count > 0 && (
+ <span className="ml-auto mr-3 rounded-full px-2 py-0.5 text-sm font-semibold text-neutral-700">
+ {link.count > 99 ? "99+" : link.count}
+ </span>
+ )}
</Link>
);
}
diff --git a/src/components/compose/compose-context.tsx b/src/components/compose/compose-context.tsx
index cad86c3..c6411ec 100644
--- a/src/components/compose/compose-context.tsx
+++ b/src/components/compose/compose-context.tsx
@@ -5,7 +5,9 @@ import type { ReactNode } from "react";
type ComposeContextValue = {
open: boolean;
+ draftId: string | null;
openComposer: () => void;
+ openDraftComposer: (draftId: string) => void;
closeComposer: () => void;
};
@@ -19,13 +21,25 @@ export function useCompose() {
export function ComposeProvider({ children }: { children: ReactNode }) {
const [open, setOpen] = useState(false);
+ const [draftId, setDraftId] = useState<string | null>(null);
return (
<ComposeContext.Provider
value={{
open,
- openComposer: () => setOpen(true),
- closeComposer: () => setOpen(false),
+ draftId,
+ openComposer: () => {
+ setDraftId(null);
+ setOpen(true);
+ },
+ openDraftComposer: (nextDraftId) => {
+ setDraftId(nextDraftId);
+ setOpen(true);
+ },
+ closeComposer: () => {
+ setOpen(false);
+ setDraftId(null);
+ },
}}
>
{children}
diff --git a/src/components/compose/compose-form.tsx b/src/components/compose/compose-form.tsx
index 95d076a..b9fbd8e 100644
--- a/src/components/compose/compose-form.tsx
+++ b/src/components/compose/compose-form.tsx
@@ -8,17 +8,28 @@ import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { cn } from "@/lib/utils";
+import { fetchDraft } from "./utils";
type Toast = { type: "success" | "error"; message: string } | null;
-export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup"; onClose?: () => void }) {
- const { selectedMailbox } = useSelectedMailbox();
+export function ComposeForm({
+ mode = "page",
+ draftIdToLoad,
+ onClose,
+}: {
+ mode?: "page" | "popup";
+ draftIdToLoad?: string | null;
+ onClose?: () => void;
+}) {
+ const { selectedMailbox, setSelectedMailbox, mailboxes } = useSelectedMailbox();
const [draftId, setDraftId] = useState<string | null>(null);
const [to, setTo] = useState("");
const [subject, setSubject] = useState("");
const [text, setText] = useState("");
const [toast, setToast] = useState<Toast>(null);
const [loading, setLoading] = useState(false);
+ const [loadingDraft, setLoadingDraft] = useState(false);
+ const [loadedDraftMailboxId, setLoadedDraftMailboxId] = useState<string | null>(null);
const saveTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const fromAddr = useMemo(
@@ -32,9 +43,45 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
return () => clearTimeout(timer);
}, [toast]);
+ useEffect(() => {
+ if (!draftIdToLoad) return;
+
+ let cancelled = false;
+ setLoadingDraft(true);
+ fetchDraft(draftIdToLoad)
+ .then((draft) => {
+ if (cancelled) return;
+
+ setDraftId(draft.id);
+ setTo(draft.toAddr);
+ setSubject(draft.subject ?? "");
+ setText(draft.textBody ?? "");
+ setLoadedDraftMailboxId(draft.mailboxId);
+ })
+ .catch((err) => {
+ if (cancelled) return;
+ const message = err instanceof Error ? err.message : "Failed to load draft";
+ setToast({ type: "error", message });
+ })
+ .finally(() => {
+ if (!cancelled) setLoadingDraft(false);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [draftIdToLoad]);
+
+ useEffect(() => {
+ if (!loadedDraftMailboxId) return;
+
+ const draftMailbox = mailboxes.find((mailbox) => mailbox.id === loadedDraftMailboxId);
+ if (draftMailbox) setSelectedMailbox(draftMailbox);
+ }, [loadedDraftMailboxId, mailboxes, setSelectedMailbox]);
+
useEffect(() => {
const hasContent = to.trim() || subject.trim() || text.trim();
- if (!fromAddr || !hasContent) return;
+ if (!fromAddr || !hasContent || loadingDraft) return;
if (saveTimer.current) clearTimeout(saveTimer.current);
saveTimer.current = setTimeout(async () => {
@@ -57,7 +104,7 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
return () => {
if (saveTimer.current) clearTimeout(saveTimer.current);
};
- }, [draftId, fromAddr, selectedMailbox?.id, subject, text, to]);
+ }, [draftId, fromAddr, loadingDraft, selectedMailbox?.id, subject, text, to]);
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
@@ -82,13 +129,16 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
}
if (draftId) {
- void fetch(`/api/drafts/${draftId}`, { method: "DELETE" });
+ void fetch(`/api/drafts/${draftId}`, { method: "DELETE" }).finally(() => {
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
+ });
}
setDraftId(null);
setTo("");
setSubject("");
setText("");
setToast({ type: "success", message: "Message sent" });
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
}
const frameClass =
@@ -110,7 +160,7 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
)}
<form onSubmit={onSubmit} className={frameClass}>
<div className="flex h-9 items-center justify-between bg-neutral-800 px-4 text-sm font-medium text-white">
- <span>{draftId ? "Draft saved" : "New Message"}</span>
+ <span>{loadingDraft ? "Loading draft" : draftId ? "Draft saved" : "New Message"}</span>
{mode === "popup" && (
<div className="flex items-center gap-3 text-neutral-300">
<Minimize2 className="h-4 w-4" />
@@ -140,6 +190,7 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
type="email"
placeholder="Recipients"
required
+ disabled={loadingDraft}
className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"
/>
</div>
@@ -151,6 +202,7 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
onChange={(event) => setSubject(event.target.value)}
placeholder="Subject"
required
+ disabled={loadingDraft}
className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"
/>
</div>
@@ -161,13 +213,14 @@ export function ComposeForm({ mode = "page", onClose }: { mode?: "page" | "popup
value={text}
onChange={(event) => setText(event.target.value)}
required
+ disabled={loadingDraft}
className="h-full min-h-full resize-none border-0 px-0 shadow-none focus-visible:ring-0"
/>
</div>
<div className="flex items-center gap-3 border-t border-neutral-100 px-4 py-3">
<span className="flex-1" />
<p className="text-xs text-neutral-500">{draftId ? "Saved to drafts" : "Autosaves as draft"}</p>
- <Button type="submit" disabled={loading || !fromAddr} className="rounded-full px-5">
+ <Button type="submit" disabled={loading || loadingDraft || !fromAddr} className="rounded-full px-5">
<Send className="h-4 w-4" />
{loading ? "Sending" : "Send"}
</Button>
diff --git a/src/components/compose/floating-composer.tsx b/src/components/compose/floating-composer.tsx
index 582f9b7..c4df0e1 100644
--- a/src/components/compose/floating-composer.tsx
+++ b/src/components/compose/floating-composer.tsx
@@ -4,7 +4,7 @@ import { ComposeForm } from "@/components/compose/compose-form";
import { useCompose } from "@/components/compose/compose-context";
export function FloatingComposer() {
- const { open, closeComposer } = useCompose();
+ const { open, draftId, closeComposer } = useCompose();
if (!open) return null;
- return <ComposeForm mode="popup" onClose={closeComposer} />;
+ return <ComposeForm key={draftId ?? "new"} mode="popup" draftIdToLoad={draftId} onClose={closeComposer} />;
}
diff --git a/src/components/compose/types.d.ts b/src/components/compose/types.d.ts
new file mode 100644
index 0000000..41b21a6
--- /dev/null
+++ b/src/components/compose/types.d.ts
@@ -0,0 +1,14 @@
+export type ComposeDraft = {
+ id: string;
+ mailboxId: string | null;
+ fromAddr: string;
+ toAddr: string;
+ subject: string | null;
+ textBody: string | null;
+ htmlBody: string | null;
+};
+
+export type DraftResponse = {
+ draft?: ComposeDraft;
+ error?: string;
+};
diff --git a/src/components/compose/utils.ts b/src/components/compose/utils.ts
new file mode 100644
index 0000000..83820e3
--- /dev/null
+++ b/src/components/compose/utils.ts
@@ -0,0 +1,12 @@
+import type { ComposeDraft, DraftResponse } from "./types";
+
+export async function fetchDraft(draftId: string): Promise<ComposeDraft> {
+ const res = await fetch(`/api/drafts/${draftId}`);
+ const json = (await res.json()) as DraftResponse;
+
+ if (!res.ok || !json.draft) {
+ throw new Error(json.error ?? "Failed to load draft");
+ }
+
+ return json.draft;
+}
diff --git a/src/components/dashboard-nav-utils.ts b/src/components/dashboard-nav-utils.ts
new file mode 100644
index 0000000..6b28e32
--- /dev/null
+++ b/src/components/dashboard-nav-utils.ts
@@ -0,0 +1,7 @@
+import type { MessageCounts, MessageFolder } from "@/hooks/types";
+
+export function getFolderNavCount(folder: MessageFolder, counts: MessageCounts["folders"]): number {
+ const count = counts[folder];
+ if (folder === "inbox" || folder === "spam") return count.unread || count.total;
+ return count.total;
+}
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index 3bc4a05..c6dea27 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -1,20 +1,20 @@
"use client";
import Link from "next/link";
-import { usePathname } from "next/navigation";
import {
FileText,
Inbox,
MailPlus,
- PanelLeft,
Send,
Settings,
ShieldAlert,
Trash2,
} from "lucide-react";
-import { useCompose } from "@/components/compose/compose-context";
+import { useSelectedMailbox } from "@/components/mailbox-provider";
+import { useMessageCounts } from "@/hooks/use-message-counts";
import { cn } from "@/lib/utils";
import { NavItem } from "./components-nav";
+import { getFolderNavCount } from "./dashboard-nav-utils";
const links = [
{ href: "/compose", label: "Compose", icon: MailPlus, primary: true },
@@ -28,8 +28,16 @@ const links = [
];
export function DashboardNav({ className }: { className?: string }) {
- const pathname = usePathname();
- const { openComposer } = useCompose();
+ const { selectedMailbox } = useSelectedMailbox();
+ const { counts } = useMessageCounts(selectedMailbox?.id);
+ const linksWithCounts = links.map((link) => {
+ if (link.href === "/inbox") return { ...link, count: getFolderNavCount("inbox", counts.folders) };
+ if (link.href === "/sent") return { ...link, count: getFolderNavCount("sent", counts.folders) };
+ if (link.href === "/drafts") return { ...link, count: getFolderNavCount("drafts", counts.folders) };
+ if (link.href === "/spam") return { ...link, count: getFolderNavCount("spam", counts.folders) };
+ if (link.href === "/trash") return { ...link, count: getFolderNavCount("trash", counts.folders) };
+ return link;
+ });
return (
<nav className={cn("flex flex-col gap-1 flex-1", className)}>
@@ -40,7 +48,7 @@ export function DashboardNav({ className }: { className?: string }) {
<img src="/icon-96.png" height={28} width={28} />
<span className="text-lg font-semibold text-neutral-800">Mail</span>
</Link>
- {links.map((link, i) => <NavItem link={link} key={`nav-${link.href || i}`} />)}
+ {linksWithCounts.map((link, i) => <NavItem link={link} key={`nav-${link.href || i}`} />)}
</nav>
);
}
diff --git a/src/components/mail-search/mail-search-context.tsx b/src/components/mail-search/mail-search-context.tsx
new file mode 100644
index 0000000..41672fd
--- /dev/null
+++ b/src/components/mail-search/mail-search-context.tsx
@@ -0,0 +1,23 @@
+"use client";
+
+import { createContext, useContext, useState } from "react";
+import type { ReactNode } from "react";
+import type { MailSearchContextValue } from "./types";
+
+const MailSearchContext = createContext<MailSearchContextValue | null>(null);
+
+export function useMailSearch() {
+ const ctx = useContext(MailSearchContext);
+ if (!ctx) throw new Error("useMailSearch must be used within MailSearchProvider");
+ return ctx;
+}
+
+export function MailSearchProvider({ children }: { children: ReactNode }) {
+ const [query, setQuery] = useState("");
+
+ return (
+ <MailSearchContext.Provider value={{ query, setQuery }}>
+ {children}
+ </MailSearchContext.Provider>
+ );
+}
diff --git a/src/components/mail-search/mail-search-input.tsx b/src/components/mail-search/mail-search-input.tsx
new file mode 100644
index 0000000..956410e
--- /dev/null
+++ b/src/components/mail-search/mail-search-input.tsx
@@ -0,0 +1,30 @@
+"use client";
+
+import { Search, X } from "lucide-react";
+import { useMailSearch } from "./mail-search-context";
+
+export function MailSearchInput() {
+ const { query, setQuery } = useMailSearch();
+
+ return (
+ <div className="flex h-12 flex-1 max-w-3xl items-center gap-3 rounded-full bg-[#eaf1fb] px-4 text-neutral-600">
+ <Search className="h-5 w-5 shrink-0" />
+ <input
+ value={query}
+ onChange={(event) => setQuery(event.target.value)}
+ placeholder='Search mail'
+ className="h-full min-w-0 flex-1 bg-transparent text-[15px] text-neutral-800 outline-none placeholder:text-neutral-500"
+ />
+ {query && (
+ <button
+ type="button"
+ onClick={() => setQuery("")}
+ className="rounded-full p-1 text-neutral-500 hover:bg-blue-100 hover:text-neutral-800"
+ aria-label="Clear search"
+ >
+ <X className="h-4 w-4" />
+ </button>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/mail-search/types.d.ts b/src/components/mail-search/types.d.ts
new file mode 100644
index 0000000..73de578
--- /dev/null
+++ b/src/components/mail-search/types.d.ts
@@ -0,0 +1,4 @@
+export type MailSearchContextValue = {
+ query: string;
+ setQuery: (query: string) => void;
+};
diff --git a/src/components/mailbox-selector.tsx b/src/components/mailbox-selector.tsx
index 61b4935..b779277 100644
--- a/src/components/mailbox-selector.tsx
+++ b/src/components/mailbox-selector.tsx
@@ -5,6 +5,7 @@ import { usePathname, useRouter } from "next/navigation";
import { Check, LogOut, Mail, Settings } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useSelectedMailbox } from "@/components/mailbox-provider";
+import { useMessageCounts } from "@/hooks/use-message-counts";
import { cn } from "@/lib/utils";
export function MailboxSelector() {
@@ -14,6 +15,7 @@ export function MailboxSelector() {
const router = useRouter();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
+ const { counts } = useMessageCounts();
useEffect(() => {
function onPointerDown(event: PointerEvent) {
@@ -73,6 +75,9 @@ export function MailboxSelector() {
const email = `${mb.localPart}@${mb.hostname}`;
const name = mb.displayName ?? mb.localPart;
const active = !adminActive && selectedMailbox?.id === mb.id;
+ const mailboxCount = counts.mailboxes.find((count) => count.mailboxId === mb.id);
+ const unread = mailboxCount?.unread ?? 0;
+ const inbox = mailboxCount?.inbox ?? 0;
return (
<button
@@ -100,8 +105,16 @@ export function MailboxSelector() {
</span>
)}
</div>
- <p className="truncate text-xs text-neutral-500">{email}</p>
+ <p className="truncate text-xs text-neutral-500">
+ {email}
+ {inbox > 0 && ` · ${inbox} inbox`}
+ </p>
</div>
+ {unread > 0 && (
+ <span className="rounded-full bg-blue-100 px-2 py-0.5 text-[11px] font-semibold text-blue-700">
+ {unread > 99 ? "99+" : unread}
+ </span>
+ )}
{active && <Check className="h-4 w-4 text-blue-600" />}
</button>
);
@@ -120,7 +133,7 @@ export function MailboxSelector() {
</div>
<div>
<p className="text-sm font-medium text-neutral-900">Admin settings</p>
- <p className="text-xs text-neutral-500">Domains, mailboxes, routing, API keys</p>
+ <p className="text-xs text-neutral-500">Domains, mailboxes, API keys</p>
</div>
{adminActive && <Check className="ml-auto h-4 w-4 text-blue-600" />}
</Link>
diff --git a/src/components/mark-read.tsx b/src/components/mark-read.tsx
index f64e0eb..2a2a033 100644
--- a/src/components/mark-read.tsx
+++ b/src/components/mark-read.tsx
@@ -4,9 +4,13 @@ import { useEffect } from "react";
export function MarkAsRead({ messageId }: { messageId: string }) {
useEffect(() => {
- fetch(`/api/messages/${messageId}/read`, { method: "POST" }).catch(() => {
- // silently fail
- });
+ fetch(`/api/messages/${messageId}/read`, { method: "POST" })
+ .then((response) => {
+ if (response.ok) window.dispatchEvent(new Event("mailflare:messages-changed"));
+ })
+ .catch(() => {
+ // silently fail
+ });
}, [messageId]);
return null;
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 4e585eb..58a8c9c 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -17,4 +17,6 @@ export async function updateMessageFolder(messageId: string, status: MessageActi
if (!response.ok) {
throw new Error("Unable to update message");
}
+
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
}
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index 26a2862..e7f830e 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -2,6 +2,8 @@
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
+import { useCompose } from "@/components/compose/compose-context";
+import { useMailSearch } from "@/components/mail-search/mail-search-context";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMessages } from "@/hooks/use-messages";
import type { MessageListRowProps, MessageFolderConfig } from "./types";
@@ -14,13 +16,12 @@ import {
function MessageListRow({ message, config }: MessageListRowProps) {
const Icon = config.icon;
+ const { openDraftComposer } = useCompose();
const unread = message.direction === "inbound" && !message.read;
-
- return (
- <Link
- href={`${config.hrefPrefix}/${message.id}`}
- className="grid min-h-12 grid-cols-[32px_minmax(160px,240px)_1fr_auto] items-center gap-3 px-6 text-sm hover:relative hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm"
- >
+ const className =
+ "grid min-h-12 w-full grid-cols-[32px_minmax(160px,240px)_1fr_auto] items-center gap-3 px-6 text-left text-sm hover:relative hover:z-10 hover:bg-[#f2f6fc] hover:shadow-sm";
+ const content = (
+ <>
<Icon className="h-4 w-4 text-neutral-300" />
<span className={getMessagePartyClassName(message, config.folder)}>
{getMessageParty(message, config.folder)}
@@ -36,14 +37,30 @@ function MessageListRow({ message, config }: MessageListRowProps) {
{getMessageBadge(message, config.folder)}
</Badge>
)}
+ </>
+ );
+
+ if (config.folder === "drafts") {
+ return (
+ <button type="button" className={className} onClick={() => openDraftComposer(message.id)}>
+ {content}
+ </button>
+ );
+ }
+
+ return (
+ <Link href={`${config.hrefPrefix}/${message.id}`} className={className}>
+ {content}
</Link>
);
}
export function MessageFolderPage({ config }: { config: MessageFolderConfig }) {
const { selectedMailbox } = useSelectedMailbox();
- const { messages, isLoading } = useMessages(config.folder, selectedMailbox?.id);
+ const { query } = useMailSearch();
+ const { messages, isLoading } = useMessages(config.folder, selectedMailbox?.id, { query });
const headerIcons = config.headerIcons ?? [];
+ const hasActiveFilters = !!query.trim();
return (
<div className="flex h-full flex-col">
@@ -62,13 +79,15 @@ export function MessageFolderPage({ config }: { config: MessageFolderConfig }) {
</div>
<div className="divide-y divide-neutral-100">
- {isLoading && <p className="px-6 py-4 text-sm text-neutral-500">Loading...</p>}
- {!isLoading && messages.length === 0 && (
- <p className="px-6 py-4 text-sm text-neutral-500">{config.emptyText}</p>
- )}
{messages.map((message) => (
<MessageListRow key={message.id} message={message} config={config} />
))}
+ {isLoading && <p className="px-6 py-4 text-sm text-neutral-500">Loading...</p>}
+ {!isLoading && messages.length === 0 && (
+ <p className="px-6 py-4 text-sm text-neutral-500">
+ {hasActiveFilters ? "No messages match these filters" : config.emptyText}
+ </p>
+ )}
</div>
</div>
);
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index 9600837..fe3292a 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -2,6 +2,8 @@ import type { Message } from "@/hooks/types";
import type { MessageFolderConfig } from "./types";
export function getMessageParty(message: Message, folder: MessageFolderConfig["folder"]) {
+
+ console.log(message)
if (folder === "drafts") return "Draft";
if (folder === "sent") return message.toAddr || "No recipient";
return message.fromAddr || "Unknown sender";
diff --git a/src/components/ui/badge.tsx b/src/components/ui/badge.tsx
index b7d52b4..e2a51cf 100644
--- a/src/components/ui/badge.tsx
+++ b/src/components/ui/badge.tsx
@@ -6,9 +6,10 @@ const badgeVariants = cva(
{
variants: {
variant: {
+ success: "border-transparent bg-green-600/10 text-green-600",
default: "border-transparent bg-neutral-900 text-neutral-50 dark:bg-neutral-50 dark:text-neutral-900",
secondary: "border-transparent bg-neutral-100 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-50",
- outline: "text-neutral-950 dark:text-neutral-50",
+ outline: "border-neutral-200",
},
},
defaultVariants: { variant: "default" },
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
new file mode 100644
index 0000000..e3187ed
--- /dev/null
+++ b/src/components/ui/dialog.tsx
@@ -0,0 +1,53 @@
+"use client";
+
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "lucide-react";
+import * as React from "react";
+import { cn } from "@/lib/utils";
+
+export const Dialog = DialogPrimitive.Root;
+export const DialogTrigger = DialogPrimitive.Trigger;
+export const DialogClose = DialogPrimitive.Close;
+
+export function DialogContent({
+ className,
+ children,
+ ...props
+}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>) {
+ return (
+ <DialogPrimitive.Portal>
+ <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/35" />
+ <DialogPrimitive.Content
+ className={cn(
+ "fixed left-1/2 top-1/2 z-50 w-[min(520px,calc(100vw-32px))] -translate-x-1/2 -translate-y-1/2 rounded-xl border border-neutral-200 bg-white p-6 shadow-xl",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPrimitive.Portal>
+ );
+}
+
+export function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
+ return <div className={cn("mb-5 space-y-1.5", className)} {...props} />;
+}
+
+export function DialogTitle({
+ className,
+ ...props
+}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>) {
+ return <DialogPrimitive.Title className={cn("text-lg font-semibold text-neutral-900", className)} {...props} />;
+}
+
+export function DialogDescription({
+ className,
+ ...props
+}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>) {
+ return <DialogPrimitive.Description className={cn("text-sm text-neutral-500", className)} {...props} />;
+}
diff --git a/src/components/ui/textarea.tsx b/src/components/ui/textarea.tsx
index f22caa8..69a87e1 100644
--- a/src/components/ui/textarea.tsx
+++ b/src/components/ui/textarea.tsx
@@ -5,7 +5,7 @@ export const Textarea = React.forwardRef<HTMLTextAreaElement, React.ComponentPro
({ className, ...props }, ref) => (
<textarea
className={cn(
- "flex min-h-[80px] w-full rounded-md border border-neutral-200 bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800",
+ "flex min-h-[80px] w-full rounded-md border border-neutral-200 bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-400 disabled:cursor-not-allowed disabled:opacity-50",
className,
)}
ref={ref}
diff --git a/src/hooks/types.d.ts b/src/hooks/types.d.ts
index c4bb40a..2466fb5 100644
--- a/src/hooks/types.d.ts
+++ b/src/hooks/types.d.ts
@@ -19,3 +19,28 @@ export type Message = {
threadId: string | null;
createdAt: string;
};
+
+export type MessageReadFilter = "all" | "read" | "unread";
+
+export type MessageFilterOptions = {
+ query?: string;
+ read?: MessageReadFilter;
+ title?: string;
+};
+
+export type FolderCount = {
+ total: number;
+ unread: number;
+};
+
+export type MailboxCount = {
+ mailboxId: string;
+ total: number;
+ unread: number;
+ inbox: number;
+};
+
+export type MessageCounts = {
+ folders: Record<MessageFolder, FolderCount>;
+ mailboxes: MailboxCount[];
+};
diff --git a/src/hooks/use-message-counts.ts b/src/hooks/use-message-counts.ts
new file mode 100644
index 0000000..5c6c281
--- /dev/null
+++ b/src/hooks/use-message-counts.ts
@@ -0,0 +1,45 @@
+import { useEffect, useState } from "react";
+import type { MessageCounts } from "./types";
+
+const emptyCounts: MessageCounts = {
+ folders: {
+ inbox: { total: 0, unread: 0 },
+ sent: { total: 0, unread: 0 },
+ drafts: { total: 0, unread: 0 },
+ spam: { total: 0, unread: 0 },
+ trash: { total: 0, unread: 0 },
+ },
+ mailboxes: [],
+};
+
+export function useMessageCounts(mailboxId?: string | null) {
+ const [counts, setCounts] = useState<MessageCounts>(emptyCounts);
+ const [isLoading, setIsLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ async function loadCounts() {
+ setIsLoading(true);
+ try {
+ const params = new URLSearchParams();
+ if (mailboxId) params.set("mailboxId", mailboxId);
+ const res = await fetch(`/api/messages/counts?${params.toString()}`);
+ const data = (await res.json()) as { counts?: MessageCounts };
+ if (!cancelled) setCounts(data.counts ?? emptyCounts);
+ } finally {
+ if (!cancelled) setIsLoading(false);
+ }
+ }
+
+ void loadCounts();
+ window.addEventListener("mailflare:messages-changed", loadCounts);
+
+ return () => {
+ cancelled = true;
+ window.removeEventListener("mailflare:messages-changed", loadCounts);
+ };
+ }, [mailboxId]);
+
+ return { counts, isLoading };
+}
diff --git a/src/hooks/use-messages.ts b/src/hooks/use-messages.ts
index 17f3dcb..26cacf5 100644
--- a/src/hooks/use-messages.ts
+++ b/src/hooks/use-messages.ts
@@ -1,25 +1,39 @@
import { useEffect, useState } from "react";
-import type { Message, MessageFolder } from "./types";
+import type { Message, MessageFilterOptions, MessageFolder } from "./types";
import { getMessageQueryParams } from "./utils";
-export function useMessages(folder: MessageFolder, mailboxId?: string | null) {
+export function useMessages(
+ folder: MessageFolder,
+ mailboxId?: string | null,
+ filters?: MessageFilterOptions,
+) {
const [messages, setMessages] = useState<Message[]>([]);
const [isLoading, setIsLoading] = useState(true);
const unreadCount = messages.filter((m) => m.direction === "inbound" && !m.read).length;
useEffect(() => {
- setIsLoading(true);
- const params = getMessageQueryParams(folder, mailboxId);
- fetch(`/api/messages?${params.toString()}`)
- .then((res) => res.json())
- .then((data) => {
- const msgs = (data as { messages?: Message[] }).messages ?? [];
- setMessages(msgs);
- setIsLoading(false);
- })
- .catch(() => setIsLoading(false));
- }, [folder, mailboxId]);
+ let cancelled = false;
+ async function loadMessages() {
+ setIsLoading(true);
+ try {
+ const params = getMessageQueryParams(folder, mailboxId, filters);
+ const res = await fetch(`/api/messages?${params.toString()}`);
+ const data = (await res.json()) as { messages?: Message[] };
+ if (!cancelled) setMessages(data.messages ?? []);
+ } finally {
+ if (!cancelled) setIsLoading(false);
+ }
+ }
+
+ void loadMessages();
+ window.addEventListener("mailflare:messages-changed", loadMessages);
+
+ return () => {
+ cancelled = true;
+ window.removeEventListener("mailflare:messages-changed", loadMessages);
+ };
+ }, [filters?.query, filters?.read, filters?.title, folder, mailboxId]);
return { messages, unreadCount, isLoading };
}
diff --git a/src/hooks/utils.ts b/src/hooks/utils.ts
index 96994e5..3de2a00 100644
--- a/src/hooks/utils.ts
+++ b/src/hooks/utils.ts
@@ -1,6 +1,34 @@
-import type { MessageFolder } from "./types";
+import type { MessageFilterOptions, MessageFolder } from "./types";
-export function getMessageQueryParams(folder: MessageFolder, mailboxId?: string | null) {
+export function parseMessageSearchQuery(query: string): MessageFilterOptions {
+ let remaining = query;
+ const filters: MessageFilterOptions = {};
+ const titleMatch = remaining.match(/\btitle:"([^"]+)"/i) ?? remaining.match(/\btitle:([^\s]+)/i);
+
+ if (titleMatch?.[1]) {
+ filters.title = titleMatch[1].trim();
+ remaining = remaining.replace(titleMatch[0], " ");
+ }
+
+ if (/(^|\s):unread(\s|$)/i.test(remaining)) {
+ filters.read = "unread";
+ remaining = remaining.replace(/(^|\s):unread(?=\s|$)/gi, " ");
+ } else if (/(^|\s):read(\s|$)/i.test(remaining)) {
+ filters.read = "read";
+ remaining = remaining.replace(/(^|\s):read(?=\s|$)/gi, " ");
+ }
+
+ const textQuery = remaining.replace(/\s+/g, " ").trim();
+ if (textQuery) filters.query = textQuery;
+
+ return filters;
+}
+
+export function getMessageQueryParams(
+ folder: MessageFolder,
+ mailboxId?: string | null,
+ filters?: MessageFilterOptions,
+) {
const params = new URLSearchParams();
if (folder === "inbox") {
@@ -23,6 +51,10 @@ export function getMessageQueryParams(folder: MessageFolder, mailboxId?: string
}
if (mailboxId) params.set("mailboxId", mailboxId);
+ const parsedFilters = filters?.query ? { ...filters, ...parseMessageSearchQuery(filters.query) } : filters;
+ if (parsedFilters?.query?.trim()) params.set("q", parsedFilters.query.trim());
+ if (parsedFilters?.title?.trim()) params.set("title", parsedFilters.title.trim());
+ if (parsedFilters?.read && parsedFilters.read !== "all") params.set("read", parsedFilters.read);
return params;
}
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 6fb26d4..b8c73ad 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -53,6 +53,10 @@ export const mailboxSchema = z.object({
displayName: z.string().optional(),
});
+export const updateMailboxSchema = z.object({
+ displayName: z.string().max(100).nullable().optional(),
+});
+
export const routingRuleSchema = z.object({
domainId: z.string().min(1),
pattern: z.string().min(1),