Files
webmail-client/frontend/src/components/list/MessageList.tsx
T
lukasandClaude Opus 5.5 a2c52f33a8 Offline access: read recent mail without a connection
An opt-in per device (Settings → Security → Offline access) installs a
service worker that keeps the newest 50 Inbox conversations, and the ones
opened recently, for reading when the server cannot be reached. While
online everything still comes from the server; the saved copy is only the
fallback, marked X-WM-Offline so the app knows it is offline.

Offline, an amber cloud next to the theme toggle says so and when mail was
last saved; actions that need the server are greyed out and say "Not
available offline"; conversations and folders not saved here are faded or
say so. A probe notices the server coming back, shows "Back online" and
refreshes everything. Saved mail is wiped on sign-out, on any 401, and when
another user signs in. nginx never caches /sw.js, so releases reach it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 18:54:17 +02:00

419 lines
18 KiB
TypeScript

import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { useVirtualizer } from "@tanstack/react-virtual";
import { useEffect, useRef } from "react";
import { useT } from "../../i18n";
import { api } from "../../lib/api";
import { useSavedThreads } from "../../lib/offline";
import { formatClock, getDateLocale } from "../../lib/timeFormat";
import type { Address, ThreadSummary } from "../../lib/types";
import { Icon } from "../Icon";
import { AvatarImage } from "../SenderAvatar";
import { LabelChips } from "../mail/LabelChips";
function timeLabel(iso: string): string {
const d = new Date(iso);
const now = new Date();
if (d.toDateString() === now.toDateString()) return formatClock(d);
if (d.getFullYear() === now.getFullYear())
return d.toLocaleDateString(getDateLocale(), { month: "short", day: "numeric" });
return d.toLocaleDateString(getDateLocale(), { year: "2-digit", month: "short", day: "numeric" });
}
// Stable per-sender hue so a sender's avatar keeps a consistent colour.
function hue(key: string): number {
let h = 0;
for (let i = 0; i < key.length; i++) h = (h * 31 + key.charCodeAt(i)) % 360;
return h;
}
function initials(p: Address | undefined): string {
const name = (p?.name || p?.email || "?").trim();
const words = name.split(/\s+/).filter(Boolean);
if (words.length >= 2) return (words[0][0] + words[words.length - 1][0]).toUpperCase();
return name.slice(0, 2).toUpperCase();
}
// Past this many characters the sender column switches to first names only.
const SENDERS_FULL_MAX = 25;
// A lone sender's name longer than this is cut to one character less plus "...".
const SINGLE_SENDER_MAX = 22;
// The sender column's text. A single sender shows in full, or cut at
// SINGLE_SENDER_MAX. Several show as full names joined, or — when that would run
// past SENDERS_FULL_MAX — each sender's first word ("Alice Smith" -> "Alice", a
// bare address -> its local part). The user's own accounts are always `me`.
export function senderNames(
senders: Address[],
isMe: (a: Address) => boolean,
me: string,
): string {
if (senders.length === 1) {
const [a] = senders;
const name = isMe(a) ? me : a.name || a.email;
return name.length > SINGLE_SENDER_MAX ? `${name.slice(0, SINGLE_SENDER_MAX - 1)}...` : name;
}
const full = senders.map((a) => (isMe(a) ? me : a.name || a.email)).join(", ");
if (full.length <= SENDERS_FULL_MAX) return full;
return senders
.map((a) => {
if (isMe(a)) return me;
const name = a.name.trim();
return name ? name.split(/\s+/)[0] : a.email.split("@")[0];
})
.join(", ");
}
// Monocolor paperclip (inherits currentColor) — replaces the old emoji.
function Paperclip() {
return (
<svg
width="17"
height="17"
viewBox="0 0 16 16"
fill="none"
stroke="currentColor"
strokeWidth="1.4"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
className="shrink-0"
>
<path d="M12.5 6.5l-5.2 5.2a2.5 2.5 0 0 1-3.5-3.5l5.4-5.4a1.6 1.6 0 0 1 2.3 2.3l-5.3 5.3a0.8 0.8 0 0 1-1.1-1.1l4.9-4.9" />
</svg>
);
}
// Virtualized thread list (SPEC §2 list/MessageList.tsx).
export function MessageList({
threads,
page,
selectedId,
folder,
onSelect,
onArchive,
onRestore,
onTrash,
onDeletePermanent,
onTogglePin,
checkedIds,
dimmedIds,
onToggleCheck,
compact = false,
}: {
threads: ThreadSummary[];
/** Which page of the list this is. Changing it scrolls back to the top. */
page: number;
selectedId?: string;
folder: string;
onSelect: (id: string) => void;
onArchive: (id: string) => void;
onRestore: (id: string) => void;
onTrash: (id: string) => void;
onDeletePermanent: (id: string) => void;
onTogglePin: (id: string, pinned: boolean) => void;
checkedIds: Set<string>;
dimmedIds?: Set<string>;
onToggleCheck: (id: string) => void;
/** Phone layout: sender, subject and snippet stacked; no hover-only actions. */
compact?: boolean;
}) {
const t = useT();
const parentRef = useRef<HTMLDivElement>(null);
// In Trash/Spam/Archive the middle action restores; elsewhere it archives.
const isRemovalFolder = folder === "trash" || folder === "junk" || folder === "archive";
// Row selection: hovering an avatar reveals a checkbox; once anything is checked,
// every row shows a checkbox (selection mode) until all are cleared.
const checkMode = checkedIds.size > 0;
// Aggregated labels per thread (written by the reading pane) — shown before the subject.
const threadIds = threads.map((th) => th.id);
const labelsQuery = useQuery({
queryKey: ["thread-labels", threadIds],
queryFn: () => api.threadLabelsBatch(threadIds),
enabled: threadIds.length > 0,
// The key changes whenever a row joins or leaves the list; keep the chips
// already known meanwhile, or every subject jumps left and back.
placeholderData: keepPreviousData,
});
const labelMap = labelsQuery.data ?? {};
// Offline: conversations not saved on this device are shown faded.
const saved = useSavedThreads();
// The user's own addresses, shown as "me" in the sender column.
const accounts = useQuery({ queryKey: ["accounts"], queryFn: api.accounts });
const myEmails = new Set((accounts.data ?? []).map((a) => a.email.toLowerCase()));
const isMe = (a: Address) => myEmails.has(a.email.toLowerCase());
const virtualizer = useVirtualizer({
count: threads.length,
getScrollElement: () => parentRef.current,
// 68 row + the gap above it: 7px, 20px on a phone.
estimateSize: () => 68 + (compact ? 20 : 7),
overscan: 8,
});
// A new page starts at the top. Paging while scrolled down would otherwise
// drop you into the middle of the next fifty with no sense of having moved.
useEffect(() => {
parentRef.current?.scrollTo({ top: 0 });
}, [page]);
if (threads.length === 0) {
return <div className="p-6 text-[15px] text-app-faint">{t("mail.noConversations")}</div>;
}
return (
<div ref={parentRef} className="h-full overflow-y-auto" data-testid="message-list">
<div style={{ height: virtualizer.getTotalSize(), position: "relative", width: "100%" }}>
{virtualizer.getVirtualItems().map((item) => {
const thread = threads[item.index];
const unread = thread.unread_count > 0;
const selected = selectedId === thread.id;
const checked = checkedIds.has(thread.id);
const dimmed = dimmedIds?.has(thread.id) ?? false;
const unsaved = saved !== null && !saved.has(thread.id);
// The sender column lists everyone who wrote in the thread, oldest first,
// with the user's own accounts shown as "me" — so a thread you started
// and someone answered reads "me, Alice". Recipients are not listed.
const senders = thread.senders.length ? thread.senders : thread.participants.slice(0, 1);
const names = senders.length ? senderNames(senders, isMe, t("mail.me")) : "(no one)";
// The avatar is the other side of the conversation where there is one.
const primary = senders.find((a) => !isMe(a)) ?? senders[0];
// The badge still counts everyone involved — the name is narrowed, the
// "how many people are in this" signal is not.
const extra = Math.max(0, thread.participants.length - 1);
const avatarBg = `hsl(${hue(primary?.email || primary?.name || "?")} 45% 45%)`;
const stop = (fn: () => void) => (e: React.MouseEvent) => {
e.stopPropagation();
fn();
};
return (
<div
key={thread.id}
role="button"
tabIndex={dimmed ? -1 : 0}
aria-disabled={dimmed}
onClick={() => !dimmed && onSelect(thread.id)}
onKeyDown={(e) => {
if (!dimmed && (e.key === "Enter" || e.key === " ")) onSelect(thread.id);
}}
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: item.size,
transform: `translateY(${item.start}px)`,
}}
// A row leaving the list lets the ones below glide up into its place.
className={`group absolute inset-x-0 px-2 ${compact ? "pt-5" : "pt-[7px]"} motion-safe:transition-transform motion-safe:duration-200 motion-safe:ease-out ${
dimmed ? "pointer-events-none opacity-40" : "cursor-pointer"
} ${unsaved ? "opacity-45" : ""}`}
>
<div
className={`flex h-full items-center gap-3 rounded-lg px-3 ${
selected || checked ? "bg-app-active" : "group-hover:bg-app-hover"
}`}
>
{/* Avatar, replaced by a selection checkbox on avatar-hover or once
selection mode is active. An unread dot sits in the left margin. */}
<div className="group/av relative ml-5 h-[33px] w-[33px] shrink-0">
{unread && (
<span
aria-hidden
className="absolute -left-[21px] top-1/2 h-2 w-2 -translate-y-1/2 rounded-full bg-app-accent"
/>
)}
<div
className={
checkMode ? "hidden" : compact ? "contents" : "contents group-hover/av:hidden"
}
>
<span
className="relative flex h-[33px] w-[33px] items-center justify-center overflow-hidden rounded-full text-[13px] font-semibold text-white"
style={{ backgroundColor: avatarBg }}
>
{initials(primary)}
<AvatarImage email={primary?.email} />
</span>
{extra > 0 && (
<span className="absolute -bottom-1 -left-1.5 rounded-full bg-app-hover px-1 text-[10px] font-medium text-app-muted ring-2 ring-app-surface">
+{extra}
</span>
)}
</div>
<button
type="button"
aria-label={t("mail.select")}
aria-pressed={checked}
onClick={stop(() => onToggleCheck(thread.id))}
// No hover on a touch screen: the avatar itself is the (invisible)
// selection target until selection mode shows the boxes.
className={`absolute inset-0 items-center justify-center ${
checkMode ? "flex" : compact ? "flex opacity-0" : "hidden group-hover/av:flex"
}`}
>
<span
className={`flex h-[17px] w-[17px] items-center justify-center rounded-md border-2 transition-colors ${
checked
? "border-app-accent bg-app-accent text-white"
: "border-app-faint hover:border-app-muted"
}`}
>
{checked && (
<svg width="11" height="11" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round">
<path d="M3.5 8.5l3 3 6-7" />
</svg>
)}
</span>
</button>
</div>
{compact ? (
<div className="flex min-w-0 flex-1 flex-col justify-center">
<div className="flex min-w-0 items-center gap-1.5">
<span
className={`min-w-0 truncate text-[15px] ${
unread ? "font-black text-app-fg" : "text-app-fg"
}`}
>
{names}
</span>
{thread.message_count > 1 && (
<span className="shrink-0 rounded-full bg-app-hover px-1.5 text-[12px] text-app-muted">
{thread.message_count}
</span>
)}
<span className="ml-auto flex shrink-0 items-center gap-1.5 pl-2 text-app-faint">
{thread.has_attachments && <Paperclip />}
{thread.pinned && (
<Icon name="pin" size={15} className="text-[rgb(220_129_143)]" />
)}
<span
className={`whitespace-nowrap text-[13px] tabular-nums ${
unread ? "font-bold" : ""
}`}
>
{timeLabel(thread.last_message_at)}
</span>
</span>
</div>
<div
className={`flex min-w-0 items-center gap-1.5 text-[14px] ${
unread ? "font-black text-app-fg" : "text-app-fg"
}`}
>
<LabelChips labels={labelMap[thread.id] ?? []} />
<span className="truncate">{thread.subject}</span>
</div>
<div className="truncate text-xs text-app-faint">{thread.snippet}</div>
</div>
) : (
<>
{/* Sender column */}
<div className="flex w-[200px] min-w-0 shrink items-center gap-1.5">
<span
className={`truncate text-[15px] ${
unread ? "font-black text-app-fg" : "text-app-fg"
}`}
>
{names}
</span>
{thread.message_count > 1 && (
<span className="shrink-0 rounded-full bg-app-hover px-1.5 text-[12px] text-app-muted">
{thread.message_count}
</span>
)}
</div>
{/* Subject + snippet (extra left margin -> 3x the gap to the sender). */}
<div className="ml-6 flex min-w-0 flex-1 flex-col justify-center">
<div
className={`flex min-w-0 items-center gap-1.5 text-[14px] ${
unread ? "font-black text-app-fg" : "text-app-fg"
}`}
>
<LabelChips labels={labelMap[thread.id] ?? []} />
<span className="truncate">{thread.subject}</span>
</div>
<div className="truncate text-xs text-app-faint">{thread.snippet}</div>
</div>
{/* Right rail: four evenly-spaced icons, vertically centred. The
paperclip and pin keep fixed slots (archive/trash reserve their
space while hidden), and the date is an overlay on the right that
is simply hidden on hover to reveal archive + trash — so nothing
ever shifts between the normal and hover states. */}
<div className="relative flex shrink-0 items-center justify-end gap-5">
{/* Attachment: fixed slot (reserved even when empty) so the rail
width — and thus the excerpt width — is the same in every row. */}
<span className="flex w-[17px] shrink-0 justify-center text-app-faint">
{thread.has_attachments && <Paperclip />}
</span>
{/* Pin: pink and always shown when pinned; otherwise revealed on hover. */}
<button
type="button"
title={thread.pinned ? t("mail.unpin") : t("mail.pin")}
onClick={stop(() => onTogglePin(thread.id, thread.pinned))}
className={
thread.pinned
? "wm-online-only text-[rgb(220_129_143)]"
: "wm-online-only invisible text-app-muted hover:text-app-fg group-hover:visible"
}
>
<Icon name="pin" size={17} />
</button>
{/* Archive (or Restore in Trash/Spam/Archive) + delete: hover-only,
but reserve their slots always. In Trash, delete is permanent. */}
{isRemovalFolder ? (
<button
type="button"
title={t("mail.restore")}
onClick={stop(() => onRestore(thread.id))}
className="wm-online-only invisible text-app-muted hover:text-app-fg group-hover:visible"
>
<Icon name="restore" size={17} />
</button>
) : (
<button
type="button"
title={t("mail.archive")}
onClick={stop(() => onArchive(thread.id))}
className="wm-online-only invisible text-app-muted hover:text-app-fg group-hover:visible"
>
<Icon name="archive" size={15} />
</button>
)}
<button
type="button"
title={t("mail.delete")}
onClick={stop(() =>
folder === "trash" ? onDeletePermanent(thread.id) : onTrash(thread.id),
)}
className="wm-online-only invisible mr-[7px] text-app-muted hover:text-app-fg group-hover:visible"
>
<Icon name="trash" size={17} />
</button>
{/* Date overlay, aligned to the right edge (over the archive/trash
slots); hidden on hover so the actions show through. */}
<span
className={`absolute inset-y-0 right-0 flex items-center whitespace-nowrap text-[13px] tabular-nums text-app-faint group-hover:hidden ${
unread ? "font-bold" : ""
}`}
>
{timeLabel(thread.last_message_at)}
</span>
</div>
</>
)}
</div>
</div>
);
})}
</div>
</div>
);
}