Initial commit: webmail client (M0/M1)

Three-pane webmail client.
- Backend: FastAPI + async SQLAlchemy + arq worker (Postgres/Redis), IMAP/SMTP
  sync, threading, search, drafts/outbox with undo, attachments, 2FA.
- Frontend: React 18 + Vite + TypeScript + TanStack Query + Tailwind; three-pane
  UI with rich-text composer, light/dark themes, resizable panels.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-17 23:20:34 +02:00
co-authored by Claude Opus 4.8
commit a5ec0d21cb
174 changed files with 22239 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
import { useQuery } from "@tanstack/react-query";
import { useParams } from "react-router-dom";
import { Composer, draftToInit } from "../components/compose/Composer";
import { useT } from "../i18n";
import { api } from "../lib/api";
// Standalone composer shown in a popped-out window. It loads the draft the parent
// window persisted before opening this one.
export function ComposeWindow() {
const t = useT();
const { draftId } = useParams<{ draftId: string }>();
const { data, isLoading } = useQuery({
queryKey: ["draft", draftId],
queryFn: async () => {
const drafts = await api.listDrafts();
return drafts.find((d) => d.id === draftId) ?? null;
},
enabled: Boolean(draftId),
});
if (isLoading) {
return <div className="grid h-screen place-items-center bg-app-bg text-app-faint">…</div>;
}
if (!data) {
return (
<div className="grid h-screen place-items-center bg-app-bg text-app-faint">
{t("compose.noDrafts")}
</div>
);
}
return (
<div className="h-screen bg-app-bg text-app-fg">
<Composer init={draftToInit(data)} onClose={() => window.close()} fullWindow />
</div>
);
}
+91
View File
@@ -0,0 +1,91 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useT } from "../i18n";
import { api, ApiError } from "../lib/api";
export function Login() {
const t = useT();
const [handle, setHandle] = useState("");
const [password, setPassword] = useState("");
const [totp, setTotp] = useState("");
const [needTotp, setNeedTotp] = useState(false);
const navigate = useNavigate();
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: () => api.login(handle, password, needTotp ? totp : undefined),
onSuccess: (user) => {
queryClient.setQueryData(["me"], user);
navigate("/mail");
},
onError: (error) => {
if (error instanceof ApiError && (error.code === "totp_required" || error.code === "totp_invalid")) {
setNeedTotp(true);
}
},
});
const error = mutation.error instanceof ApiError ? mutation.error : null;
// Don't show the "code required" error as a failure once we've revealed the field.
const showError = error && !(needTotp && error.code === "totp_required");
return (
<div className="mx-auto mt-24 max-w-sm px-4">
<h1 className="mb-6 text-2xl font-semibold">{t("auth.signInTitle")}</h1>
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
mutation.mutate();
}}
>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none"
placeholder={t("auth.handlePlaceholder")}
value={handle}
onChange={(e) => setHandle(e.target.value)}
disabled={needTotp}
autoFocus
/>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none"
type="password"
placeholder={t("auth.password")}
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={needTotp}
/>
{needTotp && (
<div className="space-y-1">
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none tracking-widest"
placeholder="123456"
inputMode="numeric"
autoComplete="one-time-code"
value={totp}
onChange={(e) => setTotp(e.target.value)}
autoFocus
/>
<p className="text-xs text-app-muted">{t("auth.totpPrompt")}</p>
</div>
)}
<button
className="w-full rounded-lg bg-app-accent py-2 font-medium text-app-accent-fg hover:opacity-90 disabled:opacity-50"
disabled={mutation.isPending}
type="submit"
>
{mutation.isPending ? t("auth.signingIn") : t("auth.signIn")}
</button>
{showError && <p className="text-sm text-red-500">{error.message}</p>}
</form>
<p className="mt-4 text-sm text-app-muted">
{t("auth.noAccount")}{" "}
<Link className="text-app-accent" to="/register">
{t("auth.register")}
</Link>
</p>
</div>
);
}
+454
View File
@@ -0,0 +1,454 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { Link, useMatch, useNavigate } from "react-router-dom";
import { Composer, type ComposerInit, draftToInit } from "../components/compose/Composer";
import { DraftsList } from "../components/list/DraftsList";
import { Icon } from "../components/Icon";
import { MessageList } from "../components/list/MessageList";
import { Resizer } from "../components/Resizer";
import { ThemeToggle } from "../components/ThemeToggle";
import { ThreadView } from "../components/thread/ThreadView";
import { useT } from "../i18n";
import type { MessageKey } from "../i18n/en";
import { api } from "../lib/api";
import type { ThreadSummary } from "../lib/types";
import { useKeyboardShortcuts } from "../lib/useKeyboardShortcuts";
// Unified per-folder views. "Spam" maps to the IMAP special-use "junk".
const FOLDERS: { view: string; icon: string; label: MessageKey }[] = [
{ view: "folder:inbox", icon: "inbox", label: "nav.inbox" },
{ view: "folder:archive", icon: "archive", label: "nav.archive" },
{ view: "folder:drafts", icon: "drafts", label: "nav.drafts" },
{ view: "folder:sent", icon: "sent", label: "nav.sent" },
{ view: "folder:junk", icon: "spam", label: "nav.spam" },
{ view: "folder:trash", icon: "trash", label: "nav.trash" },
];
export function MailLayout() {
const t = useT();
const navigate = useNavigate();
const queryClient = useQueryClient();
const match = useMatch("/mail/t/:threadId");
const threadId = match?.params.threadId;
const [view, setView] = useState<string>("folder:inbox");
const [term, setTerm] = useState("");
const [filter, setFilter] = useState<"all" | "unread" | "pinned">("all");
const [listOrder, setListOrder] = useState<"newest" | "oldest">("newest");
const [composing, setComposing] = useState<ComposerInit | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [replySignal, setReplySignal] = useState<{ kind: string; seq: number }>();
const searchRef = useRef<HTMLInputElement>(null);
// Resizable panel widths (persisted). Drag the dividers to adjust.
const [sidebarW, setSidebarW] = useState(() => Number(localStorage.getItem("panel.sidebar")) || 240);
const [listW, setListW] = useState(() => Number(localStorage.getItem("panel.list")) || 384);
const clampSidebar = (w: number) => Math.min(Math.max(w, 180), 420);
// The list can be dragged up to 75% of the window width.
const clampList = (w: number) => Math.min(Math.max(w, 260), window.innerWidth * 0.75);
useEffect(() => localStorage.setItem("panel.sidebar", String(sidebarW)), [sidebarW]);
useEffect(() => localStorage.setItem("panel.list", String(listW)), [listW]);
const isDrafts = view === "folder:drafts";
// Which special-use folder the reading pane is showing (drives the toolbar).
const currentFolder = view.startsWith("folder:") ? view.slice("folder:".length) : "inbox";
const accountsQuery = useQuery({ queryKey: ["accounts"], queryFn: api.accounts });
const threadsQuery = useQuery({
queryKey: ["threads", view],
queryFn: () => api.threads(view),
enabled: !isDrafts,
});
const draftsQuery = useQuery({
queryKey: ["drafts"],
queryFn: api.listDrafts,
enabled: isDrafts,
});
const searchQuery = useQuery({
queryKey: ["search", term],
queryFn: () => api.search(term),
enabled: term.trim().length > 0,
});
const settingsQuery = useQuery({ queryKey: ["settings"], queryFn: api.settings });
const threadOrder: "asc" | "desc" = settingsQuery.data?.thread_order ?? "asc";
const allThreads: ThreadSummary[] = term.trim()
? (searchQuery.data?.threads ?? []).map((h) => h.thread)
: (threadsQuery.data?.threads ?? []);
const filtered = allThreads.filter((th) =>
filter === "unread" ? th.unread_count > 0 : filter === "pinned" ? th.pinned : true,
);
// The backend returns threads newest-first; reverse for an oldest-first view.
const threads = listOrder === "newest" ? filtered : [...filtered].reverse();
const threadsRef = useRef<ThreadSummary[]>(threads);
threadsRef.current = threads;
const detailQuery = useQuery({
queryKey: ["thread", threadId, threadOrder],
queryFn: () => api.thread(threadId!, threadOrder),
enabled: Boolean(threadId),
});
const markRead = useMutation({
mutationFn: (id: string) => api.threadFlags(id, ["\\Seen"], []),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["threads"] }),
});
useEffect(() => {
const detail = detailQuery.data;
if (detail && detail.messages.some((m) => m.is_unread)) markRead.mutate(detail.id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [detailQuery.data?.id]);
const afterMove = () => {
queryClient.invalidateQueries({ queryKey: ["threads"] });
navigate("/mail");
};
const archive = async () => {
if (!threadId) return;
await api.archiveThread(threadId);
afterMove();
};
const trash = async () => {
if (!threadId) return;
await api.trashThread(threadId);
afterMove();
};
const restore = async () => {
if (!threadId) return;
await api.restoreThread(threadId);
afterMove();
};
const deletePermanent = async () => {
if (!threadId) return;
await api.deleteThreadPermanent(threadId);
afterMove();
};
const togglePin = async () => {
const detail = detailQuery.data;
if (!detail) return;
await api.threadFlags(
detail.id,
detail.pinned ? [] : ["\\Flagged"],
detail.pinned ? ["\\Flagged"] : [],
);
queryClient.invalidateQueries({ queryKey: ["threads"] });
queryClient.invalidateQueries({ queryKey: ["thread", detail.id] });
};
const openRelative = (delta: number) => {
const list = threadsRef.current;
if (list.length === 0) return;
const idx = list.findIndex((th) => th.id === threadId);
const next = Math.min(Math.max((idx < 0 ? -1 : idx) + delta, 0), list.length - 1);
navigate(`/mail/t/${list[next].id}`);
};
useKeyboardShortcuts({
onSearch: () => searchRef.current?.focus(),
onCompose: () => accountsQuery.data?.[0] && setComposing({ accountId: accountsQuery.data[0].id, kind: "new" }),
onReply: () => setReplySignal({ kind: "reply", seq: Date.now() }),
onReplyAll: () => setReplySignal({ kind: "reply_all", seq: Date.now() }),
onForward: () => setReplySignal({ kind: "forward", seq: Date.now() }),
onArchive: archive,
onGoInbox: () => {
setView("folder:inbox");
navigate("/mail");
},
onEscape: () => setComposing(null),
onNext: () => openRelative(1),
onPrev: () => openRelative(-1),
});
const accounts = accountsQuery.data ?? [];
return (
<div className="flex h-screen bg-app-bg text-app-fg">
{/* Sidebar */}
<aside
style={{ width: sidebarW }}
className="flex shrink-0 flex-col border-r border-app-border bg-app-bg"
>
<div className="flex items-center justify-between px-3 pb-1 pt-3">
<span className="text-xs font-semibold uppercase tracking-wide text-app-faint">
{t("common.appName")}
</span>
<ThemeToggle />
</div>
<div className="px-3 pb-2">
<button
className="flex w-full items-center justify-center gap-2 rounded-lg bg-app-accent py-2 text-sm font-medium text-app-accent-fg shadow-sm hover:opacity-90"
onClick={() => accounts[0] && setComposing({ accountId: accounts[0].id, kind: "new" })}
>
<Icon name="compose" size={16} />
{t("nav.compose")}
</button>
</div>
<nav className="flex-1 space-y-0.5 overflow-y-auto px-2 py-1 text-sm">
{FOLDERS.map((f) => (
<SidebarItem
key={f.view}
active={view === f.view}
onClick={() => {
setView(f.view);
navigate("/mail");
}}
>
<Icon name={f.icon} size={18} />
{t(f.label)}
</SidebarItem>
))}
<div className="px-3 pb-1 pt-3 text-[11px] font-semibold uppercase tracking-wide text-app-faint">
{t("settings.accounts")}
</div>
{accounts.map((a) => (
<SidebarItem
key={a.id}
active={view === `account:${a.id}`}
onClick={() => { setView(`account:${a.id}`); navigate("/mail"); }}
>
<span className="h-2.5 w-2.5 shrink-0 rounded-full" style={{ backgroundColor: a.color }} />
<span className="truncate">{a.email}</span>
</SidebarItem>
))}
</nav>
<div className="border-t border-app-border p-2 text-sm">
<Link className="block rounded-lg px-3 py-2 text-app-muted hover:bg-app-hover hover:text-app-fg" to="/settings">
⚙ {t("nav.settings")}
</Link>
<button
className="block w-full rounded-lg px-3 py-2 text-left text-app-muted hover:bg-app-hover hover:text-app-fg"
onClick={async () => {
await api.logout();
queryClient.clear();
navigate("/login");
}}
>
{t("common.signOut")}
</button>
</div>
</aside>
<Resizer onDelta={(dx) => setSidebarW((w) => clampSidebar(w + dx))} />
{/* Message list */}
<div
style={{ width: listW }}
className="flex shrink-0 flex-col border-r border-app-border bg-app-surface"
>
<div className="flex h-[52px] shrink-0 items-center border-b border-app-border px-2.5">
<input
ref={searchRef}
className="w-full rounded-lg border border-app-border bg-app-bg px-3 py-1.5 text-sm text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none"
placeholder={t("nav.search")}
value={term}
onChange={(e) => setTerm(e.target.value)}
/>
</div>
{!isDrafts && (
<div className="flex h-[44px] shrink-0 items-center gap-5 border-b border-app-border px-3 text-sm">
<FilterTab active={filter === "all"} onClick={() => setFilter("all")}>
{t("filter.all")}
</FilterTab>
<FilterTab active={filter === "unread"} onClick={() => setFilter("unread")}>
{t("filter.unread")}
</FilterTab>
<FilterTab active={filter === "pinned"} onClick={() => setFilter("pinned")}>
{t("filter.pinned")}
</FilterTab>
<button
className="ml-auto rounded p-1.5 text-app-muted hover:bg-app-hover hover:text-app-fg"
title={listOrder === "newest" ? t("filter.sortOldest") : t("filter.sortNewest")}
aria-label={listOrder === "newest" ? t("filter.sortOldest") : t("filter.sortNewest")}
onClick={() => setListOrder((o) => (o === "newest" ? "oldest" : "newest"))}
>
<SortIcon />
</button>
</div>
)}
<div className="min-h-0 flex-1">
{isDrafts && !term.trim() ? (
<DraftsList
drafts={draftsQuery.data ?? []}
onOpen={(draft) => {
setComposing(draftToInit(draft));
setComposerExpanded(true);
}}
/>
) : (
<MessageList threads={threads} accounts={accounts} selectedId={threadId} onSelect={(id) => navigate(`/mail/t/${id}`)} />
)}
</div>
</div>
<Resizer onDelta={(dx) => setListW((w) => clampList(w + dx))} />
{/* Thread pane */}
<main className="relative min-w-0 flex-1 bg-app-surface">
{threadId && detailQuery.data ? (
<div className="flex h-full flex-col">
<div className="flex h-[52px] items-center gap-1 border-b border-app-border bg-app-surface px-3 text-sm">
{currentFolder === "archive" ? (
<>
<ToolbarButton onClick={restore}>
<Icon name="inbox" size={16} />
{t("mail.restore")}
</ToolbarButton>
<ToolbarButton onClick={trash}>
<Icon name="trash" size={16} />
{t("mail.delete")}
</ToolbarButton>
</>
) : currentFolder === "trash" ? (
<>
<ToolbarButton onClick={restore}>
<Icon name="inbox" size={16} />
{t("mail.restore")}
</ToolbarButton>
<ToolbarButton onClick={deletePermanent}>
<Icon name="trash" size={16} />
{t("mail.delete")}
</ToolbarButton>
</>
) : (
<>
<ToolbarButton onClick={archive}>
<Icon name="archive" size={16} />
{t("mail.archive")}
</ToolbarButton>
<ToolbarButton onClick={togglePin} active={detailQuery.data.pinned}>
<Icon
name="pin"
size={16}
className={detailQuery.data.pinned ? "text-[rgb(220_129_143)]" : ""}
/>
{detailQuery.data.pinned ? t("mail.unpin") : t("mail.pin")}
</ToolbarButton>
<ToolbarButton onClick={trash}>
<Icon name="trash" size={16} />
{t("mail.delete")}
</ToolbarButton>
</>
)}
<span className="ml-auto text-xs text-app-faint">
{t("mail.messageCount", { count: detailQuery.data.messages.length })}
</span>
</div>
<div className="min-h-0 flex-1 overflow-hidden">
<ThreadView
subject={detailQuery.data.subject}
messages={detailQuery.data.messages}
order={detailQuery.data.order}
replyKindSignal={replySignal}
/>
</div>
</div>
) : (
<div className="flex h-full items-center justify-center text-app-faint">
{t("mail.selectConversation")}
</div>
)}
{composing && (
<div
className={
composerExpanded
? "absolute inset-0 z-30"
: "absolute bottom-0 right-4 z-30 w-[47.5rem] max-w-[calc(100%-2rem)]"
}
>
<Composer
init={composing}
expanded={composerExpanded}
onToggleExpand={() => setComposerExpanded((v) => !v)}
onClose={() => {
setComposing(null);
setComposerExpanded(false);
queryClient.invalidateQueries({ queryKey: ["drafts"] });
}}
/>
</div>
)}
</main>
</div>
);
}
function FilterTab({
active,
onClick,
children,
}: {
active: boolean;
onClick: () => void;
children: React.ReactNode;
}) {
return (
<button
onClick={onClick}
className={`flex h-full items-center border-b-2 ${
active
? "border-app-accent font-semibold text-app-fg"
: "border-transparent text-app-muted hover:text-app-fg"
}`}
>
{children}
</button>
);
}
function SortIcon() {
return (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.4"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
>
<path d="M5 3v10M3 5l2-2 2 2M11 13V3M9 11l2 2 2-2" />
</svg>
);
}
function SidebarItem({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
return (
<button
onClick={onClick}
className={`flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-left ${
active ? "bg-app-active font-medium text-app-fg" : "text-app-muted hover:bg-app-hover hover:text-app-fg"
}`}
>
{children}
</button>
);
}
function ToolbarButton({
onClick,
active = false,
children,
}: {
onClick: () => void;
active?: boolean;
children: React.ReactNode;
}) {
return (
<button
className={`flex items-center gap-1.5 rounded px-2.5 py-1 hover:bg-app-hover hover:text-app-fg ${
active ? "text-app-fg" : "text-app-muted"
}`}
onClick={onClick}
>
{children}
</button>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { api, ApiError } from "../lib/api";
export function Register() {
const [localpart, setLocalpart] = useState("");
const [password, setPassword] = useState("");
const navigate = useNavigate();
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: () => api.register(localpart, password),
onSuccess: (user) => {
queryClient.setQueryData(["me"], user);
navigate("/mail");
},
});
return (
<div className="mx-auto mt-24 max-w-sm px-4">
<h1 className="mb-6 text-2xl font-semibold">Create account</h1>
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
mutation.mutate();
}}
>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none"
placeholder="handle (3–30 chars, a-z 0-9 . _ -)"
value={localpart}
onChange={(e) => setLocalpart(e.target.value)}
autoFocus
/>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-app-fg placeholder:text-app-faint focus:border-app-accent focus:outline-none"
type="password"
placeholder="password (min 8 chars)"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button
className="w-full rounded-lg bg-app-accent py-2 font-medium text-app-accent-fg hover:opacity-90 disabled:opacity-50"
disabled={mutation.isPending}
type="submit"
>
{mutation.isPending ? "Creating…" : "Create account"}
</button>
{mutation.error instanceof ApiError && (
<p className="text-sm text-red-500">{mutation.error.message}</p>
)}
</form>
<p className="mt-4 text-sm text-app-muted">
Already have an account?{" "}
<Link className="text-app-accent" to="/login">
Sign in
</Link>
</p>
</div>
);
}
+302
View File
@@ -0,0 +1,302 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { QRCodeSVG } from "qrcode.react";
import { useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { useT } from "../../i18n";
import { api, ApiError } from "../../lib/api";
import { useMe } from "../../lib/auth";
import { useTheme } from "../../lib/theme";
const SECTIONS = ["profile", "security", "accounts", "appearance"] as const;
type Section = (typeof SECTIONS)[number];
export function Settings() {
const t = useT();
const params = useParams();
const section = (SECTIONS.includes(params.section as Section) ? params.section : "profile") as Section;
return (
<div className="flex h-screen flex-col">
<header className="flex items-center gap-3 border-b border-app-border px-4 py-2">
<Link to="/mail" className="text-sm text-app-accent">
← {t("nav.mail")}
</Link>
<span className="font-semibold">{t("settings.title")}</span>
</header>
<div className="flex min-h-0 flex-1">
<nav className="w-52 shrink-0 border-r border-app-border p-2">
{SECTIONS.map((s) => (
<Link
key={s}
to={`/settings/${s}`}
className={`block rounded px-3 py-2 text-sm ${
section === s ? "bg-app-active font-medium text-app-fg" : "hover:bg-app-hover"
}`}
>
{t(`settings.${s}` as const)}
</Link>
))}
</nav>
<main className="flex-1 overflow-y-auto p-6">
{section === "profile" && <ProfileSection />}
{section === "security" && <SecuritySection />}
{section === "accounts" && <AccountsSection />}
{section === "appearance" && <AppearanceSection />}
</main>
</div>
</div>
);
}
function ProfileSection() {
const t = useT();
const { data } = useMe();
return (
<section className="max-w-md space-y-3">
<h2 className="text-lg font-semibold">{t("settings.profile")}</h2>
<Row label={t("settings.handle")} value={data?.handle ?? ""} />
<Row label={t("settings.recoveryEmail")} value={data?.recovery_email ?? "—"} />
</section>
);
}
function Row({ label, value }: { label: string; value: string }) {
return (
<div className="flex justify-between border-b border-app-border py-2 text-sm">
<span className="text-app-muted">{label}</span>
<span>{value}</span>
</div>
);
}
function SecuritySection() {
const t = useT();
const queryClient = useQueryClient();
const { data: me } = useMe();
const [setup, setSetup] = useState<{ secret: string; uri: string } | null>(null);
const [code, setCode] = useState("");
const [disabling, setDisabling] = useState(false);
const [disablePw, setDisablePw] = useState("");
const [error, setError] = useState("");
const sessions = useQuery({ queryKey: ["sessions"], queryFn: api.sessions });
const enabled = Boolean(me?.totp_enabled);
const startSetup = async () => {
const res = await api.totpSetup();
setSetup({ secret: res.secret, uri: res.provisioning_uri });
};
const confirm = async () => {
setError("");
try {
await api.totpEnable(code);
setSetup(null);
queryClient.invalidateQueries({ queryKey: ["me"] });
} catch (e) {
setError(e instanceof ApiError ? e.message : String(e));
}
};
const disable = async () => {
setError("");
try {
await api.totpDisable(disablePw);
setDisabling(false);
setDisablePw("");
queryClient.invalidateQueries({ queryKey: ["me"] });
} catch (e) {
setError(e instanceof ApiError ? e.message : String(e));
}
};
const revoke = useMutation({
mutationFn: (sid: string) => api.revokeSession(sid),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["sessions"] }),
});
return (
<section className="max-w-md space-y-6">
<div className="space-y-2">
<h2 className="text-lg font-semibold">{t("settings.twoFactor")}</h2>
{enabled ? (
<div className="space-y-2">
<p className="text-sm text-emerald-500">{t("settings.twoFactorOn")}</p>
{disabling ? (
<div className="space-y-2 rounded-lg border border-app-border p-3">
<p className="text-sm text-app-muted">{t("settings.disable2faPrompt")}</p>
<div className="flex gap-2">
<input
className="flex-1 rounded border border-app-border bg-app-surface px-2 py-1 text-sm"
type="password"
value={disablePw}
onChange={(e) => setDisablePw(e.target.value)}
autoFocus
/>
<button className="rounded bg-red-600 px-3 py-1 text-sm text-white" onClick={disable}>
{t("settings.disable")}
</button>
<button className="px-2 text-sm text-app-muted" onClick={() => setDisabling(false)}>
{t("common.cancel")}
</button>
</div>
</div>
) : (
<button
className="rounded border border-app-border px-3 py-1.5 text-sm text-app-fg hover:bg-app-hover"
onClick={() => setDisabling(true)}
>
{t("settings.disable2fa")}
</button>
)}
</div>
) : setup ? (
<div className="space-y-3 rounded-lg border border-app-border p-3">
<p className="text-sm text-app-muted">{t("settings.scanQr")}</p>
<div className="flex gap-4">
<div className="shrink-0 rounded bg-white p-2 ring-1 ring-gray-200">
<QRCodeSVG value={setup.uri} size={160} level="M" />
</div>
<div className="min-w-0 space-y-1">
<p className="text-xs text-app-muted">
{t("settings.secret")}:
<br />
<code className="break-all">{setup.secret}</code>
</p>
<details className="text-xs text-app-faint">
<summary className="cursor-pointer">otpauth URI</summary>
<div className="mt-1 break-all rounded bg-app-surface px-2 py-1">{setup.uri}</div>
</details>
</div>
</div>
<div className="flex gap-2">
<input
className="w-32 rounded border border-app-border bg-app-surface px-2 py-1 text-sm"
placeholder="123456"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
<button className="rounded bg-app-accent px-3 py-1 text-sm text-app-accent-fg" onClick={confirm}>
{t("settings.confirm")}
</button>
</div>
</div>
) : (
<button className="rounded bg-app-accent px-3 py-1.5 text-sm text-app-accent-fg" onClick={startSetup}>
{t("settings.enable2fa")}
</button>
)}
{error && <p className="text-sm text-red-500">{error}</p>}
</div>
<div className="space-y-2">
<h2 className="text-lg font-semibold">{t("settings.sessions")}</h2>
<ul className="divide-y divide-app-border rounded-lg border border-app-border">
{(sessions.data ?? []).map((s) => (
<li key={s.sid} className="flex items-center justify-between px-3 py-2 text-sm">
<span>
{s.ua || "session"}{" "}
{s.current && <span className="text-xs text-emerald-500">({t("settings.thisDevice")})</span>}
<span className="block text-xs text-app-faint">
{new Date(s.created).toLocaleString()}
</span>
</span>
{!s.current && (
<button className="text-xs text-red-500" onClick={() => revoke.mutate(s.sid)}>
{t("settings.revoke")}
</button>
)}
</li>
))}
</ul>
</div>
</section>
);
}
function AccountsSection() {
const t = useT();
const navigate = useNavigate();
const queryClient = useQueryClient();
const accounts = useQuery({ queryKey: ["accounts"], queryFn: api.accounts });
const remove = useMutation({
mutationFn: (id: string) => api.deleteAccount(id),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["accounts"] }),
});
return (
<section className="max-w-lg space-y-3">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold">{t("settings.accounts")}</h2>
<button
className="rounded bg-app-accent px-3 py-1.5 text-sm text-app-accent-fg"
onClick={() => navigate("/settings/accounts/new")}
>
{t("settings.addAccount")}
</button>
</div>
<ul className="divide-y divide-app-border rounded-lg border border-app-border">
{(accounts.data ?? []).map((a) => (
<li key={a.id} className="flex items-center justify-between px-3 py-2 text-sm">
<span className="flex items-center gap-2">
<span className="h-3 w-3 rounded-full" style={{ backgroundColor: a.color }} />
<span>{a.email}</span>
<span className="text-xs text-app-faint">{t("settings.syncState", { state: a.state })}</span>
</span>
<button
className="text-xs text-red-500"
onClick={() => {
if (confirm(t("settings.confirmRemoveAccount"))) remove.mutate(a.id);
}}
>
{t("common.remove")}
</button>
</li>
))}
</ul>
</section>
);
}
function AppearanceSection() {
const t = useT();
const queryClient = useQueryClient();
const { theme, setTheme } = useTheme();
const settings = useQuery({ queryKey: ["settings"], queryFn: api.settings });
const patch = useMutation({
mutationFn: api.patchSettings,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["settings"] }),
});
return (
<section className="max-w-md space-y-3">
<h2 className="text-lg font-semibold">{t("settings.appearance")}</h2>
<div className="flex items-center justify-between border-b border-app-border py-2 text-sm">
<span className="text-app-muted">{t("settings.theme")}</span>
<div className="flex gap-1 rounded-lg border border-app-border p-0.5">
{(["light", "dark", "system"] as const).map((value) => (
<button
key={value}
onClick={() => setTheme(value)}
className={`rounded px-3 py-1 ${
theme === value ? "bg-app-active font-medium text-app-fg" : "text-app-muted hover:bg-app-hover"
}`}
>
{t(`theme.${value}` as const)}
</button>
))}
</div>
</div>
<label className="flex items-center justify-between border-b border-app-border py-2 text-sm">
<span className="text-app-muted">{t("settings.threadOrder")}</span>
<select
className="rounded border border-app-border bg-app-surface px-2 py-1"
value={settings.data?.thread_order ?? "asc"}
onChange={(e) => patch.mutate({ thread_order: e.target.value as "asc" | "desc" })}
>
<option value="asc">{t("mail.orderOldest")}</option>
<option value="desc">{t("mail.orderNewest")}</option>
</select>
</label>
<Row label={t("settings.timezone")} value={settings.data?.tz ?? "UTC"} />
</section>
);
}
@@ -0,0 +1,224 @@
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useT } from "../../i18n";
import { api, ApiError } from "../../lib/api";
import type { ServerConfig } from "../../lib/types";
const PALETTE = ["#2563eb", "#16a34a", "#d4762a", "#9333ea", "#dc2626", "#0891b2"];
const EMPTY: ServerConfig = { host: "", port: 993, tls: "ssl", auth: "password" };
export function AccountWizard() {
const t = useT();
const navigate = useNavigate();
const queryClient = useQueryClient();
const [step, setStep] = useState<1 | 2 | 3>(1);
const [email, setEmail] = useState("");
const [displayName, setDisplayName] = useState("");
const [password, setPassword] = useState("");
const [color, setColor] = useState(PALETTE[0]);
const [imap, setImap] = useState<ServerConfig>(EMPTY);
const [smtp, setSmtp] = useState<ServerConfig>({ ...EMPTY, port: 465 });
const [source, setSource] = useState<string>("");
const [busy, setBusy] = useState(false);
const [tested, setTested] = useState(false);
const [error, setError] = useState("");
const discover = async () => {
setBusy(true);
setError("");
try {
const res = await api.discover(email);
const cand = res.candidates[0];
if (cand) {
setImap({ ...cand.imap });
setSmtp({ ...cand.smtp });
setSource(cand.source);
} else {
setSource("manual");
}
setStep(2);
} catch (e) {
setError(e instanceof ApiError ? e.message : String(e));
} finally {
setBusy(false);
}
};
const test = async () => {
setBusy(true);
setError("");
setTested(false);
try {
await api.testAccount({ imap, smtp, email, password });
setTested(true);
} catch (e) {
setError(e instanceof ApiError ? e.message : String(e));
} finally {
setBusy(false);
}
};
const create = async () => {
setBusy(true);
setError("");
try {
await api.createAccount({
email,
display_name: displayName || email,
color,
imap,
smtp,
password,
});
await queryClient.invalidateQueries({ queryKey: ["accounts"] });
setStep(3);
} catch (e) {
setError(e instanceof ApiError ? e.message : String(e));
} finally {
setBusy(false);
}
};
const serverFields = (
cfg: ServerConfig,
set: (c: ServerConfig) => void,
label: string,
) => (
<fieldset className="rounded-lg border border-app-border p-3">
<legend className="px-1 text-xs text-app-muted">{label}</legend>
<div className="flex gap-2">
<input
className="flex-1 rounded border border-app-border bg-app-surface px-2 py-1 text-sm"
placeholder={t("wizard.host")}
value={cfg.host}
onChange={(e) => set({ ...cfg, host: e.target.value })}
/>
<input
className="w-20 rounded border border-app-border bg-app-surface px-2 py-1 text-sm"
type="number"
value={cfg.port}
onChange={(e) => set({ ...cfg, port: Number(e.target.value) })}
/>
<select
className="rounded border border-app-border bg-app-surface px-2 py-1 text-sm"
value={cfg.tls}
onChange={(e) => set({ ...cfg, tls: e.target.value })}
>
<option value="ssl">SSL</option>
<option value="starttls">STARTTLS</option>
</select>
</div>
</fieldset>
);
return (
<div className="mx-auto mt-16 max-w-lg px-4">
<h1 className="mb-6 text-2xl font-semibold">{t("wizard.title")}</h1>
{step === 1 && (
<form
className="space-y-3"
onSubmit={(e) => {
e.preventDefault();
discover();
}}
>
<label className="block text-sm text-app-muted">{t("wizard.step1")}</label>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2"
type="email"
placeholder={t("wizard.emailPlaceholder")}
value={email}
onChange={(e) => setEmail(e.target.value)}
autoFocus
/>
<button
className="rounded bg-app-accent px-4 py-2 text-app-accent-fg disabled:opacity-50"
disabled={busy || !email.includes("@")}
>
{busy ? t("wizard.discovering") : t("wizard.discover")}
</button>
</form>
)}
{step === 2 && (
<div className="space-y-3">
{source && source !== "manual" && (
<p className="text-sm text-emerald-500">{t("wizard.foundVia", { source })}</p>
)}
{serverFields(imap, setImap, t("wizard.imapServer"))}
{serverFields(smtp, setSmtp, t("wizard.smtpServer"))}
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-sm"
placeholder={t("wizard.displayName")}
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
/>
<input
className="w-full rounded-lg border border-app-border bg-app-surface px-3 py-2 text-sm"
type="password"
placeholder={t("wizard.accountPassword")}
value={password}
onChange={(e) => {
setPassword(e.target.value);
setTested(false);
}}
/>
<p className="text-xs text-app-faint">{t("wizard.appPasswordHint")}</p>
<div className="flex items-center gap-2">
<span className="text-xs text-app-muted">Color</span>
{PALETTE.map((c) => (
<button
key={c}
onClick={() => setColor(c)}
className={`h-5 w-5 rounded-full ${color === c ? "ring-2 ring-offset-1" : ""}`}
style={{ backgroundColor: c }}
aria-label={c}
/>
))}
</div>
{tested && <p className="text-sm text-emerald-500">{t("wizard.testOk")}</p>}
<div className="flex gap-2">
{!tested ? (
<button
className="rounded bg-app-accent px-4 py-2 text-app-accent-fg disabled:opacity-50"
onClick={test}
disabled={busy || !password || !imap.host}
>
{busy ? t("wizard.testing") : t("wizard.test")}
</button>
) : (
<button
className="rounded bg-app-accent px-4 py-2 text-app-accent-fg disabled:opacity-50"
onClick={create}
disabled={busy}
>
{busy ? t("wizard.creating") : t("wizard.create")}
</button>
)}
<button className="px-3 py-2 text-sm text-app-muted" onClick={() => setStep(1)}>
{t("common.back")}
</button>
</div>
</div>
)}
{step === 3 && (
<div className="space-y-4">
<p className="text-emerald-500">{t("wizard.created")}</p>
<button
className="rounded bg-app-accent px-4 py-2 text-app-accent-fg"
onClick={() => navigate("/mail")}
>
{t("wizard.startReading")}
</button>
</div>
)}
{error && <p className="mt-3 text-sm text-red-500">{error}</p>}
</div>
);
}