frontend: redesign the thread reading panel

Rework the conversation view to match the new dark-theme mockups:
- Subject bar gains a print button and an expand/collapse-all toggle (default
  action expands all; collapsing leaves only the newest message open).
- Collapsed messages are compact single-line cards (40px avatar, colored sender
  name, snippet, relative date) that overlap into a stack; alignment follows the
  sort order (top edge for oldest-first, bottom edge for newest-first) and the
  always-open newest card overlaps its neighbour in both orders.
- Expanded messages show sender+address (whole header row toggles collapse), a
  detail disclosure (From/To/Cc/Subject/Date/Size), the message location
  (Inbox/Sent), a read/unread circle (per-message flag toggle), a quick
  Reply/Reply-all, and an Actions menu (reply/forward/print/delete). The
  Reply/Reply all/Forward bar now sits inside the newest card above a divider.
- Message body: the quoted original is hidden by default with a "•••" toggle
  injected after the "On … wrote:" attribution; the iframe now collapses-then-
  measures so it shrinks back when the quote is hidden.
- Avatars use the sender's IMAP-account colour when the address matches one of
  our accounts, else a stable per-sender hue; two initials for multi-word names.
- Brighter dark-theme border token; new print/expand-all/collapse-all icons.

Backend: add size_bytes to the message envelope (shown in message details).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-19 18:58:01 +02:00
co-authored by Claude Opus 4.8
parent 293945480b
commit 1a83e0fb9b
13 changed files with 442 additions and 62 deletions
+375 -57
View File
@@ -1,19 +1,22 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Fragment, useEffect, useMemo, useRef, useState } from "react";
import { useT } from "../../i18n";
import type { MessageEnvelope } from "../../lib/types";
import { api } from "../../lib/api";
import type { AccountOut, MailboxOut, MessageEnvelope } from "../../lib/types";
import { Composer, type ComposerInit } from "../compose/Composer";
import { Icon } from "../Icon";
import { MessageBody } from "./MessageBody";
// Direction-agnostic thread view (invariant I-5 / SPEC §9.4).
// `messages` is ALWAYS ascending (oldest first); the ONLY branch on `order` is the
// visual reversal below. The composer anchor is attached to the newest message;
// any expanded message can additionally start a reply of its own.
// visual reversal below. The composer anchor is attached to the newest message.
export interface ThreadViewProps {
subject: string;
messages: MessageEnvelope[];
order: "asc" | "desc";
mailboxes?: MailboxOut[];
accounts?: AccountOut[];
replyKindSignal?: { kind: string; seq: number };
}
@@ -26,8 +29,12 @@ function formatList(addrs: { name: string; email: string }[]): string {
return addrs.length > 0 ? addrs.map(formatAddress).join(", ") : "(no recipient)";
}
// Attribution line prefixed to a quoted original, e.g.
// "On Fri, Jul 17, 2026, at 2:04 PM, Lukas Remis wrote:".
function recipientSummary(addrs: { name: string; email: string }[]): string {
if (addrs.length === 0) return "(no recipient)";
const first = addrs[0].name || addrs[0].email;
return addrs.length > 1 ? `${first} +${addrs.length - 1}` : first;
}
function attributionFor(msg: MessageEnvelope): string {
const d = new Date(msg.date);
const date = d.toLocaleDateString("en-US", {
@@ -71,69 +78,286 @@ function buildReplyInit(subject: string, msg: MessageEnvelope, kind: string): Co
}
function initials(msg: MessageEnvelope): string {
const name = msg.from_addr[0]?.name || msg.from_addr[0]?.email || "?";
return name.trim().slice(0, 1).toUpperCase();
const name = (msg.from_addr[0]?.name || msg.from_addr[0]?.email || "?").trim();
const words = name.split(/\s+/).filter(Boolean);
if (words.length >= 2) return (words[0][0] + words[1][0]).toUpperCase();
return name.slice(0, 1).toUpperCase();
}
// Stable per-sender hue so a sender's avatar + name share a colour (like the mockup).
function hue(msg: MessageEnvelope): number {
const key = (msg.from_addr[0]?.email || msg.from_addr[0]?.name || "?").toLowerCase();
let h = 0;
for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % 360;
return h;
}
function fmtRelative(iso: string): string {
const d = new Date(iso);
const base = d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
const diff = Date.now() - d.getTime();
const mins = Math.round(diff / 60000);
const hrs = Math.round(diff / 3600000);
const days = Math.round(diff / 86400000);
let rel = "";
if (mins < 1) rel = "just now";
else if (mins < 60) rel = `${mins} min ago`;
else if (hrs < 24) rel = `${hrs} hour${hrs === 1 ? "" : "s"} ago`;
else if (days < 30) rel = `${days} day${days === 1 ? "" : "s"} ago`;
return rel ? `${base} (${rel})` : `${base} ${d.getFullYear()}`;
}
function fmtFull(iso: string): string {
return new Date(iso).toLocaleString("en-US", {
weekday: "short",
year: "numeric",
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
function fmtSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
const LOCATION_LABEL: Record<string, string> = {
inbox: "Inbox",
sent: "Sent",
archive: "Archive",
drafts: "Drafts",
trash: "Trash",
junk: "Spam",
};
function ActionsMenu({
onReply,
onPrint,
onDelete,
}: {
onReply: (kind: string) => void;
onPrint: () => void;
onDelete: () => void;
}) {
const t = useT();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!open) return;
const onDoc = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener("mousedown", onDoc);
return () => document.removeEventListener("mousedown", onDoc);
}, [open]);
const item = (label: string, onClick: () => void) => (
<button
className="block w-full px-3 py-1.5 text-left text-xs text-app-fg hover:bg-app-hover"
onClick={() => {
setOpen(false);
onClick();
}}
>
{label}
</button>
);
return (
<div ref={ref} className="relative">
<button
className="flex items-center gap-1 rounded px-1.5 py-1 text-xs text-app-muted hover:bg-app-hover hover:text-app-fg"
onClick={() => setOpen((v) => !v)}
>
{t("mail.actions")}
<span className="text-[9px]">▾</span>
</button>
{open && (
<div className="absolute right-0 z-20 mt-1 w-52 overflow-hidden rounded-md border border-app-border bg-app-elevated py-1 shadow-lg">
{item(t("mail.reply"), () => onReply("reply"))}
{item(t("mail.replyAll"), () => onReply("reply_all"))}
{item(t("mail.forward"), () => onReply("forward"))}
{item(t("mail.forwardAsAttachment"), () => onReply("forward"))}
{item(t("mail.print"), onPrint)}
<div className="my-1 border-t border-app-border" />
{item(t("mail.delete"), onDelete)}
</div>
)}
</div>
);
}
function MessageItem({
message,
expanded,
showReply,
location,
align,
accentColor,
boxClassName,
zIndex,
showReplyBar,
onToggle,
onReply,
onToggleRead,
onPrint,
onDelete,
innerRef,
}: {
message: MessageEnvelope;
expanded: boolean;
showReply: boolean;
location: string;
align: "start" | "end";
accentColor: string | null;
boxClassName: string;
zIndex: number;
showReplyBar: boolean;
onToggle: () => void;
onReply: (kind: string) => void;
onToggleRead: () => void;
onPrint: () => void;
onDelete: () => void;
innerRef?: (el: HTMLDivElement | null) => void;
}) {
const t = useT();
const [showDetails, setShowDetails] = useState(false);
const replyBtn = (kind: string, label: string, icon: string) => (
<button
className="flex items-center gap-1.5 rounded-md border border-app-border px-2.5 py-1 text-xs text-app-fg hover:bg-app-hover"
className="flex items-center gap-1.5 rounded-md border border-app-border px-3 py-1.5 text-xs text-app-fg hover:bg-app-hover"
onClick={() => onReply(kind)}
>
<Icon name={icon} size={14} />
{label}
</button>
);
const h = hue(message);
// Our own IMAP accounts use their assigned colour; everyone else a stable hue.
const avatarBg = accentColor ?? `hsl(${h} 45% 45%)`;
const nameColor = accentColor ?? `hsl(${h} 55% 62%)`;
const avatar = () => (
<span
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-semibold text-white"
style={{ backgroundColor: avatarBg }}
>
{initials(message)}
</span>
);
const senderName = (
<span className="font-semibold" style={{ color: nameColor }}>
{message.from_addr[0]?.name || message.from_addr[0]?.email || "(unknown)"}
</span>
);
const multiRecipient = message.to_addr.length + message.cc_addr.length > 1;
return (
<div
data-testid="message"
data-message-id={message.id}
ref={innerRef}
className="overflow-hidden rounded-lg border border-app-border bg-app-surface"
style={{ zIndex }}
className={`relative ${boxClassName}`}
>
<button className="flex w-full items-start gap-3 px-3 py-2.5 text-left hover:bg-app-hover" onClick={onToggle}>
<span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-app-active text-sm font-medium text-app-fg">
{initials(message)}
</span>
<span className="min-w-0 flex-1">
<span className="flex items-baseline gap-2">
{message.is_unread && <span className="h-2 w-2 shrink-0 rounded-full bg-app-accent" />}
<span className="min-w-0 flex-1 truncate text-sm">
<span className="font-medium text-app-fg">{formatAddress(message.from_addr[0])}</span>
<span className="text-app-faint"> → {formatList(message.to_addr)}</span>
{message.cc_addr.length > 0 && (
<span className="text-app-faint"> · cc: {formatList(message.cc_addr)}</span>
)}
{message.bcc_addr.length > 0 && (
<span className="text-app-faint"> · bcc: {formatList(message.bcc_addr)}</span>
)}
</span>
<span className="shrink-0 text-xs text-app-faint">{new Date(message.date).toLocaleString()}</span>
{!expanded ? (
// Collapsed: single-line row (avatar · sender · inline snippet · date).
// Aligned to the visible (non-overlapped) edge of the stacked card.
<button
className={`flex w-full gap-3 px-4 py-2.5 text-left hover:bg-app-hover ${
align === "end" ? "items-end" : "items-start"
}`}
onClick={onToggle}
>
{avatar()}
<span className="min-w-0 flex-1 truncate text-sm">
{senderName}
<span className="ml-2 text-app-faint">{message.snippet}</span>
</span>
<span className="block truncate text-[13px] text-app-muted">{message.snippet}</span>
</span>
</button>
{expanded && (
<div className="border-t border-app-border">
<MessageBody message={message} />
{showReply && (
<div className="flex justify-end gap-2 border-t border-app-border px-3 py-2">
<span className="shrink-0 text-xs text-app-faint">{fmtRelative(message.date)}</span>
</button>
) : (
<div>
<div className="flex items-start gap-3 px-4 pb-2 pt-3">
{avatar()}
<div className="min-w-0 flex-1">
{/* line 1: sender + email ············· date (whole row collapses) */}
<button
className="flex w-full items-baseline justify-between gap-2 text-left"
onClick={onToggle}
>
<span className="min-w-0 truncate text-sm">
{senderName}
{message.from_addr[0]?.email && (
<span className="text-app-faint"> &lt;{message.from_addr[0].email}&gt;</span>
)}
</span>
<span className="shrink-0 text-xs text-app-faint">{fmtRelative(message.date)}</span>
</button>
{/* line 2: to … ▼ ············· location ○ reply actions */}
<div className="mt-0.5 flex items-center justify-between gap-2">
<button
className="flex min-w-0 items-center gap-1 text-left text-xs text-app-muted"
onClick={() => setShowDetails((v) => !v)}
aria-expanded={showDetails}
>
<span className="truncate">
{t("mail.to")} {recipientSummary(message.to_addr)}
</span>
<span className="text-[9px] text-app-faint">{showDetails ? "▲" : "▼"}</span>
</button>
<div className="flex shrink-0 items-center gap-3 text-xs">
{location && <span className="font-semibold text-app-fg">{location}</span>}
<button
title={t("mail.markReadUnread")}
aria-label={t("mail.markReadUnread")}
onClick={onToggleRead}
className="grid h-4 w-4 place-items-center"
>
<span
className={`h-3 w-3 rounded-full border ${
message.is_unread
? "border-app-accent bg-app-accent"
: "border-app-faint"
}`}
/>
</button>
<button
className="flex items-center gap-1 text-app-muted hover:text-app-fg"
onClick={() => onReply(multiRecipient ? "reply_all" : "reply")}
>
<Icon name={multiRecipient ? "reply-all" : "reply"} size={14} />
{multiRecipient ? t("mail.replyAll") : t("mail.reply")}
</button>
<ActionsMenu onReply={onReply} onPrint={onPrint} onDelete={onDelete} />
</div>
</div>
{showDetails && (
<dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 border-t border-app-border pt-2 text-xs text-app-muted">
<dt className="text-app-faint">{t("mail.from")}</dt>
<dd className="truncate">{formatList(message.from_addr)}</dd>
<dt className="text-app-faint">{t("mail.to")}</dt>
<dd className="truncate">{formatList(message.to_addr)}</dd>
{message.cc_addr.length > 0 && (
<>
<dt className="text-app-faint">Cc</dt>
<dd className="truncate">{formatList(message.cc_addr)}</dd>
</>
)}
<dt className="text-app-faint">{t("mail.subjectLabel")}</dt>
<dd className="truncate">{message.subject || "(no subject)"}</dd>
<dt className="text-app-faint">{t("mail.dateLabel")}</dt>
<dd>{fmtFull(message.date)}</dd>
<dt className="text-app-faint">{t("mail.sizeLabel")}</dt>
<dd>{fmtSize(message.size_bytes)}</dd>
</dl>
)}
</div>
</div>
<div className="px-4 pb-3">
<MessageBody message={message} />
</div>
{showReplyBar && (
<div className="flex gap-2 border-t border-app-border px-4 py-3">
{replyBtn("reply", t("mail.reply"), "reply")}
{replyBtn("reply_all", t("mail.replyAll"), "reply-all")}
{replyBtn("forward", t("mail.forward"), "forward")}
@@ -145,8 +369,16 @@ function MessageItem({
);
}
export function ThreadView({ subject, messages, order, replyKindSignal }: ThreadViewProps) {
export function ThreadView({
subject,
messages,
order,
mailboxes,
accounts,
replyKindSignal,
}: ThreadViewProps) {
const t = useT();
const queryClient = useQueryClient();
const newest = messages.length > 0 ? messages[messages.length - 1] : undefined;
const defaultExpanded = useMemo(() => {
@@ -159,9 +391,54 @@ export function ThreadView({ subject, messages, order, replyKindSignal }: Thread
const [expanded, setExpanded] = useState<Set<string>>(defaultExpanded);
useEffect(() => setExpanded(defaultExpanded), [defaultExpanded]);
// The reply currently open: which message it targets, and its prefilled draft.
const [composing, setComposing] = useState<{ anchorId: string; init: ComposerInit } | null>(null);
const flags = useMutation({
mutationFn: ({ id, add, remove }: { id: string; add: string[]; remove: string[] }) =>
api.messageFlags(id, add, remove),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["thread"] });
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
const move = useMutation({
mutationFn: ({ id, mailboxId }: { id: string; mailboxId: string }) =>
api.moveMessage(id, mailboxId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["thread"] });
queryClient.invalidateQueries({ queryKey: ["threads"] });
},
});
const specialUse = useMemo(() => {
const m = new Map<string, string | null>();
for (const mb of mailboxes ?? []) m.set(mb.id, mb.special_use);
return m;
}, [mailboxes]);
const locationFor = (msg: MessageEnvelope) => {
const su = specialUse.get(msg.mailbox_id);
return su ? (LOCATION_LABEL[su] ?? su.charAt(0).toUpperCase() + su.slice(1)) : "";
};
const trashFor = (accountId: string) =>
(mailboxes ?? []).find((m) => m.account_id === accountId && m.special_use === "trash")?.id;
const accountColor = useMemo(() => {
const m = new Map<string, string>();
for (const a of accounts ?? []) m.set(a.email.toLowerCase(), a.color);
return m;
}, [accounts]);
const accentFor = (msg: MessageEnvelope) =>
accountColor.get((msg.from_addr[0]?.email ?? "").toLowerCase()) ?? null;
const toggleRead = (msg: MessageEnvelope) =>
flags.mutate(
msg.is_unread ? { id: msg.id, add: ["\\Seen"], remove: [] } : { id: msg.id, add: [], remove: ["\\Seen"] },
);
const deleteMessage = (msg: MessageEnvelope) => {
const trash = trashFor(msg.account_id);
if (trash) move.mutate({ id: msg.id, mailboxId: trash });
};
const openReply = (msg: MessageEnvelope, kind: string) => {
setExpanded((prev) => new Set(prev).add(msg.id));
setComposing({ anchorId: msg.id, init: buildReplyInit(subject, msg, kind) });
@@ -178,6 +455,7 @@ export function ThreadView({ subject, messages, order, replyKindSignal }: Thread
}, [newest?.id]);
const visual = order === "asc" ? messages : [...messages].reverse();
const allExpanded = messages.length > 0 && messages.every((m) => expanded.has(m.id));
const toggle = (id: string) =>
setExpanded((prev) => {
@@ -187,43 +465,83 @@ export function ThreadView({ subject, messages, order, replyKindSignal }: Thread
return next;
});
// Default action expands everything; collapsing leaves only the latest message open.
const toggleAll = () =>
setExpanded(
allExpanded ? new Set(newest ? [newest.id] : []) : new Set(messages.map((m) => m.id)),
);
const composerFor = (id: string) =>
composing?.anchorId === id ? (
<div className="py-2">
<div className="px-4 py-3">
<Composer init={composing.init} onClose={() => setComposing(null)} />
</div>
) : null;
return (
<div data-testid="thread-view" className="flex h-full flex-col overflow-y-auto bg-app-bg">
<div className="sticky top-0 z-10 flex h-[44px] shrink-0 items-center justify-between border-b border-app-border bg-app-surface px-4">
<div className="sticky top-0 z-10 flex h-[44px] shrink-0 items-center justify-between gap-2 border-b border-app-border bg-app-surface px-4">
<h2 className="truncate text-base font-semibold text-app-fg">{subject || "(no subject)"}</h2>
<button
className="shrink-0 text-xs text-app-accent hover:underline"
onClick={() => setExpanded(new Set(messages.map((m) => m.id)))}
>
{t("mail.expandAll")}
</button>
<div className="flex shrink-0 items-center gap-1">
<button
className="rounded p-1.5 text-app-muted hover:bg-app-hover hover:text-app-fg"
title={t("mail.print")}
aria-label={t("mail.print")}
onClick={() => window.print()}
>
<Icon name="print" size={16} />
</button>
<button
className="rounded p-1.5 text-app-muted hover:bg-app-hover hover:text-app-fg"
title={allExpanded ? t("mail.collapseAll") : t("mail.expandAll")}
aria-label={allExpanded ? t("mail.collapseAll") : t("mail.expandAll")}
onClick={toggleAll}
>
<Icon name={allExpanded ? "collapse-all" : "expand-all"} size={16} />
</button>
</div>
</div>
<div className="space-y-2 p-3">
{visual.map((message) => {
const isNewest = Boolean(newest && message.id === newest.id);
const isComposing = composing?.anchorId === message.id;
<div className="p-3">
{visual.map((message, i) => {
const isNewest = Boolean(newest && newest.id === message.id);
const isExpanded = expanded.has(message.id);
const prev = i > 0 ? visual[i - 1] : undefined;
const prevCollapsed = prev ? !expanded.has(prev.id) : false;
const prevIsNewest = Boolean(prev && newest && prev.id === newest.id);
// Overlap onto a preceding collapsed card, and also onto the always-open
// newest message — so the newest stacks with its neighbour in both sort
// orders (bottom card in oldest-first, top card in newest-first). z-index
// keeps the newer/"current" edge on top so text stays visible.
const overlap = prevCollapsed || prevIsNewest;
const margin = i === 0 ? "" : overlap ? "-mt-[20px]" : "mt-2";
const z = order === "asc" ? i + 1 : visual.length - i;
const boxClassName = `${margin} rounded-lg border border-app-border bg-app-surface ${
isExpanded ? "" : "shadow-sm"
}`;
return (
<Fragment key={message.id}>
<MessageItem
message={message}
expanded={expanded.has(message.id)}
showReply={expanded.has(message.id) && !isComposing}
expanded={isExpanded}
location={locationFor(message)}
align={order === "asc" ? "start" : "end"}
accentColor={accentFor(message)}
boxClassName={boxClassName}
zIndex={z}
showReplyBar={isNewest && composing?.anchorId !== message.id}
onToggle={() => toggle(message.id)}
onReply={(kind) => openReply(message, kind)}
onToggleRead={() => toggleRead(message)}
onPrint={() => window.print()}
onDelete={() => deleteMessage(message)}
innerRef={isNewest ? (el) => (newestRef.current = el) : undefined}
/>
{isNewest ? (
<div data-testid="composer-anchor">{composerFor(message.id)}</div>
) : (
composerFor(message.id)
{isNewest && (
<div data-testid="composer-anchor">
{composing?.anchorId === message.id ? composerFor(message.id) : null}
</div>
)}
{composing?.anchorId === message.id && !isNewest && composerFor(message.id)}
</Fragment>
);
})}