Skip to content

Email for professionals and teams

various UI improvements

Hieu Nguyen (Jack)5d3b6c480ef1
diff --git a/drizzle/migrations/0011_add_folder_colors.sql b/drizzle/migrations/0011_add_folder_colors.sql
new file mode 100644
index 0000000..bf93421
--- /dev/null
+++ b/drizzle/migrations/0011_add_folder_colors.sql
@@ -0,0 +1,3 @@
+ALTER TABLE `folders` ADD `color` text DEFAULT '#2563eb' NOT NULL;
+ALTER TABLE `contacts` ADD `blocked` integer DEFAULT false NOT NULL;
+ALTER TABLE `mailboxes` ADD `avatar_key` text;
\ No newline at end of file
diff --git a/drizzle/migrations/meta/_journal.json b/drizzle/migrations/meta/_journal.json
index 801ce47..75e4878 100644
--- a/drizzle/migrations/meta/_journal.json
+++ b/drizzle/migrations/meta/_journal.json
@@ -78,6 +78,13 @@
"when": 1784285031058,
"tag": "0010_hard_squirrel_girl",
"breakpoints": true
+ },
+ {
+ "idx": 11,
+ "version": "6",
+ "when": 1787529600000,
+ "tag": "0011_add_folder_colors",
+ "breakpoints": true
}
]
-}
\ No newline at end of file
+}
diff --git a/next.config.ts b/next.config.ts
index f713877..9d13158 100644
--- a/next.config.ts
+++ b/next.config.ts
@@ -5,6 +5,7 @@ const nextConfig: NextConfig = {
turbopack: {
root: import.meta.dirname,
},
+ allowedDevOrigins: ['mail.dev'],
typescript: {
// !! WARN !!
// Dangerously allow production builds to successfully complete
diff --git a/package.json b/package.json
index 6d9d2a2..abd450b 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,5 @@
{
- "name": "mailflare-team",
+ "name": "mailflare",
"version": "0.1.11",
"private": true,
"scripts": {
diff --git a/src/app/(admin)/activity/page.tsx b/src/app/(admin)/activity/page.tsx
index 515309c..62ecc6b 100644
--- a/src/app/(admin)/activity/page.tsx
+++ b/src/app/(admin)/activity/page.tsx
@@ -3,64 +3,103 @@
import { useQuery } from "@tanstack/react-query";
import { LogIn, LogOut } from "lucide-react";
import { Badge } from "@/components/ui/badge";
-import { SkeletonRows } from "@/components/ui/skeleton";
+import { Skeleton } from "@/components/ui/skeleton";
import {
- fetchActivity,
- formatActivityDate,
- getActivityLabel,
- getActivityMetadata,
+ fetchActivity,
+ formatActivityDate,
+ getActivityLabel,
+ getActivityMetadata,
} from "./utils";
export default function ActivityPage() {
- const activity = useQuery({
- queryKey: ["activity"],
- queryFn: fetchActivity,
- });
+ const activity = useQuery({
+ queryKey: ["activity"],
+ queryFn: fetchActivity,
+ });
- return (
- <div className="space-y-6">
- <div>
- <h1 className="text-2xl font-semibold text-neutral-900">Activity</h1>
- <p className="mt-1 text-sm text-neutral-500">Login and logout activity across user accounts.</p>
- </div>
+ return (
+ <div className="space-y-6">
+ <div>
+ <h1 className="text-3xl font-medium text-neutral-900">Activity</h1>
+ <p className="mt-1 text-sm text-neutral-500">
+ Login and logout activity across user accounts.
+ </p>
+ </div>
- <section className="overflow-x-auto rounded-lg border border-neutral-200 bg-white">
- <div className="grid min-w-[980px] grid-cols-[110px_1.2fr_130px_130px_110px_110px_120px_170px] gap-4 border-b border-neutral-100 bg-neutral-50 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
- <span>Activity</span>
- <span>User</span>
- <span>IP Address</span>
- <span>City</span>
- <span>Country</span>
- <span>Device</span>
- <span>Platform</span>
- <span>Time</span>
- </div>
- {activity.isLoading && <SkeletonRows count={7} />}
- {!activity.isLoading && (activity.data ?? []).length === 0 && (
- <p className="px-4 py-3 text-sm text-neutral-500">No login or logout activity yet</p>
- )}
- {(activity.data ?? []).map((log) => {
- const metadata = getActivityMetadata(log);
- const Icon = log.action === "auth.logout" ? LogOut : LogIn;
- return (
- <div key={log.id} className="grid min-w-[980px] grid-cols-[110px_1.2fr_130px_130px_110px_110px_120px_170px] gap-4 border-b border-neutral-100 px-4 py-3 last:border-b-0">
- <div className="min-w-0">
- <Badge variant="outline" className="gap-1">
- <Icon className="h-3 w-3" />
- {getActivityLabel(log.action)}
- </Badge>
- </div>
- <p className="truncate no-font-mono text-sm text-neutral-700">{log.actorEmail ?? "Unknown"}</p>
- <p className="truncate no-font-mono text-sm text-neutral-700">{metadata.ipAddress ?? "Unknown"}</p>
- <p className="truncate text-sm text-neutral-700">{metadata.city || "Unknown"}</p>
- <p className="truncate text-sm text-neutral-700">{metadata.country || "Unknown"}</p>
- <p className="truncate text-sm text-neutral-700">{metadata.device || "Unknown"}</p>
- <p className="truncate text-sm text-neutral-700">{metadata.platform || "Unknown"}</p>
- <p className="text-sm text-neutral-500">{formatActivityDate(log.createdAt)}</p>
- </div>
- );
- })}
- </section>
- </div>
- );
+ <section className="overflow-x-auto rounded-3xl bg-white">
+ <table className="w-full min-w-[760px] table-fixed text-left">
+ <thead className="border-b border-neutral-100 bg-neutral-50 text-xs font-semibold uppercase tracking-wide text-neutral-500">
+ <tr>
+ <th className="w-32 px-5 py-3">Activity</th>
+ <th className="px-5 py-3">User</th>
+ <th className="w-64 px-5 py-3">Device</th>
+ <th className="w-48 px-5 py-3">Time</th>
+ </tr>
+ </thead>
+ <tbody className="divide-y divide-neutral-100">
+ {activity.isLoading &&
+ Array.from({ length: 7 }, (_, index) => (
+ <tr key={index}>
+ <td className="px-5 py-4">
+ <Skeleton className="h-6 w-20" />
+ </td>
+ <td className="px-5 py-4">
+ <Skeleton className="h-9 w-48" />
+ </td>
+ <td className="px-5 py-4">
+ <Skeleton className="h-9 w-40" />
+ </td>
+ <td className="px-5 py-4">
+ <Skeleton className="h-4 w-32" />
+ </td>
+ </tr>
+ ))}
+ {!activity.isLoading && (activity.data ?? []).length === 0 && (
+ <tr>
+ <td colSpan={4} className="px-5 py-4 text-sm text-neutral-500">
+ No login or logout activity yet
+ </td>
+ </tr>
+ )}
+ {(activity.data ?? []).map((log) => {
+ const metadata = getActivityMetadata(log);
+ const Icon = log.action === "auth.logout" ? LogOut : LogIn;
+ return (
+ <tr key={log.id} className="align-top hover:bg-neutral-50/70">
+ <td className="px-5 py-4">
+ <Badge variant="outline" className="gap-1">
+ <Icon className="h-3 w-3" />
+ {getActivityLabel(log.action)}
+ </Badge>
+ </td>
+ <td className="px-5 py-4">
+ <p className="flex flex-col truncate no-font-mono">
+ <span>{log.actorEmail ?? "(unknown email)"}</span>
+ </p>
+ <small className="text-neutral-500">
+ {metadata.city || "(unknown city)"} •{" "}
+ {metadata.country || "(unknown country)"}
+ </small>
+ </td>
+ <td className="px-5 py-4">
+ <p className="flex flex-col truncate no-font-mono">
+ {metadata.device ?? "(unknown device)"}
+ </p>
+
+ <small className="text-neutral-500">
+ {metadata.platform || "(unknown platform)"} •{" "}
+ {metadata.ipAddress ?? "(unknown IP)"}
+ </small>
+ </td>
+ <td className="px-5 py-4 text-sm text-neutral-500">
+ {formatActivityDate(log.createdAt)}
+ </td>
+ </tr>
+ );
+ })}
+ </tbody>
+ </table>
+ </section>
+ </div>
+ );
}
diff --git a/src/app/(admin)/admin/page.tsx b/src/app/(admin)/admin/page.tsx
index ecfdcb2..1859c63 100644
--- a/src/app/(admin)/admin/page.tsx
+++ b/src/app/(admin)/admin/page.tsx
@@ -40,25 +40,25 @@ export default function AdminSettingsPage() {
return (
<div>
<div className="mb-8">
- <h1 className="text-2xl font-normal text-neutral-900">Admin settings</h1>
+ <h1 className="text-3xl font-medium text-neutral-900">Admin settings</h1>
<p className="mt-2 text-sm text-neutral-500">
Manage workspace-level mail infrastructure and integrations.
</p>
</div>
- <div className="grid max-w-5xl gap-4 md:grid-cols-2">
+ <div className="grid gap-4">
{sections.map((section) => {
const Icon = section.icon;
return (
<Link key={section.href} href={section.href}>
- <Card className="h-full transition-shadow hover:shadow-md">
- <CardHeader className="flex-row items-center gap-4 space-y-0">
+ <Card className="h-full rounded-3xl border-0 bg-white p-6 transition-colors hover:bg-blue-50/60">
+ <CardHeader className="flex-row items-center gap-4 space-y-0 py-0">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 text-blue-700">
<Icon className="h-5 w-5" />
</div>
<CardTitle className="text-base">{section.title}</CardTitle>
</CardHeader>
- <CardContent>
+ <CardContent className="pt-4">
<p className="text-sm text-neutral-500">{section.description}</p>
</CardContent>
</Card>
diff --git a/src/app/(admin)/api-keys/page.tsx b/src/app/(admin)/api-keys/page.tsx
index be00f94..0379611 100644
--- a/src/app/(admin)/api-keys/page.tsx
+++ b/src/app/(admin)/api-keys/page.tsx
@@ -104,7 +104,7 @@ export default function ApiKeysPage() {
No API keys yet
</p>
)}
- <div className="grid gap-3 md:grid-cols-2">
+ <div className="grid gap-3">
{(data?.apiKeys ?? []).map((key) => (
<div
key={key.id}
diff --git a/src/app/(admin)/backups/page.tsx b/src/app/(admin)/backups/page.tsx
index a0ffc69..1ea20ce 100644
--- a/src/app/(admin)/backups/page.tsx
+++ b/src/app/(admin)/backups/page.tsx
@@ -5,245 +5,315 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { DatabaseBackup, Download, Play, Save, Trash2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { SkeletonRows } from "@/components/ui/skeleton";
+import { Switch } from "@/components/ui/switch";
import type { BackupItem, BackupSettings } from "./types";
import {
- WEEKDAYS,
- downloadBackup,
- fetchBackups,
- formatBackupDate,
- formatBackupSize,
- getStatusClass,
- removeBackup,
- saveBackupSettings,
- startBackup,
+ WEEKDAYS,
+ downloadBackup,
+ fetchBackups,
+ formatBackupDate,
+ formatBackupSize,
+ getStatusClass,
+ removeBackup,
+ saveBackupSettings,
+ startBackup,
} from "./utils";
export default function BackupsPage() {
- const queryClient = useQueryClient();
- const [settings, setSettings] = useState<BackupSettings | null>(null);
- const backups = useQuery({
- queryKey: ["backups"],
- queryFn: fetchBackups,
- refetchInterval: (query) =>
- query.state.data?.backups.some((backup) => backup.status === "queued" || backup.status === "running")
- ? 5000
- : false,
- });
-
- useEffect(() => {
- if (backups.data?.settings) setSettings(backups.data.settings);
- }, [backups.data?.settings]);
-
- const saveSettings = useMutation({
- mutationFn: async () => {
- if (!settings) return;
- await saveBackupSettings(settings);
- },
- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
- });
-
- const runBackup = useMutation({
- mutationFn: startBackup,
- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
- });
-
- const deleteBackup = useMutation({
- mutationFn: removeBackup,
- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
- });
-
- const download = useMutation({ mutationFn: downloadBackup });
- const error = backups.error || saveSettings.error || runBackup.error || deleteBackup.error || download.error;
-
- return (
- <div className="space-y-6">
- <div className="flex items-start justify-between gap-4">
- <div>
- <h1 className="text-2xl font-semibold text-neutral-900">Database Backups</h1>
- <p className="mt-1 text-sm text-neutral-500">
- Create full D1 SQL exports and store them in the configured R2 bucket.
- </p>
- </div>
- <Button onClick={() => runBackup.mutate()} disabled={runBackup.isPending}>
- <Play className="h-4 w-4" />
- {runBackup.isPending ? "Starting..." : "Back up now"}
- </Button>
- </div>
-
- {error && (
- <p className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
- {error instanceof Error ? error.message : "Backup operation failed"}
- </p>
- )}
-
- <Card>
- <CardHeader>
- <CardTitle>Automatic backup</CardTitle>
- <CardDescription>
- The schedule runs at 02:00 UTC. Monthly schedules are limited to days 1-28.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-5">
- {settings && (
- <>
- <label className="flex items-center gap-3 text-sm font-medium">
- <input
- type="checkbox"
- checked={settings.enabled}
- onChange={(event) => setSettings({ ...settings, enabled: event.target.checked })}
- className="h-4 w-4 rounded border-neutral-300"
- />
- Enable automatic backups
- </label>
-
- <div className="grid gap-4 md:grid-cols-2">
- <div className="space-y-2">
- <Label htmlFor="schedule-type">Frequency</Label>
- <select
- id="schedule-type"
- value={settings.scheduleType}
- onChange={(event) => {
- const scheduleType = event.target.value as BackupSettings["scheduleType"];
- setSettings({
- ...settings,
- scheduleType,
- scheduleValue: scheduleType === "weekly" ? 1 : scheduleType === "monthly" ? 1 : null,
- });
- }}
- className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"
- >
- <option value="daily">Daily</option>
- <option value="weekly">Selected day of week</option>
- <option value="monthly">Selected day of month</option>
- </select>
- </div>
-
- {settings.scheduleType === "weekly" && (
- <div className="space-y-2">
- <Label htmlFor="weekday">Day of week</Label>
- <select
- id="weekday"
- value={settings.scheduleValue ?? 1}
- onChange={(event) => setSettings({ ...settings, scheduleValue: Number(event.target.value) })}
- className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"
- >
- {WEEKDAYS.map((day) => (
- <option key={day.value} value={day.value}>{day.label}</option>
- ))}
- </select>
- </div>
- )}
-
- {settings.scheduleType === "monthly" && (
- <div className="space-y-2">
- <Label htmlFor="month-day">Day of month</Label>
- <Input
- id="month-day"
- type="number"
- min={1}
- max={28}
- value={settings.scheduleValue ?? 1}
- onChange={(event) => setSettings({ ...settings, scheduleValue: Number(event.target.value) })}
- />
- </div>
- )}
- </div>
-
- <div className="grid gap-4 border-t border-neutral-100 pt-5 md:grid-cols-2">
- <label className="flex items-center gap-3 text-sm font-medium">
- <input
- type="checkbox"
- checked={settings.retentionEnabled}
- onChange={(event) => setSettings({ ...settings, retentionEnabled: event.target.checked })}
- className="h-4 w-4 rounded border-neutral-300"
- />
- Delete old backups automatically
- </label>
- <div className="space-y-2">
- <Label htmlFor="retention-days">Delete backups older than</Label>
- <div className="flex items-center gap-2">
- <Input
- id="retention-days"
- type="number"
- min={1}
- max={3650}
- value={settings.retentionDays}
- disabled={!settings.retentionEnabled}
- onChange={(event) => setSettings({ ...settings, retentionDays: Number(event.target.value) })}
- />
- <span className="text-sm text-neutral-500">days</span>
- </div>
- </div>
- </div>
-
- <Button onClick={() => saveSettings.mutate()} disabled={saveSettings.isPending}>
- <Save className="h-4 w-4" />
- {saveSettings.isPending ? "Saving..." : "Save settings"}
- </Button>
- </>
- )}
- </CardContent>
- </Card>
-
- <section className="overflow-hidden rounded-xl border border-neutral-200 bg-white">
- <div className="flex items-center gap-3 border-b border-neutral-100 px-4 py-4">
- <DatabaseBackup className="h-5 w-5 text-neutral-500" />
- <h2 className="font-semibold text-neutral-900">Backup history</h2>
- </div>
- <div className="grid grid-cols-[1fr_110px_110px_170px_120px] gap-4 border-b border-neutral-100 bg-neutral-50 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
- <span>File</span>
- <span>Status</span>
- <span>Size</span>
- <span>Created</span>
- <span>Actions</span>
- </div>
- {backups.isLoading && <SkeletonRows count={5} />}
- {!backups.isLoading && (backups.data?.backups ?? []).length === 0 && (
- <p className="px-4 py-6 text-sm text-neutral-500">No backups yet.</p>
- )}
- {(backups.data?.backups ?? []).map((backup: BackupItem) => (
- <div key={backup.id} className="grid grid-cols-[1fr_110px_110px_170px_120px] items-center gap-4 border-b border-neutral-100 px-4 py-3 last:border-b-0">
- <div className="min-w-0">
- <p className="truncate text-sm font-medium text-neutral-900">{backup.filename ?? backup.id}</p>
- <p className="truncate text-xs text-neutral-500">
- {backup.trigger === "manual" ? "Manual" : "Scheduled"}
- {backup.error ? `: ${backup.error}` : ""}
- </p>
- </div>
- <Badge variant="outline" className={getStatusClass(backup.status)}>{backup.status}</Badge>
- <span className="text-sm text-neutral-600">{formatBackupSize(backup.size)}</span>
- <span className="text-sm text-neutral-600">{formatBackupDate(backup.createdAt)}</span>
- <div className="flex gap-1">
- <Button
- size="sm"
- variant="ghost"
- title="Download backup"
- disabled={backup.status !== "completed" || download.isPending}
- onClick={() => download.mutate(backup)}
- >
- <Download className="h-4 w-4" />
- </Button>
- <Button
- size="sm"
- variant="ghost"
- title="Delete backup"
- disabled={
- deleteBackup.isPending
- || backup.status === "queued"
- || backup.status === "running"
- }
- onClick={() => deleteBackup.mutate(backup.id)}
- >
- <Trash2 className="h-4 w-4 text-red-600" />
- </Button>
- </div>
- </div>
- ))}
- </section>
- </div>
- );
+ const queryClient = useQueryClient();
+ const [settings, setSettings] = useState<BackupSettings | null>(null);
+ const backups = useQuery({
+ queryKey: ["backups"],
+ queryFn: fetchBackups,
+ refetchInterval: (query) =>
+ query.state.data?.backups.some(
+ (backup) => backup.status === "queued" || backup.status === "running",
+ )
+ ? 5000
+ : false,
+ });
+
+ useEffect(() => {
+ if (backups.data?.settings) setSettings(backups.data.settings);
+ }, [backups.data?.settings]);
+
+ const saveSettings = useMutation({
+ mutationFn: async () => {
+ if (!settings) return;
+ await saveBackupSettings(settings);
+ },
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
+ });
+
+ const runBackup = useMutation({
+ mutationFn: startBackup,
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
+ });
+
+ const deleteBackup = useMutation({
+ mutationFn: removeBackup,
+ onSuccess: () => queryClient.invalidateQueries({ queryKey: ["backups"] }),
+ });
+
+ const download = useMutation({ mutationFn: downloadBackup });
+ const error =
+ backups.error ||
+ saveSettings.error ||
+ runBackup.error ||
+ deleteBackup.error ||
+ download.error;
+
+ return (
+ <div className="space-y-6">
+ <div className="flex items-start justify-between gap-4">
+ <div>
+ <h1 className="text-3xl font-medium text-neutral-900">
+ Database Backups
+ </h1>
+ <p className="mt-1 text-sm text-neutral-500">
+ Create full D1 SQL exports and store them in the configured R2
+ bucket.
+ </p>
+ </div>
+ <Button
+ onClick={() => runBackup.mutate()}
+ disabled={runBackup.isPending}
+ >
+ <Play className="h-4 w-4" />
+ {runBackup.isPending ? "Starting..." : "Back up now"}
+ </Button>
+ </div>
+
+ {error && (
+ <p className="rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
+ {error instanceof Error ? error.message : "Backup operation failed"}
+ </p>
+ )}
+
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0">
+ <CardTitle>Automatic backup</CardTitle>
+ <CardDescription>
+ The schedule runs at 02:00 UTC. Monthly schedules are limited to
+ days 1-28.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-5 pt-5">
+ {settings && (
+ <>
+ <div className="flex items-center gap-3 text-sm font-medium">
+ <Switch
+ checked={settings.enabled}
+ onCheckedChange={(enabled) =>
+ setSettings({ ...settings, enabled })
+ }
+ aria-label="Enable automatic backups"
+ />
+ <span>Enable automatic backups</span>
+ </div>
+
+ {settings.enabled && (
+ <>
+ <div className="grid gap-4">
+ <div className="space-y-2">
+ <Label htmlFor="schedule-type">Frequency</Label>
+ <select
+ id="schedule-type"
+ value={settings.scheduleType}
+ onChange={(event) => {
+ const scheduleType = event.target
+ .value as BackupSettings["scheduleType"];
+ setSettings({
+ ...settings,
+ scheduleType,
+ scheduleValue:
+ scheduleType === "weekly"
+ ? 1
+ : scheduleType === "monthly"
+ ? 1
+ : null,
+ });
+ }}
+ className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"
+ >
+ <option value="daily">Daily</option>
+ <option value="weekly">Selected day of week</option>
+ <option value="monthly">Selected day of month</option>
+ </select>
+ </div>
+
+ {settings.scheduleType === "weekly" && (
+ <div className="space-y-2">
+ <Label htmlFor="weekday">Day of week</Label>
+ <select
+ id="weekday"
+ value={settings.scheduleValue ?? 1}
+ onChange={(event) =>
+ setSettings({
+ ...settings,
+ scheduleValue: Number(event.target.value),
+ })
+ }
+ className="flex h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm"
+ >
+ {WEEKDAYS.map((day) => (
+ <option key={day.value} value={day.value}>
+ {day.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ )}
+
+ {settings.scheduleType === "monthly" && (
+ <div className="space-y-2">
+ <Label htmlFor="month-day">Day of month</Label>
+ <Input
+ id="month-day"
+ type="number"
+ min={1}
+ max={28}
+ value={settings.scheduleValue ?? 1}
+ onChange={(event) =>
+ setSettings({
+ ...settings,
+ scheduleValue: Number(event.target.value),
+ })
+ }
+ />
+ </div>
+ )}
+ </div>
+
+ <div className="grid gap-4 border-t border-neutral-100 pt-5">
+ <div className="flex items-center gap-3 text-sm font-medium">
+ <Switch
+ checked={settings.retentionEnabled}
+ onCheckedChange={(retentionEnabled) =>
+ setSettings({
+ ...settings,
+ retentionEnabled,
+ })
+ }
+ aria-label="Delete old backups automatically"
+ />
+ <span>Delete old backups automatically</span>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="retention-days">
+ Delete backups older than
+ </Label>
+ <div className="flex items-center gap-2">
+ <Input
+ id="retention-days"
+ type="number"
+ min={1}
+ max={3650}
+ value={settings.retentionDays}
+ disabled={!settings.retentionEnabled}
+ onChange={(event) =>
+ setSettings({
+ ...settings,
+ retentionDays: Number(event.target.value),
+ })
+ }
+ />
+ <span className="text-sm text-neutral-500">days</span>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+
+ <Button
+ onClick={() => saveSettings.mutate()}
+ disabled={saveSettings.isPending}
+ >
+ <Save className="h-4 w-4" />
+ {saveSettings.isPending ? "Saving..." : "Save settings"}
+ </Button>
+ </>
+ )}
+ </CardContent>
+ </Card>
+
+ <section className="overflow-hidden rounded-3xl bg-white">
+ <div className="flex items-center gap-3 border-b border-neutral-100 px-4 py-4">
+ <DatabaseBackup className="h-5 w-5 text-neutral-500" />
+ <h2 className="font-semibold text-neutral-900">Backup history</h2>
+ </div>
+ <div className="grid grid-cols-[1fr_110px_110px_170px_120px] gap-4 border-b border-neutral-100 bg-neutral-50 px-4 py-2 text-xs font-semibold uppercase tracking-wide text-neutral-500">
+ <span>File</span>
+ <span>Status</span>
+ <span>Size</span>
+ <span>Created</span>
+ <span>Actions</span>
+ </div>
+ {backups.isLoading && <SkeletonRows count={5} />}
+ {!backups.isLoading && (backups.data?.backups ?? []).length === 0 && (
+ <p className="px-4 py-6 text-sm text-neutral-500">No backups yet.</p>
+ )}
+ {(backups.data?.backups ?? []).map((backup: BackupItem) => (
+ <div
+ key={backup.id}
+ className="grid grid-cols-[1fr_110px_110px_170px_120px] items-center gap-4 border-b border-neutral-100 px-4 py-3 last:border-b-0"
+ >
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium text-neutral-900">
+ {backup.filename ?? backup.id}
+ </p>
+ <p className="truncate text-xs text-neutral-500">
+ {backup.trigger === "manual" ? "Manual" : "Scheduled"}
+ {backup.error ? `: ${backup.error}` : ""}
+ </p>
+ </div>
+ <Badge variant="outline" className={getStatusClass(backup.status)}>
+ {backup.status}
+ </Badge>
+ <span className="text-sm text-neutral-600">
+ {formatBackupSize(backup.size)}
+ </span>
+ <span className="text-sm text-neutral-600">
+ {formatBackupDate(backup.createdAt)}
+ </span>
+ <div className="flex gap-1">
+ <Button
+ size="sm"
+ variant="ghost"
+ title="Download backup"
+ disabled={backup.status !== "completed" || download.isPending}
+ onClick={() => download.mutate(backup)}
+ >
+ <Download className="h-4 w-4" />
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ title="Delete backup"
+ disabled={
+ deleteBackup.isPending ||
+ backup.status === "queued" ||
+ backup.status === "running"
+ }
+ onClick={() => deleteBackup.mutate(backup.id)}
+ >
+ <Trash2 className="h-4 w-4 text-red-600" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </section>
+ </div>
+ );
}
diff --git a/src/app/(admin)/domains/DomainItemCard.tsx b/src/app/(admin)/domains/DomainItemCard.tsx
index f0f753f..875a7e3 100644
--- a/src/app/(admin)/domains/DomainItemCard.tsx
+++ b/src/app/(admin)/domains/DomainItemCard.tsx
@@ -14,7 +14,7 @@ export default function DomainItemCard({ item, dns, remove, loadDns }: any) {
return (
<div
key={item.id}
- className="flex flex-col gap-3 rounded-lg border border-neutral-200 bg-white p-4 shadow-sm shadow-neutral-100"
+ className="flex flex-col gap-3 rounded-3xl bg-white p-5"
>
<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">
diff --git a/src/app/(admin)/domains/page.tsx b/src/app/(admin)/domains/page.tsx
index ff9b105..ca6b5db 100644
--- a/src/app/(admin)/domains/page.tsx
+++ b/src/app/(admin)/domains/page.tsx
@@ -89,7 +89,7 @@ export default function DomainsPage() {
<div className="space-y-6">
<div className="flex items-center justify-between gap-4">
<div>
- <h1 className="text-2xl font-semibold">Domains</h1>
+ <h1 className="text-3xl font-medium">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.
@@ -143,11 +143,11 @@ export default function DomainsPage() {
<CardGridSkeleton />
)}
{!isLoading && (data?.domains ?? []).length === 0 && (
- <p className="rounded-lg border border-neutral-200 bg-white px-4 py-3 text-sm text-neutral-500">
+ <p className="rounded-2xl bg-white px-5 py-4 text-sm text-neutral-500">
No domains yet
</p>
)}
- <div className="grid gap-3 md:grid-cols-2">
+ <div className="grid gap-3">
{(data?.domains ?? []).map((d) => {
const dns = data?.dns?.[d.id];
return (
@@ -163,11 +163,11 @@ export default function DomainsPage() {
</div>
</section>
{dnsView && (
- <Card>
- <CardHeader>
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0">
<CardTitle>DNS — {dnsView.domain.hostname}</CardTitle>
</CardHeader>
- <CardContent className="space-y-4 text-xs no-font-mono">
+ <CardContent className="space-y-4 pt-5 text-xs no-font-mono">
<div>
<p className="font-sans font-medium text-sm mb-2">
Email Routing
diff --git a/src/app/(admin)/layout.tsx b/src/app/(admin)/layout.tsx
index 95512f3..23efc6f 100644
--- a/src/app/(admin)/layout.tsx
+++ b/src/app/(admin)/layout.tsx
@@ -18,27 +18,16 @@ export default function DashboardLayout({
<AuthGuard requireMailbox requireRole="admin">
<MailboxProvider>
<ComposeProvider>
- <div className="grid h-[100dvh] grid-cols-[256px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">
- <aside className="min-h-0 overflow-y-auto overscroll-contain px-3 py-4 [scrollbar-gutter:stable]">
+ <div className="grid h-dvh grid-cols-[256px_minmax(0,1fr)] overflow-hidden bg-[#eef3fb]">
+ <aside className="min-h-0 overflow-y-auto overscroll-contain px-3 py-4 scrollbar-gutter-stable">
<AdminNav />
</aside>
<div className="flex min-h-0 min-w-0 flex-col">
- <header className="flex h-16 w-full shrink-0 items-center gap-4 pr-4 text-sm">
- <div className="flex h-12 flex-1 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>
+ <span className="fixed top-6 right-6">
<MailboxSelector />
- </header>
- <main className="min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain rounded-t-3xl bg-white px-12 py-8 [scrollbar-gutter:stable]">
- {children}
+ </span>
+ <main className="min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain px-6 py-10 scrollbar-gutter-stable lg:px-12">
+ <div className="w-full max-w-3xl">{children}</div>
</main>
</div>
<FloatingComposer />
diff --git a/src/app/(admin)/mailboxes/[id]/MailboxAvatarForm.tsx b/src/app/(admin)/mailboxes/[id]/MailboxAvatarForm.tsx
new file mode 100644
index 0000000..fd98b0d
--- /dev/null
+++ b/src/app/(admin)/mailboxes/[id]/MailboxAvatarForm.tsx
@@ -0,0 +1,101 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { Camera, LoaderCircle, User } from "lucide-react";
+import { dispatchMailboxAvatarChanged } from "@/lib/mailboxes/avatar-client";
+import type { MailboxAvatarFormProps } from "./types";
+import {
+ getMailboxAvatarUrl,
+ MAILBOX_AVATAR_ACCEPT,
+ uploadMailboxAvatar,
+ validateMailboxAvatar,
+} from "./avatar-utils";
+
+export default function MailboxAvatarForm({
+ mailboxId,
+ hasAvatar: initialHasAvatar,
+ name,
+}: MailboxAvatarFormProps) {
+ const queryClient = useQueryClient();
+ const [hasAvatar, setHasAvatar] = useState(initialHasAvatar);
+ const [avatarUrl, setAvatarUrl] = useState(`/api/mailboxes/${mailboxId}/avatar`);
+ const [status, setStatus] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ useEffect(() => {
+ setHasAvatar(initialHasAvatar);
+ setAvatarUrl(`/api/mailboxes/${mailboxId}/avatar`);
+ }, [initialHasAvatar, mailboxId]);
+
+ async function onPick(event: React.ChangeEvent<HTMLInputElement>) {
+ const picked = event.target.files?.[0] ?? null;
+ event.target.value = "";
+ if (!picked) return;
+
+ const validationError = validateMailboxAvatar(picked);
+ if (validationError) {
+ setStatus(validationError);
+ return;
+ }
+
+ setBusy(true);
+ setStatus(null);
+ try {
+ await uploadMailboxAvatar(mailboxId, picked);
+ const nextAvatarUrl = getMailboxAvatarUrl(mailboxId);
+ setAvatarUrl(nextAvatarUrl);
+ setHasAvatar(true);
+ dispatchMailboxAvatarChanged(mailboxId, nextAvatarUrl);
+ await queryClient.invalidateQueries({ queryKey: ["mailboxes"] });
+ } catch (error) {
+ setStatus(error instanceof Error ? error.message : "Upload failed");
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <div className="flex flex-col items-start gap-2">
+ <input
+ ref={inputRef}
+ type="file"
+ accept={MAILBOX_AVATAR_ACCEPT}
+ className="hidden"
+ onChange={onPick}
+ />
+ <button
+ type="button"
+ onClick={() => inputRef.current?.click()}
+ disabled={busy}
+ className="group relative h-24 w-24 overflow-hidden rounded-full border border-neutral-200 bg-blue-600 text-white shadow-sm outline-none ring-blue-500 transition focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait"
+ aria-label={hasAvatar ? `Change ${name} profile picture` : `Upload ${name} profile picture`}
+ >
+ {hasAvatar ? (
+ <img
+ src={avatarUrl}
+ alt={`${name} profile picture`}
+ className="h-full w-full object-cover"
+ onError={() => setHasAvatar(false)}
+ />
+ ) : (
+ <span className="flex h-full w-full items-center justify-center">
+ <User className="h-9 w-9" />
+ </span>
+ )}
+ <span className="absolute inset-0 flex items-center justify-center bg-neutral-950/55 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100">
+ {busy ? (
+ <LoaderCircle className="h-6 w-6 animate-spin" />
+ ) : (
+ <span className="flex flex-col items-center gap-1 text-[11px] font-medium">
+ <Camera className="h-5 w-5" />
+ {hasAvatar ? "Change" : "Upload"}
+ </span>
+ )}
+ </span>
+ </button>
+ {status && <p className="max-w-xs text-xs text-red-600">{status}</p>}
+ </div>
+ );
+}
diff --git a/src/app/(admin)/mailboxes/[id]/avatar-utils.ts b/src/app/(admin)/mailboxes/[id]/avatar-utils.ts
new file mode 100644
index 0000000..5c6ace5
--- /dev/null
+++ b/src/app/(admin)/mailboxes/[id]/avatar-utils.ts
@@ -0,0 +1,33 @@
+import { authFetch } from "@/lib/auth/client";
+import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
+import {
+ PROFILE_AVATAR_ACCEPT,
+ validateProfileAvatar,
+} from "@/components/settings/profile-avatar-form-utils";
+import type { MailboxAvatarUploadResponse } from "./types";
+
+export const MAILBOX_AVATAR_ACCEPT = PROFILE_AVATAR_ACCEPT;
+
+export function getMailboxAvatarUrl(mailboxId: string): string {
+ return `/api/mailboxes/${mailboxId}/avatar?v=${Date.now()}`;
+}
+
+export function validateMailboxAvatar(file: File): string | null {
+ return validateProfileAvatar(file);
+}
+
+export async function uploadMailboxAvatar(mailboxId: string, file: File): Promise<void> {
+ const body = new FormData();
+ body.append("file", file, file.name);
+ const response = await authFetch(`/api/mailboxes/${mailboxId}/avatar`, {
+ method: "POST",
+ body,
+ });
+ if (response.ok) {
+ clearMailboxesCache();
+ return;
+ }
+
+ const data = (await response.json().catch(() => null)) as MailboxAvatarUploadResponse | null;
+ throw new Error(data?.error ?? "Upload failed");
+}
diff --git a/src/app/(admin)/mailboxes/[id]/page.tsx b/src/app/(admin)/mailboxes/[id]/page.tsx
index a739259..a73545d 100644
--- a/src/app/(admin)/mailboxes/[id]/page.tsx
+++ b/src/app/(admin)/mailboxes/[id]/page.tsx
@@ -8,154 +8,166 @@ import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
- Card,
- CardContent,
- CardDescription,
- CardHeader,
- CardTitle,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
-import {
- fetchMailbox,
- getMailboxAddress,
- updateMailboxName,
-} from "./utils";
+import { fetchMailbox, getMailboxAddress, updateMailboxName } from "./utils";
+import MailboxAvatarForm from "./MailboxAvatarForm";
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,
- });
+ const params = useParams<{ id: string }>();
+ const mailboxId = params.id;
+ const qc = useQueryClient();
+ const [displayName, setDisplayName] = useState("");
- useEffect(() => {
- if (mailbox.data) setDisplayName(mailbox.data.displayName ?? "");
- }, [mailbox.data]);
+ const mailbox = useQuery({
+ queryKey: ["mailbox", mailboxId],
+ queryFn: () => fetchMailbox(mailboxId),
+ enabled: !!mailboxId,
+ });
- const updateName = useMutation({
- mutationFn: () => updateMailboxName(mailboxId, displayName),
- onSuccess: (updatedMailbox) => {
- qc.setQueryData(["mailbox", mailboxId], updatedMailbox);
- qc.invalidateQueries({ queryKey: ["mailboxes"] });
- },
- });
+ useEffect(() => {
+ if (mailbox.data) setDisplayName(mailbox.data.displayName ?? "");
+ }, [mailbox.data]);
- const address = mailbox.data ? getMailboxAddress(mailbox.data) : "";
+ const updateName = useMutation({
+ mutationFn: () => updateMailboxName(mailboxId, displayName),
+ onSuccess: (updatedMailbox) => {
+ qc.setQueryData(["mailbox", mailboxId], updatedMailbox);
+ qc.invalidateQueries({ queryKey: ["mailboxes"] });
+ },
+ });
- 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>
+ const address = mailbox.data ? getMailboxAddress(mailbox.data) : "";
- <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>
- {address ? (
- <p className="mt-1 truncate no-font-mono text-sm text-neutral-500">
- {address}
- </p>
- ) : (
- <Skeleton className="mt-2 h-4 w-52" />
- )}
- </div>
- <div className="flex shrink-0 items-center gap-2">
- {mailbox.data?.type === "shared" && <Badge variant="secondary">Shared</Badge>}
- {mailbox.data?.isPrimary && <Badge variant="secondary">Primary</Badge>}
- </div>
- </div>
+ return (
+ <div className="space-y-6">
+ <div className="flex items-start justify-between gap-4">
+ <div className="min-w-0">
+ <h1 className="truncate text-3xl font-medium text-neutral-900">
+ Settings
+ </h1>
+ {address ? (
+ <p className="mt-1 truncate no-font-mono text-sm text-neutral-500">
+ {address}
+ </p>
+ ) : (
+ <Skeleton className="mt-2 h-4 w-52" />
+ )}
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {mailbox.data?.type === "shared" && (
+ <Badge variant="secondary">Shared</Badge>
+ )}
+ {mailbox.data?.isPrimary && (
+ <Badge variant="secondary">Primary</Badge>
+ )}
+ </div>
+ </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>
- )}
+ {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 className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0">
+ <CardTitle>Account</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-4 pt-5">
+ {mailbox.data ? (
+ <MailboxAvatarForm
+ mailboxId={mailbox.data.id}
+ hasAvatar={!!mailbox.data.hasAvatar}
+ name={mailbox.data.displayName || mailbox.data.localPart}
+ />
+ ) : (
+ <Skeleton className="h-24 w-24 rounded-full" />
+ )}
- <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 no-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 no-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 no-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>
- );
+ <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 className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0">
+ <CardTitle>Address</CardTitle>
+ <CardDescription>
+ The email address, username, and domain are managed as routing
+ resources.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="grid gap-4 pt-5">
+ <div className="space-y-1">
+ <p className="text-xs font-medium uppercase tracking-wide text-neutral-500">
+ Email
+ </p>
+ <p className="truncate no-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 no-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 no-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
index 1f302c3..030ade1 100644
--- a/src/app/(admin)/mailboxes/[id]/types.d.ts
+++ b/src/app/(admin)/mailboxes/[id]/types.d.ts
@@ -4,6 +4,7 @@ export type MailboxDetail = {
domainId: string;
localPart: string;
displayName: string | null;
+ hasAvatar?: boolean;
type?: "personal" | "shared";
permission?: "read_only" | "send_as" | "send_on_behalf" | "full_access";
disabled?: boolean;
@@ -16,3 +17,13 @@ export type MailboxDetailResponse = {
mailbox?: MailboxDetail;
error?: string;
};
+
+export type MailboxAvatarFormProps = {
+ mailboxId: string;
+ hasAvatar: boolean;
+ name: string;
+};
+
+export type MailboxAvatarUploadResponse = {
+ error?: string;
+};
diff --git a/src/app/(admin)/mailboxes/[id]/utils.ts b/src/app/(admin)/mailboxes/[id]/utils.ts
index a92689d..d35a94d 100644
--- a/src/app/(admin)/mailboxes/[id]/utils.ts
+++ b/src/app/(admin)/mailboxes/[id]/utils.ts
@@ -1,4 +1,5 @@
import { authFetch } from "@/lib/auth/client";
+import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
import type { MailboxDetail, MailboxDetailResponse } from "./types";
export function getMailboxAddress(mailbox: Pick<MailboxDetail, "localPart" | "hostname">): string {
@@ -28,5 +29,6 @@ export async function updateMailboxName(id: string, displayName: string): Promis
throw new Error(json.error ?? "Failed to update mailbox");
}
+ clearMailboxesCache();
return json.mailbox;
}
diff --git a/src/app/(admin)/mailboxes/page.tsx b/src/app/(admin)/mailboxes/page.tsx
index 606a2cc..52d108e 100644
--- a/src/app/(admin)/mailboxes/page.tsx
+++ b/src/app/(admin)/mailboxes/page.tsx
@@ -2,8 +2,8 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import Link from "next/link";
-import { useState } from "react";
-import { Mail, Plus } from "lucide-react";
+import { useEffect, useState } from "react";
+import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -16,16 +16,31 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { CardGridSkeleton } from "@/components/page-skeletons";
+import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
import { authFetch } from "@/lib/auth/client";
-import type { Domain, Mailbox } from "./types";
+import type { CurrentAccountResponse, Domain, Mailbox } from "./types";
import { getMailboxAddress, getMailboxName } from "./utils";
export default function MailboxesPage() {
const qc = useQueryClient();
+ const [displayName, setDisplayName] = useState("");
const [localPart, setLocalPart] = useState("");
const [domainId, setDomainId] = useState("");
const [createOpen, setCreateOpen] = useState(false);
+ const account = useQuery({
+ queryKey: ["auth", "me"],
+ queryFn: async () => {
+ const res = await authFetch("/api/auth/me", { redirectOnUnauthorized: false });
+ return (await res.json()) as CurrentAccountResponse;
+ },
+ });
+
+ useEffect(() => {
+ if (!createOpen) return;
+ setDisplayName((currentName) => currentName || account.data?.user?.name?.trim() || "");
+ }, [account.data?.user?.name, createOpen]);
+
const domains = useQuery({
queryKey: ["domains"],
queryFn: async () => {
@@ -47,14 +62,16 @@ export default function MailboxesPage() {
const res = await authFetch("/api/mailboxes", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ domainId, localPart, displayName: localPart }),
+ body: JSON.stringify({ domainId, localPart, displayName: displayName.trim() }),
});
const json = (await res.json()) as { error?: string };
if (!res.ok) throw new Error(json.error ?? "Failed");
+ setDisplayName("");
setLocalPart("");
setDomainId("");
},
onSuccess: () => {
+ clearMailboxesCache();
setCreateOpen(false);
qc.invalidateQueries({ queryKey: ["mailboxes"] });
},
@@ -67,7 +84,7 @@ export default function MailboxesPage() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between gap-4">
- <h1 className="text-2xl font-semibold">Mailboxes</h1>
+ <h1 className="text-3xl font-medium">Mailboxes</h1>
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogTrigger asChild>
<Button>
@@ -82,39 +99,46 @@ export default function MailboxesPage() {
</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>
+ <Label htmlFor="mailbox-name">Name</Label>
<Input
- value={localPart}
- onChange={(event) => setLocalPart(event.target.value)}
- placeholder="support"
+ id="mailbox-name"
+ value={displayName}
+ onChange={(event) => setDisplayName(event.target.value)}
+ placeholder="Mailbox name"
/>
- {domainId && (
- <span className="absolute bottom-2.5 right-4 text-sm text-neutral-400">
- @{domainMap.get(domainId)}
- </span>
- )}
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="mailbox-username">Email address</Label>
+ <div className="flex h-10 overflow-hidden rounded-md border border-neutral-200 bg-white shadow-sm shadow-neutral-200/50 focus-within:border-blue-600">
+ <Input
+ id="mailbox-username"
+ value={localPart}
+ onChange={(event) => setLocalPart(event.target.value)}
+ placeholder="support"
+ className="min-w-0 flex-1 rounded-none border-0 shadow-none focus-visible:border-0"
+ />
+ <span className="flex items-center text-sm text-neutral-400">@</span>
+ <select
+ aria-label="Domain"
+ className="min-w-0 max-w-[55%] bg-transparent px-3 text-sm text-neutral-700 focus-visible:outline-none 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>
{create.isError && (
<p className="text-sm text-red-600">{(create.error as Error).message}</p>
)}
<Button
onClick={() => create.mutate()}
- disabled={!domainId || !localPart || create.isPending}
+ disabled={!displayName.trim() || !domainId || !localPart || create.isPending}
>
{create.isPending ? "Creating..." : "Create mailbox"}
</Button>
@@ -132,11 +156,11 @@ export default function MailboxesPage() {
<CardGridSkeleton />
)}
{!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">
+ <p className="rounded-2xl bg-white px-5 py-4 text-sm text-neutral-500">
No mailboxes yet
</p>
)}
- <div className="grid gap-3 md:grid-cols-2">
+ <div className="grid gap-3">
{(mailboxes.data?.mailboxes ?? []).map((mailbox) => {
const mailboxWithHostname = {
...mailbox,
@@ -147,12 +171,20 @@ export default function MailboxesPage() {
<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"
+ className="group flex items-start gap-4 rounded-3xl bg-white p-5 transition-colors hover:bg-blue-50/10"
>
- <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 className="relative flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-full bg-blue-100 text-sm font-semibold text-blue-700">
+ {getMailboxName(mailboxWithHostname).trim().charAt(0).toUpperCase() || "?"}
+ {mailbox.hasAvatar && (
+ <img
+ src={`/api/mailboxes/${mailbox.id}/avatar`}
+ alt={`${getMailboxName(mailboxWithHostname)} profile`}
+ className="absolute inset-0 h-full w-full object-cover"
+ onError={(event) => event.currentTarget.remove()}
+ />
+ )}
</span>
- <span className="min-w-0 space-y-1">
+ <span className="min-w-0">
<span className="flex min-w-0 items-center gap-2">
<span className="block truncate text-sm font-semibold text-neutral-900">
{getMailboxName(mailboxWithHostname)}
diff --git a/src/app/(admin)/mailboxes/types.d.ts b/src/app/(admin)/mailboxes/types.d.ts
index 6fef876..6e003e0 100644
--- a/src/app/(admin)/mailboxes/types.d.ts
+++ b/src/app/(admin)/mailboxes/types.d.ts
@@ -2,6 +2,7 @@ export type Mailbox = {
id: string;
localPart: string;
displayName: string | null;
+ hasAvatar?: boolean;
domainId: string;
hostname: string;
type?: "personal" | "shared";
@@ -13,3 +14,9 @@ export type Domain = {
id: string;
hostname: string;
};
+
+export type CurrentAccountResponse = {
+ user?: {
+ name?: string | null;
+ };
+};
diff --git a/src/app/(dashboard)/inbox/[messageId]/page.tsx b/src/app/(dashboard)/inbox/[messageId]/page.tsx
index 40171a8..67a7edc 100644
--- a/src/app/(dashboard)/inbox/[messageId]/page.tsx
+++ b/src/app/(dashboard)/inbox/[messageId]/page.tsx
@@ -6,6 +6,8 @@ import { useEffect, useState } from "react";
import { ArrowLeft, Cloud, ExternalLink } from "lucide-react";
import dayjs from "dayjs";
import { MarkAsRead } from "@/components/mark-read";
+import { useSelectedMailbox } from "@/components/mailbox-provider";
+import { ContactDetailsTrigger } from "@/components/contacts/contact-details";
import { MessageActions } from "@/components/message-actions/message-actions";
import { MessageAttachmentViewer } from "@/components/message-attachment-viewer";
import { MessageAttachmentCard } from "@/components/message-attachment-card";
@@ -24,6 +26,7 @@ import { sanitizeEmailHtml } from "./email-html-sanitizer";
export default function MessageDetailPage() {
const params = useParams<{ messageId: string }>();
+ const { selectedMailbox } = useSelectedMailbox();
const messageId = params.messageId;
const [data, setData] = useState<MessageDetailResponse | null>(null);
const [loading, setLoading] = useState(true);
@@ -61,7 +64,12 @@ export default function MessageDetailPage() {
}
const { message, body, attachments = [] } = data;
- const { fromName, fromAddress, toName } = getMessageHeaderParties(message);
+ const currentAccountName =
+ selectedMailbox?.displayName ?? selectedMailbox?.localPart;
+ const { fromName, fromAddress, toName } = getMessageHeaderParties(
+ message,
+ currentAccountName,
+ );
const ownAddress =
message.direction === "inbound" ? message.toAddr : message.fromAddr;
const bodyDisplay = getMessageBodyDisplay(
@@ -113,10 +121,31 @@ export default function MessageDetailPage() {
<div className="mb-6 flex items-start justify-between border-b border-neutral-100 pb-5">
<div>
<p className="text-sm text-neutral-900">
- <b>{fromName}</b>{" "}
+ <b>
+ {message.direction === "inbound" ? (
+ <ContactDetailsTrigger
+ mailboxId={message.mailboxId}
+ address={message.fromAddr}
+ name={fromName}
+ />
+ ) : (
+ fromName
+ )}
+ </b>{" "}
<span className="text-neutral-500">&lt;{fromAddress}&gt;</span>
</p>
- <p className="text-xs text-neutral-500">to {toName}</p>
+ <p className="text-xs text-neutral-500">
+ to{" "}
+ {message.direction === "outbound" ? (
+ <ContactDetailsTrigger
+ mailboxId={message.mailboxId}
+ address={message.toAddr}
+ name={toName}
+ />
+ ) : (
+ toName
+ )}
+ </p>
</div>
<p className="text-xs text-neutral-400">
{dayjs(message.createdAt).format("MMM DD, YYYY, hh:mmA")}
diff --git a/src/app/(dashboard)/inbox/[messageId]/utils.ts b/src/app/(dashboard)/inbox/[messageId]/utils.ts
index 72b868a..d68c3bd 100644
--- a/src/app/(dashboard)/inbox/[messageId]/utils.ts
+++ b/src/app/(dashboard)/inbox/[messageId]/utils.ts
@@ -10,11 +10,17 @@ export async function fetchMessageDetail(messageId: string): Promise<MessageDeta
return (await response.json()) as MessageDetailResponse;
}
-export function getMessageHeaderParties(message: Message) {
+export function getMessageHeaderParties(message: Message, currentAccountName?: string) {
return {
- fromName: getDisplayNameForAddress(message.fromAddr, message.fromContactName),
+ fromName:
+ message.direction === "outbound" && currentAccountName
+ ? currentAccountName
+ : getDisplayNameForAddress(message.fromAddr, message.fromContactName),
fromAddress: getEmailAddress(message.fromAddr),
- toName: getDisplayNameForAddress(message.toAddr, message.toContactName),
+ toName:
+ message.direction === "inbound"
+ ? "me"
+ : getDisplayNameForAddress(message.toAddr, message.toContactName),
};
}
diff --git a/src/app/(dashboard)/settings/page.tsx b/src/app/(dashboard)/settings/page.tsx
deleted file mode 100644
index 46b8058..0000000
--- a/src/app/(dashboard)/settings/page.tsx
+++ /dev/null
@@ -1,13 +0,0 @@
-import { CurrentMailboxForm } from "@/components/settings/current-mailbox-form";
-import { ProfileAvatarForm } from "@/components/settings/profile-avatar-form";
-
-export default function SettingsPage() {
- return (
- <div className="space-y-6">
- <CurrentMailboxForm />
- <div className="max-w-2xl px-8 pb-8">
- <ProfileAvatarForm />
- </div>
- </div>
- );
-}
diff --git a/src/app/(settings)/layout.tsx b/src/app/(settings)/layout.tsx
new file mode 100644
index 0000000..2263895
--- /dev/null
+++ b/src/app/(settings)/layout.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import Link from "next/link";
+import { HelpCircle } from "lucide-react";
+import { AuthGuard } from "@/components/auth/auth-guard";
+import { ComposeProvider } from "@/components/compose/compose-context";
+import { FloatingComposer } from "@/components/compose/floating-composer";
+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 { DashboardNav } from "@/components/dashboard-nav";
+
+export default function DashboardLayout({
+ children,
+}: {
+ children: React.ReactNode;
+}) {
+ return (
+ <AuthGuard requireMailbox>
+ <MailboxProvider>
+ <ComposeProvider>
+ <MailSearchProvider>
+ <div className="grid h-[100dvh] grid-cols-[256px_minmax(0,1fr)] overflow-hidden bg-[#f6f8fc]">
+ <aside className="min-h-0 overflow-y-auto overscroll-contain px-3 py-4 [scrollbar-gutter:stable]">
+ <DashboardNav />
+ </aside>
+ <div className="flex min-h-0 min-w-0 flex-col">
+ <header className="flex h-16 w-full shrink-0 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="min-h-0 flex-1 overflow-y-auto overscroll-contain scrollbar-gutter-stable">
+ {children}
+ </main>
+ </div>
+ <FloatingComposer />
+ </div>
+ </MailSearchProvider>
+ </ComposeProvider>
+ </MailboxProvider>
+ </AuthGuard>
+ );
+}
diff --git a/src/app/(dashboard)/settings/export/page.tsx b/src/app/(settings)/settings/export/page.tsx
similarity index 88%
rename from src/app/(dashboard)/settings/export/page.tsx
rename to src/app/(settings)/settings/export/page.tsx
index a4f78db..626015b 100644
--- a/src/app/(dashboard)/settings/export/page.tsx
+++ b/src/app/(settings)/settings/export/page.tsx
@@ -25,22 +25,22 @@ export default function SettingsExportPage() {
}
return (
- <div className="max-w-3xl space-y-6 p-8">
+ <div className="space-y-6">
<div>
- <h1 className="text-2xl font-semibold text-neutral-900">Export</h1>
+ <h1 className="text-3xl font-medium text-neutral-900">Export</h1>
<p className="mt-1 text-sm text-neutral-500">
Download mail from the currently selected mailbox.
</p>
</div>
- <Card>
- <CardHeader>
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="py-0">
<CardDescription>
Download message headers and bodies from the selected mailbox as an .mbox file.
Attachments are not included in this export.
</CardDescription>
</CardHeader>
- <CardContent className="space-y-3">
+ <CardContent className="space-y-3 pt-5">
<Button type="button" variant="outline" disabled={!selectedMailbox || exportState.loading} onClick={onExport}>
{exportState.loading ? "Preparing..." : "Download .mbox"}
</Button>
diff --git a/src/app/(dashboard)/settings/export/types.d.ts b/src/app/(settings)/settings/export/types.d.ts
similarity index 100%
rename from src/app/(dashboard)/settings/export/types.d.ts
rename to src/app/(settings)/settings/export/types.d.ts
diff --git a/src/app/(dashboard)/settings/export/utils.ts b/src/app/(settings)/settings/export/utils.ts
similarity index 100%
rename from src/app/(dashboard)/settings/export/utils.ts
rename to src/app/(settings)/settings/export/utils.ts
diff --git a/src/app/(dashboard)/settings/import-export/page.tsx b/src/app/(settings)/settings/import-export/page.tsx
similarity index 100%
rename from src/app/(dashboard)/settings/import-export/page.tsx
rename to src/app/(settings)/settings/import-export/page.tsx
diff --git a/src/app/(dashboard)/settings/import/page.tsx b/src/app/(settings)/settings/import/page.tsx
similarity index 93%
rename from src/app/(dashboard)/settings/import/page.tsx
rename to src/app/(settings)/settings/import/page.tsx
index d421779..8cb9bf6 100644
--- a/src/app/(dashboard)/settings/import/page.tsx
+++ b/src/app/(settings)/settings/import/page.tsx
@@ -15,7 +15,6 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { importMessageFiles } from "@/components/settings/import-messages-utils";
-import { cn } from "@/lib/utils";
import type {
ImapFormState,
ImportResult,
@@ -157,36 +156,32 @@ export default function SettingsImportPage() {
}
return (
- <div className="max-w-3xl space-y-6 p-8">
+ <div className="space-y-6">
<div>
- <h1 className="text-2xl font-semibold text-neutral-900">Import</h1>
+ <h1 className="text-3xl font-medium text-neutral-900">Import</h1>
<p className="mt-1 text-sm text-neutral-500">
Move mail from selected source sections into the matching sections of
the current mailbox.
</p>
</div>
- <Card>
- <div className="flex rounded-xl border border-neutral-200 bg-neutral-50 p-1 m-2">
- {(["file", "imap"] as ImportTab[]).map((tab) => (
- <button
- key={tab}
- type="button"
- onClick={() => setActiveTab(tab)}
- className={cn(
- "flex-1 rounded-lg px-4 py-2 text-sm font-medium transition-colors",
- activeTab === tab
- ? "bg-white text-neutral-900 shadow-sm"
- : "text-neutral-500 hover:text-neutral-900",
- )}
- >
- {tab === "file" ? "Backup File" : "IMAP"}
- </button>
- ))}
+
+ <div className="space-y-6 rounded-3xl bg-white p-6">
+ <div className="space-y-2">
+ <Label htmlFor="import-source">Import source</Label>
+ <select
+ id="import-source"
+ value={activeTab}
+ onChange={(event) => setActiveTab(event.target.value as ImportTab)}
+ className="h-10 w-full rounded-md border border-neutral-200 bg-white px-3 text-sm text-neutral-900 shadow-sm shadow-neutral-200/50 outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-100"
+ >
+ <option value="file">Backup File</option>
+ <option value="imap">IMAP</option>
+ </select>
</div>
{/* <Card className="m-2">
<CardContent className="space-y-2 py-4"> */}
- <div className="p-6 space-y-2">
- <h2 className="font-semibold">Choose import sections</h2>
+ <div className="space-y-2">
+ <Label>Choose import sections</Label>
<div className="relative">
<button
@@ -231,7 +226,7 @@ export default function SettingsImportPage() {
<CardContent>
<form onSubmit={onFileSubmit} className="space-y-4">
<div className="space-y-2">
- <h2 className="font-semibold">Select Backup File</h2>
+ <Label>Select Backup File</Label>
<input
id="import-files"
type="file"
@@ -240,7 +235,7 @@ export default function SettingsImportPage() {
onChange={(event) =>
setFiles(Array.from(event.target.files ?? []))
}
- className="block w-full rounded-md border border-neutral-200 bg-white px-3 py-2 text-sm shadow-sm shadow-neutral-200/50 file:mr-3 file:rounded-md file:border-0 file:bg-neutral-100 file:px-3 file:py-1.5 file:text-sm file:font-medium"
+ className="block w-full rounded-md border border-neutral-200 bg-white px-3 py-1 text-sm shadow-sm shadow-neutral-200/50 file:mr-3 file:rounded-md file:border-0 file:bg-neutral-100 file:px-3 file:py-1.5 file:text-sm file:font-medium"
/>
<p className="text-xs leading-5 text-neutral-500">
Upload exported .eml or .mbox files. File exports do not
@@ -400,7 +395,7 @@ export default function SettingsImportPage() {
</CardContent>
</>
)}
- </Card>
+ </div>
</div>
);
}
diff --git a/src/app/(dashboard)/settings/import/types.d.ts b/src/app/(settings)/settings/import/types.d.ts
similarity index 100%
rename from src/app/(dashboard)/settings/import/types.d.ts
rename to src/app/(settings)/settings/import/types.d.ts
diff --git a/src/app/(dashboard)/settings/import/utils.ts b/src/app/(settings)/settings/import/utils.ts
similarity index 100%
rename from src/app/(dashboard)/settings/import/utils.ts
rename to src/app/(settings)/settings/import/utils.ts
diff --git a/src/app/(dashboard)/settings/layout.tsx b/src/app/(settings)/settings/layout.tsx
similarity index 54%
rename from src/app/(dashboard)/settings/layout.tsx
rename to src/app/(settings)/settings/layout.tsx
index 36e9e87..a128ba0 100644
--- a/src/app/(dashboard)/settings/layout.tsx
+++ b/src/app/(settings)/settings/layout.tsx
@@ -3,8 +3,10 @@ import { SettingsNav } from "@/components/settings/settings-nav";
export default function SettingsLayout({ children }: { children: ReactNode }) {
return (
- <div className="flex flex-row">
- <main className="flex-1">{children}</main>
+ <div className="flex flex-row gap-4 min-h-[calc(100dvh-4rem)] bg-inherit">
+ <div className="min-w-0 flex-1 pt-4">
+ <div className="mx-auto w-full max-w-3xl">{children}</div>
+ </div>
<SettingsNav />
</div>
);
diff --git a/src/app/(settings)/settings/page.tsx b/src/app/(settings)/settings/page.tsx
new file mode 100644
index 0000000..a88c060
--- /dev/null
+++ b/src/app/(settings)/settings/page.tsx
@@ -0,0 +1,7 @@
+import { CurrentMailboxForm } from "@/components/settings/current-mailbox-form";
+
+export default function SettingsPage() {
+ return (
+ <CurrentMailboxForm />
+ );
+}
diff --git a/src/app/(dashboard)/settings/rules/page.tsx b/src/app/(settings)/settings/rules/page.tsx
similarity index 61%
rename from src/app/(dashboard)/settings/rules/page.tsx
rename to src/app/(settings)/settings/rules/page.tsx
index f7a9b78..5e2a89e 100644
--- a/src/app/(dashboard)/settings/rules/page.tsx
+++ b/src/app/(settings)/settings/rules/page.tsx
@@ -2,14 +2,16 @@ import { InboxRules } from "@/components/settings/inbox-rules";
export default function SettingsRulesPage() {
return (
- <div className="max-w-3xl space-y-8 p-8">
+ <div className="space-y-8">
<div>
- <h1 className="text-2xl font-semibold text-neutral-900">Rules</h1>
+ <h1 className="text-3xl font-medium text-neutral-900">Rules</h1>
<p className="mt-1 text-sm text-neutral-500">
Manage routing and filtering rules for the selected mailbox.
</p>
</div>
- <InboxRules />
+ <div className="rounded-3xl bg-white p-6">
+ <InboxRules />
+ </div>
</div>
);
}
diff --git a/src/app/api/contacts/block/route.ts b/src/app/api/contacts/block/route.ts
new file mode 100644
index 0000000..8525c3e
--- /dev/null
+++ b/src/app/api/contacts/block/route.ts
@@ -0,0 +1,29 @@
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { requireUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { blockContact } from "@/lib/contacts/service";
+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
+import type { BlockContactRequest } from "./types";
+
+export async function POST(request: Request) {
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const body = (await request.json()) as BlockContactRequest;
+ if (!body.mailboxId || !body.address?.trim()) {
+ return NextResponse.json({ error: "Mailbox and contact are required" }, { status: 400 });
+ }
+
+ const access = await getMailboxAccessLevel(getDb(env), user, body.mailboxId);
+ if (!access?.canManage) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+
+ const contact = await blockContact(env, {
+ userId: access.mailbox.userId,
+ mailboxId: access.mailbox.id,
+ domainId: access.mailbox.domainId,
+ address: body.address,
+ });
+ return NextResponse.json({ contact });
+}
diff --git a/src/app/api/contacts/block/types.d.ts b/src/app/api/contacts/block/types.d.ts
new file mode 100644
index 0000000..8b86c0d
--- /dev/null
+++ b/src/app/api/contacts/block/types.d.ts
@@ -0,0 +1,4 @@
+export type BlockContactRequest = {
+ mailboxId?: string;
+ address?: string;
+};
diff --git a/src/app/api/contacts/route.ts b/src/app/api/contacts/route.ts
new file mode 100644
index 0000000..86f1a39
--- /dev/null
+++ b/src/app/api/contacts/route.ts
@@ -0,0 +1,58 @@
+import { NextResponse } from "next/server";
+import { getDb } from "@/db";
+import { requireUser } from "@/lib/auth/cookies";
+import { getEnv } from "@/lib/cloudflare";
+import { normalizeEmailAddress } from "@/lib/email/address";
+import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
+import type { ContactRequestInput } from "./types";
+import { getContactByEmail, saveManualContactName } from "./utils";
+
+export async function GET(request: Request) {
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const url = new URL(request.url);
+ const mailboxId = url.searchParams.get("mailboxId");
+ const email = normalizeEmailAddress(url.searchParams.get("address") ?? "");
+ if (!mailboxId || !email) {
+ return NextResponse.json({ error: "Mailbox and contact are required" }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const access = await getMailboxAccessLevel(db, user, mailboxId);
+ if (!access?.canRead) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+ const contact = await getContactByEmail(db, access.mailbox.userId, email);
+ return NextResponse.json({
+ contact: contact ?? {
+ email,
+ displayName: null,
+ source: null,
+ blocked: false,
+ lastSeenAt: null,
+ },
+ });
+}
+
+export async function PATCH(request: Request) {
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const body = (await request.json()) as ContactRequestInput;
+ const email = normalizeEmailAddress(body.address ?? "");
+ const displayName = body.displayName?.trim() ?? "";
+ if (!body.mailboxId || !email || !displayName || displayName.length > 100) {
+ return NextResponse.json({ error: "A valid contact name is required" }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const access = await getMailboxAccessLevel(db, user, body.mailboxId);
+ if (!access?.canManage) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+ const contact = await saveManualContactName(db, {
+ userId: access.mailbox.userId,
+ email,
+ displayName,
+ });
+ return NextResponse.json({ contact });
+}
diff --git a/src/app/api/contacts/types.d.ts b/src/app/api/contacts/types.d.ts
new file mode 100644
index 0000000..00e8337
--- /dev/null
+++ b/src/app/api/contacts/types.d.ts
@@ -0,0 +1,5 @@
+export type ContactRequestInput = {
+ mailboxId?: string;
+ address?: string;
+ displayName?: string;
+};
diff --git a/src/app/api/contacts/utils.ts b/src/app/api/contacts/utils.ts
new file mode 100644
index 0000000..5216ac0
--- /dev/null
+++ b/src/app/api/contacts/utils.ts
@@ -0,0 +1,39 @@
+import { and, eq } from "drizzle-orm";
+import type { getDb } from "@/db";
+import { contacts } from "@/db/schema";
+import { getContactId } from "@/lib/contacts/utils";
+
+type Db = ReturnType<typeof getDb>;
+
+export async function getContactByEmail(db: Db, userId: string, email: string) {
+ const [contact] = await db
+ .select()
+ .from(contacts)
+ .where(and(eq(contacts.userId, userId), eq(contacts.email, email)))
+ .limit(1);
+ return contact ?? null;
+}
+
+export async function saveManualContactName(
+ db: Db,
+ input: { userId: string; email: string; displayName: string },
+) {
+ const existing = await getContactByEmail(db, input.userId, input.email);
+ if (existing) {
+ await db
+ .update(contacts)
+ .set({ displayName: input.displayName, source: "manual" })
+ .where(eq(contacts.id, existing.id));
+ return { ...existing, displayName: input.displayName, source: "manual" as const };
+ }
+
+ const id = getContactId(input.userId, input.email);
+ await db.insert(contacts).values({
+ id,
+ userId: input.userId,
+ email: input.email,
+ displayName: input.displayName,
+ source: "manual",
+ });
+ return getContactByEmail(db, input.userId, input.email);
+}
diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.ts
index 85c16bd..6309003 100644
--- a/src/app/api/folders/route.ts
+++ b/src/app/api/folders/route.ts
@@ -57,7 +57,8 @@ export async function POST(request: Request) {
userId: access.mailboxUserId,
mailboxId: parsed.data.mailboxId,
name,
+ color: parsed.data.color,
});
- return NextResponse.json({ id, mailboxId: parsed.data.mailboxId, name });
+ return NextResponse.json({ id, mailboxId: parsed.data.mailboxId, name, color: parsed.data.color });
}
diff --git a/src/app/api/folders/types.d.ts b/src/app/api/folders/types.d.ts
index 7f546cd..b1e52c0 100644
--- a/src/app/api/folders/types.d.ts
+++ b/src/app/api/folders/types.d.ts
@@ -3,5 +3,6 @@ export type FolderListItem = {
userId: string;
mailboxId: string;
name: string;
+ color: string;
createdAt: Date;
};
diff --git a/src/app/api/mailboxes/[id]/avatar/route.ts b/src/app/api/mailboxes/[id]/avatar/route.ts
new file mode 100644
index 0000000..01621e9
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/avatar/route.ts
@@ -0,0 +1,75 @@
+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 { getMailboxAccessLevel } from "@/lib/mailboxes/access";
+import {
+ ALLOWED_AVATAR_TYPES,
+ MAX_AVATAR_SIZE,
+ isUploadedAvatarFile,
+} from "@/app/api/profile/avatar/utils";
+import type { MailboxAvatarRouteParams } from "./types";
+import { mailboxAvatarKeyFor } from "./utils";
+
+export async function GET(request: Request, { params }: MailboxAvatarRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const db = getDb(env);
+ const access = await getMailboxAccessLevel(db, user, id);
+ if (!access?.canRead) return new Response("Not found", { status: 404 });
+
+ const [mailbox] = await db
+ .select({ avatarKey: mailboxes.avatarKey })
+ .from(mailboxes)
+ .where(eq(mailboxes.id, id))
+ .limit(1);
+ if (!mailbox?.avatarKey) return new Response("Not found", { status: 404 });
+
+ const object = await env.BUCKET.get(mailbox.avatarKey);
+ if (!object) return new Response("Not found", { status: 404 });
+
+ const headers = new Headers();
+ headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream");
+ headers.set("X-Content-Type-Options", "nosniff");
+ headers.set("Content-Security-Policy", "default-src 'none'; img-src 'self'; sandbox");
+ headers.set("Cache-Control", "private, no-cache");
+ return new Response(object.body, { headers });
+}
+
+export async function POST(request: Request, { params }: MailboxAvatarRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const db = getDb(env);
+ const access = await getMailboxAccessLevel(db, user, id);
+ if (!access?.canManage) {
+ return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
+ }
+
+ let form: FormData;
+ try {
+ form = await request.formData();
+ } catch {
+ return NextResponse.json({ error: "Expected multipart form data" }, { status: 400 });
+ }
+ const file = form.get("file");
+ if (!isUploadedAvatarFile(file)) {
+ return NextResponse.json({ error: "Missing image file" }, { status: 400 });
+ }
+ if (!ALLOWED_AVATAR_TYPES.includes(file.type)) {
+ return NextResponse.json({ error: "Use a JPEG, PNG, WebP, or GIF image" }, { status: 400 });
+ }
+ if (file.size > MAX_AVATAR_SIZE) {
+ return NextResponse.json({ error: "Image must be 2 MB or smaller" }, { status: 413 });
+ }
+
+ const key = mailboxAvatarKeyFor(id);
+ await env.BUCKET.put(key, await file.arrayBuffer(), {
+ httpMetadata: { contentType: file.type },
+ });
+ await db.update(mailboxes).set({ avatarKey: key }).where(eq(mailboxes.id, id));
+ return NextResponse.json({ ok: true });
+}
diff --git a/src/app/api/mailboxes/[id]/avatar/types.d.ts b/src/app/api/mailboxes/[id]/avatar/types.d.ts
new file mode 100644
index 0000000..dd7a85d
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/avatar/types.d.ts
@@ -0,0 +1,3 @@
+export type MailboxAvatarRouteParams = {
+ params: Promise<{ id: string }>;
+};
diff --git a/src/app/api/mailboxes/[id]/avatar/utils.ts b/src/app/api/mailboxes/[id]/avatar/utils.ts
new file mode 100644
index 0000000..0c2a1bf
--- /dev/null
+++ b/src/app/api/mailboxes/[id]/avatar/utils.ts
@@ -0,0 +1,3 @@
+export function mailboxAvatarKeyFor(mailboxId: string): string {
+ return `mailbox-avatars/${mailboxId}`;
+}
diff --git a/src/app/api/mailboxes/[id]/route.ts b/src/app/api/mailboxes/[id]/route.ts
index 3f39603..23f5626 100644
--- a/src/app/api/mailboxes/[id]/route.ts
+++ b/src/app/api/mailboxes/[id]/route.ts
@@ -23,10 +23,12 @@ export async function GET(request: Request, { params }: MailboxRouteParams) {
if (!mailbox) {
return NextResponse.json({ error: "Mailbox not found" }, { status: 404 });
}
+ const { avatarKey, ...mailboxDetails } = mailbox;
return NextResponse.json({
mailbox: {
- ...mailbox,
+ ...mailboxDetails,
+ hasAvatar: !!avatarKey,
permission: access.permission,
isPrimary: `${mailbox.localPart}@${mailbox.hostname}` === user.email,
},
@@ -60,10 +62,12 @@ export async function PATCH(request: Request, { params }: MailboxRouteParams) {
}
const [mailbox] = await selectMailboxForUser(db, user.id, id);
+ const { avatarKey, ...mailboxDetails } = mailbox!;
return NextResponse.json({
mailbox: {
- ...mailbox,
+ ...mailboxDetails,
+ hasAvatar: !!avatarKey,
permission: access.permission,
isPrimary: `${mailbox!.localPart}@${mailbox!.hostname}` === user.email,
},
diff --git a/src/app/api/mailboxes/[id]/utils.ts b/src/app/api/mailboxes/[id]/utils.ts
index ec0e31d..5c6a155 100644
--- a/src/app/api/mailboxes/[id]/utils.ts
+++ b/src/app/api/mailboxes/[id]/utils.ts
@@ -13,6 +13,7 @@ export function selectMailboxForUser(db: Db, userId: string, mailboxId: string)
domainId: mailboxes.domainId,
localPart: mailboxes.localPart,
displayName: mailboxes.displayName,
+ avatarKey: mailboxes.avatarKey,
type: mailboxes.type,
disabled: mailboxes.disabled,
createdAt: mailboxes.createdAt,
diff --git a/src/app/api/messages/route.ts b/src/app/api/messages/route.ts
index 6d40e95..35c49b5 100644
--- a/src/app/api/messages/route.ts
+++ b/src/app/api/messages/route.ts
@@ -8,7 +8,7 @@ import { messages } from "@/db/schema";
import { getContactDisplayNameMap } from "@/lib/contacts/service";
import { normalizeEmailAddress } from "@/lib/email/address";
import { getLatestEmailContent } from "@/lib/email/reply-content-utils";
-import { getMailboxAccessLevel, listAccessibleMailboxIds } from "@/lib/mailboxes/access";
+import { getMailboxAccessLevel, listAccessibleMailboxes } from "@/lib/mailboxes/access";
export async function GET(request: Request) {
const env = getEnv();
@@ -29,7 +29,8 @@ export async function GET(request: Request) {
const offset = Math.max(Number(url.searchParams.get("offset") ?? 0), 0);
const db = getDb(env);
- const accessibleMailboxIds = await listAccessibleMailboxIds(db, user);
+ const accessibleMailboxes = await listAccessibleMailboxes(db, user);
+ const accessibleMailboxIds = accessibleMailboxes.map((mailbox) => mailbox.id);
const conditions: SQL[] = [];
if (mailboxId) {
const access = await getMailboxAccessLevel(db, user, mailboxId);
@@ -86,17 +87,39 @@ export async function GET(request: Request) {
.orderBy(desc(messages.createdAt))
.limit(limit)
.offset(offset);
- const contactMap = await getContactDisplayNameMap(
- env,
- user.id,
- rows.flatMap((message) => [message.fromAddr, message.toAddr]),
+ const mailboxNameMap = new Map(
+ accessibleMailboxes.map((mailbox) => [
+ mailbox.id,
+ mailbox.displayName ?? mailbox.localPart,
+ ]),
);
- const enrichedRows = rows.map((message) => ({
- ...message,
- snippet: getLatestEmailContent(message.snippet),
- fromContactName: contactMap.get(normalizeEmailAddress(message.fromAddr)) ?? null,
- toContactName: contactMap.get(normalizeEmailAddress(message.toAddr)) ?? null,
- }));
+ const contactMapsByUserId = new Map(
+ await Promise.all(
+ Array.from(new Set(rows.map((message) => message.userId))).map(async (userId) => [
+ userId,
+ await getContactDisplayNameMap(
+ env,
+ userId,
+ rows
+ .filter((message) => message.userId === userId)
+ .flatMap((message) => [message.fromAddr, message.toAddr]),
+ ),
+ ] as const),
+ ),
+ );
+ const enrichedRows = rows.map((message) => {
+ const contactMap = contactMapsByUserId.get(message.userId);
+ const accountName = message.mailboxId ? mailboxNameMap.get(message.mailboxId) : null;
+ return {
+ ...message,
+ snippet: getLatestEmailContent(message.snippet),
+ fromContactName:
+ (message.direction === "outbound" ? accountName : null) ??
+ contactMap?.get(normalizeEmailAddress(message.fromAddr)) ??
+ null,
+ toContactName: contactMap?.get(normalizeEmailAddress(message.toAddr)) ?? null,
+ };
+ });
return NextResponse.json({ messages: enrichedRows, total: totalRow?.total ?? 0, limit, offset });
}
diff --git a/src/app/api/profile/avatar/route.ts b/src/app/api/profile/avatar/route.ts
index ccfd220..79473f5 100644
--- a/src/app/api/profile/avatar/route.ts
+++ b/src/app/api/profile/avatar/route.ts
@@ -4,13 +4,12 @@ import { getDb } from "@/db";
import { users } from "@/db/schema";
import { getCurrentUser } from "@/lib/auth/cookies";
import { getEnv } from "@/lib/cloudflare";
-
-const MAX_AVATAR_SIZE = 2 * 1024 * 1024;
-const ALLOWED_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
-
-function avatarKeyFor(userId: string) {
- return `avatars/${userId}`;
-}
+import {
+ ALLOWED_AVATAR_TYPES,
+ MAX_AVATAR_SIZE,
+ avatarKeyFor,
+ isUploadedAvatarFile,
+} from "./utils";
export async function GET(request: Request) {
const env = getEnv();
@@ -22,7 +21,7 @@ export async function GET(request: Request) {
if (!object) return new Response("Not found", { status: 404 });
const headers = new Headers();
- object.writeHttpMetadata(headers);
+ headers.set("Content-Type", object.httpMetadata?.contentType ?? "application/octet-stream");
headers.set("X-Content-Type-Options", "nosniff");
headers.set(
"Content-Security-Policy",
@@ -44,10 +43,10 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "Expected multipart form data" }, { status: 400 });
}
const file = form.get("file");
- if (!(file instanceof File)) {
+ if (!isUploadedAvatarFile(file)) {
return NextResponse.json({ error: "Missing image file" }, { status: 400 });
}
- if (!ALLOWED_TYPES.includes(file.type)) {
+ if (!ALLOWED_AVATAR_TYPES.includes(file.type)) {
return NextResponse.json({ error: "Use a JPEG, PNG, WebP, or GIF image" }, { status: 400 });
}
if (file.size > MAX_AVATAR_SIZE) {
diff --git a/src/app/api/profile/avatar/types.d.ts b/src/app/api/profile/avatar/types.d.ts
new file mode 100644
index 0000000..05541fe
--- /dev/null
+++ b/src/app/api/profile/avatar/types.d.ts
@@ -0,0 +1 @@
+export type UploadedAvatarFile = File;
diff --git a/src/app/api/profile/avatar/utils.ts b/src/app/api/profile/avatar/utils.ts
new file mode 100644
index 0000000..d55a156
--- /dev/null
+++ b/src/app/api/profile/avatar/utils.ts
@@ -0,0 +1,18 @@
+import type { UploadedAvatarFile } from "./types";
+
+export const MAX_AVATAR_SIZE = 2 * 1024 * 1024;
+export const ALLOWED_AVATAR_TYPES = ["image/jpeg", "image/png", "image/webp", "image/gif"];
+
+export function avatarKeyFor(userId: string): string {
+ return `avatars/${userId}`;
+}
+
+export function isUploadedAvatarFile(value: FormDataEntryValue | null): value is UploadedAvatarFile {
+ return (
+ value !== null &&
+ typeof value !== "string" &&
+ typeof value.arrayBuffer === "function" &&
+ typeof value.size === "number" &&
+ typeof value.type === "string"
+ );
+}
diff --git a/src/app/api/routing-rules/[id]/route.ts b/src/app/api/routing-rules/[id]/route.ts
index dd9a670..0a50585 100644
--- a/src/app/api/routing-rules/[id]/route.ts
+++ b/src/app/api/routing-rules/[id]/route.ts
@@ -1,12 +1,66 @@
-import { eq } from "drizzle-orm";
+import { and, eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import { getDb } from "@/db";
-import { routingRules } from "@/db/schema";
+import { folders, routingRules } from "@/db/schema";
import { requireUser } from "@/lib/auth/cookies";
import { getEnv } from "@/lib/cloudflare";
import { getMailboxAccessLevel } from "@/lib/mailboxes/access";
+import { routingRuleSchema } from "@/lib/validators";
import type { RoutingRuleRouteParams } from "./types";
+export async function PATCH(request: Request, { params }: RoutingRuleRouteParams) {
+ const { id } = await params;
+ const env = getEnv();
+ const user = await requireUser(env, request);
+ const parsed = routingRuleSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
+ }
+
+ const db = getDb(env);
+ const [rule] = await db.select().from(routingRules).where(eq(routingRules.id, id)).limit(1);
+ if (!rule?.mailboxId || rule.mailboxId !== parsed.data.mailboxId) {
+ return NextResponse.json({ error: "Rule not found" }, { status: 404 });
+ }
+ const access = await getMailboxAccessLevel(db, user, rule.mailboxId);
+ if (!access?.canManage) {
+ return NextResponse.json({ error: "Rule not found" }, { status: 404 });
+ }
+
+ const destination = parsed.data.destination ?? (parsed.data.folderId ? `folder:${parsed.data.folderId}` : "");
+ const systemAction = destination === "spam" || destination === "trash" ? destination : null;
+ const folderId = destination.startsWith("folder:") ? destination.slice("folder:".length) : null;
+ if (!systemAction && !folderId) {
+ return NextResponse.json({ error: "Destination is required" }, { status: 400 });
+ }
+ if (folderId) {
+ const [folder] = await db
+ .select()
+ .from(folders)
+ .where(and(eq(folders.id, folderId), eq(folders.mailboxId, rule.mailboxId)))
+ .limit(1);
+ if (!folder) {
+ return NextResponse.json({ error: "Folder not found" }, { status: 404 });
+ }
+ }
+
+ await db
+ .update(routingRules)
+ .set({
+ pattern: parsed.data.matchValue.trim(),
+ matchField: parsed.data.matchField,
+ matchOperator: parsed.data.matchOperator,
+ matchValue: parsed.data.matchValue.trim(),
+ action: systemAction ?? "store",
+ folderId,
+ forwardTo: null,
+ priority: parsed.data.priority,
+ })
+ .where(eq(routingRules.id, id));
+
+ return NextResponse.json({ ok: true });
+}
+
export async function DELETE(request: Request, { params }: RoutingRuleRouteParams) {
const { id } = await params;
const env = getEnv();
diff --git a/src/app/globals.css b/src/app/globals.css
index f856cf5..ea2d695 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -31,4 +31,61 @@ pre {
.text {
font-family: var(--font-geist-sans), system-ui, sans-serif;
-}
\ No newline at end of file
+}
+
+@keyframes dialog-overlay-show {
+ from { opacity: 0; }
+ to { opacity: 1; }
+}
+
+@keyframes dialog-overlay-hide {
+ from { opacity: 1; }
+ to { opacity: 0; }
+}
+
+@keyframes dialog-content-show {
+ from {
+ opacity: 0;
+ transform: scale(0.94);
+ }
+ to {
+ opacity: 1;
+ transform: scale(1);
+ }
+}
+
+@keyframes dialog-content-hide {
+ from {
+ opacity: 1;
+ transform: scale(1);
+ }
+ to {
+ opacity: 0;
+ transform: scale(0.97);
+ }
+}
+
+.dialog-overlay[data-state="open"] {
+ animation: dialog-overlay-show 180ms ease-out;
+}
+
+.dialog-overlay[data-state="closed"] {
+ animation: dialog-overlay-hide 130ms ease-in;
+}
+
+.dialog-content[data-state="open"] {
+ transform-origin: center;
+ animation: dialog-content-show 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
+}
+
+.dialog-content[data-state="closed"] {
+ transform-origin: center;
+ animation: dialog-content-hide 130ms ease-in;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .dialog-overlay,
+ .dialog-content {
+ animation-duration: 1ms !important;
+ }
+}
diff --git a/src/components/admin-update-card.tsx b/src/components/admin-update-card.tsx
index f5f7206..92c4182 100644
--- a/src/components/admin-update-card.tsx
+++ b/src/components/admin-update-card.tsx
@@ -51,8 +51,8 @@ export function AdminUpdateCard() {
}
return (
- <Card className="max-w-5xl">
- <CardHeader className="flex-row items-center gap-4 space-y-0">
+ <Card className="rounded-3xl border-0 bg-white p-6">
+ <CardHeader className="flex-row items-center gap-4 space-y-0 py-0">
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-blue-100 text-blue-700">
<RefreshCw className="h-5 w-5" />
</div>
@@ -63,7 +63,7 @@ export function AdminUpdateCard() {
</p>
</div>
</CardHeader>
- <CardContent className="flex items-center gap-4">
+ <CardContent className="flex items-center gap-4 pt-5">
<Button type="button" onClick={handleUpdate} disabled={isChecking || isPending || !status?.available}>
<RefreshCw className={isPending ? "h-4 w-4 animate-spin" : "h-4 w-4"} />
{isPending ? "Starting update..." : "Update Mailflare"}
diff --git a/src/components/components-nav-types.d.ts b/src/components/components-nav-types.d.ts
index bd842e2..cf44371 100644
--- a/src/components/components-nav-types.d.ts
+++ b/src/components/components-nav-types.d.ts
@@ -4,6 +4,7 @@ export type NavLink = {
href?: string;
label?: string;
icon?: LucideIcon;
+ iconColor?: string;
primary?: boolean;
count?: number;
onMessageDrop?: (messageIds: string[]) => void;
diff --git a/src/components/components-nav.tsx b/src/components/components-nav.tsx
index d40ab3b..a602015 100644
--- a/src/components/components-nav.tsx
+++ b/src/components/components-nav.tsx
@@ -54,7 +54,7 @@ export function NavItem({ link }:{ link: NavLink }) {
className={classes}
{...dropProps}
>
- <Icon className="h-4 w-4" />
+ <Icon className="h-4 w-4" style={{ color: link.iconColor }} />
<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">
@@ -71,7 +71,7 @@ export function NavItem({ link }:{ link: NavLink }) {
className={cn("-ml-3 pl-6", classes)}
{...dropProps}
>
- <Icon className="h-4 w-4" />
+ <Icon className="h-4 w-4" style={{ color: link.iconColor }} />
<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">
diff --git a/src/components/contacts/contact-details-types.d.ts b/src/components/contacts/contact-details-types.d.ts
new file mode 100644
index 0000000..eca4f9c
--- /dev/null
+++ b/src/components/contacts/contact-details-types.d.ts
@@ -0,0 +1,19 @@
+export type ContactDetailsRecord = {
+ email: string;
+ displayName: string | null;
+ source: "manual" | "inbound" | "outbound" | null;
+ blocked: boolean;
+ lastSeenAt: string | null;
+};
+
+export type ContactDetailsResponse = {
+ contact?: ContactDetailsRecord;
+ error?: string;
+};
+
+export type ContactDetailsTriggerProps = {
+ mailboxId: string | null;
+ address: string;
+ name: string;
+ className?: string;
+};
diff --git a/src/components/contacts/contact-details-utils.ts b/src/components/contacts/contact-details-utils.ts
new file mode 100644
index 0000000..b70dc5f
--- /dev/null
+++ b/src/components/contacts/contact-details-utils.ts
@@ -0,0 +1,33 @@
+import { authFetch } from "@/lib/auth/client";
+import { getEmailAddress } from "@/lib/email/address";
+import type { ContactDetailsRecord, ContactDetailsResponse } from "./contact-details-types";
+
+export async function fetchContactDetails(
+ mailboxId: string,
+ address: string,
+): Promise<ContactDetailsRecord> {
+ const params = new URLSearchParams({ mailboxId, address: getEmailAddress(address) });
+ const response = await authFetch(`/api/contacts?${params.toString()}`);
+ const data = (await response.json()) as ContactDetailsResponse;
+ if (!response.ok || !data.contact) throw new Error(data.error ?? "Unable to load contact");
+ return data.contact;
+}
+
+export async function updateContactName(
+ mailboxId: string,
+ address: string,
+ displayName: string,
+): Promise<ContactDetailsRecord> {
+ const response = await authFetch("/api/contacts", {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mailboxId, address: getEmailAddress(address), displayName }),
+ });
+ const data = (await response.json()) as ContactDetailsResponse;
+ if (!response.ok || !data.contact) throw new Error(data.error ?? "Unable to update contact");
+ return data.contact;
+}
+
+export function getContactInitial(name: string, address: string): string {
+ return (name.trim() || getEmailAddress(address)).slice(0, 1).toUpperCase();
+}
diff --git a/src/components/contacts/contact-details.tsx b/src/components/contacts/contact-details.tsx
new file mode 100644
index 0000000..ae984ca
--- /dev/null
+++ b/src/components/contacts/contact-details.tsx
@@ -0,0 +1,146 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import dayjs from "dayjs";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { ContactDetailsRecord, ContactDetailsTriggerProps } from "./contact-details-types";
+import {
+ fetchContactDetails,
+ getContactInitial,
+ updateContactName,
+} from "./contact-details-utils";
+
+export function ContactDetailsTrigger({
+ mailboxId,
+ address,
+ name,
+ className,
+}: ContactDetailsTriggerProps) {
+ const [open, setOpen] = useState(false);
+ const [shownName, setShownName] = useState(name);
+ const [contact, setContact] = useState<ContactDetailsRecord | null>(null);
+ const [displayName, setDisplayName] = useState(name);
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ setShownName(name);
+ }, [name]);
+
+ useEffect(() => {
+ if (!open || !mailboxId) return;
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ fetchContactDetails(mailboxId, address)
+ .then((nextContact) => {
+ if (cancelled) return;
+ setContact(nextContact);
+ setDisplayName(nextContact.displayName ?? shownName);
+ })
+ .catch((loadError) => {
+ if (!cancelled) setError(loadError instanceof Error ? loadError.message : "Unable to load contact");
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [address, mailboxId, open, shownName]);
+
+ async function saveContact() {
+ if (!mailboxId || !displayName.trim()) return;
+ setSaving(true);
+ setError(null);
+ try {
+ const updated = await updateContactName(mailboxId, address, displayName);
+ const nextName = updated.displayName ?? displayName.trim();
+ setContact(updated);
+ setShownName(nextName);
+ setOpen(false);
+ window.dispatchEvent(new CustomEvent("mailflare:contact-changed", {
+ detail: { email: updated.email, displayName: nextName },
+ }));
+ } catch (saveError) {
+ setError(saveError instanceof Error ? saveError.message : "Unable to update contact");
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ if (!mailboxId) return <span className={className}>{shownName}</span>;
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className={`${className ?? ""} rounded-sm text-left hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-200`}
+ >
+ {shownName}
+ </button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Contact details</DialogTitle>
+ <DialogDescription>Update how this contact appears in your mailbox.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-5">
+ <div className="flex items-center gap-4">
+ <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-full bg-blue-100 text-lg font-semibold text-blue-700">
+ {getContactInitial(shownName, address)}
+ </div>
+ <div className="min-w-0">
+ <p className="truncate font-medium text-neutral-900">{shownName}</p>
+ <p className="truncate text-sm text-neutral-500">{contact?.email ?? address}</p>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="contact-display-name">Name</Label>
+ <Input
+ id="contact-display-name"
+ value={displayName}
+ onChange={(event) => setDisplayName(event.target.value)}
+ disabled={loading || saving}
+ />
+ </div>
+ <div className="grid gap-3 rounded-lg bg-neutral-50 p-3 text-sm sm:grid-cols-2">
+ <div>
+ <p className="text-xs font-medium uppercase text-neutral-400">Source</p>
+ <p className="mt-1 capitalize text-neutral-700">{contact?.source ?? "Email"}</p>
+ </div>
+ <div>
+ <p className="text-xs font-medium uppercase text-neutral-400">Last seen</p>
+ <p className="mt-1 text-neutral-700">
+ {contact?.lastSeenAt ? dayjs(contact.lastSeenAt).format("MMM DD, YYYY") : "Unknown"}
+ </p>
+ </div>
+ {contact?.blocked && (
+ <p className="text-sm font-medium text-red-600">Blocked contact</p>
+ )}
+ </div>
+ {error && <p className="text-sm text-red-600">{error}</p>}
+ <Button
+ type="button"
+ onClick={saveContact}
+ disabled={loading || saving || !displayName.trim()}
+ >
+ {saving ? "Saving..." : "Save contact"}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/src/components/dashboard-nav-types.d.ts b/src/components/dashboard-nav-types.d.ts
index ee29ea6..7979a1f 100644
--- a/src/components/dashboard-nav-types.d.ts
+++ b/src/components/dashboard-nav-types.d.ts
@@ -1,4 +1,5 @@
export type CustomFolder = {
id: string;
name: string;
+ color: string;
};
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index 53f7c62..7d66bb7 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -11,7 +11,6 @@ import {
MailPlus,
Plus,
Send,
- Settings,
ShieldAlert,
Trash2,
} from "lucide-react";
@@ -29,6 +28,8 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useMessageCounts } from "@/hooks/use-message-counts";
import { authFetch } from "@/lib/auth/client";
+import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_OPTIONS } from "@/lib/folders/colors";
+import type { FolderColor } from "@/lib/folders/types";
import { cn } from "@/lib/utils";
import { NavItem } from "./components-nav";
import type { NavLink } from "./components-nav-types";
@@ -46,15 +47,12 @@ const links = [
{ href: "/trash", label: "Trash", icon: Trash2 },
];
-const secondaryLinks = [
- { href: "/settings", label: "Settings", icon: Settings },
-];
-
export function DashboardNav({ className }: { className?: string }) {
const { selectedMailbox, isLoading } = useSelectedMailbox();
const { counts } = useMessageCounts(selectedMailbox?.id, !isLoading);
const [folders, setFolders] = useState<CustomFolder[]>([]);
const [newFolderName, setNewFolderName] = useState("");
+ const [newFolderColor, setNewFolderColor] = useState<FolderColor>(DEFAULT_FOLDER_COLOR);
const [addingFolder, setAddingFolder] = useState(false);
const [folderDialogOpen, setFolderDialogOpen] = useState(false);
const linksWithCounts: NavLink[] = links.map((link): NavLink => {
@@ -122,12 +120,17 @@ export function DashboardNav({ className }: { className?: string }) {
const response = await authFetch("/api/folders", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ mailboxId: selectedMailbox.id, name: newFolderName }),
+ body: JSON.stringify({
+ mailboxId: selectedMailbox.id,
+ name: newFolderName,
+ color: newFolderColor,
+ }),
});
if (!response.ok) return;
const folder = (await response.json()) as CustomFolder;
setFolders((items) => [...items, folder].sort((a, b) => a.name.localeCompare(b.name)));
setNewFolderName("");
+ setNewFolderColor(DEFAULT_FOLDER_COLOR);
setFolderDialogOpen(false);
} finally {
setAddingFolder(false);
@@ -173,6 +176,28 @@ export function DashboardNav({ className }: { className?: string }) {
autoFocus
/>
</div>
+ <div className="space-y-2">
+ <Label>Color</Label>
+ <div className="flex flex-wrap gap-2" role="radiogroup" aria-label="Folder color">
+ {FOLDER_COLOR_OPTIONS.map((option) => (
+ <button
+ key={option.value}
+ type="button"
+ role="radio"
+ aria-checked={newFolderColor === option.value}
+ aria-label={option.label}
+ title={option.label}
+ onClick={() => setNewFolderColor(option.value)}
+ className={`h-8 w-8 rounded-full border-2 transition-transform hover:scale-110 ${
+ newFolderColor === option.value
+ ? "border-neutral-900 ring-2 ring-neutral-300 ring-offset-2"
+ : "border-transparent"
+ }`}
+ style={{ backgroundColor: option.value }}
+ />
+ ))}
+ </div>
+ </div>
<Button type="submit" disabled={addingFolder || !newFolderName.trim()}>
{addingFolder ? "Creating..." : "Create folder"}
</Button>
@@ -193,13 +218,13 @@ export function DashboardNav({ className }: { className?: string }) {
href: `/folders/${folder.id}`,
label: folder.name,
icon: Folder,
+ iconColor: folder.color,
count: counts.customFolders[folder.id]?.unread,
onMessageDrop: (messageIds: string[]) => void moveMessagesToCustomFolder(messageIds, folder.id),
}}
/>
))}
<span className="flex-1" />
- {secondaryLinks.map((link) => <NavItem link={link} key={link.href} />)}
<SidebarFooter />
</nav>
);
diff --git a/src/components/mailbox-provider-utils.ts b/src/components/mailbox-provider-utils.ts
index 2db3eea..75ee190 100644
--- a/src/components/mailbox-provider-utils.ts
+++ b/src/components/mailbox-provider-utils.ts
@@ -32,6 +32,7 @@ export async function fetchMailboxOptions(force = false): Promise<MailboxOption[
localPart: m.localPart,
hostname: m.hostname,
displayName: m.displayName,
+ hasAvatar: m.hasAvatar,
type: m.type,
permission: m.permission,
isPrimary: m.isPrimary,
diff --git a/src/components/mailbox-provider.tsx b/src/components/mailbox-provider.tsx
index f51a1eb..e0a3ccc 100644
--- a/src/components/mailbox-provider.tsx
+++ b/src/components/mailbox-provider.tsx
@@ -22,6 +22,7 @@ export type MailboxOption = {
localPart: string;
hostname: string;
displayName: string | null;
+ hasAvatar?: boolean;
type?: "personal" | "shared";
permission?: "read_only" | "send_as" | "send_on_behalf" | "full_access";
isPrimary?: boolean;
diff --git a/src/components/mailbox-selector-types.d.ts b/src/components/mailbox-selector-types.d.ts
new file mode 100644
index 0000000..1eac21d
--- /dev/null
+++ b/src/components/mailbox-selector-types.d.ts
@@ -0,0 +1,24 @@
+import type { MailboxOption } from "./mailbox-provider";
+
+export type MailboxSelectorUser = {
+ id: string;
+ email: string;
+ name: string;
+ role: "admin" | "user";
+ hasAvatar: boolean;
+};
+
+export type AccountAvatarProps = {
+ name: string;
+ hasAvatar?: boolean;
+ avatarUrl?: string;
+ size?: "small" | "large";
+ onAvatarError?: () => void;
+};
+
+export type MailboxAccountRowProps = {
+ mailbox: MailboxOption;
+ unread: number;
+ avatarUrl?: string;
+ onSelect: () => void;
+};
diff --git a/src/components/mailbox-selector-utils.ts b/src/components/mailbox-selector-utils.ts
new file mode 100644
index 0000000..282eae8
--- /dev/null
+++ b/src/components/mailbox-selector-utils.ts
@@ -0,0 +1,25 @@
+import type { MailboxOption } from "./mailbox-provider";
+
+export function getMailboxAddress(mailbox: MailboxOption): string {
+ return `${mailbox.localPart}@${mailbox.hostname}`;
+}
+
+export function getMailboxName(mailbox: MailboxOption): string {
+ return mailbox.displayName ?? mailbox.localPart;
+}
+
+export function getAccountInitial(value: string): string {
+ return value.trim().slice(0, 1).toUpperCase() || "M";
+}
+
+export function isAdminPath(pathname: string): boolean {
+ return (
+ pathname === "/admin" ||
+ pathname.startsWith("/mailboxes") ||
+ pathname.startsWith("/domains") ||
+ pathname.startsWith("/api-keys") ||
+ pathname.startsWith("/webhooks") ||
+ pathname.startsWith("/activity") ||
+ pathname.startsWith("/backups")
+ );
+}
diff --git a/src/components/mailbox-selector.tsx b/src/components/mailbox-selector.tsx
index e3d7ae7..cd11472 100644
--- a/src/components/mailbox-selector.tsx
+++ b/src/components/mailbox-selector.tsx
@@ -2,23 +2,107 @@
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
-import { Check, LogOut, Mail, Settings } from "lucide-react";
+import { Check, LogOut, ShieldCheck, UserRound } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMessageCounts } from "@/hooks/use-message-counts";
import { authFetch } from "@/lib/auth/client";
import { logoutClientSession } from "@/lib/auth/logout";
-import { cn } from "@/lib/utils";
+import {
+ PROFILE_AVATAR_CHANGED_EVENT,
+ getProfileAvatarUrl,
+} from "@/lib/profile/avatar-client";
+import type { ProfileAvatarChangedDetail } from "@/lib/profile/types";
+import { MAILBOX_AVATAR_CHANGED_EVENT } from "@/lib/mailboxes/avatar-client";
+import type { MailboxAvatarChangedDetail } from "@/lib/mailboxes/avatar-client-types";
import { Skeleton } from "@/components/ui/skeleton";
+import type {
+ AccountAvatarProps,
+ MailboxAccountRowProps,
+ MailboxSelectorUser,
+} from "./mailbox-selector-types";
+import {
+ getAccountInitial,
+ getMailboxAddress,
+ getMailboxName,
+ isAdminPath,
+} from "./mailbox-selector-utils";
+
+function AccountAvatar({
+ name,
+ hasAvatar = false,
+ avatarUrl = "/api/profile/avatar",
+ size = "small",
+ onAvatarError,
+}: AccountAvatarProps) {
+ const sizeClass = size === "large" ? "h-16 w-16 text-xl" : "h-10 w-10 text-sm";
+ const [imageFailed, setImageFailed] = useState(false);
+
+ useEffect(() => {
+ setImageFailed(false);
+ }, [avatarUrl, hasAvatar]);
+
+ if (hasAvatar && !imageFailed) {
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={avatarUrl}
+ alt={`${name} profile picture`}
+ className={`${sizeClass} shrink-0 rounded-full border border-neutral-200 object-cover`}
+ onError={() => {
+ setImageFailed(true);
+ onAvatarError?.();
+ }}
+ />
+ );
+ }
+
+ return (
+ <div
+ className={`${sizeClass} flex shrink-0 items-center justify-center rounded-full bg-blue-600 font-semibold text-white`}
+ aria-hidden="true"
+ >
+ {getAccountInitial(name)}
+ </div>
+ );
+}
+
+function MailboxAccountRow({ mailbox, unread, avatarUrl, onSelect }: MailboxAccountRowProps) {
+ const name = getMailboxName(mailbox);
+
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ className="flex w-full items-center gap-3 rounded-2xl px-4 py-3 text-left transition-colors hover:bg-white"
+ >
+ <AccountAvatar
+ name={name}
+ hasAvatar={!!mailbox.hasAvatar || !!avatarUrl}
+ avatarUrl={avatarUrl ?? `/api/mailboxes/${mailbox.id}/avatar`}
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-semibold text-neutral-900">{name}</p>
+ <p className="truncate text-xs text-neutral-500">{getMailboxAddress(mailbox)}</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>
+ )}
+ </button>
+ );
+}
export function MailboxSelector() {
- const { selectedMailbox, setSelectedMailbox, mailboxes, isLoading } =
- useSelectedMailbox();
+ const { selectedMailbox, setSelectedMailbox, mailboxes, isLoading } = useSelectedMailbox();
const pathname = usePathname();
const router = useRouter();
const [open, setOpen] = useState(false);
- const [isAdmin, setIsAdmin] = useState(false);
+ const [user, setUser] = useState<MailboxSelectorUser | null>(null);
const [hasAvatar, setHasAvatar] = useState(false);
+ const [avatarUrl, setAvatarUrl] = useState("/api/profile/avatar");
+ const [mailboxAvatarUrls, setMailboxAvatarUrls] = useState<Record<string, string>>({});
const ref = useRef<HTMLDivElement>(null);
const { counts } = useMessageCounts(null, open);
@@ -33,37 +117,57 @@ export function MailboxSelector() {
useEffect(() => {
authFetch("/api/auth/me", { redirectOnUnauthorized: false })
- .then((response) => response.ok ? response.json() : null)
+ .then((response) => (response.ok ? response.json() : null))
.then((data) => {
- const authData = data as { user?: { role?: string; hasAvatar?: boolean } } | null;
- setIsAdmin(authData?.user?.role === "admin");
+ const authData = data as { user?: MailboxSelectorUser } | null;
+ setUser(authData?.user ?? null);
setHasAvatar(!!authData?.user?.hasAvatar);
})
- .catch(() => setIsAdmin(false));
+ .catch(() => setUser(null));
+ }, []);
+
+ useEffect(() => {
+ function onAvatarChanged(event: Event) {
+ const detail = (event as CustomEvent<ProfileAvatarChangedDetail>).detail;
+ setAvatarUrl(detail?.url ?? getProfileAvatarUrl());
+ setHasAvatar(true);
+ }
+
+ window.addEventListener(PROFILE_AVATAR_CHANGED_EVENT, onAvatarChanged);
+ return () => window.removeEventListener(PROFILE_AVATAR_CHANGED_EVENT, onAvatarChanged);
+ }, []);
+
+ useEffect(() => {
+ function onMailboxAvatarChanged(event: Event) {
+ const detail = (event as CustomEvent<MailboxAvatarChangedDetail>).detail;
+ if (!detail?.mailboxId || !detail.url) return;
+ setMailboxAvatarUrls((current) => ({
+ ...current,
+ [detail.mailboxId]: detail.url,
+ }));
+ }
+
+ window.addEventListener(MAILBOX_AVATAR_CHANGED_EVENT, onMailboxAvatarChanged);
+ return () => window.removeEventListener(MAILBOX_AVATAR_CHANGED_EVENT, onMailboxAvatarChanged);
}, []);
if (isLoading) {
- return (
- <div className="flex items-center gap-3 px-2">
- <div className="space-y-1.5">
- <Skeleton className="h-3.5 w-24" />
- <Skeleton className="h-2.5 w-16" />
- </div>
- <Skeleton className="h-8 w-8 rounded-full" />
- </div>
- );
+ return <Skeleton className="h-10 w-10 rounded-full" />;
}
- const selectedName = selectedMailbox?.displayName ?? selectedMailbox?.localPart ?? "All mailboxes";
- const selectedEmail = selectedMailbox
- ? `${selectedMailbox.localPart}@${selectedMailbox.hostname}`
- : "All domains";
- const adminActive =
- pathname === "/admin" ||
- pathname.startsWith("/mailboxes") ||
- pathname.startsWith("/domains") ||
- pathname.startsWith("/api-keys") ||
- pathname.startsWith("/webhooks");
+ const selectedName = selectedMailbox ? getMailboxName(selectedMailbox) : user?.name ?? "Account";
+ const selectedEmail = selectedMailbox ? getMailboxAddress(selectedMailbox) : user?.email ?? "";
+ const selectedMailboxAvatarUrl = selectedMailbox
+ ? mailboxAvatarUrls[selectedMailbox.id]
+ : undefined;
+ const selectedHasAvatar = selectedMailbox
+ ? !!selectedMailbox.hasAvatar || !!selectedMailboxAvatarUrl
+ : hasAvatar;
+ const selectedAvatarUrl = selectedMailbox
+ ? selectedMailboxAvatarUrl ?? `/api/mailboxes/${selectedMailbox.id}/avatar`
+ : avatarUrl;
+ const otherMailboxes = mailboxes.filter((mailbox) => mailbox.id !== selectedMailbox?.id);
+ const adminActive = isAdminPath(pathname);
async function logout() {
await logoutClientSession();
@@ -77,111 +181,96 @@ export function MailboxSelector() {
<button
type="button"
onClick={() => setOpen((value) => !value)}
- className="flex items-center justify-between gap-3 rounded-full pr-2 pl-4 py-1.5 text-left hover:bg-neutral-200"
+ className="rounded-full p-1 transition-colors hover:bg-neutral-200"
+ aria-label="Open account menu"
+ aria-expanded={open}
>
- <div className="flex min-w-0 items-center gap-3">
- <div className="min-w-0 text-right flex flex-col justify-center">
- <p className="truncate text-sm font-medium text-neutral-800">{selectedName}</p>
- <p className="truncate text-[11px] text-neutral-500">{selectedEmail}</p>
- </div>
- {hasAvatar ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src="/api/profile/avatar"
- alt="Profile"
- className="h-8 w-8 shrink-0 rounded-full object-cover"
- onError={() => setHasAvatar(false)}
- />
- ) : (
- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-600 text-white">
- <Mail className="h-4 w-4" />
- </div>
- )}
- </div>
- {/* <ChevronDown className="h-4 w-4 shrink-0 text-neutral-500" /> */}
+ <AccountAvatar
+ name={selectedName}
+ hasAvatar={selectedHasAvatar}
+ avatarUrl={selectedAvatarUrl}
+ onAvatarError={() => {
+ if (!selectedMailbox) setHasAvatar(false);
+ }}
+ />
</button>
+
{open && (
- <div className="absolute right-0 top-12 z-50 w-80 overflow-hidden rounded-2xl border border-neutral-200 bg-white py-2 shadow-xl">
- <div className="px-4 pt-3 pb-2">
- <p className="text-sm font-medium text-neutral-900">Mailboxes</p>
- <p className="text-xs text-neutral-500">Choose the active sending and inbox account.</p>
- </div>
- {mailboxes.map((mb) => {
- 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;
-
- return (
- <button
- key={mb.id}
- type="button"
- onClick={() => {
- setSelectedMailbox(mb);
- setOpen(false);
- router.push("/inbox");
+ <div className="absolute right-0 top-14 z-50 w-[360px] overflow-hidden rounded-[28px] border border-neutral-200 bg-[#eef3fb] p-3 shadow-2xl shadow-neutral-900/20">
+ <div className="rounded-[22px] bg-white px-5 py-5">
+ <div className="flex items-center gap-4">
+ <AccountAvatar
+ name={selectedName}
+ hasAvatar={selectedHasAvatar}
+ avatarUrl={selectedAvatarUrl}
+ size="large"
+ onAvatarError={() => {
+ if (!selectedMailbox) setHasAvatar(false);
}}
- className={cn(
- "flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-[#f2f6fc]",
- active && "bg-blue-50",
- )}
- >
- <div className="flex h-9 w-9 items-center justify-center rounded-full bg-blue-100 text-blue-700">
- {name.slice(0, 1).toUpperCase()}
- </div>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- <p className="truncate text-sm font-medium text-neutral-900">{name}</p>
- {mb.isPrimary && (
- <span className="rounded-full bg-blue-100 px-2 py-0.5 text-[10px] font-medium text-blue-700">
- Primary
- </span>
- )}
- </div>
- <p className="truncate text-xs text-neutral-500">{email}</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>
- );
- })}
- <div className="mt-2 border-t divide-y divide-neutral-100 border-neutral-100 pt-2">
- {isAdmin && (
+ />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-lg font-semibold text-neutral-900">
+ {selectedName}
+ </p>
+ <p className="truncate text-sm text-neutral-500">
+ {selectedEmail}
+ </p>
+ </div>
+ <Check className="h-5 w-5 shrink-0 text-blue-600" />
+ </div>
+ </div>
+
+ {otherMailboxes.length > 0 && (
+ <div className="mt-2 rounded-[22px] bg-white/55 p-1">
+ <p className="px-4 pb-1 pt-3 text-xs font-semibold uppercase tracking-wide text-neutral-500">
+ Other accounts
+ </p>
+ {otherMailboxes.map((mailbox) => {
+ const mailboxCount = counts.mailboxes.find((count) => count.mailboxId === mailbox.id);
+ return (
+ <MailboxAccountRow
+ key={mailbox.id}
+ mailbox={mailbox}
+ unread={mailboxCount?.unread ?? 0}
+ avatarUrl={mailboxAvatarUrls[mailbox.id]}
+ onSelect={() => {
+ setSelectedMailbox(mailbox);
+ setOpen(false);
+ router.push("/inbox");
+ }}
+ />
+ );
+ })}
+ </div>
+ )}
+
+ <div className="mt-2 overflow-hidden rounded-[22px] bg-white">
+ <Link
+ href="/settings"
+ onClick={() => setOpen(false)}
+ className="flex items-center gap-3 px-5 py-4 text-sm font-medium text-neutral-800 hover:bg-[#f2f6fc]"
+ >
+ <UserRound className="h-5 w-5 text-neutral-600" />
+ Account
+ </Link>
+ {user?.role === "admin" && (
<Link
href="/admin"
onClick={() => setOpen(false)}
- className={cn(
- "flex items-center gap-3 px-4 py-3 text-sm font-medium text-neutral-700 hover:bg-[#f2f6fc]",
- adminActive && "bg-blue-50",
- )}
+ className={`flex items-center gap-3 border-t border-neutral-100 px-5 py-4 text-sm font-medium text-neutral-800 hover:bg-[#f2f6fc] ${adminActive ? "bg-blue-50" : ""}`}
>
- <div className="flex h-9 w-9 items-center justify-center rounded-full bg-neutral-100 text-neutral-700">
- <Settings className="h-4 w-4" />
- </div>
- <div>
- <p className="text-sm font-medium text-neutral-900">Admin settings</p>
- <p className="text-xs text-neutral-500">Domains, mailboxes, API keys</p>
- </div>
+ <ShieldCheck className="h-5 w-5 text-neutral-600" />
+ Admin
{adminActive && <Check className="ml-auto h-4 w-4 text-blue-600" />}
</Link>
)}
<button
type="button"
onClick={logout}
- className="flex w-full items-center gap-3 px-4 py-3 text-left text-sm font-medium text-red-600 hover:bg-red-50"
+ className="flex w-full items-center gap-3 border-t border-neutral-100 px-5 py-4 text-left text-sm font-medium text-neutral-800 hover:bg-[#f2f6fc]"
>
- <div className="flex h-9 w-9 items-center justify-center rounded-full bg-red-50 text-red-600">
- <LogOut className="h-4 w-4" />
- </div>
- <div>
- <p className="text-sm font-medium">Log out</p>
- <p className="text-xs text-red-500/80">Sign out of this session</p>
- </div>
+ <LogOut className="h-5 w-5 text-neutral-600" />
+ Sign out
</button>
</div>
</div>
diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx
index 6f1dd51..d9282b3 100644
--- a/src/components/message-actions/message-actions.tsx
+++ b/src/components/message-actions/message-actions.tsx
@@ -1,8 +1,8 @@
"use client";
-import { useState } from "react";
+import { createElement, useState } from "react";
import { useRouter } from "next/navigation";
-import { Archive, Mail, MailOpen, MoreVertical, Reply, ShieldAlert, Trash2 } from "lucide-react";
+import { Archive, Ban, Icon, Mail, MailOpen, MoreVertical, Reply, ShieldAlert, Trash2 } from "lucide-react";
import { useCompose } from "@/components/compose/compose-context";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
@@ -10,9 +10,11 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { MessageActionsProps } from "./types";
import {
confirmTrashWithoutUnsubscribe,
+ blockMessageContact,
createReplyDraft,
createTrashSenderRule,
getMessageActionRedirect,
+ getMoveMessageActions,
openUnsubscribeUrl,
runSingleMessageAction,
} from "./utils";
@@ -32,7 +34,7 @@ export function MessageActions({
const router = useRouter();
const { openDraftComposer } = useCompose();
const [pendingAction, setPendingAction] = useState<
- BulkMessageAction | "unsubscribe" | "reply" | null
+ BulkMessageAction | "unsubscribe" | "reply" | "block" | null
>(null);
const [error, setError] = useState<string | null>(null);
const [moreOpen, setMoreOpen] = useState(false);
@@ -97,8 +99,30 @@ export function MessageActions({
}
}
+ async function onBlockContact() {
+ setMoreOpen(false);
+ setError(null);
+ if (!mailboxId) {
+ setError("Could not block contact");
+ return;
+ }
+
+ setPendingAction("block");
+ try {
+ await blockMessageContact({ mailboxId, senderAddress });
+ await runSingleMessageAction(messageId, "trash");
+ router.push("/trash");
+ router.refresh();
+ } catch (blockError) {
+ setError(blockError instanceof Error ? blockError.message : "Could not block contact");
+ } finally {
+ setPendingAction(null);
+ }
+ }
+
const disabled = pendingAction !== null;
const markAction: BulkMessageAction = read ? "unread" : "read";
+ const moveActions = getMoveMessageActions(status, direction);
return (
<div className="flex items-center gap-3 text-neutral-600">
@@ -175,39 +199,42 @@ export function MessageActions({
</Button>
</Tooltip>
{moreOpen && (
- <div className="absolute right-0 z-20 mt-2 w-44 rounded-xl border border-neutral-200 bg-white p-2 shadow-lg">
+ <div className="absolute right-0 z-20 mt-2 w-54 rounded-xl border border-neutral-200 bg-white p-2 shadow-lg">
{direction === "inbound" && (
+ <>
+ <button
+ type="button"
+ className="w-full rounded-lg px-3 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-400"
+ disabled={!unsubscribeUrl && status === "trash"}
+ onClick={() => void onUnsubscribe()}
+ >
+ Unsubscribe
+ </button>
+ <button
+ type="button"
+ className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100"
+ onClick={() => void onBlockContact()}
+ >
+ <Ban className="h-4 w-4" />
+ Block contact
+ </button>
+ <hr />
+ </>
+ )}
+ <p className="mt-1 px-3 pb-1 pt-2 text-sm font-medium text-neutral-500">
+ Move to
+ </p>
+ {moveActions.map((item) => (
<button
+ key={item.action}
type="button"
- className="w-full rounded-lg px-3 py-2 text-left text-sm text-neutral-700 hover:bg-neutral-100 disabled:cursor-not-allowed disabled:text-neutral-400"
- disabled={!unsubscribeUrl && status === "trash"}
- onClick={() => void onUnsubscribe()}
+ className="w-full rounded-lg px-3 py-2 text-neutral-700 hover:bg-neutral-100 flex flex-row gap-2 items-center cursor-pointer"
+ onClick={() => void runAction(item.action)}
>
- Unsubscribe
+ {createElement(item.icon, { size: 16 })}
+ {item.label}
</button>
- )}
- <label className="mt-1 block px-3 text-xs font-medium text-neutral-500" htmlFor={`move-message-${messageId}`}>
- Move to
- </label>
- <select
- id={`move-message-${messageId}`}
- className="mt-1 h-8 w-full rounded-lg border border-neutral-200 bg-white px-2 text-xs text-neutral-700"
- defaultValue=""
- aria-label="Move message"
- onChange={(event) => {
- if (!event.target.value) return;
- void runAction(event.target.value as BulkMessageAction);
- event.target.value = "";
- }}
- >
- <option value="">Select folder...</option>
- {status === "archived" && direction === "inbound" && (
- <option value="inbox">Inbox</option>
- )}
- {status !== "archived" && <option value="archive">Archived</option>}
- <option value="spam">Spam</option>
- <option value="trash">Trash</option>
- </select>
+ ))}
</div>
)}
</div>
diff --git a/src/components/message-actions/types.d.ts b/src/components/message-actions/types.d.ts
index 3c41827..cf886d9 100644
--- a/src/components/message-actions/types.d.ts
+++ b/src/components/message-actions/types.d.ts
@@ -1,5 +1,6 @@
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { MessageDirection } from "@/hooks/types";
+import { IconNode } from "lucide-react";
export type MessageActionsProps = {
messageId: string;
@@ -28,3 +29,14 @@ export type TrashSenderRuleInput = {
mailboxId: string;
senderAddress: string;
};
+
+export type BlockMessageContactInput = {
+ mailboxId: string;
+ senderAddress: string;
+};
+
+export type MoveMessageActionItem = {
+ action: BulkMessageAction;
+ label: string;
+ icon: any
+};
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 8621a98..85fb4ce 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -2,107 +2,171 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import { authFetch } from "@/lib/auth/client";
import { getEmailAddress } from "@/lib/email/address";
import { getLatestEmailContent } from "@/lib/email/reply-content-utils";
-import type { ReplyDraftInput, TrashSenderRuleInput } from "./types";
+import type {
+ BlockMessageContactInput,
+ MoveMessageActionItem,
+ ReplyDraftInput,
+ TrashSenderRuleInput,
+} from "./types";
+import {
+ ArchiveIcon,
+ Inbox,
+ InboxIcon,
+ ShieldAlertIcon,
+ ShieldIcon,
+ Trash2Icon,
+ TrashIcon,
+} from "lucide-react";
-export function getMessageBackHref(direction: "inbound" | "outbound", status: string) {
- if (status === "trash") return "/trash";
- if (status === "spam") return "/spam";
- if (status === "archived") return "/archived";
- if (status === "draft") return "/drafts";
- return direction === "inbound" ? "/inbox" : "/sent";
+export function getMessageBackHref(
+ direction: "inbound" | "outbound",
+ status: string,
+) {
+ if (status === "trash") return "/trash";
+ if (status === "spam") return "/spam";
+ if (status === "archived") return "/archived";
+ if (status === "draft") return "/drafts";
+ return direction === "inbound" ? "/inbox" : "/sent";
}
-export async function runSingleMessageAction(messageId: string, action: BulkMessageAction) {
- const response = await authFetch("/api/messages/bulk", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ messageIds: [messageId], action }),
- });
+export async function runSingleMessageAction(
+ messageId: string,
+ action: BulkMessageAction,
+) {
+ const response = await authFetch("/api/messages/bulk", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ messageIds: [messageId], action }),
+ });
- if (!response.ok) {
- throw new Error("Unable to update message");
- }
+ if (!response.ok) {
+ throw new Error("Unable to update message");
+ }
- window.dispatchEvent(new Event("mailflare:messages-changed"));
+ window.dispatchEvent(new Event("mailflare:messages-changed"));
}
export function openUnsubscribeUrl(url: string) {
- window.open(url, "_blank", "noopener,noreferrer");
+ window.open(url, "_blank", "noopener,noreferrer");
}
export function confirmTrashWithoutUnsubscribe() {
- return window.confirm(
- "This email does not provide an unsubscribe link. It will be moved to Trash, and future emails from this sender will also be moved to Trash.",
- );
+ return window.confirm(
+ "This email does not provide an unsubscribe link. It will be moved to Trash, and future emails from this sender will also be moved to Trash.",
+ );
}
-export async function createTrashSenderRule({ mailboxId, senderAddress }: TrashSenderRuleInput) {
- const sender = getEmailAddress(senderAddress).trim().toLowerCase();
- if (!sender) throw new Error("Sender address is required");
+export async function createTrashSenderRule({
+ mailboxId,
+ senderAddress,
+}: TrashSenderRuleInput) {
+ const sender = getEmailAddress(senderAddress).trim().toLowerCase();
+ if (!sender) throw new Error("Sender address is required");
- const response = await authFetch("/api/routing-rules", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- mailboxId,
- matchField: "email",
- matchOperator: "exact",
- matchValue: sender,
- destination: "trash",
- priority: 0,
- }),
- });
- const data = (await response.json()) as { error?: string };
- if (!response.ok) throw new Error(data.error ?? "Unable to create trash rule");
+ const response = await authFetch("/api/routing-rules", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ mailboxId,
+ matchField: "email",
+ matchOperator: "exact",
+ matchValue: sender,
+ destination: "trash",
+ priority: 0,
+ }),
+ });
+ const data = (await response.json()) as { error?: string };
+ if (!response.ok)
+ throw new Error(data.error ?? "Unable to create trash rule");
}
-export function getMessageActionRedirect(action: BulkMessageAction, direction: "inbound" | "outbound") {
- if (action === "trash") return "/trash";
- if (action === "spam") return "/spam";
- if (action === "archive") return "/archived";
- if (action === "inbox") return "/inbox";
- return null;
+export async function blockMessageContact({
+ mailboxId,
+ senderAddress,
+}: BlockMessageContactInput) {
+ const response = await authFetch("/api/contacts/block", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ mailboxId, address: senderAddress }),
+ });
+ const data = (await response.json()) as { error?: string };
+ if (!response.ok) throw new Error(data.error ?? "Unable to block contact");
+}
+
+export function getMoveMessageActions(
+ status: string,
+ direction: "inbound" | "outbound",
+): MoveMessageActionItem[] {
+ const actions: MoveMessageActionItem[] = [];
+ if (status === "archived" && direction === "inbound") {
+ actions.push({ action: "inbox", label: "Inbox", icon: InboxIcon });
+ }
+ if (status !== "archived")
+ actions.push({ action: "archive", label: "Archived", icon: ArchiveIcon });
+ if (status !== "spam")
+ actions.push({ action: "spam", label: "Spam", icon: ShieldAlertIcon });
+ if (status !== "trash")
+ actions.push({ action: "trash", label: "Trash", icon: Trash2Icon });
+ return actions;
+}
+
+export function getMessageActionRedirect(
+ action: BulkMessageAction,
+ direction: "inbound" | "outbound",
+) {
+ if (action === "trash") return "/trash";
+ if (action === "spam") return "/spam";
+ if (action === "archive") return "/archived";
+ if (action === "inbox") return "/inbox";
+ return null;
}
export function buildReplySubject(subject: string | null | undefined) {
- const trimmed = (subject ?? "").trim();
- if (!trimmed) return "Re:";
- return /^re:/i.test(trimmed) ? trimmed : `Re: ${trimmed}`;
+ const trimmed = (subject ?? "").trim();
+ if (!trimmed) return "Re:";
+ return /^re:/i.test(trimmed) ? trimmed : `Re: ${trimmed}`;
}
-export function buildReplyQuote(senderAddress: string, bodyText: string | null | undefined) {
- const latest = getLatestEmailContent(bodyText).trim();
- if (!latest) return "";
- const quoted = latest
- .split("\n")
- .map((line) => `> ${line}`)
- .join("\n");
- return `\n\n${getEmailAddress(senderAddress)} wrote:\n${quoted}\n`;
+export function buildReplyQuote(
+ senderAddress: string,
+ bodyText: string | null | undefined,
+) {
+ const latest = getLatestEmailContent(bodyText).trim();
+ if (!latest) return "";
+ const quoted = latest
+ .split("\n")
+ .map((line) => `> ${line}`)
+ .join("\n");
+ return `\n\n${getEmailAddress(senderAddress)} wrote:\n${quoted}\n`;
}
export async function createReplyDraft({
- mailboxId,
- senderAddress,
- ownAddress,
- subject,
- bodyText,
+ mailboxId,
+ senderAddress,
+ ownAddress,
+ subject,
+ bodyText,
}: ReplyDraftInput) {
- const to = getEmailAddress(senderAddress).trim();
- if (!to) throw new Error("Sender address is required");
+ const to = getEmailAddress(senderAddress).trim();
+ if (!to) throw new Error("Sender address is required");
- const response = await authFetch("/api/drafts", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- mailboxId,
- // The API rejects the draft unless `from` matches the mailbox address.
- from: getEmailAddress(ownAddress ?? ""),
- to,
- subject: buildReplySubject(subject),
- text: buildReplyQuote(senderAddress, bodyText),
- }),
- });
- const data = (await response.json()) as { draft?: { id: string }; error?: string };
- if (!response.ok || !data.draft) throw new Error(data.error ?? "Unable to create reply draft");
- return data.draft.id;
+ const response = await authFetch("/api/drafts", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ mailboxId,
+ // The API rejects the draft unless `from` matches the mailbox address.
+ from: getEmailAddress(ownAddress ?? ""),
+ to,
+ subject: buildReplySubject(subject),
+ text: buildReplyQuote(senderAddress, bodyText),
+ }),
+ });
+ const data = (await response.json()) as {
+ draft?: { id: string };
+ error?: string;
+ };
+ if (!response.ok || !data.draft)
+ throw new Error(data.error ?? "Unable to create reply draft");
+ return data.draft.id;
}
diff --git a/src/components/messages/custom-folder-config-types.d.ts b/src/components/messages/custom-folder-config-types.d.ts
index f3ee071..e9b1f00 100644
--- a/src/components/messages/custom-folder-config-types.d.ts
+++ b/src/components/messages/custom-folder-config-types.d.ts
@@ -1,4 +1,5 @@
export type CustomFolderSummary = {
id: string;
name: string;
+ color: string;
};
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index f30d8a6..6c4795c 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -3,7 +3,6 @@
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
-import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { SkeletonRows } from "@/components/ui/skeleton";
@@ -19,7 +18,6 @@ import type { MessageFolderPageProps, MessageListRowProps } from "./types";
import {
formatMessageListTimestamp,
getPageRange,
- getMessageBadge,
getMessageParty,
getMessagePartyClassName,
getMessagePreview,
@@ -36,6 +34,7 @@ function MessageListRow({
selected,
active = false,
compact = false,
+ currentAccountName,
onSelectedChange,
dragMessageIds,
}: MessageListRowProps) {
@@ -43,7 +42,7 @@ function MessageListRow({
const { openDraftComposer } = useCompose();
const unread = message.direction === "inbound" && !message.read;
const draggable = config.folder === "inbox" && message.direction === "inbound";
- const party = getMessageParty(message, config.folder);
+ const party = getMessageParty(message, config.folder, currentAccountName);
const preview = getMessagePreview(message, config.folder);
const href = `${config.hrefPrefix}/${message.id}`;
@@ -102,7 +101,7 @@ function MessageListRow({
<>
<Icon className="h-4 w-4 text-neutral-300" />
<span className={getMessagePartyClassName(message, config.folder)}>
- {getMessageParty(message, config.folder)}
+ {party}
</span>
<span className="truncate text-neutral-700">
<span className={unread ? "font-bold text-neutral-900" : ""}>
@@ -110,11 +109,14 @@ function MessageListRow({
</span>
<span className="text-neutral-500"> - {getMessagePreview(message, config.folder)}</span>
</span>
- {config.showRowBadge !== false && (
- <Badge variant={config.badgeVariant ?? "secondary"}>
- {getMessageBadge(message, config.folder)}
- </Badge>
- )}
+ <time
+ dateTime={message.createdAt}
+ className={`min-w-[96px] whitespace-nowrap text-right text-xs ${
+ unread ? "font-semibold text-neutral-800" : "text-neutral-500"
+ }`}
+ >
+ {formatMessageListTimestamp(message.createdAt)}
+ </time>
</>
);
@@ -185,6 +187,7 @@ export function MessageFolderPage({
const titleTotal = folderCount?.total ?? total;
const titleUnread = folderCount?.unread ?? 0;
const mailboxAddress = getMailboxAddress(selectedMailbox);
+ const currentAccountName = selectedMailbox?.displayName ?? selectedMailbox?.localPart;
const pageRange = getPageRange(offset, messages.length, total);
const selectedMessages = selection?.selectedMessages ?? internalSelectedMessages;
const setSelectedMessages =
@@ -329,6 +332,7 @@ export function MessageFolderPage({
selected={selectedIds.includes(message.id)}
active={message.id === selectedMessageId}
compact={compact}
+ currentAccountName={currentAccountName}
onSelectedChange={updateSelectedMessage}
dragMessageIds={selectedIds.includes(message.id) ? selectedIds : [message.id]}
/>
diff --git a/src/components/messages/types.d.ts b/src/components/messages/types.d.ts
index 7f1ac51..c11a275 100644
--- a/src/components/messages/types.d.ts
+++ b/src/components/messages/types.d.ts
@@ -21,6 +21,7 @@ export type MessageListRowProps = {
selected: boolean;
active?: boolean;
compact?: boolean;
+ currentAccountName?: string;
onSelectedChange: (messageId: string, selected: boolean) => void;
dragMessageIds: string[];
};
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index 6679ca5..2f17f11 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -7,9 +7,14 @@ import type { EmailPageTitleInput } from "./types";
import type { MessageFolderConfig } from "./types";
import type { PageRange } from "./types";
-export function getMessageParty(message: Message, folder: MessageFolderConfig["folder"]) {
+export function getMessageParty(
+ message: Message,
+ folder: MessageFolderConfig["folder"],
+ currentAccountName?: string,
+) {
if (folder === "drafts") return "Draft";
if (folder === "sent") return message.toContactName ?? (message.toAddr ? getEmailDisplayName(message.toAddr) : "No recipient");
+ if (message.direction === "outbound" && currentAccountName) return currentAccountName;
return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : "Unknown sender");
}
@@ -25,17 +30,11 @@ export function getMessagePreview(message: Message, folder: MessageFolderConfig[
return message.snippet || "No preview";
}
-export function getMessageBadge(message: Message, folder: MessageFolderConfig["folder"]) {
- if (folder === "drafts") return "draft";
- if (folder === "archived" || folder === "trash" || folder === "spam") return message.status;
- return message.direction;
-}
-
export function formatMessageListTimestamp(createdAt: string): string {
const date = dayjs(createdAt);
- if (date.isSame(dayjs(), "day")) return date.format("h:mm A");
- if (date.isSame(dayjs(), "year")) return date.format("MMM D");
- return date.format("M/D/YY");
+ if (date.isSame(dayjs(), "day")) return date.format("hh:mm A");
+ if (date.isSame(dayjs(), "year")) return date.format("MMM DD");
+ return date.format("MMM DD, YYYY");
}
export function getPageRange(offset: number, count: number, total: number): PageRange {
diff --git a/src/components/new-message-popup.tsx b/src/components/new-message-popup.tsx
index 6bf5e0a..d798084 100644
--- a/src/components/new-message-popup.tsx
+++ b/src/components/new-message-popup.tsx
@@ -2,6 +2,7 @@
import Link from "next/link";
import { Mail, X } from "lucide-react";
+import { getEmailDisplayName } from "@/lib/email/address";
import type { NewMessagePopupProps } from "./new-message-popup-types";
export function NewMessagePopup({
@@ -26,7 +27,7 @@ export function NewMessagePopup({
{notification.subject || "(no subject)"}
</p>
<p className="mt-1 truncate text-xs text-neutral-500">
- From {notification.from}
+ From {notification.fromName ?? getEmailDisplayName(notification.from)}
</p>
</Link>
<button
diff --git a/src/components/settings/current-mailbox-form.tsx b/src/components/settings/current-mailbox-form.tsx
index 68e24ae..fdb9544 100644
--- a/src/components/settings/current-mailbox-form.tsx
+++ b/src/components/settings/current-mailbox-form.tsx
@@ -9,6 +9,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/com
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Skeleton } from "@/components/ui/skeleton";
+import { ProfileAvatarForm } from "./profile-avatar-form";
import { getMailboxAddress, updateCurrentMailboxName } from "./utils";
export function CurrentMailboxForm() {
@@ -46,9 +47,9 @@ export function CurrentMailboxForm() {
if (isLoading) {
return (
- <div className="max-w-2xl space-y-6 p-8">
+ <div className="space-y-6">
<Skeleton className="h-8 w-32" />
- <Card>
+ <Card className="rounded-3xl border-0 bg-white p-6">
<CardContent className="space-y-4 p-6">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-10 w-full" />
@@ -61,9 +62,9 @@ export function CurrentMailboxForm() {
if (!selectedMailbox) {
return (
- <div className="max-w-2xl space-y-6 p-8">
- <h1 className="text-2xl font-semibold text-neutral-900">Settings</h1>
- <Card>
+ <div className="space-y-6">
+ <h1 className="text-3xl font-medium text-neutral-900">Settings</h1>
+ <Card className="rounded-3xl border-0 bg-white p-6">
<CardContent className="p-6 text-sm text-neutral-500">
Select a mailbox to view its settings.
</CardContent>
@@ -76,18 +77,18 @@ export function CurrentMailboxForm() {
const hasChanges = displayName.trim() !== savedDisplayName;
return (
- <div className="max-w-3xl space-y-8 p-8">
+ <div className="space-y-8">
<div>
- <h1 className="text-2xl font-semibold text-neutral-900">Settings</h1>
+ <h1 className="text-3xl font-medium text-neutral-900">Settings</h1>
<p className="mt-1 text-sm text-neutral-500">{address}</p>
</div>
- <Card>
- <CardHeader>
- <CardTitle>Mailbox</CardTitle>
- <CardDescription>Update the currently selected mailbox.</CardDescription>
- </CardHeader>
- <CardContent>
+ <CardContent className="space-y-6 rounded-3xl bg-white p-6">
+ <ProfileAvatarForm
+ mailboxId={selectedMailbox.id}
+ initialHasAvatar={!!selectedMailbox.hasAvatar}
+ name={selectedMailbox.displayName || selectedMailbox.localPart}
+ />
<form onSubmit={onSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="displayName">Name</Label>
@@ -99,16 +100,6 @@ export function CurrentMailboxForm() {
disabled={saving}
/>
</div>
- <div className="grid gap-4 rounded-md border border-neutral-200 bg-neutral-50 px-3 py-3 sm:grid-cols-2">
- <div className="space-y-1">
- <p className="text-xs font-medium uppercase text-neutral-500">Email</p>
- <p className="truncate no-font-mono text-sm text-neutral-900">{address}</p>
- </div>
- <div className="space-y-1">
- <p className="text-xs font-medium uppercase text-neutral-500">Domain</p>
- <p className="truncate no-font-mono text-sm text-neutral-900">{selectedMailbox.hostname}</p>
- </div>
- </div>
<div className="flex items-center gap-3">
<Button type="submit" disabled={saving || !hasChanges}>
<Save className="h-4 w-4" />
@@ -118,7 +109,6 @@ export function CurrentMailboxForm() {
</div>
</form>
</CardContent>
- </Card>
</div>
);
}
diff --git a/src/components/settings/inbox-rules-types.d.ts b/src/components/settings/inbox-rules-types.d.ts
index 7a1c325..c6d1b9e 100644
--- a/src/components/settings/inbox-rules-types.d.ts
+++ b/src/components/settings/inbox-rules-types.d.ts
@@ -14,6 +14,15 @@ export type InboxRule = {
priority: number;
};
+export type InboxRuleInput = {
+ mailboxId: string;
+ matchField: "email" | "content" | "title";
+ matchOperator: "contains" | "exact";
+ matchValue: string;
+ destination: string;
+ priority: number;
+};
+
export type InboxRulesResponse = {
rules: InboxRule[];
error?: string;
diff --git a/src/components/settings/inbox-rules-utils.ts b/src/components/settings/inbox-rules-utils.ts
index 3454df4..c57e642 100644
--- a/src/components/settings/inbox-rules-utils.ts
+++ b/src/components/settings/inbox-rules-utils.ts
@@ -1,5 +1,5 @@
import { authFetch } from "@/lib/auth/client";
-import type { InboxRulesResponse, RuleFoldersResponse } from "./inbox-rules-types";
+import type { InboxRule, InboxRuleInput, InboxRulesResponse, RuleFoldersResponse } from "./inbox-rules-types";
export async function fetchInboxRules(mailboxId: string): Promise<InboxRulesResponse> {
const params = new URLSearchParams({ mailboxId });
@@ -13,14 +13,7 @@ export async function fetchRuleFolders(mailboxId: string): Promise<RuleFoldersRe
return (await response.json()) as RuleFoldersResponse;
}
-export async function createInboxRule(input: {
- mailboxId: string;
- matchField: "email" | "content" | "title";
- matchOperator: "contains" | "exact";
- matchValue: string;
- destination: string;
- priority: number;
-}) {
+export async function createInboxRule(input: InboxRuleInput) {
const response = await authFetch("/api/routing-rules", {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -31,6 +24,17 @@ export async function createInboxRule(input: {
return data;
}
+export async function updateInboxRule(ruleId: string, input: InboxRuleInput) {
+ const response = await authFetch(`/api/routing-rules/${ruleId}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(input),
+ });
+ const data = (await response.json()) as { error?: string };
+ if (!response.ok) throw new Error(data.error ?? "Failed to update rule");
+ return data;
+}
+
export async function deleteInboxRule(ruleId: string) {
const response = await authFetch(`/api/routing-rules/${ruleId}`, {
method: "DELETE",
@@ -47,3 +51,8 @@ export function getRuleFieldLabel(field: string): string {
export function getRuleOperatorLabel(operator: string): string {
return operator === "exact" ? "exact match" : "contains";
}
+
+export function getInboxRuleDestination(rule: Pick<InboxRule, "action" | "folderId">): string {
+ if (rule.action === "spam" || rule.action === "trash") return rule.action;
+ return rule.folderId ? `folder:${rule.folderId}` : "";
+}
diff --git a/src/components/settings/inbox-rules.tsx b/src/components/settings/inbox-rules.tsx
index c659abf..1b9cfef 100644
--- a/src/components/settings/inbox-rules.tsx
+++ b/src/components/settings/inbox-rules.tsx
@@ -1,191 +1,291 @@
"use client";
+import type { FormEvent, KeyboardEvent } from "react";
import { useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { Folder, Route, ShieldAlert, Trash2 } from "lucide-react";
+import { Folder, Plus, ShieldAlert, Trash2 } from "lucide-react";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import type { InboxRule, InboxRuleInput } from "./inbox-rules-types";
import {
- createInboxRule,
- deleteInboxRule,
- fetchInboxRules,
- fetchRuleFolders,
- getRuleFieldLabel,
- getRuleOperatorLabel,
+ createInboxRule,
+ deleteInboxRule,
+ fetchInboxRules,
+ fetchRuleFolders,
+ getInboxRuleDestination,
+ getRuleFieldLabel,
+ getRuleOperatorLabel,
+ updateInboxRule,
} from "./inbox-rules-utils";
export function InboxRules() {
- const queryClient = useQueryClient();
- const { selectedMailbox } = useSelectedMailbox();
- const [matchField, setMatchField] = useState<"email" | "content" | "title">("email");
- const [matchOperator, setMatchOperator] = useState<"contains" | "exact">("contains");
- const [matchValue, setMatchValue] = useState("");
- const [destination, setDestination] = useState("");
- const mailboxId = selectedMailbox?.id ?? "";
+ const queryClient = useQueryClient();
+ const { selectedMailbox } = useSelectedMailbox();
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [editingRule, setEditingRule] = useState<InboxRule | null>(null);
+ const [matchField, setMatchField] = useState<"email" | "content" | "title">(
+ "email",
+ );
+ const [matchOperator, setMatchOperator] = useState<"contains" | "exact">(
+ "contains",
+ );
+ const [matchValue, setMatchValue] = useState("");
+ const [destination, setDestination] = useState("");
+ const mailboxId = selectedMailbox?.id ?? "";
+
+ const folders = useQuery({
+ queryKey: ["folders", mailboxId],
+ enabled: !!mailboxId,
+ queryFn: () => fetchRuleFolders(mailboxId),
+ });
+ const rules = useQuery({
+ queryKey: ["routing-rules", mailboxId],
+ enabled: !!mailboxId,
+ queryFn: () => fetchInboxRules(mailboxId),
+ });
+
+ const save = useMutation({
+ mutationFn: () => {
+ const input: InboxRuleInput = {
+ mailboxId,
+ matchField,
+ matchOperator,
+ matchValue,
+ destination,
+ priority: editingRule?.priority ?? 10,
+ };
+ return editingRule
+ ? updateInboxRule(editingRule.id, input)
+ : createInboxRule(input);
+ },
+ onSuccess: () => {
+ setDialogOpen(false);
+ setEditingRule(null);
+ queryClient.invalidateQueries({ queryKey: ["routing-rules", mailboxId] });
+ },
+ });
+ const remove = useMutation({
+ mutationFn: deleteInboxRule,
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: ["routing-rules", mailboxId] }),
+ });
+
+ const folderMap = new Map(
+ (folders.data?.folders ?? []).map((folder) => [folder.id, folder.name]),
+ );
+
+ function getRuleDestinationLabel(
+ rule: Pick<InboxRule, "action" | "folderId">,
+ ) {
+ if (rule.action === "spam") return "Spam";
+ if (rule.action === "trash") return "Trash";
+ return folderMap.get(rule.folderId ?? "") ?? "Unknown folder";
+ }
- const folders = useQuery({
- queryKey: ["folders", mailboxId],
- enabled: !!mailboxId,
- queryFn: () => fetchRuleFolders(mailboxId),
- });
- const rules = useQuery({
- queryKey: ["routing-rules", mailboxId],
- enabled: !!mailboxId,
- queryFn: () => fetchInboxRules(mailboxId),
- });
+ function openCreateDialog() {
+ setEditingRule(null);
+ setMatchField("email");
+ setMatchOperator("contains");
+ setMatchValue("");
+ setDestination("");
+ save.reset();
+ setDialogOpen(true);
+ }
- const create = useMutation({
- mutationFn: () => createInboxRule({
- mailboxId,
- matchField,
- matchOperator,
- matchValue,
- destination,
- priority: 10,
- }),
- onSuccess: () => {
- setMatchField("email");
- setMatchOperator("contains");
- setMatchValue("");
- setDestination("");
- queryClient.invalidateQueries({ queryKey: ["routing-rules", mailboxId] });
- },
- });
- const remove = useMutation({
- mutationFn: deleteInboxRule,
- onSuccess: () => queryClient.invalidateQueries({ queryKey: ["routing-rules", mailboxId] }),
- });
+ function openEditDialog(rule: InboxRule) {
+ setEditingRule(rule);
+ setMatchField(rule.matchField);
+ setMatchOperator(rule.matchOperator);
+ setMatchValue(rule.matchValue || rule.pattern);
+ setDestination(getInboxRuleDestination(rule));
+ save.reset();
+ setDialogOpen(true);
+ }
- const folderMap = new Map((folders.data?.folders ?? []).map((folder) => [folder.id, folder.name]));
+ function onRuleKeyDown(
+ event: KeyboardEvent<HTMLDivElement>,
+ rule: InboxRule,
+ ) {
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ openEditDialog(rule);
+ }
- function getRuleDestination(rule: { action: string; folderId: string | null }) {
- if (rule.action === "spam") return "Spam";
- if (rule.action === "trash") return "Trash";
- return folderMap.get(rule.folderId ?? "") ?? "Unknown folder";
- }
+ function onSubmit(event: FormEvent<HTMLFormElement>) {
+ event.preventDefault();
+ save.mutate();
+ }
- return (
- <section>
- <Card>
- <CardHeader>
- <CardTitle className="flex items-center gap-2 text-base">
- <Route className="h-4 w-4" />
- New rule
- </CardTitle>
- <CardDescription>Choose what to match and where the message should go.</CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="grid gap-3 md:grid-cols-[1fr_1fr_2fr]">
- <div className="space-y-2">
- <Label htmlFor="matchField">Field</Label>
- <select
- id="matchField"
- className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
- value={matchField}
- onChange={(event) => setMatchField(event.target.value as "email" | "content" | "title")}
- >
- <option value="email">Email address</option>
- <option value="content">Content</option>
- <option value="title">Title</option>
- </select>
- </div>
- <div className="space-y-2">
- <Label htmlFor="matchOperator">Match</Label>
- <select
- id="matchOperator"
- className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
- value={matchOperator}
- onChange={(event) => setMatchOperator(event.target.value as "contains" | "exact")}
- >
- <option value="contains">Contains</option>
- <option value="exact">Exact match</option>
- </select>
- </div>
- <div className="space-y-2">
- <Label htmlFor="matchValue">Value</Label>
- <Input
- id="matchValue"
- value={matchValue}
- onChange={(event) => setMatchValue(event.target.value)}
- placeholder={matchField === "email" ? "[email protected]" : "Invoice"}
- />
- </div>
- </div>
- <div className="space-y-2">
- <Label htmlFor="destination">Destination</Label>
- <select
- id="destination"
- className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
- value={destination}
- onChange={(event) => setDestination(event.target.value)}
- >
- <option value="">Select destination</option>
- <option value="spam">Spam</option>
- <option value="trash">Trash</option>
- {(folders.data?.folders ?? []).map((folder) => (
- <option key={folder.id} value={`folder:${folder.id}`}>
- {folder.name}
- </option>
- ))}
- </select>
- </div>
- {create.isError && <p className="text-sm text-red-600">{create.error.message}</p>}
- <Button
- onClick={() => create.mutate()}
- disabled={!mailboxId || !destination || !matchValue.trim() || create.isPending}
- >
- {create.isPending ? "Adding..." : "Add rule"}
- </Button>
- </CardContent>
- </Card>
+ return (
+ <section className="space-y-4">
+ <div className="flex flex-row justify-end">
+ <Button
+ type="button"
+ size="sm"
+ onClick={openCreateDialog}
+ disabled={!mailboxId}
+ >
+ <Plus className="h-4 w-4" />
+ New rule
+ </Button>
+ </div>
+ {(rules.data?.rules ?? []).length === 0 && (
+ <p className="rounded-lg border border-dashed border-neutral-200 px-4 py-5 text-sm text-neutral-500">
+ No rules yet
+ </p>
+ )}
+ <div className="divide-y divide-neutral-100">
+ {(rules.data?.rules ?? []).map((rule) => (
+ <div
+ key={rule.id}
+ role="button"
+ tabIndex={0}
+ onClick={() => openEditDialog(rule)}
+ onKeyDown={(event) => onRuleKeyDown(event, rule)}
+ className="group -mx-3 flex cursor-pointer items-center gap-3 rounded-lg px-3 py-3 outline-none transition-colors hover:bg-neutral-50 focus-visible:bg-neutral-50 focus-visible:ring-2 focus-visible:ring-blue-200"
+ >
+ <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-700">
+ {rule.action === "spam" ? (
+ <ShieldAlert className="h-4 w-4" />
+ ) : rule.action === "trash" ? (
+ <Trash2 className="h-4 w-4" />
+ ) : (
+ <Folder className="h-4 w-4" />
+ )}
+ </div>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium text-neutral-900">
+ {getRuleFieldLabel(rule.matchField)}{" "}
+ {getRuleOperatorLabel(rule.matchOperator)}{" "}
+ {rule.matchValue || rule.pattern}
+ </p>
+ <p className="truncate text-xs text-neutral-500">
+ {getRuleDestinationLabel(rule)}
+ </p>
+ </div>
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ disabled={remove.isPending}
+ onClick={(event) => {
+ event.stopPropagation();
+ remove.mutate(rule.id);
+ }}
+ onKeyDown={(event) => event.stopPropagation()}
+ className="opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100"
+ aria-label="Delete rule"
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </div>
+ ))}
+ </div>
- <Card>
- <CardHeader>
- <CardTitle className="text-base">Existing rules</CardTitle>
- </CardHeader>
- <CardContent>
- {(rules.data?.rules ?? []).length === 0 && (
- <p className="rounded-lg border border-dashed border-neutral-200 px-4 py-5 text-sm text-neutral-500">
- No rules yet
- </p>
- )}
- <div className="divide-y divide-neutral-100">
- {(rules.data?.rules ?? []).map((rule) => (
- <div key={rule.id} className="flex items-center gap-3 py-3">
- <div className="flex h-9 w-9 items-center justify-center rounded-lg bg-blue-50 text-blue-700">
- {rule.action === "spam" ? (
- <ShieldAlert className="h-4 w-4" />
- ) : rule.action === "trash" ? (
- <Trash2 className="h-4 w-4" />
- ) : (
- <Folder className="h-4 w-4" />
- )}
- </div>
- <div className="min-w-0 flex-1">
- <p className="truncate text-sm font-medium text-neutral-900">
- {getRuleFieldLabel(rule.matchField)} {getRuleOperatorLabel(rule.matchOperator)}{" "}
- {rule.matchValue || rule.pattern}
- </p>
- <p className="truncate text-xs text-neutral-500">{getRuleDestination(rule)}</p>
- </div>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={remove.isPending}
- onClick={() => remove.mutate(rule.id)}
- aria-label="Delete rule"
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </div>
- ))}
- </div>
- </CardContent>
- </Card>
- </section>
- );
+ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>
+ {editingRule ? "Update rule" : "New rule"}
+ </DialogTitle>
+ <DialogDescription>
+ Choose what to match and where the message should go.
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={onSubmit} className="space-y-4">
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div className="space-y-2">
+ <Label htmlFor="matchField">Field</Label>
+ <select
+ id="matchField"
+ className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
+ value={matchField}
+ onChange={(event) =>
+ setMatchField(
+ event.target.value as "email" | "content" | "title",
+ )
+ }
+ >
+ <option value="email">Email address</option>
+ <option value="content">Content</option>
+ <option value="title">Title</option>
+ </select>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="matchOperator">Match</Label>
+ <select
+ id="matchOperator"
+ className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
+ value={matchOperator}
+ onChange={(event) =>
+ setMatchOperator(event.target.value as "contains" | "exact")
+ }
+ >
+ <option value="contains">Contains</option>
+ <option value="exact">Exact match</option>
+ </select>
+ </div>
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="matchValue">Value</Label>
+ <Input
+ id="matchValue"
+ value={matchValue}
+ onChange={(event) => setMatchValue(event.target.value)}
+ placeholder={
+ matchField === "email" ? "[email protected]" : "Invoice"
+ }
+ />
+ </div>
+ <div className="space-y-2">
+ <Label htmlFor="destination">Destination</Label>
+ <select
+ id="destination"
+ className="h-10 w-full rounded-md border border-neutral-200 px-3 text-sm"
+ value={destination}
+ onChange={(event) => setDestination(event.target.value)}
+ >
+ <option value="">Select destination</option>
+ <option value="spam">Spam</option>
+ <option value="trash">Trash</option>
+ {(folders.data?.folders ?? []).map((folder) => (
+ <option key={folder.id} value={`folder:${folder.id}`}>
+ {folder.name}
+ </option>
+ ))}
+ </select>
+ </div>
+ {save.isError && (
+ <p className="text-sm text-red-600">{save.error.message}</p>
+ )}
+ <Button
+ type="submit"
+ disabled={
+ !mailboxId ||
+ !destination ||
+ !matchValue.trim() ||
+ save.isPending
+ }
+ >
+ {save.isPending
+ ? "Saving..."
+ : editingRule
+ ? "Update rule"
+ : "Add rule"}
+ </Button>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </section>
+ );
}
diff --git a/src/components/settings/profile-avatar-form-utils.ts b/src/components/settings/profile-avatar-form-utils.ts
new file mode 100644
index 0000000..7e5d720
--- /dev/null
+++ b/src/components/settings/profile-avatar-form-utils.ts
@@ -0,0 +1,46 @@
+import { authFetch } from "@/lib/auth/client";
+import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
+import type { ProfileAvatarUploadResponse } from "./types";
+
+export const PROFILE_AVATAR_ACCEPT = "image/jpeg,image/png,image/webp,image/gif";
+const MAX_PROFILE_AVATAR_SIZE = 2 * 1024 * 1024;
+
+export function validateProfileAvatar(file: File): string | null {
+ if (!PROFILE_AVATAR_ACCEPT.split(",").includes(file.type)) {
+ return "Use a JPEG, PNG, WebP, or GIF image";
+ }
+ if (file.size > MAX_PROFILE_AVATAR_SIZE) {
+ return "Image must be 2 MB or smaller";
+ }
+ return null;
+}
+
+export async function uploadProfileAvatar(file: File): Promise<void> {
+ const body = new FormData();
+ body.append("file", file, file.name);
+ const response = await authFetch("/api/profile/avatar", { method: "POST", body });
+ if (response.ok) return;
+
+ const data = (await response.json().catch(() => null)) as ProfileAvatarUploadResponse | null;
+ throw new Error(data?.error ?? "Upload failed");
+}
+
+export function getMailboxProfileAvatarUrl(mailboxId: string): string {
+ return `/api/mailboxes/${mailboxId}/avatar?v=${Date.now()}`;
+}
+
+export async function uploadMailboxProfileAvatar(mailboxId: string, file: File): Promise<void> {
+ const body = new FormData();
+ body.append("file", file, file.name);
+ const response = await authFetch(`/api/mailboxes/${mailboxId}/avatar`, {
+ method: "POST",
+ body,
+ });
+ if (response.ok) {
+ clearMailboxesCache();
+ return;
+ }
+
+ const data = (await response.json().catch(() => null)) as ProfileAvatarUploadResponse | null;
+ throw new Error(data?.error ?? "Upload failed");
+}
diff --git a/src/components/settings/profile-avatar-form.tsx b/src/components/settings/profile-avatar-form.tsx
index 9ae71f6..41fe83a 100644
--- a/src/components/settings/profile-avatar-form.tsx
+++ b/src/components/settings/profile-avatar-form.tsx
@@ -1,130 +1,128 @@
"use client";
import { useEffect, useRef, useState } from "react";
-import { Trash2, Upload, User } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import { Camera, LoaderCircle, User } from "lucide-react";
import { authFetch } from "@/lib/auth/client";
+import {
+ dispatchProfileAvatarChanged,
+ getProfileAvatarUrl,
+} from "@/lib/profile/avatar-client";
+import { dispatchMailboxAvatarChanged } from "@/lib/mailboxes/avatar-client";
+import type { ProfileAvatarFormProps, ProfileAvatarSessionResponse } from "./types";
+import {
+ getMailboxProfileAvatarUrl,
+ PROFILE_AVATAR_ACCEPT,
+ uploadMailboxProfileAvatar,
+ uploadProfileAvatar,
+ validateProfileAvatar,
+} from "./profile-avatar-form-utils";
-export function ProfileAvatarForm() {
- const [hasAvatar, setHasAvatar] = useState(false);
- const [preview, setPreview] = useState<string | null>(null);
- const [file, setFile] = useState<File | null>(null);
+export function ProfileAvatarForm({
+ mailboxId,
+ initialHasAvatar = false,
+ name = "Profile",
+}: ProfileAvatarFormProps) {
+ const [hasAvatar, setHasAvatar] = useState(initialHasAvatar);
+ const [avatarUrl, setAvatarUrl] = useState(
+ mailboxId ? `/api/mailboxes/${mailboxId}/avatar` : "/api/profile/avatar",
+ );
const [status, setStatus] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
+ if (mailboxId) {
+ setHasAvatar(initialHasAvatar);
+ setAvatarUrl(`/api/mailboxes/${mailboxId}/avatar`);
+ return;
+ }
+
authFetch("/api/auth/me", { redirectOnUnauthorized: false })
.then((response) => (response.ok ? response.json() : null))
.then((data) => {
- const authData = data as { user?: { hasAvatar?: boolean } } | null;
+ const authData = data as ProfileAvatarSessionResponse | null;
setHasAvatar(!!authData?.user?.hasAvatar);
})
.catch(() => setHasAvatar(false));
- }, []);
-
- useEffect(() => {
- if (!file) {
- setPreview(null);
- return;
- }
- const url = URL.createObjectURL(file);
- setPreview(url);
- return () => URL.revokeObjectURL(url);
- }, [file]);
+ }, [initialHasAvatar, mailboxId]);
- function onPick(event: React.ChangeEvent<HTMLInputElement>) {
+ async function onPick(event: React.ChangeEvent<HTMLInputElement>) {
const picked = event.target.files?.[0] ?? null;
- setStatus(null);
- if (picked && picked.size > 2 * 1024 * 1024) {
- setStatus("Image must be 2 MB or smaller");
+ event.target.value = "";
+ if (!picked) return;
+
+ const validationError = validateProfileAvatar(picked);
+ if (validationError) {
+ setStatus(validationError);
return;
}
- setFile(picked);
- }
- async function upload() {
- if (!file) return;
setBusy(true);
setStatus(null);
try {
- const body = new FormData();
- body.append("file", file);
- const response = await authFetch("/api/profile/avatar", { method: "POST", body });
- if (!response.ok) {
- const json = (await response.json().catch(() => null)) as { error?: string } | null;
- throw new Error(json?.error ?? "Upload failed");
+ if (mailboxId) {
+ await uploadMailboxProfileAvatar(mailboxId, picked);
+ } else {
+ await uploadProfileAvatar(picked);
}
- window.location.reload();
- } catch (err) {
- setStatus(err instanceof Error ? err.message : "Upload failed");
+ const nextAvatarUrl = mailboxId
+ ? getMailboxProfileAvatarUrl(mailboxId)
+ : getProfileAvatarUrl();
+ setAvatarUrl(nextAvatarUrl);
+ setHasAvatar(true);
setBusy(false);
- }
- }
-
- async function remove() {
- setBusy(true);
- setStatus(null);
- try {
- const response = await authFetch("/api/profile/avatar", { method: "DELETE" });
- if (!response.ok) throw new Error("Failed to remove picture");
- window.location.reload();
- } catch (err) {
- setStatus(err instanceof Error ? err.message : "Failed to remove picture");
+ if (mailboxId) {
+ dispatchMailboxAvatarChanged(mailboxId, nextAvatarUrl);
+ } else {
+ dispatchProfileAvatarChanged(nextAvatarUrl);
+ }
+ } catch (error) {
+ setStatus(error instanceof Error ? error.message : "Upload failed");
setBusy(false);
}
}
- const shownImage = preview ?? (hasAvatar ? "/api/profile/avatar" : null);
-
return (
- <Card>
- <CardHeader>
- <CardTitle>Profile picture</CardTitle>
- <CardDescription>
- Shown in the top-right corner of your dashboard. JPEG, PNG, WebP, or GIF up to 2 MB.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center gap-4">
- {shownImage ? (
- // eslint-disable-next-line @next/next/no-img-element
- <img
- src={shownImage}
- alt="Profile picture"
- className="h-16 w-16 rounded-full border border-neutral-200 object-cover"
- />
+ <div className="flex flex-col items-start gap-2">
+ <input
+ ref={inputRef}
+ type="file"
+ accept={PROFILE_AVATAR_ACCEPT}
+ className="hidden"
+ onChange={onPick}
+ />
+ <button
+ type="button"
+ onClick={() => inputRef.current?.click()}
+ disabled={busy}
+ className="group relative h-24 w-24 overflow-hidden rounded-full border border-neutral-200 bg-blue-600 text-white shadow-sm outline-none ring-blue-500 transition focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait"
+ aria-label={hasAvatar ? `Change ${name} profile picture` : `Upload ${name} profile picture`}
+ >
+ {hasAvatar ? (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={avatarUrl}
+ alt={`${name} profile picture`}
+ className="h-full w-full object-cover"
+ onError={() => setHasAvatar(false)}
+ />
+ ) : (
+ <span className="flex h-full w-full items-center justify-center">
+ <User className="h-9 w-9" />
+ </span>
+ )}
+ <span className="absolute inset-0 flex items-center justify-center bg-neutral-950/55 opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100">
+ {busy ? (
+ <LoaderCircle className="h-6 w-6 animate-spin" />
) : (
- <div className="flex h-16 w-16 items-center justify-center rounded-full bg-blue-600 text-white">
- <User className="h-7 w-7" />
- </div>
+ <span className="flex flex-col items-center gap-1 text-[11px] font-medium">
+ <Camera className="h-5 w-5" />
+ {hasAvatar ? "Change" : "Upload"}
+ </span>
)}
- <div className="flex flex-wrap items-center gap-2">
- <input
- ref={inputRef}
- type="file"
- accept="image/jpeg,image/png,image/webp,image/gif"
- className="hidden"
- onChange={onPick}
- />
- <Button type="button" variant="outline" onClick={() => inputRef.current?.click()} disabled={busy}>
- Choose image
- </Button>
- <Button type="button" onClick={upload} disabled={busy || !file}>
- <Upload className="h-4 w-4" />
- {busy ? "Saving..." : "Save picture"}
- </Button>
- {hasAvatar && (
- <Button type="button" variant="destructive" onClick={remove} disabled={busy}>
- <Trash2 className="h-4 w-4" />
- Remove
- </Button>
- )}
- </div>
- </div>
- {status && <p className="text-sm text-red-600">{status}</p>}
- </CardContent>
- </Card>
+ </span>
+ </button>
+ {status && <p className="max-w-xs text-xs text-red-600">{status}</p>}
+ </div>
);
}
diff --git a/src/components/settings/settings-nav.tsx b/src/components/settings/settings-nav.tsx
index 3716772..dd03e09 100644
--- a/src/components/settings/settings-nav.tsx
+++ b/src/components/settings/settings-nav.tsx
@@ -9,10 +9,10 @@ export function SettingsNav() {
const pathname = usePathname();
return (
- <aside className="px-4 py-5 w-60">
- <div className="sticky top-6 space-y-2 bg-neutral-100/60 p-4 rounded-2xl">
- <h2 className="px-2 text-xs uppercase font-semibold text-neutral-400">Settings</h2>
- <nav className="">
+ <aside className="min-h-full border-r border-blue-100/70 px-4 py-10 w-64">
+ <div className="sticky top-6 space-y-3">
+ <h2 className="px-4 text-xs font-semibold uppercase tracking-wide text-neutral-500">Settings</h2>
+ <nav className="space-y-1">
{settingsNavItems.map((item) => {
const active = isActiveSettingsPath(pathname, item.href);
return (
@@ -20,10 +20,10 @@ export function SettingsNav() {
key={item.href}
href={item.href}
className={cn(
- "block rounded-lg px-2 py-1.5 text-sm font-medium transition-colors",
+ "block rounded-full px-4 py-2.5 text-sm font-medium transition-colors",
active
- ? "text-blue-700"
- : "text-neutral-500 hover:bg-neutral-50 hover:text-neutral-900",
+ ? "bg-blue-100 text-blue-900"
+ : "text-neutral-600 hover:bg-white/70 hover:text-neutral-900",
)}
>
{item.label}
diff --git a/src/components/settings/types.d.ts b/src/components/settings/types.d.ts
index 8393660..be65ca4 100644
--- a/src/components/settings/types.d.ts
+++ b/src/components/settings/types.d.ts
@@ -12,12 +12,29 @@ export type ProfileFormResponse = {
error?: unknown;
};
+export type ProfileAvatarSessionResponse = {
+ user?: {
+ hasAvatar?: boolean;
+ };
+};
+
+export type ProfileAvatarUploadResponse = {
+ error?: string;
+};
+
+export type ProfileAvatarFormProps = {
+ mailboxId?: string;
+ initialHasAvatar?: boolean;
+ name?: string;
+};
+
export type CurrentMailboxFormResponse = {
mailbox?: {
id: string;
localPart: string;
hostname: string;
displayName: string | null;
+ hasAvatar?: boolean;
isPrimary?: boolean;
};
error?: unknown;
diff --git a/src/components/settings/utils.ts b/src/components/settings/utils.ts
index ba3866a..8acaf96 100644
--- a/src/components/settings/utils.ts
+++ b/src/components/settings/utils.ts
@@ -1,4 +1,5 @@
import type { MailboxOption } from "@/components/mailbox-provider";
+import { clearMailboxesCache } from "@/components/mailbox-provider-utils";
import { authFetch } from "@/lib/auth/client";
import type { CurrentMailboxFormResponse } from "./types";
@@ -17,12 +18,14 @@ export async function updateCurrentMailboxName(id: string, displayName: string):
if (!res.ok || !data.mailbox) {
throw new Error(typeof data.error === "string" ? data.error : "Failed to update mailbox");
}
+ clearMailboxesCache();
return {
id: data.mailbox.id,
localPart: data.mailbox.localPart,
hostname: data.mailbox.hostname,
displayName: data.mailbox.displayName,
+ hasAvatar: data.mailbox.hasAvatar,
isPrimary: data.mailbox.isPrimary,
};
}
diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx
index cd8a7f0..f31a77a 100644
--- a/src/components/ui/card.tsx
+++ b/src/components/ui/card.tsx
@@ -5,7 +5,7 @@ export function Card({ className, ...props }: React.HTMLAttributes<HTMLDivElemen
return (
<div
className={cn(
- "rounded-xl border border-neutral-200 bg-white shadow-md shadow-neutral-100",
+ "border-t border-neutral-200",
className,
)}
{...props}
@@ -14,7 +14,7 @@ export function Card({ className, ...props }: React.HTMLAttributes<HTMLDivElemen
}
export function CardHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
- return <div className={cn("flex flex-col gap-1.5 p-6", className)} {...props} />;
+ return <div className={cn("flex flex-col gap-1.5 py-6", className)} {...props} />;
}
export function CardTitle({ className, ...props }: React.HTMLAttributes<HTMLHeadingElement>) {
@@ -26,5 +26,5 @@ export function CardDescription({ className, ...props }: React.HTMLAttributes<HT
}
export function CardContent({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
- return <div className={cn("p-6 pt-0", className)} {...props} />;
+ return <div className={cn("pb-0", className)} {...props} />;
}
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index e3187ed..ba4ab05 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -16,10 +16,10 @@ export function DialogContent({
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>) {
return (
<DialogPrimitive.Portal>
- <DialogPrimitive.Overlay className="fixed inset-0 z-50 bg-black/35" />
+ <DialogPrimitive.Overlay className="dialog-overlay 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",
+ "dialog-content 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}
diff --git a/src/components/ui/switch-types.d.ts b/src/components/ui/switch-types.d.ts
new file mode 100644
index 0000000..e2d9748
--- /dev/null
+++ b/src/components/ui/switch-types.d.ts
@@ -0,0 +1,9 @@
+import type { ButtonHTMLAttributes } from "react";
+
+export type SwitchProps = Omit<
+ ButtonHTMLAttributes<HTMLButtonElement>,
+ "onChange" | "role"
+> & {
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+};
diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsx
new file mode 100644
index 0000000..ca18a33
--- /dev/null
+++ b/src/components/ui/switch.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import type { SwitchProps } from "./switch-types";
+
+export function Switch({
+ checked,
+ onCheckedChange,
+ className,
+ disabled,
+ ...props
+}: SwitchProps) {
+ return (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked}
+ disabled={disabled}
+ onClick={() => onCheckedChange(!checked)}
+ className={cn(
+ "relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-600 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ checked ? "bg-blue-600" : "bg-neutral-300",
+ className,
+ )}
+ {...props}
+ >
+ <span
+ className={cn(
+ "pointer-events-none block h-5 w-5 rounded-full bg-white shadow-sm transition-transform",
+ checked ? "translate-x-[21px]" : "translate-x-0.5",
+ )}
+ />
+ </button>
+ );
+}
diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts
index 5999d54..bf80d14 100644
--- a/src/db/schema/index.ts
+++ b/src/db/schema/index.ts
@@ -54,6 +54,7 @@ export const mailboxes = sqliteTable(
.references(() => domains.id, { onDelete: "cascade" }),
localPart: text("local_part").notNull(),
displayName: text("display_name"),
+ avatarKey: text("avatar_key"),
type: text("type", { enum: ["personal", "shared"] }).notNull().default("personal"),
disabled: integer("disabled", { mode: "boolean" }).notNull().default(false),
createdAt: integer("created_at", { mode: "timestamp" })
@@ -100,6 +101,7 @@ export const contacts = sqliteTable(
source: text("source", { enum: ["manual", "inbound", "outbound"] })
.notNull()
.default("inbound"),
+ blocked: integer("blocked", { mode: "boolean" }).notNull().default(false),
lastSeenAt: integer("last_seen_at", { mode: "timestamp" }),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
@@ -122,6 +124,7 @@ export const folders = sqliteTable(
.notNull()
.references(() => mailboxes.id, { onDelete: "cascade" }),
name: text("name").notNull(),
+ color: text("color").notNull().default("#2563eb"),
createdAt: integer("created_at", { mode: "timestamp" })
.notNull()
.$defaultFn(() => new Date()),
diff --git a/src/hooks/message-realtime-types.d.ts b/src/hooks/message-realtime-types.d.ts
index 6b72d6b..69a73fa 100644
--- a/src/hooks/message-realtime-types.d.ts
+++ b/src/hooks/message-realtime-types.d.ts
@@ -1,5 +1,6 @@
export interface NewMessageEvent {
from: string;
+ fromName: string | null;
mailboxId: string;
messageId: string;
subject: string | null;
diff --git a/src/hooks/message-realtime-utils.ts b/src/hooks/message-realtime-utils.ts
index 91b71a2..4c774ab 100644
--- a/src/hooks/message-realtime-utils.ts
+++ b/src/hooks/message-realtime-utils.ts
@@ -30,6 +30,7 @@ export function parseNewMessageEvent(value: string): NewMessageEvent | null {
messageId: payload.messageId,
mailboxId: payload.mailboxId,
from: payload.from,
+ fromName: typeof payload.fromName === "string" ? payload.fromName : null,
subject: typeof payload.subject === "string" ? payload.subject : null,
};
} catch {
@@ -47,7 +48,7 @@ export function showBrowserNewMessageNotification(event: NewMessageEvent): void
}
const notification = new Notification(event.subject || "New email", {
- body: `From ${event.from}`,
+ body: `From ${event.fromName ?? event.from}`,
icon: "/icon-96.png",
tag: event.messageId,
});
diff --git a/src/lib/contacts/service.ts b/src/lib/contacts/service.ts
index 5a41448..8b47941 100644
--- a/src/lib/contacts/service.ts
+++ b/src/lib/contacts/service.ts
@@ -1,8 +1,8 @@
import { and, eq, inArray } from "drizzle-orm";
import { getDb } from "@/db";
-import { contacts } from "@/db/schema";
+import { contacts, routingRules } from "@/db/schema";
import { normalizeEmailAddress } from "@/lib/email/address";
-import type { ContactInput, MessageContactNames } from "@/lib/contacts/types";
+import type { BlockContactInput, ContactInput, MessageContactNames } from "@/lib/contacts/types";
import { getContactId, getContactNameFromAddress } from "@/lib/contacts/utils";
export async function upsertContactFromAddress(env: CloudflareEnv, input: ContactInput) {
@@ -78,6 +78,62 @@ export async function getMessageContactNames(
};
}
+export async function blockContact(env: CloudflareEnv, input: BlockContactInput) {
+ const email = normalizeEmailAddress(input.address);
+ if (!email) throw new Error("Contact email is required");
+
+ const db = getDb(env);
+ const contactId = getContactId(input.userId, email);
+ const [existingContact] = await db
+ .select()
+ .from(contacts)
+ .where(and(eq(contacts.userId, input.userId), eq(contacts.email, email)))
+ .limit(1);
+ if (existingContact) {
+ await db.update(contacts).set({ blocked: true }).where(eq(contacts.id, existingContact.id));
+ } else {
+ await db.insert(contacts).values({
+ id: contactId,
+ userId: input.userId,
+ email,
+ displayName: getContactNameFromAddress(input.address),
+ source: "inbound",
+ blocked: true,
+ lastSeenAt: new Date(),
+ });
+ }
+
+ const [existingRule] = await db
+ .select()
+ .from(routingRules)
+ .where(
+ and(
+ eq(routingRules.mailboxId, input.mailboxId),
+ eq(routingRules.matchField, "email"),
+ eq(routingRules.matchOperator, "exact"),
+ eq(routingRules.matchValue, email),
+ eq(routingRules.action, "trash"),
+ ),
+ )
+ .limit(1);
+ if (!existingRule) {
+ await db.insert(routingRules).values({
+ id: `block:${input.mailboxId}:${email}`,
+ userId: input.userId,
+ domainId: input.domainId,
+ pattern: email,
+ matchField: "email",
+ matchOperator: "exact",
+ matchValue: email,
+ mailboxId: input.mailboxId,
+ action: "trash",
+ priority: 100,
+ });
+ }
+
+ return { email, blocked: true };
+}
+
function getNextDisplayName(existingName: string | null, source: string, nextName: string | null): string | null {
if (source === "manual") return existingName;
if (nextName) return nextName;
diff --git a/src/lib/contacts/types.d.ts b/src/lib/contacts/types.d.ts
index 6e5377f..25fe701 100644
--- a/src/lib/contacts/types.d.ts
+++ b/src/lib/contacts/types.d.ts
@@ -9,6 +9,13 @@ export type ContactInput = {
source: ContactSource;
};
+export type BlockContactInput = {
+ userId: string;
+ mailboxId: string;
+ domainId: string;
+ address: string;
+};
+
export type MessageContactNames = {
fromContactName: string | null;
toContactName: string | null;
diff --git a/src/lib/email/inbound.ts b/src/lib/email/inbound.ts
index eb92ba5..b552aff 100644
--- a/src/lib/email/inbound.ts
+++ b/src/lib/email/inbound.ts
@@ -70,7 +70,7 @@ export async function processInboundMessage(
subject: parsed.subject,
content: [parsed.text, parsed.html, snippet].filter(Boolean).join(" "),
});
- await upsertContactFromAddress(env, {
+ const contact = await upsertContactFromAddress(env, {
userId: decision.mailbox.userId,
address: fromAddr,
source: "inbound",
@@ -115,6 +115,7 @@ export async function processInboundMessage(
messageId,
mailboxId: decision.mailbox.mailboxId,
from: fromAddr,
+ fromName: contact?.displayName ?? null,
subject: parsed.subject,
});
await dispatchWebhooks(env, decision.mailbox.userId, "message.inbound", {
@@ -170,7 +171,7 @@ export async function getMessageWithBodyForUser(env: CloudflareEnv, user: Sessio
.from(messageBodies)
.where(eq(messageBodies.messageId, messageId))
.limit(1);
- const contactNames = await getMessageContactNames(env, user.id, message.fromAddr, message.toAddr);
+ const contactNames = await getMessageContactNames(env, message.userId, message.fromAddr, message.toAddr);
const attachments = await listMessageAttachments(env, messageId);
const unsubscribeUrl = await getUnsubscribeUrlFromRawR2Key(env, body?.rawR2Key ?? null);
return { message: { ...message, ...contactNames }, body, attachments, unsubscribeUrl };
diff --git a/src/lib/folders/colors.ts b/src/lib/folders/colors.ts
new file mode 100644
index 0000000..454a360
--- /dev/null
+++ b/src/lib/folders/colors.ts
@@ -0,0 +1,25 @@
+import type { FolderColorOption } from "./types";
+
+export const FOLDER_COLOR_VALUES = [
+ "#2563eb",
+ "#7c3aed",
+ "#db2777",
+ "#dc2626",
+ "#ea580c",
+ "#d97706",
+ "#16a34a",
+ "#0d9488",
+] as const;
+
+export const DEFAULT_FOLDER_COLOR = FOLDER_COLOR_VALUES[0];
+
+export const FOLDER_COLOR_OPTIONS: FolderColorOption[] = [
+ { value: "#2563eb", label: "Blue" },
+ { value: "#7c3aed", label: "Purple" },
+ { value: "#db2777", label: "Pink" },
+ { value: "#dc2626", label: "Red" },
+ { value: "#ea580c", label: "Orange" },
+ { value: "#d97706", label: "Amber" },
+ { value: "#16a34a", label: "Green" },
+ { value: "#0d9488", label: "Teal" },
+];
diff --git a/src/lib/folders/types.d.ts b/src/lib/folders/types.d.ts
new file mode 100644
index 0000000..9b6e35b
--- /dev/null
+++ b/src/lib/folders/types.d.ts
@@ -0,0 +1,14 @@
+export type FolderColor =
+ | "#2563eb"
+ | "#7c3aed"
+ | "#db2777"
+ | "#dc2626"
+ | "#ea580c"
+ | "#d97706"
+ | "#16a34a"
+ | "#0d9488";
+
+export type FolderColorOption = {
+ value: FolderColor;
+ label: string;
+};
diff --git a/src/lib/mailboxes/access.ts b/src/lib/mailboxes/access.ts
index 92d4b26..6e7d375 100644
--- a/src/lib/mailboxes/access.ts
+++ b/src/lib/mailboxes/access.ts
@@ -39,6 +39,7 @@ export async function listAccessibleMailboxes(db: AppDatabase, user: Pick<Sessio
domainId: mailboxes.domainId,
localPart: mailboxes.localPart,
displayName: mailboxes.displayName,
+ avatarKey: mailboxes.avatarKey,
type: mailboxes.type,
disabled: mailboxes.disabled,
createdAt: mailboxes.createdAt,
@@ -54,11 +55,15 @@ export async function listAccessibleMailboxes(db: AppDatabase, user: Pick<Sessio
if (isAdmin(user) && row.domainUserId === user.id) return true;
return false;
})
- .map((row) => ({
- ...row,
- permission: "full_access" as MailboxPermission,
- isPrimary: `${row.localPart}@${row.hostname}` === user.email,
- }));
+ .map((row) => {
+ const { avatarKey, ...mailbox } = row;
+ return {
+ ...mailbox,
+ hasAvatar: !!avatarKey,
+ permission: "full_access" as MailboxPermission,
+ isPrimary: `${row.localPart}@${row.hostname}` === user.email,
+ };
+ });
}
export async function listAccessibleMailboxIds(db: AppDatabase, user: Pick<SessionUser, "id" | "email" | "role">) {
diff --git a/src/lib/mailboxes/avatar-client-types.d.ts b/src/lib/mailboxes/avatar-client-types.d.ts
new file mode 100644
index 0000000..d1dacbd
--- /dev/null
+++ b/src/lib/mailboxes/avatar-client-types.d.ts
@@ -0,0 +1,4 @@
+export type MailboxAvatarChangedDetail = {
+ mailboxId: string;
+ url: string;
+};
diff --git a/src/lib/mailboxes/avatar-client.ts b/src/lib/mailboxes/avatar-client.ts
new file mode 100644
index 0000000..7e3d8f0
--- /dev/null
+++ b/src/lib/mailboxes/avatar-client.ts
@@ -0,0 +1,11 @@
+import type { MailboxAvatarChangedDetail } from "./avatar-client-types";
+
+export const MAILBOX_AVATAR_CHANGED_EVENT = "mailflare:mailbox-avatar-changed";
+
+export function dispatchMailboxAvatarChanged(mailboxId: string, url: string): void {
+ window.dispatchEvent(
+ new CustomEvent<MailboxAvatarChangedDetail>(MAILBOX_AVATAR_CHANGED_EVENT, {
+ detail: { mailboxId, url },
+ }),
+ );
+}
diff --git a/src/lib/profile/avatar-client.ts b/src/lib/profile/avatar-client.ts
new file mode 100644
index 0000000..49f77ad
--- /dev/null
+++ b/src/lib/profile/avatar-client.ts
@@ -0,0 +1,15 @@
+import type { ProfileAvatarChangedDetail } from "./types";
+
+export const PROFILE_AVATAR_CHANGED_EVENT = "mailflare:profile-avatar-changed";
+
+export function getProfileAvatarUrl(): string {
+ return `/api/profile/avatar?v=${Date.now()}`;
+}
+
+export function dispatchProfileAvatarChanged(url: string): void {
+ window.dispatchEvent(
+ new CustomEvent<ProfileAvatarChangedDetail>(PROFILE_AVATAR_CHANGED_EVENT, {
+ detail: { url },
+ }),
+ );
+}
diff --git a/src/lib/profile/types.d.ts b/src/lib/profile/types.d.ts
new file mode 100644
index 0000000..7724896
--- /dev/null
+++ b/src/lib/profile/types.d.ts
@@ -0,0 +1,3 @@
+export type ProfileAvatarChangedDetail = {
+ url: string;
+};
diff --git a/src/lib/realtime/types.d.ts b/src/lib/realtime/types.d.ts
index 64ed9f9..a579259 100644
--- a/src/lib/realtime/types.d.ts
+++ b/src/lib/realtime/types.d.ts
@@ -1,5 +1,6 @@
export interface NewMessageNotification {
from: string;
+ fromName: string | null;
mailboxId: string;
messageId: string;
subject: string | null;
diff --git a/src/lib/validators.ts b/src/lib/validators.ts
index 301f17b..d5bbbe9 100644
--- a/src/lib/validators.ts
+++ b/src/lib/validators.ts
@@ -1,4 +1,5 @@
import { z } from "zod";
+import { DEFAULT_FOLDER_COLOR, FOLDER_COLOR_VALUES } from "@/lib/folders/colors";
export const sendEmailSchema = z.object({
from: z.string().min(3).max(500),
@@ -108,6 +109,7 @@ export const updateMailboxSchema = z.object({
export const folderSchema = z.object({
mailboxId: z.string().min(1),
name: z.string().trim().min(1).max(80),
+ color: z.enum(FOLDER_COLOR_VALUES).default(DEFAULT_FOLDER_COLOR),
});
export const updateProfileSchema = z.object({