Skip to content

Email for professionals and teams

Translate message list, reader, actions and snooze UI

Hieu Nguyen (Jack)23e49056b4f5
diff --git a/src/components/message-actions/message-actions.tsx b/src/components/message-actions/message-actions.tsx
index b5e59a3..88d06ff 100644
--- a/src/components/message-actions/message-actions.tsx
+++ b/src/components/message-actions/message-actions.tsx
@@ -3,6 +3,7 @@
import { createElement, useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import { Archive, Ban, BellOff, Clock, FileCode2, Forward, Mail, MailOpen, MoreVertical, Reply, ReplyAll, ShieldAlert, Trash2 } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
import { useCompose } from "@/components/compose/compose-context";
import { MessageSourceDialog } from "@/components/messages/message-source-dialog";
import { MessageSnoozeDialog } from "./message-snooze-dialog";
@@ -45,6 +46,7 @@ export function MessageActions({
messageMeta,
bodyHtml,
}: MessageActionsProps) {
+ const { t } = useLanguage();
const router = useRouter();
const isMobile = useIsMobile();
const { openDraftComposer } = useCompose();
@@ -67,17 +69,17 @@ export function MessageActions({
if (redirect) router.push(redirect);
router.refresh();
} catch {
- setError("Could not update message");
+ setError(t("actions.error.update"));
} finally {
setPendingAction(null);
}
- }, [messageId, direction, router]);
+ }, [messageId, direction, router, t]);
// In Trash and Spam the delete button removes the message for good instead of
// being a no-op, after the user confirms.
const canDeleteForever = supportsPermanentDelete(status);
const deleteForever = useCallback(async () => {
- if (!window.confirm(getPermanentDeleteConfirmText(1))) return;
+ if (!window.confirm(getPermanentDeleteConfirmText(1, t))) return;
setMoreOpen(false);
setPendingAction("delete");
setError(null);
@@ -86,12 +88,12 @@ export function MessageActions({
router.push(getMessageBackHref(direction, status));
router.refresh();
} catch {
- setError("Could not delete message");
+ setError(t("actions.error.delete"));
setPendingAction(null);
}
- }, [messageId, direction, status, router]);
+ }, [messageId, direction, status, router, t]);
const onTrashClick = () => (canDeleteForever ? void deleteForever() : void runAction("trash"));
- const trashLabel = canDeleteForever ? "Delete forever" : "Move to trash";
+ const trashLabel = canDeleteForever ? t("common.deleteForever") : t("actions.moveToTrash");
const replyable = useMemo(() => message ?? {
direction,
@@ -121,17 +123,17 @@ export function MessageActions({
});
openDraftComposer(draftId);
} catch (replyError) {
- setError(replyError instanceof Error ? replyError.message : "Could not start reply");
+ setError(replyError instanceof Error ? replyError.message : t("message.error.reply"));
} finally {
setPendingAction(null);
}
- }, [mailboxId, senderAddress, ownAddress, subject, bodyText, bodyHtml, messageMeta?.createdAt, replyable, ownAddresses, openDraftComposer]);
+ }, [mailboxId, senderAddress, ownAddress, subject, bodyText, bodyHtml, messageMeta?.createdAt, replyable, ownAddresses, openDraftComposer, t]);
const shortcuts = useMemo(
() => [
{
key: "e",
- label: "Archive Message",
+ label: t("shortcut.archiveMessage"),
category: "Actions" as const,
action: () => {
if (status !== "archived") void runAction("archive");
@@ -139,7 +141,7 @@ export function MessageActions({
},
{
key: "y",
- label: "Archive Message",
+ label: t("shortcut.archiveMessage"),
category: "Actions" as const,
action: () => {
if (status !== "archived") void runAction("archive");
@@ -147,7 +149,7 @@ export function MessageActions({
},
{
key: "#",
- label: "Move to Trash",
+ label: t("shortcut.moveToTrash"),
category: "Actions" as const,
action: () => {
if (status !== "trash") void runAction("trash");
@@ -155,13 +157,13 @@ export function MessageActions({
},
{
key: "r",
- label: "Reply to Message",
+ label: t("shortcut.replyToMessage"),
category: "Composing" as const,
action: () => void handleReply("reply"),
},
{
key: "!",
- label: "Report Spam",
+ label: t("shortcut.reportSpam"),
category: "Actions" as const,
action: () => {
if (status !== "spam" && direction === "inbound") void runAction("spam");
@@ -169,12 +171,12 @@ export function MessageActions({
},
{
key: "u",
- label: "Back to List",
+ label: t("shortcut.backToList"),
category: "Navigation" as const,
action: () => router.back(),
},
],
- [status, direction, runAction, handleReply, router]
+ [status, direction, runAction, handleReply, router, t]
);
useHotkeys(shortcuts, { enabled: shortcutsEnabled });
@@ -190,7 +192,7 @@ export function MessageActions({
if (!confirmTrashWithoutUnsubscribe()) return;
setPendingAction("unsubscribe");
if (!mailboxId) {
- setError("Could not create trash rule");
+ setError(t("actions.error.trashRule"));
setPendingAction(null);
return;
}
@@ -199,7 +201,7 @@ export function MessageActions({
await createTrashSenderRule({ mailboxId, senderAddress });
await runAction("trash");
} catch {
- setError("Could not create trash rule");
+ setError(t("actions.error.trashRule"));
setPendingAction(null);
}
}
@@ -218,7 +220,7 @@ export function MessageActions({
});
openDraftComposer(draftId);
} catch (forwardError) {
- setError(forwardError instanceof Error ? forwardError.message : "Could not start forward");
+ setError(forwardError instanceof Error ? forwardError.message : t("message.error.forward"));
} finally {
setPendingAction(null);
}
@@ -227,7 +229,7 @@ export function MessageActions({
setMoreOpen(false);
setError(null);
if (!mailboxId) {
- setError("Could not block contact");
+ setError(t("message.error.block"));
return;
}
@@ -238,7 +240,7 @@ export function MessageActions({
router.push("/trash");
router.refresh();
} catch (blockError) {
- setError(blockError instanceof Error ? blockError.message : "Could not block contact");
+ setError(blockError instanceof Error ? blockError.message : t("message.error.block"));
} finally {
setPendingAction(null);
}
@@ -258,7 +260,7 @@ export function MessageActions({
type="button"
variant="ghost"
size="roundedSM"
- aria-label="Reply"
+ aria-label={t("message.reply")}
disabled={disabled}
onClick={() => handleReply("reply")}
>
@@ -276,7 +278,7 @@ export function MessageActions({
<Button
variant="ghost"
size="roundedSM"
- aria-label="Report spam"
+ aria-label={t("common.reportSpam")}
disabled={disabled || status === "spam" || direction !== "inbound"}
onClick={() => runAction("spam")}
>
@@ -286,33 +288,33 @@ export function MessageActions({
)}
{!isMobile && (
<>
- <Tooltip label={shortcutsEnabled ? "Archive (e)" : "Archive"}>
+ <Tooltip label={shortcutsEnabled ? t("actions.archiveHint") : t("common.archive")}>
<Button
variant="ghost"
size="roundedSM"
- aria-label={shortcutsEnabled ? "Archive (e)" : "Archive"}
+ aria-label={shortcutsEnabled ? t("actions.archiveHint") : t("common.archive")}
disabled={disabled || status === "archived"}
onClick={() => runAction("archive")}
>
<Archive size={iconSize} />
</Button>
</Tooltip>
- <Tooltip label={shortcutsEnabled ? "Report spam (!)" : "Report spam"}>
+ <Tooltip label={shortcutsEnabled ? t("actions.reportSpamHint") : t("common.reportSpam")}>
<Button
variant="ghost"
size="roundedSM"
- aria-label={shortcutsEnabled ? "Report spam (!)" : "Report spam"}
+ aria-label={shortcutsEnabled ? t("actions.reportSpamHint") : t("common.reportSpam")}
disabled={disabled || status === "spam" || direction !== "inbound"}
onClick={() => runAction("spam")}
>
<ShieldAlert size={iconSize} />
</Button>
</Tooltip>
- <Tooltip label={canDeleteForever ? "Delete forever" : shortcutsEnabled ? "Delete (#)" : "Delete"}>
+ <Tooltip label={canDeleteForever ? t("common.deleteForever") : shortcutsEnabled ? t("actions.deleteHint") : t("common.delete")}>
<Button
variant="ghost"
size="roundedSM"
- aria-label={canDeleteForever ? trashLabel : shortcutsEnabled ? "Move to trash (#)" : "Move to trash"}
+ aria-label={canDeleteForever ? trashLabel : shortcutsEnabled ? t("actions.moveToTrashHint") : t("actions.moveToTrash")}
disabled={disabled}
onClick={onTrashClick}
className={canDeleteForever ? "text-red-600 hover:text-red-700" : undefined}
@@ -323,12 +325,12 @@ export function MessageActions({
<span className="h-5 mx-2 bg-gray-200 w-px inline-block" />
- <Tooltip label={shortcutsEnabled ? "Reply (r)" : "Reply"}>
+ <Tooltip label={shortcutsEnabled ? t("actions.replyHint") : t("message.reply")}>
<Button
type="button"
variant="ghost"
size="roundedSM"
- aria-label={shortcutsEnabled ? "Reply (r)" : "Reply"}
+ aria-label={shortcutsEnabled ? t("actions.replyHint") : t("message.reply")}
disabled={disabled}
onClick={() => handleReply("reply")}
>
@@ -336,12 +338,12 @@ export function MessageActions({
</Button>
</Tooltip>
{canReplyAll && (
- <Tooltip label="Reply all">
+ <Tooltip label={t("message.replyAll")}>
<Button
type="button"
variant="ghost"
size="roundedSM"
- aria-label="Reply all"
+ aria-label={t("message.replyAll")}
disabled={disabled}
onClick={() => handleReply("replyAll")}
>
@@ -350,12 +352,12 @@ export function MessageActions({
</Tooltip>
)}
{message && messageMeta && (
- <Tooltip label="Forward">
+ <Tooltip label={t("message.forward")}>
<Button
type="button"
variant="ghost"
size="roundedSM"
- aria-label="Forward"
+ aria-label={t("message.forward")}
disabled={disabled}
onClick={() => void handleForward()}
>
@@ -364,11 +366,11 @@ export function MessageActions({
</Tooltip>
)}
- <Tooltip label={read ? "Mark as unread" : "Mark as read"}>
+ <Tooltip label={read ? t("common.markUnread") : t("common.markRead")}>
<Button
variant="ghost"
size="roundedSM"
- aria-label={read ? "Mark as unread" : "Mark as read"}
+ aria-label={read ? t("common.markUnread") : t("common.markRead")}
disabled={disabled}
onClick={() => runAction(markAction)}
>
@@ -378,12 +380,12 @@ export function MessageActions({
</>
)}
<div className="relative">
- <Tooltip label="More actions">
+ <Tooltip label={t("common.moreActions")}>
<Button
type="button"
variant="ghost"
size="roundedSM"
- aria-label="More actions"
+ aria-label={t("common.moreActions")}
aria-expanded={moreOpen}
disabled={disabled}
onClick={() => setMoreOpen((open) => !open)}
@@ -399,23 +401,23 @@ export function MessageActions({
<>
<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 disabled:text-neutral-400" disabled={status === "archived"} onClick={() => void runAction("archive")}>
<Archive className="h-4 w-4" />
- Archive
+ {t("common.archive")}
</button>
{canReplyAll && (
<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 disabled:text-neutral-400" onClick={() => { setMoreOpen(false); void handleReply("replyAll"); }}>
<ReplyAll className="h-4 w-4" />
- Reply all
+ {t("message.replyAll")}
</button>
)}
{message && messageMeta && (
<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 disabled:text-neutral-400" onClick={() => { setMoreOpen(false); void handleForward(); }}>
<Forward className="h-4 w-4" />
- Forward
+ {t("message.forward")}
</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 disabled:text-neutral-400" onClick={() => void runAction(markAction)}>
{read ? <Mail className="h-4 w-4" /> : <MailOpen className="h-4 w-4" />}
- {read ? "Mark as unread" : "Mark as read"}
+ {read ? t("common.markUnread") : t("common.markRead")}
</button>
<hr className="my-1 border-neutral-100" />
</>
@@ -427,7 +429,7 @@ export function MessageActions({
onClick={() => { setMoreOpen(false); setSnoozeOpen(true); }}
>
<Clock className="h-4 w-4" />
- Snooze
+ {t("common.snooze")}
</button>
)}
{direction === "inbound" && (
@@ -439,7 +441,7 @@ export function MessageActions({
onClick={() => void onUnsubscribe()}
>
<BellOff className="h-4 w-4 shrink-0" />
- Unsubscribe
+ {t("actions.unsubscribe")}
</button>
<button
type="button"
@@ -447,7 +449,7 @@ export function MessageActions({
onClick={() => void onBlockContact()}
>
<Ban className="h-4 w-4" />
- Block contact
+ {t("message.blockContact")}
</button>
<hr className="my-1 border-neutral-100" />
</>
@@ -458,11 +460,11 @@ export function MessageActions({
onClick={() => { setMoreOpen(false); setSourceOpen(true); }}
>
<FileCode2 className="h-4 w-4" />
- Show original
+ {t("message.showOriginal")}
</button>
<hr className="my-1 border-neutral-100" />
<p className="mt-1 px-3 pb-1 pt-2 text-sm font-medium text-neutral-500">
- Move to
+ {t("common.moveTo")}
</p>
{moveActions.map((item) => (
<button
@@ -472,7 +474,7 @@ export function MessageActions({
onClick={() => void runAction(item.action)}
>
{createElement(item.icon, { size: 16 })}
- {item.label}
+ {t(item.labelKey)}
</button>
))}
</div>
diff --git a/src/components/message-actions/message-snooze-dialog.tsx b/src/components/message-actions/message-snooze-dialog.tsx
index 651abd3..a336bb5 100644
--- a/src/components/message-actions/message-snooze-dialog.tsx
+++ b/src/components/message-actions/message-snooze-dialog.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import { getSnoozePresets, snoozeMessage } from "@/components/messages/message-list-row-actions-utils";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -9,6 +10,7 @@ import type { MessageSnoozeDialogProps } from "./types";
import { getUserTimeZone } from "@/lib/time/utils";
export function MessageSnoozeDialog({ messageId, open, onOpenChange }: MessageSnoozeDialogProps) {
+ const { t } = useLanguage();
const [snoozedUntil, setSnoozedUntil] = useState(() => getSnoozePresets()[0].value);
const [snoozing, setSnoozing] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -21,7 +23,7 @@ export function MessageSnoozeDialog({ messageId, open, onOpenChange }: MessageSn
await snoozeMessage(messageId, snoozedUntil);
onOpenChange(false);
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Unable to snooze message");
+ setError(nextError instanceof Error ? nextError.message : t("snooze.failed"));
} finally {
setSnoozing(false);
}
@@ -31,24 +33,24 @@ export function MessageSnoozeDialog({ messageId, open, onOpenChange }: MessageSn
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
- <DialogTitle>Snooze email</DialogTitle>
- <DialogDescription>Hide this email from the inbox until the time you choose.</DialogDescription>
+ <DialogTitle>{t("snooze.title")}</DialogTitle>
+ <DialogDescription>{t("snooze.description")}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="grid gap-2 sm:grid-cols-3">
{snoozePresets.map((preset) => (
- <Button key={preset.label} type="button" variant="outline" size="sm" onClick={() => setSnoozedUntil(preset.value)}>
- {preset.label}
+ <Button key={preset.labelKey} type="button" variant="outline" size="sm" onClick={() => setSnoozedUntil(preset.value)}>
+ {t(preset.labelKey)}
</Button>
))}
</div>
<div className="space-y-2">
- <label htmlFor={`header-snooze-until-${messageId}`} className="text-sm font-medium text-neutral-700">Select date and time ({getUserTimeZone()})</label>
+ <label htmlFor={`header-snooze-until-${messageId}`} className="text-sm font-medium text-neutral-700">{t("snooze.selectDateTime", { timeZone: getUserTimeZone() })}</label>
<Input id={`header-snooze-until-${messageId}`} type="datetime-local" value={snoozedUntil} onChange={(event) => setSnoozedUntil(event.target.value)} />
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<Button type="button" onClick={() => void handleSnooze()} disabled={snoozing}>
- {snoozing ? "Snoozing..." : "Snooze"}
+ {snoozing ? t("common.snoozing") : t("common.snooze")}
</Button>
</div>
</DialogContent>
diff --git a/src/components/message-actions/types.d.ts b/src/components/message-actions/types.d.ts
index 1508ca3..ef9792f 100644
--- a/src/components/message-actions/types.d.ts
+++ b/src/components/message-actions/types.d.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from "@/lib/i18n/types";
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
import type { Message, MessageDirection } from "@/hooks/types";
import { IconNode } from "lucide-react";
@@ -78,6 +79,6 @@ export type BlockMessageContactInput = {
export type MoveMessageActionItem = {
action: BulkMessageAction;
- label: string;
+ labelKey: TranslationKey;
icon: any
};
diff --git a/src/components/message-actions/utils.ts b/src/components/message-actions/utils.ts
index 4a248e6..699f186 100644
--- a/src/components/message-actions/utils.ts
+++ b/src/components/message-actions/utils.ts
@@ -108,14 +108,14 @@ export function getMoveMessageActions(
): MoveMessageActionItem[] {
const actions: MoveMessageActionItem[] = [];
if ((status === "archived" || status === "spam") && direction === "inbound") {
- actions.push({ action: "inbox", label: status === "spam" ? "Not spam" : "Inbox", icon: InboxIcon });
+ actions.push({ action: "inbox", labelKey: status === "spam" ? "common.notSpam" : "navigation.inbox", icon: InboxIcon });
}
if (status !== "archived")
- actions.push({ action: "archive", label: "Archived", icon: ArchiveIcon });
+ actions.push({ action: "archive", labelKey: "navigation.archived", icon: ArchiveIcon });
if (status !== "spam")
- actions.push({ action: "spam", label: "Spam", icon: ShieldAlertIcon });
+ actions.push({ action: "spam", labelKey: "navigation.spam", icon: ShieldAlertIcon });
if (status !== "trash")
- actions.push({ action: "trash", label: "Trash", icon: Trash2Icon });
+ actions.push({ action: "trash", labelKey: "navigation.trash", icon: Trash2Icon });
return actions;
}
diff --git a/src/components/messages/bulk-message-selection-pane.tsx b/src/components/messages/bulk-message-selection-pane.tsx
index cfe3033..ca7c9c7 100644
--- a/src/components/messages/bulk-message-selection-pane.tsx
+++ b/src/components/messages/bulk-message-selection-pane.tsx
@@ -3,6 +3,7 @@
import { CheckSquare2 } from "lucide-react";
import { useState } from "react";
import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
+import { useLanguage } from "@/components/language-provider";
import { BulkMessageToolbar } from "./bulk-message-toolbar";
import type { BulkMessageSelectionPaneProps } from "./types";
import { runBulkMessageAction } from "./utils";
@@ -12,6 +13,7 @@ export function BulkMessageSelectionPane({
selectedMessages,
onClearSelection,
}: BulkMessageSelectionPaneProps) {
+ const { t } = useLanguage();
const [pending, setPending] = useState(false);
const hasUnreadSelection = selectedMessages.some((message) => !message.read);
@@ -39,10 +41,10 @@ export function BulkMessageSelectionPane({
<CheckSquare2 className="h-6 w-6" />
</div>
<h2 className="mt-4 text-lg font-semibold text-neutral-900">
- {selectedMessages.length} selected
+ {t("common.selectedCount", { count: selectedMessages.length })}
</h2>
<p className="mt-1 text-sm text-neutral-500">
- Choose an action to apply to the selected emails.
+ {t("common.chooseBulkAction")}
</p>
<div className="mt-5 rounded-xl border border-neutral-200 bg-white p-3 shadow-sm">
<BulkMessageToolbar
diff --git a/src/components/messages/bulk-message-toolbar.tsx b/src/components/messages/bulk-message-toolbar.tsx
index fcfa474..a6fea01 100644
--- a/src/components/messages/bulk-message-toolbar.tsx
+++ b/src/components/messages/bulk-message-toolbar.tsx
@@ -2,6 +2,7 @@
import { Archive, ArchiveRestore, ChevronDown, Folder, FolderInput, Inbox, Mail, MailOpen, MoreVertical, ShieldAlert, ShieldCheck, Trash2, Undo2, X } from "lucide-react";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { useSelectedMailbox } from "@/components/mailbox-provider";
import { useMailboxFolders } from "./use-mailbox-folders";
@@ -23,23 +24,24 @@ export function BulkMessageToolbar({
pending,
folder,
}: BulkMessageToolbarProps) {
+ const { t } = useLanguage();
// In archived, spam and trash the usual button would be a no-op, so it becomes the way back to the inbox.
const archive = folder === "archived"
- ? { action: "inbox", label: "Unarchive", Icon: ArchiveRestore }
- : { action: "archive", label: "Archive", Icon: Archive };
+ ? { action: "inbox", label: t("common.unarchive"), Icon: ArchiveRestore }
+ : { action: "archive", label: t("common.archive"), Icon: Archive };
const spam = folder === "spam"
- ? { action: "inbox", label: "Not spam", Icon: ShieldCheck }
- : { action: "spam", label: "Report spam", Icon: ShieldAlert };
+ ? { action: "inbox", label: t("common.notSpam"), Icon: ShieldCheck }
+ : { action: "spam", label: t("common.reportSpam"), Icon: ShieldAlert };
const trash = folder === "trash"
- ? { action: "inbox", label: "Restore", Icon: Undo2 }
- : { action: "trash", label: "Delete", Icon: Trash2 };
+ ? { action: "inbox", label: t("common.restore"), Icon: Undo2 }
+ : { action: "trash", label: t("common.delete"), Icon: Trash2 };
// Trash and Spam also offer the irreversible delete; the page confirms before running it.
const canDeleteForever = supportsPermanentDelete(folder);
const moveOptions = [
- { value: "inbox", label: "Inbox", Icon: Inbox, hidden: !folder || folder === "inbox" },
- { value: "archive", label: "Archived", Icon: Archive, hidden: folder === "archived" },
- { value: "spam", label: "Spam", Icon: ShieldAlert, hidden: folder === "spam" },
- { value: "trash", label: "Trash", Icon: Trash2, hidden: folder === "trash" },
+ { value: "inbox", label: t("navigation.inbox"), Icon: Inbox, hidden: !folder || folder === "inbox" },
+ { value: "archive", label: t("navigation.archived"), Icon: Archive, hidden: folder === "archived" },
+ { value: "spam", label: t("navigation.spam"), Icon: ShieldAlert, hidden: folder === "spam" },
+ { value: "trash", label: t("navigation.trash"), Icon: Trash2, hidden: folder === "trash" },
].filter((option) => !option.hidden);
const { selectedMailbox } = useSelectedMailbox();
const folders = useMailboxFolders(selectedMailbox?.id);
@@ -47,7 +49,7 @@ export function BulkMessageToolbar({
<div className="flex min-w-0 items-center gap-2 text-neutral-600 w-full">
{!hideSelectedCount && (
<span className="mr-2 text-sm font-medium text-neutral-800">
- {selectedCount} selected
+ {t("common.selectedCount", { count: selectedCount })}
</span>
)}
<span className="flex-1 md:hidden" />
@@ -67,30 +69,30 @@ export function BulkMessageToolbar({
</Button>
</Tooltip>
{canDeleteForever && (
- <Tooltip label="Delete forever">
- <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700" onClick={() => onAction("delete")} disabled={pending} aria-label="Delete forever">
+ <Tooltip label={t("common.deleteForever")}>
+ <Button variant="ghost" size="sm" className="text-red-600 hover:text-red-700" onClick={() => onAction("delete")} disabled={pending} aria-label={t("common.deleteForever")}>
<Trash2 className="h-4 w-4" />
</Button>
</Tooltip>
)}
- <Tooltip label={hasUnreadSelection ? "Mark as read" : "Mark as unread"}>
+ <Tooltip label={hasUnreadSelection ? t("common.markRead") : t("common.markUnread")}>
<Button
variant="ghost"
size="sm"
onClick={() => onAction(hasUnreadSelection ? "read" : "unread")}
disabled={pending}
- aria-label={hasUnreadSelection ? "Mark as read" : "Mark as unread"}
+ aria-label={hasUnreadSelection ? t("common.markRead") : t("common.markUnread")}
>
{hasUnreadSelection ? <MailOpen className="h-4 w-4" /> : <Mail className="h-4 w-4" />}
</Button>
</Tooltip>
<span className="flex-1 max-md:hidden" />
<DropdownMenu.Root>
- <Tooltip label="Move selected messages" className="max-md:hidden">
+ <Tooltip label={t("common.moveSelected")} className="max-md:hidden">
<DropdownMenu.Trigger asChild>
- <Button variant="ghost" size="sm" className="max-md:hidden gap-1.5 bg-white text-xs font-medium text-neutral-700" disabled={pending} aria-label="Move selected messages">
+ <Button variant="ghost" size="sm" className="max-md:hidden gap-1.5 bg-white text-xs font-medium text-neutral-700" disabled={pending} aria-label={t("common.moveSelected")}>
<FolderInput className="h-4 w-4" />
- Move to
+ {t("common.moveTo")}
<ChevronDown className="h-3.5 w-3.5 text-neutral-500" />
</Button>
</DropdownMenu.Trigger>
@@ -103,7 +105,7 @@ export function BulkMessageToolbar({
{folders.length > 0 && (
<>
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
- <DropdownMenu.Label className={menuLabelClass}>Folders</DropdownMenu.Label>
+ <DropdownMenu.Label className={menuLabelClass}>{t("navigation.folders")}</DropdownMenu.Label>
{folders.map((item) => (
<DropdownMenu.Item key={item.id} className={menuItemClass} onSelect={() => onAction("folder", item.id)}>
<Folder className="h-4 w-4 shrink-0" style={{ color: item.color }} />
@@ -115,14 +117,14 @@ export function BulkMessageToolbar({
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
- <Tooltip label="Clear selection" className="max-md:hidden">
- <Button variant="ghost" size="sm" onClick={onClearSelection} disabled={pending} aria-label="Clear selection">
+ <Tooltip label={t("common.clearSelection")} className="max-md:hidden">
+ <Button variant="ghost" size="sm" onClick={onClearSelection} disabled={pending} aria-label={t("common.clearSelection")}>
<X className="h-4 w-4" />
</Button>
</Tooltip>
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
- <Button variant="ghost" size="sm" className="md:hidden" disabled={pending} aria-label="More actions">
+ <Button variant="ghost" size="sm" className="md:hidden" disabled={pending} aria-label={t("common.moreActions")}>
<MoreVertical className="h-4 w-4" />
</Button>
</DropdownMenu.Trigger>
@@ -131,10 +133,10 @@ export function BulkMessageToolbar({
<DropdownMenu.Item className={menuItemClass} onSelect={() => onAction(archive.action as BulkMessageAction)}><archive.Icon className="h-4 w-4" />{archive.label}</DropdownMenu.Item>
<DropdownMenu.Item className={menuItemClass} onSelect={() => onAction(spam.action as BulkMessageAction)}><spam.Icon className="h-4 w-4" />{spam.label}</DropdownMenu.Item>
{canDeleteForever && (
- <DropdownMenu.Item className={`${menuItemClass} text-red-600`} onSelect={() => onAction("delete")}><Trash2 className="h-4 w-4" />Delete forever</DropdownMenu.Item>
+ <DropdownMenu.Item className={`${menuItemClass} text-red-600`} onSelect={() => onAction("delete")}><Trash2 className="h-4 w-4" />{t("common.deleteForever")}</DropdownMenu.Item>
)}
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
- <DropdownMenu.Item className={menuItemClass} onSelect={onClearSelection}><X className="h-4 w-4" />Clear selection</DropdownMenu.Item>
+ <DropdownMenu.Item className={menuItemClass} onSelect={onClearSelection}><X className="h-4 w-4" />{t("common.clearSelection")}</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Portal>
</DropdownMenu.Root>
diff --git a/src/components/messages/conversation-thread.tsx b/src/components/messages/conversation-thread.tsx
index f25516c..ee021a5 100644
--- a/src/components/messages/conversation-thread.tsx
+++ b/src/components/messages/conversation-thread.tsx
@@ -9,6 +9,7 @@ import { runSingleMessageAction } from "@/components/message-actions/utils";
import { EmailHtmlRenderer } from "./email-html-renderer";
import { getMessageBodyDisplay, resolveInlineAttachmentUrls } from "@/app/(dashboard)/inbox/[messageId]/utils";
+import { useLanguage } from "@/components/language-provider";
import { cn } from "@/lib/utils";
import type { ConversationMessageCardProps, ConversationThreadProps } from "./conversation-thread-types";
import { ThreadMessageActions } from "./thread-message-actions";
@@ -39,17 +40,18 @@ export function ConversationThread({
onExpandedAllChange,
showFullRecipientAddresses = false,
}: ConversationThreadProps) {
+ const { t } = useLanguage();
const slice = partitionThread(messages, currentMessageId, position, latestMessagesFirst);
if (slice.length === 0) return null;
const firstMessage = slice[0];
const lastMessage = slice.at(-1)!;
const middleMessages = slice.slice(1, -1);
const collapsed = !expandedAll && middleMessages.length > 0;
- const collapsedLabel = `${middleMessages.length} ${position === "before" ? "older" : "newer"} message${middleMessages.length === 1 ? "" : "s"}`;
+ const collapsedLabel = t(position === "before" ? "thread.messagesCollapsed.older" : "thread.messagesCollapsed.newer", { count: middleMessages.length });
return (
<section
- aria-label={position === "before" ? "Earlier messages in this conversation" : "Later messages in this conversation"}
+ aria-label={position === "before" ? t("thread.earlier") : t("thread.later")}
className={cn(position === (latestMessagesFirst ? "before" : "after") ? "pb-6" : "")}
>
<ol className={cn(!collapsed && "divide-y divide-neutral-200/50", latestMessagesFirst ? "border-t" : "border-b", "border-neutral-200")}>
@@ -70,8 +72,8 @@ export function ConversationThread({
<button
type="button"
onClick={() => onExpandedAllChange(true)}
- aria-label={`Expand ${collapsedLabel}`}
- title={`Expand ${collapsedLabel}`}
+ aria-label={t("thread.expand", { label: collapsedLabel })}
+ title={t("thread.expand", { label: collapsedLabel })}
className="inline-flex h-6 w-6 items-center justify-center rounded-full text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900"
>
<ChevronsUpDown className="h-4 w-4" />
@@ -118,6 +120,7 @@ export function ConversationMessageCard({
defaultExpanded = false,
showFullRecipientAddresses = false,
}: ConversationMessageCardProps) {
+ const { t } = useLanguage();
const [locallyExpanded, setLocallyExpanded] = useState(defaultExpanded);
const [locallyRead, setLocallyRead] = useState(message.read);
const expanded = locallyExpanded;
@@ -174,15 +177,15 @@ export function ConversationMessageCard({
{sender}
{expanded && <span className="text-xs ml-1 opacity-50 font-normal">&lt;{senderEmail}&gt;</span>}
</span>
- {expanded && recipients && <span className="text-xs font-normal text-neutral-500">to {recipients}</span>}
+ {expanded && recipients && <span className="text-xs font-normal text-neutral-500">{t("thread.to", { recipients })}</span>}
</div>
{!expanded && (
- <span className={clsx(!locallyRead ? "font-semibold" : "text-neutral-500", "block truncate text-[13px]")}>{message.snippet || "No preview"}</span>
+ <span className={clsx(!locallyRead ? "font-semibold" : "text-neutral-500", "block truncate text-[13px]")}>{message.snippet || t("thread.noPreview")}</span>
)}
</span>
</button>
<span className={clsx(!locallyRead ? "font-semibold" : "", "flex shrink-0 items-center gap-2 text-xs mr-2 mt-2")}>
- {attachments.length > 0 && <Paperclip className="h-3.5 w-3.5" aria-label={`${attachments.length} attachments`} />}
+ {attachments.length > 0 && <Paperclip className="h-3.5 w-3.5" aria-label={t("thread.attachmentCount", { count: attachments.length })} />}
{formatUserDate(message.createdAt, { month: "short", day: "2-digit", year: "numeric", hour: "2-digit", minute: "2-digit" })}
</span>
<ThreadMessageActions
diff --git a/src/components/messages/message-detail-navigation.tsx b/src/components/messages/message-detail-navigation.tsx
index adeb987..eabcb68 100644
--- a/src/components/messages/message-detail-navigation.tsx
+++ b/src/components/messages/message-detail-navigation.tsx
@@ -3,6 +3,7 @@
import { createContext, useCallback, useContext, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronLeft, ChevronRight } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import { useSelectedMailbox } from "@/components/mailbox-provider";
@@ -64,6 +65,7 @@ export function MessageDetailNavigationProvider({ children, config }: MessageDet
}
export function MessageDetailNavigation({ messageId, unread }: MessageDetailNavigationProps) {
+ const { t } = useLanguage();
const context = useContext(NavigationContext);
const router = useRouter();
useEffect(() => {
@@ -76,16 +78,16 @@ export function MessageDetailNavigation({ messageId, unread }: MessageDetailNavi
<div className="ml-auto flex shrink-0 items-center gap-2 text-neutral-500">
{totalUnread > 0 && (
<span className="mr-2 whitespace-nowrap text-xs" aria-live="polite">
- {unreadOrder} of {totalUnread} unread
+ {t("message.nav.unreadPosition", { position: unreadOrder, total: totalUnread })}
</span>
)}
- <Tooltip label="Newer email">
- <Button type="button" variant="ghost" size="roundedSM" aria-label="Newer email" disabled={!previousId} onClick={() => previousId && router.push(`${context.hrefPrefix}/${previousId}`)}>
+ <Tooltip label={t("message.nav.newer")}>
+ <Button type="button" variant="ghost" size="roundedSM" aria-label={t("message.nav.newer")} disabled={!previousId} onClick={() => previousId && router.push(`${context.hrefPrefix}/${previousId}`)}>
<ChevronLeft size={18} />
</Button>
</Tooltip>
- <Tooltip label="Older email">
- <Button type="button" variant="ghost" size="roundedSM" aria-label="Older email" disabled={!nextId} onClick={() => nextId && router.push(`${context.hrefPrefix}/${nextId}`)}>
+ <Tooltip label={t("message.nav.older")}>
+ <Button type="button" variant="ghost" size="roundedSM" aria-label={t("message.nav.older")} disabled={!nextId} onClick={() => nextId && router.push(`${context.hrefPrefix}/${nextId}`)}>
<ChevronRight size={18} />
</Button>
</Tooltip>
diff --git a/src/components/messages/message-folder-configs.ts b/src/components/messages/message-folder-configs.ts
index 060ddb1..7307c21 100644
--- a/src/components/messages/message-folder-configs.ts
+++ b/src/components/messages/message-folder-configs.ts
@@ -4,6 +4,8 @@ import type { MessageFolderConfig } from "./types";
export const inboxFolderConfig: MessageFolderConfig = {
folder: "inbox",
title: "Inbox",
+ titleKey: "navigation.inbox",
+ emptyTextKey: "folder.empty.inbox",
emptyText: "No emails",
hrefPrefix: "/inbox",
icon: Star,
@@ -14,6 +16,8 @@ export const inboxFolderConfig: MessageFolderConfig = {
export const starredFolderConfig: MessageFolderConfig = {
folder: "starred",
title: "Starred",
+ titleKey: "navigation.starred",
+ emptyTextKey: "folder.empty.starred",
emptyText: "No starred emails",
hrefPrefix: "/starred",
icon: Star,
@@ -23,6 +27,8 @@ export const starredFolderConfig: MessageFolderConfig = {
export const snoozedFolderConfig: MessageFolderConfig = {
folder: "snoozed",
title: "Snoozed",
+ titleKey: "navigation.snoozed",
+ emptyTextKey: "folder.empty.snoozed",
emptyText: "No snoozed emails",
hrefPrefix: "/snoozed",
icon: Clock,
@@ -32,6 +38,8 @@ export const snoozedFolderConfig: MessageFolderConfig = {
export const sentFolderConfig: MessageFolderConfig = {
folder: "sent",
title: "Sent",
+ titleKey: "navigation.sent",
+ emptyTextKey: "folder.empty.inbox",
emptyText: "No emails",
hrefPrefix: "/sent",
icon: Send,
@@ -42,6 +50,8 @@ export const sentFolderConfig: MessageFolderConfig = {
export const archivedFolderConfig: MessageFolderConfig = {
folder: "archived",
title: "Archived",
+ titleKey: "navigation.archived",
+ emptyTextKey: "folder.empty.archived",
emptyText: "No archived emails",
hrefPrefix: "/archived",
icon: Archive,
@@ -51,6 +61,8 @@ export const archivedFolderConfig: MessageFolderConfig = {
export const spamFolderConfig: MessageFolderConfig = {
folder: "spam",
title: "Spam",
+ titleKey: "navigation.spam",
+ emptyTextKey: "folder.empty.spam",
emptyText: "No spam",
hrefPrefix: "/spam",
icon: ShieldAlert,
@@ -60,6 +72,8 @@ export const spamFolderConfig: MessageFolderConfig = {
export const trashFolderConfig: MessageFolderConfig = {
folder: "trash",
title: "Trash",
+ titleKey: "navigation.trash",
+ emptyTextKey: "folder.empty.trash",
emptyText: "No emails in trash",
hrefPrefix: "/trash",
icon: Trash2,
diff --git a/src/components/messages/message-folder-page.tsx b/src/components/messages/message-folder-page.tsx
index 9ac17bd..7e5ae20 100644
--- a/src/components/messages/message-folder-page.tsx
+++ b/src/components/messages/message-folder-page.tsx
@@ -4,6 +4,7 @@ import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import type { MouseEvent } from "react";
import { Archive, ChevronLeft, ChevronRight, ListFilter, Mail, MailOpen, Trash2 } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Tooltip } from "@/components/ui/tooltip";
@@ -39,6 +40,7 @@ import {
import {
getEmptyFolderConfirmText,
getEmptyFolderLabel,
+ getPermanentDeleteFolderLabel,
getPermanentDeleteConfirmText,
supportsPermanentDelete,
} from "@/lib/messages/permanent-delete-utils";
@@ -57,6 +59,7 @@ function MessageListRow({
onMessageAction,
dragMessageIds,
}: MessageListRowProps) {
+ const { t } = useLanguage();
const Icon = config.icon;
const [read, setRead] = useState(message.read);
const [threadUnread, setThreadUnread] = useState(message.threadUnread);
@@ -67,8 +70,8 @@ function MessageListRow({
const rowMessage = { ...message, read, starred, threadUnread };
const unread = isMessageListRowUnread(rowMessage);
const draggable = config.folder === "inbox" && message.direction === "inbound";
- const party = getMessageParty(rowMessage, config.folder, currentAccountName);
- const preview = getMessagePreview(rowMessage, config.folder);
+ const party = getMessageParty(rowMessage, config.folder, currentAccountName, t);
+ const preview = getMessagePreview(rowMessage, config.folder, t);
const href = `${config.hrefPrefix}/${message.id}`;
const navigation = useMessageNavigation(href, rowMessage);
@@ -134,7 +137,7 @@ function MessageListRow({
checked={selected}
onChange={(event) => onSelectedChange(message.id, event.target.checked)}
className="mt-1 h-4 w-4 rounded border-neutral-300"
- aria-label={`Select message from ${party}`}
+ aria-label={t("list.selectFrom", { sender: party })}
/>
<Link href={href} onClick={onMessageNavigate} className="min-w-0">
<span className="flex items-baseline justify-between gap-3">
@@ -153,7 +156,7 @@ function MessageListRow({
className={`mt-1 block truncate text-sm ${unread ? "font-semibold text-neutral-900" : "text-neutral-700"
}`}
>
- {message.subject ?? "(no subject)"}
+ {message.subject ?? t("list.noSubject")}
</span>
<span className="mt-0.5 block truncate text-xs leading-5 text-neutral-500">
{preview}
@@ -165,13 +168,13 @@ function MessageListRow({
return (
<SwipeableRow
startAction={{
- label: read ? "Mark unread" : "Mark read",
+ label: read ? t("list.markUnread") : t("list.markRead"),
icon: read ? Mail : MailOpen,
className: "bg-blue-600",
onTrigger: () => void runRowAction(read ? "unread" : "read").catch(() => undefined),
}}
endAction={{
- label: "Archive",
+ label: t("common.archive"),
icon: Archive,
className: "bg-emerald-600",
onTrigger: () => void runRowAction("archive").catch(() => undefined),
@@ -188,7 +191,7 @@ function MessageListRow({
const content = (
<>
{config.folder === "inbox" && message.direction === "inbound" && (
- <Tooltip label={starred ? "Starred" : "Not starred"}>
+ <Tooltip label={starred ? t("list.starred") : t("list.notStarred")}>
<Button
type="button"
variant="ghost"
@@ -198,7 +201,7 @@ function MessageListRow({
event.stopPropagation();
void toggleMessageStar(message.id).then((result) => setStarred(result.starred));
}}
- aria-label={starred ? "Starred" : "Not starred"}
+ aria-label={starred ? t("list.starred") : t("list.notStarred")}
>
<Icon className={`h-4 w-4 ${starred ? "fill-amber-400 text-amber-400" : "text-neutral-300"}`} />
</Button>
@@ -216,9 +219,9 @@ function MessageListRow({
</span>
<span className="truncate text-neutral-700">
<span className={unread ? "font-semibold text-neutral-900" : ""}>
- {rowMessage.subject ?? "(no subject)"}
+ {rowMessage.subject ?? t("list.noSubject")}
</span>
- <span className="text-neutral-500"> - {getMessagePreview(rowMessage, config.folder)}</span>
+ <span className="text-neutral-500"> - {getMessagePreview(rowMessage, config.folder, t)}</span>
</span>
<time
dateTime={message.createdAt}
@@ -237,7 +240,7 @@ function MessageListRow({
checked={selected}
onChange={(event) => onSelectedChange(message.id, event.target.checked)}
className="h-4 w-4 rounded border-neutral-300"
- aria-label="Select message"
+ aria-label={t("list.selectMessage")}
/>
<Link href={href} className="contents text-left">
{content}
@@ -260,7 +263,7 @@ function MessageListRow({
checked={selected}
onChange={(event) => onSelectedChange(message.id, event.target.checked)}
className="h-4 w-4 rounded border-neutral-300"
- aria-label="Select message"
+ aria-label={t("list.selectMessage")}
/>
<Link href={href} onClick={onMessageNavigate} className="contents">
{content}
@@ -281,6 +284,8 @@ export function MessageFolderPage({
selectedMessageId,
selection,
}: MessageFolderPageProps) {
+ const { t } = useLanguage();
+ const title = config.titleKey ? t(config.titleKey) : config.title;
const { selectedMailbox, isLoading: mailboxesLoading } = useSelectedMailbox();
const { query } = useMailSearch();
const isMobile = useIsMobile();
@@ -339,12 +344,13 @@ export function MessageFolderPage({
useEffect(() => {
if (mailboxesLoading) return;
document.title = formatEmailPageTitle({
- location: config.title,
+ location: title,
+ inbox: config.folder === "inbox" && !config.folderId,
total: titleTotal,
unread: titleUnread,
emailAddress: mailboxAddress,
});
- }, [config.title, mailboxAddress, mailboxesLoading, titleTotal, titleUnread]);
+ }, [title, config.folder, config.folderId, mailboxAddress, mailboxesLoading, titleTotal, titleUnread]);
function updateSelectedMessage(messageId: string, selected: boolean) {
const message = messages.find((item) => item.id === messageId);
@@ -375,14 +381,14 @@ export function MessageFolderPage({
const permanentDeleteFolder = !config.folderId && supportsPermanentDelete(config.folder) ? config.folder : null;
async function emptyFolder() {
if (!permanentDeleteFolder || !selectedMailbox?.id) return;
- if (!window.confirm(getEmptyFolderConfirmText(permanentDeleteFolder, titleTotal))) return;
+ if (!window.confirm(getEmptyFolderConfirmText(permanentDeleteFolder, titleTotal, t))) return;
setEmptyingFolder(true);
try {
await emptyMessageFolder(selectedMailbox.id, permanentDeleteFolder);
setOffset(0);
} catch (error) {
console.error(error);
- window.alert(`Could not empty ${permanentDeleteFolder === "trash" ? "Trash" : "Spam"}. Please try again.`);
+ window.alert(t("list.emptyFailed", { folder: getPermanentDeleteFolderLabel(permanentDeleteFolder, t) }));
} finally {
setEmptyingFolder(false);
}
@@ -392,7 +398,7 @@ export function MessageFolderPage({
if (selectedIds.length === 0) return;
if (action === "delete") {
const ids = expandSelectedIds(selectedIds);
- if (!window.confirm(getPermanentDeleteConfirmText(ids.length))) return;
+ if (!window.confirm(getPermanentDeleteConfirmText(ids.length, t))) return;
}
setPendingBulkAction(true);
@@ -432,13 +438,13 @@ export function MessageFolderPage({
<div className="flex h-full min-h-0 flex-col">
<div className={`flex h-14 shrink-0 items-center justify-between border-b border-neutral-200 ${compact ? "px-4" : "px-4.5 md:px-6"}`}>
<div className="flex items-center gap-3 w-full">
- <Tooltip label="Select all visible messages">
+ <Tooltip label={t("list.selectAll")}>
<Checkbox
checked={allVisibleSelected}
disabled={messages.length === 0}
onChange={(event) => toggleAllVisible(event.target.checked)}
className="h-4 w-4 rounded border-neutral-300"
- aria-label="Select all visible messages"
+ aria-label={t("list.selectAll")}
/>
</Tooltip>
{selectedIds.length > 0 && !compact ? (
@@ -452,44 +458,44 @@ export function MessageFolderPage({
/>
) : (
(compact || isMobile) && (
- <h1 className="truncate font-semibold text-neutral-900 pl-1">{config.title}</h1>
+ <h1 className="truncate font-semibold text-neutral-900 pl-1">{title}</h1>
)
)}
</div>
{(selectedIds.length === 0 || compact) && (
<div className="flex items-center gap-2 text-neutral-500">
<span className="text-xs text-neutral-500 whitespace-nowrap">
- {pageRange.start} - {pageRange.end} of {pageRange.total}
+ {t("list.range", { start: pageRange.start, end: pageRange.end, total: pageRange.total })}
</span>
- <Tooltip label="Previous page">
+ <Tooltip label={t("list.previousPage")}>
<Button
variant="ghost"
size="sm"
disabled={offset === 0 || isLoading}
onClick={() => setOffset(Math.max(offset - limit, 0))}
- aria-label="Previous page"
+ aria-label={t("list.previousPage")}
>
<ChevronLeft className="h-4 w-4" />
</Button>
</Tooltip>
- <Tooltip label="Next page">
+ <Tooltip label={t("list.nextPage")}>
<Button
variant="ghost"
size="sm"
disabled={offset + messages.length >= total || isLoading}
onClick={() => setOffset(offset + limit)}
- aria-label="Next page"
+ aria-label={t("list.nextPage")}
>
<ChevronRight className="h-4 w-4" />
</Button>
</Tooltip>
{config.folder === "inbox" && (
- <Tooltip label={unreadOnly ? "Showing unread emails" : "Show unread emails only"}>
+ <Tooltip label={unreadOnly ? t("list.showingUnread") : t("list.showUnreadOnly")}>
<Button
type="button"
variant="ghost"
size="sm"
- aria-label="Show unread emails only"
+ aria-label={t("list.showUnreadOnly")}
aria-pressed={unreadOnly}
onClick={() => setUnreadOnly((current) => !current)}
className={unreadOnly ? "bg-blue-100 text-blue-700 hover:bg-blue-100" : undefined}
@@ -499,18 +505,18 @@ export function MessageFolderPage({
</Tooltip>
)}
{permanentDeleteFolder && (
- <Tooltip label={getEmptyFolderLabel(permanentDeleteFolder)}>
+ <Tooltip label={getEmptyFolderLabel(permanentDeleteFolder, t)}>
<Button
type="button"
variant="ghost"
size="sm"
- aria-label={getEmptyFolderLabel(permanentDeleteFolder)}
+ aria-label={getEmptyFolderLabel(permanentDeleteFolder, t)}
disabled={emptyingFolder || isLoading || total === 0}
onClick={() => void emptyFolder()}
className="gap-1.5 text-xs font-medium text-red-600 hover:text-red-700"
>
<Trash2 className="h-4 w-4" />
- {!compact && <span className="max-md:hidden">{emptyingFolder ? "Emptying…" : getEmptyFolderLabel(permanentDeleteFolder)}</span>}
+ {!compact && <span className="max-md:hidden">{emptyingFolder ? t("list.emptying") : getEmptyFolderLabel(permanentDeleteFolder, t)}</span>}
</Button>
</Tooltip>
)}
@@ -540,7 +546,7 @@ export function MessageFolderPage({
))}
{!isLoading && messages.length === 0 && (
<p className="px-6 py-4 text-sm text-neutral-500">
- {hasActiveFilters ? "No messages match these filters" : config.emptyText}
+ {hasActiveFilters ? t("list.noMatch") : config.emptyTextKey ? t(config.emptyTextKey) : config.emptyText}
</p>
)}
</div>
diff --git a/src/components/messages/message-list-row-actions-utils.ts b/src/components/messages/message-list-row-actions-utils.ts
index 07c294a..99fafa7 100644
--- a/src/components/messages/message-list-row-actions-utils.ts
+++ b/src/components/messages/message-list-row-actions-utils.ts
@@ -1,9 +1,10 @@
+import type { TranslationKey } from "@/lib/i18n/types";
import { authFetch } from "@/lib/auth/client";
import type { MessageCountsDelta } from "@/hooks/types";
import { dateFromZonedFields, formatUserDateTimeLocal, getUserTimeZone, parseUserDateTimeLocal, zonedDateFields } from "@/lib/time/utils";
export type SnoozePreset = {
- label: string;
+ labelKey: TranslationKey;
value: string;
};
@@ -21,9 +22,9 @@ export function getSnoozePresets(now = new Date()): SnoozePreset[] {
nextMonth.setUTCMonth(nextMonth.getUTCMonth() + 1);
return [
- { label: "Tomorrow", value: formatSnoozeDateTime(dateFromZonedFields(tomorrow, getUserTimeZone())) },
- { label: "Next week", value: formatSnoozeDateTime(dateFromZonedFields(nextWeek, getUserTimeZone())) },
- { label: "Next month", value: formatSnoozeDateTime(dateFromZonedFields(nextMonth, getUserTimeZone())) },
+ { labelKey: "snooze.tomorrow", value: formatSnoozeDateTime(dateFromZonedFields(tomorrow, getUserTimeZone())) },
+ { labelKey: "snooze.nextWeek", value: formatSnoozeDateTime(dateFromZonedFields(nextWeek, getUserTimeZone())) },
+ { labelKey: "snooze.nextMonth", value: formatSnoozeDateTime(dateFromZonedFields(nextMonth, getUserTimeZone())) },
];
}
diff --git a/src/components/messages/message-list-row-actions.tsx b/src/components/messages/message-list-row-actions.tsx
index 428b399..c226512 100644
--- a/src/components/messages/message-list-row-actions.tsx
+++ b/src/components/messages/message-list-row-actions.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import { Archive, Clock, Mail, MailOpen, Trash2 } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -11,6 +12,7 @@ import { getSnoozePresets, isMessageSnoozed, snoozeMessage, unsnoozeMessage } fr
import { getUserTimeZone } from "@/lib/time/utils";
export function MessageListRowActions({ message, onAction }: MessageListRowActionsProps) {
+ const { t } = useLanguage();
const [snoozeOpen, setSnoozeOpen] = useState(false);
const [snoozedUntil, setSnoozedUntil] = useState(() => getSnoozePresets()[0].value);
const [snoozing, setSnoozing] = useState(false);
@@ -26,7 +28,7 @@ export function MessageListRowActions({ message, onAction }: MessageListRowActio
await snoozeMessage(message.id, snoozedUntil);
setSnoozeOpen(false);
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Unable to snooze message");
+ setError(nextError instanceof Error ? nextError.message : t("snooze.failed"));
} finally {
setSnoozing(false);
}
@@ -35,29 +37,29 @@ export function MessageListRowActions({ message, onAction }: MessageListRowActio
return (
<>
<div className="pointer-events-none absolute right-6 top-1/2 z-10 flex -translate-y-1/2 items-center gap-1 pl-3 opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100 bg-[#f2f6fc]">
- <Tooltip label="Archive">
- <Button type="button" variant="ghost" size="sm" onClick={() => void onAction("archive")} aria-label="Archive">
+ <Tooltip label={t("common.archive")}>
+ <Button type="button" variant="ghost" size="sm" onClick={() => void onAction("archive")} aria-label={t("common.archive")}>
<Archive className="h-4 w-4" />
</Button>
</Tooltip>
- <Tooltip label="Trash">
- <Button type="button" variant="ghost" size="sm" onClick={() => void onAction("trash")} aria-label="Trash">
+ <Tooltip label={t("common.trash")}>
+ <Button type="button" variant="ghost" size="sm" onClick={() => void onAction("trash")} aria-label={t("common.trash")}>
<Trash2 className="h-4 w-4" />
</Button>
</Tooltip>
- <Tooltip label={readAction === "read" ? "Mark as read" : "Mark as unread"}>
- <Button type="button" variant="ghost" size="sm" onClick={() => void onAction(readAction)} aria-label={readAction === "read" ? "Mark as read" : "Mark as unread"}>
+ <Tooltip label={readAction === "read" ? t("common.markRead") : t("common.markUnread")}>
+ <Button type="button" variant="ghost" size="sm" onClick={() => void onAction(readAction)} aria-label={readAction === "read" ? t("common.markRead") : t("common.markUnread")}>
{readAction === "read" ? <MailOpen className="h-4 w-4" /> : <Mail className="h-4 w-4" />}
</Button>
</Tooltip>
- <Tooltip label={snoozed ? "Unsnooze" : "Snooze"}>
+ <Tooltip label={snoozed ? t("common.unsnooze") : t("common.snooze")}>
<Button type="button" variant="ghost" size="sm" onClick={() => {
if (snoozed) {
void unsnoozeMessage(message.id);
return;
}
setSnoozeOpen(true);
- }} aria-label={snoozed ? "Unsnooze" : "Snooze"}>
+ }} aria-label={snoozed ? t("common.unsnooze") : t("common.snooze")}>
<Clock className="h-4 w-4" />
</Button>
</Tooltip>
@@ -66,24 +68,24 @@ export function MessageListRowActions({ message, onAction }: MessageListRowActio
<Dialog open={snoozeOpen} onOpenChange={setSnoozeOpen}>
<DialogContent>
<DialogHeader>
- <DialogTitle>Snooze email</DialogTitle>
- <DialogDescription>Hide this email from the inbox until the time you choose.</DialogDescription>
+ <DialogTitle>{t("snooze.title")}</DialogTitle>
+ <DialogDescription>{t("snooze.description")}</DialogDescription>
</DialogHeader>
<div className="space-y-4">
<div className="grid gap-2 sm:grid-cols-3">
{snoozePresets.map((preset) => (
- <Button key={preset.label} type="button" variant="outline" size="sm" onClick={() => setSnoozedUntil(preset.value)}>
- {preset.label}
+ <Button key={preset.labelKey} type="button" variant="outline" size="sm" onClick={() => setSnoozedUntil(preset.value)}>
+ {t(preset.labelKey)}
</Button>
))}
</div>
<div className="space-y-2">
- <label htmlFor={`snooze-until-${message.id}`} className="text-sm font-medium text-neutral-700">Select date and time ({getUserTimeZone()})</label>
+ <label htmlFor={`snooze-until-${message.id}`} className="text-sm font-medium text-neutral-700">{t("snooze.selectDateTime", { timeZone: getUserTimeZone() })}</label>
<Input id={`snooze-until-${message.id}`} type="datetime-local" value={snoozedUntil} onChange={(event) => setSnoozedUntil(event.target.value)} />
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<Button type="button" onClick={() => void handleSnooze()} disabled={snoozing}>
- {snoozing ? "Snoozing..." : "Snooze"}
+ {snoozing ? t("common.snoozing") : t("common.snooze")}
</Button>
</div>
</DialogContent>
diff --git a/src/components/messages/message-reading-header-button.tsx b/src/components/messages/message-reading-header-button.tsx
index bfe478e..c7691f0 100644
--- a/src/components/messages/message-reading-header-button.tsx
+++ b/src/components/messages/message-reading-header-button.tsx
@@ -3,16 +3,18 @@
import { useRouter } from "next/navigation";
import { ArrowLeft, Columns2 } from "lucide-react";
import clsx from "clsx";
+import { useLanguage } from "@/components/language-provider";
import { Tooltip } from "@/components/ui/tooltip";
import { useMessageListVisibility } from "./message-list-visibility";
import type { MessageReadingHeaderButtonProps } from "./message-reading-header-button-types";
export function MessageReadingHeaderButton({ assistantVisible }: MessageReadingHeaderButtonProps) {
+ const { t } = useLanguage();
const router = useRouter();
const { visible, toggle, singleColumn, backHref, backLabel } = useMessageListVisibility();
const label = singleColumn
- ? `Back to ${backLabel}`
- : assistantVisible ? null : visible ? "Hide email list" : "Show email list";
+ ? t("message.nav.backTo", { folder: backLabel })
+ : assistantVisible ? null : visible ? t("message.nav.hideList") : t("message.nav.showList");
function handleClick() {
if (singleColumn) router.push(backHref);
@@ -26,7 +28,7 @@ export function MessageReadingHeaderButton({ assistantVisible }: MessageReadingH
className={clsx(!singleColumn && assistantVisible ? "opacity-40" : !singleColumn && !visible ? "opacity-60 hover:opacity-100" : "", (singleColumn || !assistantVisible) && "hover:bg-neutral-100 hover:text-neutral-900", "relative z-10 shrink-0 rounded-full p-2 text-neutral-600 duration-200")}
onClick={handleClick}
disabled={!singleColumn && assistantVisible}
- aria-label={label ?? "Email list unavailable"}
+ aria-label={label ?? t("message.nav.listUnavailable")}
aria-pressed={singleColumn ? undefined : visible}
>
{singleColumn ? <ArrowLeft size={18} /> : <Columns2 size={18} />}
diff --git a/src/components/messages/message-source-dialog.tsx b/src/components/messages/message-source-dialog.tsx
index 3ad50b4..f48f9aa 100644
--- a/src/components/messages/message-source-dialog.tsx
+++ b/src/components/messages/message-source-dialog.tsx
@@ -2,12 +2,14 @@
import { useEffect, useMemo, useState } from "react";
import { CheckCircle2, Copy, Download, LoaderCircle } from "lucide-react";
+import { useLanguage } from "@/components/language-provider";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import type { MessageSourceDialogProps } from "./message-source-dialog-types";
import { copyMessageSource, downloadMessageSource, fetchMessageSource, summarizeMessageSource } from "./message-source-utils";
export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSourceDialogProps) {
+ const { t } = useLanguage();
const [source, setSource] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
@@ -28,7 +30,7 @@ export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSo
if (!controller.signal.aborted) setSource(value);
})
.catch((reason) => {
- if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : "Unable to load original message");
+ if (!controller.signal.aborted) setError(reason instanceof Error ? reason.message : t("source.loadFailed"));
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
@@ -40,24 +42,24 @@ export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSo
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[90vh] w-[min(960px,calc(100vw-32px))] overflow-y-auto">
<DialogHeader>
- <DialogTitle>Original Message</DialogTitle>
- <DialogDescription>Message details and full source, including headers and MIME body.</DialogDescription>
+ <DialogTitle>{t("source.title")}</DialogTitle>
+ <DialogDescription>{t("source.description")}</DialogDescription>
</DialogHeader>
- {loading && <div className="flex items-center gap-2 text-sm text-neutral-500"><LoaderCircle className="h-4 w-4 animate-spin" />Loading source…</div>}
+ {loading && <div className="flex items-center gap-2 text-sm text-neutral-500"><LoaderCircle className="h-4 w-4 animate-spin" />{t("source.loading")}</div>}
{error && <p className="text-sm text-neutral-600">{error}</p>}
{source !== null && summary && (
<div className="space-y-5">
<div className="overflow-hidden rounded-lg border border-neutral-200 text-sm">
{([
- ["Message ID", summary.messageId],
- ["Created at", summary.createdAt],
- ["From", summary.from],
- ["To", summary.to],
- ["Subject", summary.subject],
+ ["messageId", summary.messageId],
+ ["createdAt", summary.createdAt],
+ ["from", summary.from],
+ ["to", summary.to],
+ ["subject", summary.subject],
] as const).map(([label, value]) => (
<div key={label} className="grid gap-1 border-b border-neutral-200 px-4 py-3 last:border-b-0 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">
- <span className="font-medium text-neutral-700">{label}</span>
- <span className={label === "Message ID" && value ? "break-all text-green-700" : "break-words text-neutral-900"}>{value || "Unavailable"}</span>
+ <span className="font-medium text-neutral-700">{t(`source.${label}`)}</span>
+ <span className={label === "messageId" && value ? "break-all text-green-700" : "break-words text-neutral-900"}>{value || t("source.unavailable")}</span>
</div>
))}
{(["spf", "dkim", "dmarc"] as const).map((method) => {
@@ -66,18 +68,18 @@ export function MessageSourceDialog({ messageId, open, onOpenChange }: MessageSo
<div key={method} className="grid gap-1 border-b border-neutral-200 px-4 py-3 last:border-b-0 sm:grid-cols-[140px_minmax(0,1fr)] sm:gap-4">
<span className="font-medium uppercase text-neutral-700">{method}</span>
<span className="flex min-w-0 items-center gap-1.5 break-all text-neutral-900">
- {result?.status === "PASS" && <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" aria-label={`${method.toUpperCase()} passed`} />}
- {result ? `${result.status}${result.detail ? ` ${result.detail}` : ""}` : "No result in message headers"}
+ {result?.status === "PASS" && <CheckCircle2 className="h-4 w-4 shrink-0 text-green-600" aria-label={t("source.passed", { method: method.toUpperCase() })} />}
+ {result ? `${result.status}${result.detail ? ` ${result.detail}` : ""}` : t("source.noResult")}
</span>
</div>
);
})}
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
- <Button type="button" variant="ghost" size="sm" className="text-blue-600 hover:text-blue-700" onClick={() => downloadMessageSource(source, messageId)}><Download className="h-4 w-4" />Download Original</Button>
+ <Button type="button" variant="ghost" size="sm" className="text-blue-600 hover:text-blue-700" onClick={() => downloadMessageSource(source, messageId)}><Download className="h-4 w-4" />{t("source.download")}</Button>
<div className="flex items-center gap-2">
- {copyError && <span role="alert" className="text-xs text-red-600">Could not copy</span>}
- <Button type="button" size="sm" onClick={() => { void copyMessageSource(source).then(() => { setCopied(true); setCopyError(false); }).catch(() => { setCopied(false); setCopyError(true); }); }}><Copy className="h-4 w-4" />{copied ? "Copied" : "Copy to clipboard"}</Button>
+ {copyError && <span role="alert" className="text-xs text-red-600">{t("source.couldNotCopy")}</span>}
+ <Button type="button" size="sm" onClick={() => { void copyMessageSource(source).then(() => { setCopied(true); setCopyError(false); }).catch(() => { setCopied(false); setCopyError(true); }); }}><Copy className="h-4 w-4" />{copied ? t("source.copied") : t("source.copy")}</Button>
</div>
</div>
<pre className="max-h-[40vh] overflow-auto rounded-lg border border-neutral-200 bg-neutral-50 p-4 font-mono text-xs leading-relaxed text-neutral-700 whitespace-pre">{source}</pre>
diff --git a/src/components/messages/message-split-layout.tsx b/src/components/messages/message-split-layout.tsx
index 00fbe18..196e2af 100644
--- a/src/components/messages/message-split-layout.tsx
+++ b/src/components/messages/message-split-layout.tsx
@@ -2,6 +2,7 @@
import { usePathname } from "next/navigation";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { useLanguage } from "@/components/language-provider";
import { useSidebar } from "@/components/sidebar-state";
import { useAssistantOpen } from "@/components/agent/assistant-open-state";
import { readColumnWidth, readInitialColumnWidth, saveColumnWidth } from "@/components/column-width-preferences";
@@ -28,6 +29,7 @@ export function MessageSplitLayout({
const containerRef = useRef<HTMLDivElement>(null);
const startWidth = useRef(listWidth);
const resizedWidth = useRef(listWidth);
+ const { t } = useLanguage();
const { userId, setForcedMinimal } = useSidebar();
const assistantOpen = useAssistantOpen();
const listVisible = twoColumnReading && !assistantOpen && manualListVisible;
@@ -81,7 +83,7 @@ export function MessageSplitLayout({
/>
</div>
<ResizeHandle
- label="Resize message list"
+ label={t("list.resize")}
onResizeStart={() => { startWidth.current = listWidth; resizedWidth.current = listWidth; }}
onResize={(delta) => {
const requestedWidth = startWidth.current + delta;
@@ -93,7 +95,7 @@ export function MessageSplitLayout({
/>
</aside>
)}
- <MessageListVisibilityContext.Provider value={{ visible: listVisible, toggle: () => { const visible = !manualListVisible; setManualListVisible(visible); saveMessageListVisible(visible); }, singleColumn: !twoColumnReading, backHref: config.hrefPrefix, backLabel: config.title }}>
+ <MessageListVisibilityContext.Provider value={{ visible: listVisible, toggle: () => { const visible = !manualListVisible; setManualListVisible(visible); saveMessageListVisible(visible); }, singleColumn: !twoColumnReading, backHref: config.hrefPrefix, backLabel: config.titleKey ? t(config.titleKey) : config.title }}>
<MessageDetailNavigationProvider config={config}>
<section className="min-h-0 min-w-0 overflow-hidden bg-white flex flex-col h-full">
{twoColumnReading && selectedMessages.length > 0 ? (
diff --git a/src/components/messages/quoted-email-toggle.tsx b/src/components/messages/quoted-email-toggle.tsx
index c045355..71d3b94 100644
--- a/src/components/messages/quoted-email-toggle.tsx
+++ b/src/components/messages/quoted-email-toggle.tsx
@@ -1,10 +1,12 @@
+import { useLanguage } from "@/components/language-provider";
import type { QuotedEmailToggleProps } from "./quoted-email-toggle-types";
import { EmailHtmlRenderer } from "./email-html-renderer";
export function QuotedEmailToggle({ html }: QuotedEmailToggleProps) {
+ const { t } = useLanguage();
return (
<details className="email-quote-toggle">
- <summary aria-label="Toggle quoted email" title="Show or hide quoted email" />
+ <summary aria-label={t("message.quote.toggle")} title={t("message.quote.title")} />
<EmailHtmlRenderer html={html} preserveLeadingQuote />
</details>
);
diff --git a/src/components/messages/spam-score-details.tsx b/src/components/messages/spam-score-details.tsx
index 7169d38..22de50f 100644
--- a/src/components/messages/spam-score-details.tsx
+++ b/src/components/messages/spam-score-details.tsx
@@ -1,25 +1,27 @@
+import { useLanguage } from "@/components/language-provider";
import type { SpamScoreDetailsProps } from "./spam-score-details-types";
import { parseSpamSignals } from "./spam-score-details-utils";
export function SpamScoreDetails({ score, verdict, signals, analysisError }: SpamScoreDetailsProps) {
+ const { t } = useLanguage();
if (score == null && !analysisError) return null;
const parsedSignals = parseSpamSignals(signals);
return (
<details className="mb-2 rounded-xl border border-neutral-200 bg-neutral-50 px-4 py-3">
<summary className="cursor-pointer text-sm font-medium text-neutral-800">
- {score == null ? "Spam analysis unavailable" : `Spam score: ${score} · ${verdict ?? "inbox"}`}
+ {score == null ? t("message.spam.unavailable") : t("message.spam.score", { score, verdict: verdict ?? t("message.spam.inbox") })}
</summary>
{analysisError ? (
- <p className="mt-2 text-sm text-neutral-600">The filter could not analyze this message. It was delivered normally.</p>
+ <p className="mt-2 text-sm text-neutral-600">{t("message.spam.failed")}</p>
) : parsedSignals.length > 0 ? (
<div className="mt-3 space-y-1.5 text-sm text-neutral-600">
- <p className="font-medium text-neutral-800">Why Mailflare gave this score</p>
+ <p className="font-medium text-neutral-800">{t("message.spam.why")}</p>
{parsedSignals.map((signal) => (
<p key={signal.id}><span className={signal.score > 0 ? "text-red-600" : "text-green-700"}>{signal.score > 0 ? "+" : ""}{signal.score}</span>{" "}{signal.reason}</p>
))}
</div>
) : (
- <p className="mt-2 text-sm text-neutral-600">No significant spam signals were found.</p>
+ <p className="mt-2 text-sm text-neutral-600">{t("message.spam.none")}</p>
)}
</details>
);
diff --git a/src/components/messages/thread-message-actions.tsx b/src/components/messages/thread-message-actions.tsx
index c55d13f..7221939 100644
--- a/src/components/messages/thread-message-actions.tsx
+++ b/src/components/messages/thread-message-actions.tsx
@@ -5,6 +5,7 @@ import { Ban, FileCode2, Forward, Mail, MailOpen, MoreVertical, Reply, ReplyAll,
import { useCompose } from "@/components/compose/compose-context";
import { MessageSourceDialog } from "@/components/messages/message-source-dialog";
import { getOwnAddressForMessage } from "@/app/(dashboard)/inbox/[messageId]/utils";
+import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Tooltip } from "@/components/ui/tooltip";
import {
@@ -28,6 +29,7 @@ export function ThreadMessageActions({
ownAddresses = [],
starOnly = false,
}: ThreadMessageActionsProps) {
+ const { t } = useLanguage();
const { openDraftComposer } = useCompose();
const [starred, setStarred] = useState(message.starred);
const [moreOpen, setMoreOpen] = useState(false);
@@ -51,7 +53,7 @@ export function ThreadMessageActions({
try {
setStarred(await toggleMessageStar(message.id));
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Unable to update star");
+ setError(nextError instanceof Error ? nextError.message : t("message.error.star"));
} finally {
setPending(false);
}
@@ -75,7 +77,7 @@ export function ThreadMessageActions({
});
openDraftComposer(draftId);
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Could not start reply");
+ setError(nextError instanceof Error ? nextError.message : t("message.error.reply"));
} finally {
setPending(false);
}
@@ -95,7 +97,7 @@ export function ThreadMessageActions({
});
openDraftComposer(draftId);
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Could not start forward");
+ setError(nextError instanceof Error ? nextError.message : t("message.error.forward"));
} finally {
setPending(false);
}
@@ -108,7 +110,7 @@ export function ThreadMessageActions({
try {
await runSingleMessageAction(message.id, action);
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Could not update message");
+ setError(nextError instanceof Error ? nextError.message : t("message.error.update"));
} finally {
setPending(false);
}
@@ -123,7 +125,7 @@ export function ThreadMessageActions({
await blockMessageContact({ mailboxId, senderAddress: message.fromAddr });
await runSingleMessageAction(message.id, "trash");
} catch (nextError) {
- setError(nextError instanceof Error ? nextError.message : "Could not block contact");
+ setError(nextError instanceof Error ? nextError.message : t("message.error.block"));
} finally {
setPending(false);
}
@@ -132,13 +134,13 @@ export function ThreadMessageActions({
return (
<div className="flex items-center gap-0.5">
{error && <span className="mr-1 max-w-32 truncate text-xs text-red-600" title={error}>{error}</span>}
- <Tooltip label={starred ? "Remove star" : "Star"}>
+ <Tooltip label={starred ? t("message.removeStar") : t("message.star")}>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 px-0"
- aria-label={starred ? "Remove star" : "Star"}
+ aria-label={starred ? t("message.removeStar") : t("message.star")}
aria-pressed={starred}
disabled={pending}
onClick={() => void onToggleStar()}
@@ -148,13 +150,13 @@ export function ThreadMessageActions({
</Tooltip>
{!starOnly && (
<>
- <Tooltip label="Reply">
+ <Tooltip label={t("message.reply")}>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 px-0"
- aria-label="Reply"
+ aria-label={t("message.reply")}
disabled={pending}
onClick={() => void onReply("reply")}
>
@@ -162,13 +164,13 @@ export function ThreadMessageActions({
</Button>
</Tooltip>
<div className="relative">
- <Tooltip label="More actions">
+ <Tooltip label={t("common.moreActions")}>
<Button
type="button"
variant="ghost"
size="sm"
className="h-8 w-8 px-0"
- aria-label="More actions"
+ aria-label={t("common.moreActions")}
aria-expanded={moreOpen}
disabled={pending}
onClick={() => setMoreOpen((open) => !open)}
@@ -179,34 +181,34 @@ export function ThreadMessageActions({
{moreOpen && (
<div className="absolute right-0 z-30 mt-1 w-56 rounded-xl border border-neutral-200 bg-white p-2 text-neutral-700 shadow-lg">
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onReply("reply")}>
- <Reply className="h-4 w-4" /> Reply
+ <Reply className="h-4 w-4" /> {t("message.reply")}
</button>
{canReplyAll && (
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onReply("replyAll")}>
- <ReplyAll className="h-4 w-4" /> Reply all
+ <ReplyAll className="h-4 w-4" /> {t("message.replyAll")}
</button>
)}
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onForward()}>
- <Forward className="h-4 w-4" /> Forward
+ <Forward className="h-4 w-4" /> {t("message.forward")}
</button>
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => { setMoreOpen(false); setSourceOpen(true); }}>
- <FileCode2 className="h-4 w-4" /> Show original
+ <FileCode2 className="h-4 w-4" /> {t("message.showOriginal")}
</button>
<hr className="my-1 border-neutral-100" />
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onMessageAction(message.read ? "unread" : "read")}>
{message.read ? <Mail className="h-4 w-4" /> : <MailOpen className="h-4 w-4" />}
- {message.read ? "Mark as unread" : "Mark as read"}
+ {message.read ? t("common.markUnread") : t("common.markRead")}
</button>
{moveActions.map((item) => (
<button key={item.action} type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onMessageAction(item.action)}>
- {createElement(item.icon, { size: 16 })} {item.label}
+ {createElement(item.icon, { size: 16 })} {t(item.labelKey)}
</button>
))}
{message.direction === "inbound" && mailboxId && (
<>
<hr className="my-1 border-neutral-100" />
<button type="button" className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm hover:bg-neutral-100" onClick={() => void onBlock()}>
- <Ban className="h-4 w-4" /> Block contact
+ <Ban className="h-4 w-4" /> {t("message.blockContact")}
</button>
</>
)}
diff --git a/src/components/messages/types.d.ts b/src/components/messages/types.d.ts
index 1863bbb..1f4a812 100644
--- a/src/components/messages/types.d.ts
+++ b/src/components/messages/types.d.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from "@/lib/i18n/types";
import type { LucideIcon } from "lucide-react";
import type { Dispatch, ReactNode, SetStateAction } from "react";
import type { Message, MessageFolder } from "@/hooks/types";
@@ -6,7 +7,10 @@ import type { BulkMessageAction } from "@/app/api/messages/bulk/types";
export type MessageFolderConfig = {
folder: MessageFolder;
title: string;
+ /** Translation keys for built-in folders; custom folders show `title` as typed by the user. */
+ titleKey?: TranslationKey;
emptyText: string;
+ emptyTextKey?: TranslationKey;
hrefPrefix: string;
folderId?: string;
icon: LucideIcon;
@@ -89,4 +93,6 @@ export type EmailPageTitleInput = {
total: number;
unread: number;
emailAddress: string | null;
+ /** Set for the Inbox, which shows only the unread count. */
+ inbox?: boolean;
};
diff --git a/src/components/messages/utils.ts b/src/components/messages/utils.ts
index 15bc901..c5e2b22 100644
--- a/src/components/messages/utils.ts
+++ b/src/components/messages/utils.ts
@@ -7,6 +7,7 @@ import type { MailboxOption } from "@/components/mailbox-provider";
import type { EmailPageTitleInput } from "./types";
import type { MessageFolderConfig } from "./types";
import type { PageRange } from "./types";
+import { defaultTranslator, type Translator } from "@/lib/i18n/utils";
import type { PermanentDeleteFolder } from "@/app/api/messages/bulk/types";
import type { EmptyFolderResponse } from "@/app/api/messages/empty/types";
@@ -14,17 +15,18 @@ export function getMessageParty(
message: Message,
folder: MessageFolderConfig["folder"],
currentAccountName?: string,
+ t: Translator = defaultTranslator,
) {
- if (folder === "drafts") return "Draft";
- if (folder === "sent") return formatRecipientSummary(message.toAddr, message.toContactName);
+ if (folder === "drafts") return t("list.draft");
+ if (folder === "sent") return formatRecipientSummary(message.toAddr, message.toContactName, t);
if (message.direction === "outbound" && currentAccountName) return currentAccountName;
- return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : "Unknown sender");
+ return message.fromContactName ?? (message.fromAddr ? getEmailDisplayName(message.fromAddr) : t("list.unknownSender"));
}
/** "Maya Chen, +2" for a multi-recipient message, or just the one name. */
-export function formatRecipientSummary(toAddr: string, firstContactName?: string | null): string {
+export function formatRecipientSummary(toAddr: string, firstContactName?: string | null, t: Translator = defaultTranslator): string {
const entries = splitEmailAddressList(toAddr);
- if (entries.length === 0) return "No recipient";
+ if (entries.length === 0) return t("list.noRecipient");
const first = firstContactName ?? getEmailDisplayName(entries[0]);
return entries.length > 1 ? `${first}, +${entries.length - 1}` : first;
}
@@ -42,9 +44,9 @@ export function isMessageListRowUnread(message: Message): boolean {
return message.direction === "inbound" && !message.read;
}
-export function getMessagePreview(message: Message, folder: MessageFolderConfig["folder"]) {
- if (folder === "drafts") return message.snippet || message.toAddr || "No content";
- return message.snippet || "No preview";
+export function getMessagePreview(message: Message, folder: MessageFolderConfig["folder"], t: Translator = defaultTranslator) {
+ if (folder === "drafts") return message.snippet || message.toAddr || t("list.noContent");
+ return message.snippet || t("thread.noPreview");
}
export function formatMessageListTimestamp(createdAt: string): string {
@@ -75,8 +77,8 @@ export function getEmailPageTitleCount(total: number, unread: number): number {
return unread > 0 ? unread : total;
}
-export function formatEmailPageTitle({ location, total, unread, emailAddress }: EmailPageTitleInput): string {
- if (location === "Inbox") return unread > 0 ? `Inbox (${unread})` : "Inbox";
+export function formatEmailPageTitle({ location, total, unread, emailAddress, inbox = location === "Inbox" }: EmailPageTitleInput): string {
+ if (inbox) return unread > 0 ? `${location} (${unread})` : location;
const count = getEmailPageTitleCount(total, unread);
const suffix = emailAddress ? ` - ${emailAddress}` : "";
return `${location} (${count})${suffix}`;
@@ -89,7 +91,7 @@ export async function runBulkMessageAction(messageIds: string[], action: string,
body: JSON.stringify({ messageIds, action, folderId }),
});
- if (!response.ok) throw new Error("Unable to update selected messages");
+ if (!response.ok) throw new Error(defaultTranslator("error.updateSelected"));
if (action === "read" || action === "unread") markMessagesReadInCaches(messageIds, action === "read");
if (notify) window.dispatchEvent(new Event("mailflare:messages-changed"));
}
@@ -107,7 +109,7 @@ export async function emptyMessageFolder(mailboxId: string, folder: PermanentDel
body: JSON.stringify({ mailboxId, folder }),
});
const data = (await response.json().catch(() => ({}))) as EmptyFolderResponse;
- if (!response.ok) throw new Error(data.error ?? "Unable to empty folder");
+ if (!response.ok) throw new Error(data.error ?? defaultTranslator("error.emptyFolder"));
deletedTotal += data.deleted ?? 0;
if (!data.remaining || !data.deleted) break;
}
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
index fdd152a..2649903 100644
--- a/src/lib/i18n/en.json
+++ b/src/lib/i18n/en.json
@@ -33,5 +33,137 @@
"color.amber": "Amber",
"color.green": "Green",
"color.teal": "Teal",
- "language.label": "Language"
+ "language.label": "Language",
+ "common.archive": "Archive",
+ "common.unarchive": "Unarchive",
+ "common.notSpam": "Not spam",
+ "common.reportSpam": "Report spam",
+ "common.restore": "Restore",
+ "common.delete": "Delete",
+ "common.deleteForever": "Delete forever",
+ "common.markRead": "Mark as read",
+ "common.markUnread": "Mark as unread",
+ "common.moveSelected": "Move selected messages",
+ "common.moveTo": "Move to",
+ "common.clearSelection": "Clear selection",
+ "common.moreActions": "More actions",
+ "common.selectedCount": "{count} selected",
+ "common.chooseBulkAction": "Choose an action to apply to the selected emails.",
+ "common.trash": "Trash",
+ "common.snooze": "Snooze",
+ "common.unsnooze": "Unsnooze",
+ "common.snoozing": "Snoozing...",
+ "snooze.title": "Snooze email",
+ "snooze.description": "Hide this email from the inbox until the time you choose.",
+ "snooze.selectDateTime": "Select date and time ({timeZone})",
+ "snooze.failed": "Unable to snooze message",
+ "thread.messagesCollapsed.older.one": "{count} older message",
+ "thread.messagesCollapsed.older.other": "{count} older messages",
+ "thread.messagesCollapsed.newer.one": "{count} newer message",
+ "thread.messagesCollapsed.newer.other": "{count} newer messages",
+ "thread.earlier": "Earlier messages in this conversation",
+ "thread.later": "Later messages in this conversation",
+ "thread.expand": "Expand {label}",
+ "thread.to": "to {recipients}",
+ "thread.noPreview": "No preview",
+ "thread.attachmentCount.one": "{count} attachment",
+ "thread.attachmentCount.other": "{count} attachments",
+ "snooze.tomorrow": "Tomorrow",
+ "snooze.nextWeek": "Next week",
+ "snooze.nextMonth": "Next month",
+ "message.reply": "Reply",
+ "message.replyAll": "Reply all",
+ "message.forward": "Forward",
+ "message.showOriginal": "Show original",
+ "message.blockContact": "Block contact",
+ "message.star": "Star",
+ "message.removeStar": "Remove star",
+ "message.error.star": "Unable to update star",
+ "message.error.reply": "Could not start reply",
+ "message.error.forward": "Could not start forward",
+ "message.error.update": "Could not update message",
+ "message.error.block": "Could not block contact",
+ "message.nav.newer": "Newer email",
+ "message.nav.older": "Older email",
+ "message.nav.unreadPosition": "{position} of {total} unread",
+ "message.nav.backTo": "Back to {folder}",
+ "message.nav.hideList": "Hide email list",
+ "message.nav.showList": "Show email list",
+ "message.nav.listUnavailable": "Email list unavailable",
+ "message.quote.toggle": "Toggle quoted email",
+ "message.quote.title": "Show or hide quoted email",
+ "message.spam.unavailable": "Spam analysis unavailable",
+ "message.spam.score": "Spam score: {score} · {verdict}",
+ "message.spam.inbox": "inbox",
+ "message.spam.failed": "The filter could not analyze this message. It was delivered normally.",
+ "message.spam.why": "Why Mailflare gave this score",
+ "message.spam.none": "No significant spam signals were found.",
+ "source.title": "Original Message",
+ "source.description": "Message details and full source, including headers and MIME body.",
+ "source.loading": "Loading source…",
+ "source.loadFailed": "Unable to load original message",
+ "source.messageId": "Message ID",
+ "source.createdAt": "Created at",
+ "source.from": "From",
+ "source.to": "To",
+ "source.subject": "Subject",
+ "source.unavailable": "Unavailable",
+ "source.passed": "{method} passed",
+ "source.noResult": "No result in message headers",
+ "source.download": "Download Original",
+ "source.couldNotCopy": "Could not copy",
+ "source.copied": "Copied",
+ "source.copy": "Copy to clipboard",
+ "common.notSpamOrInbox": "Not spam",
+ "actions.error.update": "Could not update message",
+ "actions.error.delete": "Could not delete message",
+ "actions.error.trashRule": "Could not create trash rule",
+ "actions.moveToTrash": "Move to trash",
+ "actions.moveToTrashHint": "Move to trash (#)",
+ "actions.archiveHint": "Archive (e)",
+ "actions.reportSpamHint": "Report spam (!)",
+ "actions.deleteHint": "Delete (#)",
+ "actions.replyHint": "Reply (r)",
+ "actions.unsubscribe": "Unsubscribe",
+ "shortcut.archiveMessage": "Archive Message",
+ "shortcut.moveToTrash": "Move to Trash",
+ "shortcut.replyToMessage": "Reply to Message",
+ "shortcut.reportSpam": "Report Spam",
+ "shortcut.backToList": "Back to List",
+ "folder.empty.inbox": "No emails",
+ "folder.empty.starred": "No starred emails",
+ "folder.empty.snoozed": "No snoozed emails",
+ "folder.empty.archived": "No archived emails",
+ "folder.empty.spam": "No spam",
+ "folder.empty.trash": "No emails in trash",
+ "folder.empty.custom": "No emails",
+ "list.noMatch": "No messages match these filters",
+ "list.draft": "Draft",
+ "list.unknownSender": "Unknown sender",
+ "list.noRecipient": "No recipient",
+ "list.noContent": "No content",
+ "list.noSubject": "(no subject)",
+ "list.markUnread": "Mark unread",
+ "list.markRead": "Mark read",
+ "list.starred": "Starred",
+ "list.notStarred": "Not starred",
+ "list.selectFrom": "Select message from {sender}",
+ "list.selectMessage": "Select message",
+ "list.selectAll": "Select all visible messages",
+ "list.range": "{start} - {end} of {total}",
+ "list.previousPage": "Previous page",
+ "list.nextPage": "Next page",
+ "list.showingUnread": "Showing unread emails",
+ "list.showUnreadOnly": "Show unread emails only",
+ "list.emptying": "Emptying…",
+ "list.emptyFolder": "Empty {folder}",
+ "list.emptyFailed": "Could not empty {folder}. Please try again.",
+ "delete.confirm.one": "Permanently delete this message? This cannot be undone.",
+ "delete.confirm.other": "Permanently delete these {count} messages? This cannot be undone.",
+ "empty.confirm.one": "Permanently delete the 1 message in {folder}? This cannot be undone.",
+ "empty.confirm.many": "Permanently delete all {count} messages in {folder}? This cannot be undone.",
+ "empty.confirm.all": "Permanently delete every message in {folder}? This cannot be undone.",
+ "error.updateSelected": "Unable to update selected messages",
+ "error.emptyFolder": "Unable to empty folder",
+ "list.resize": "Resize message list"
}
diff --git a/src/lib/i18n/pt-BR.json b/src/lib/i18n/pt-BR.json
index c640f08..a765860 100644
--- a/src/lib/i18n/pt-BR.json
+++ b/src/lib/i18n/pt-BR.json
@@ -33,5 +33,137 @@
"color.amber": "Âmbar",
"color.green": "Verde",
"color.teal": "Verde-azulado",
- "language.label": "Idioma"
+ "language.label": "Idioma",
+ "common.archive": "Arquivar",
+ "common.unarchive": "Desarquivar",
+ "common.notSpam": "Não é spam",
+ "common.reportSpam": "Denunciar spam",
+ "common.restore": "Restaurar",
+ "common.delete": "Excluir",
+ "common.deleteForever": "Excluir permanentemente",
+ "common.markRead": "Marcar como lida",
+ "common.markUnread": "Marcar como não lida",
+ "common.moveSelected": "Mover mensagens selecionadas",
+ "common.moveTo": "Mover para",
+ "common.clearSelection": "Limpar seleção",
+ "common.moreActions": "Mais ações",
+ "common.selectedCount": "{count} selecionada(s)",
+ "common.chooseBulkAction": "Escolha uma ação para aplicar aos e-mails selecionados.",
+ "common.trash": "Lixeira",
+ "common.snooze": "Adiar",
+ "common.unsnooze": "Cancelar adiamento",
+ "common.snoozing": "Adiando...",
+ "snooze.title": "Adiar e-mail",
+ "snooze.description": "Oculte este e-mail da caixa de entrada até o horário escolhido.",
+ "snooze.selectDateTime": "Selecione data e hora ({timeZone})",
+ "snooze.failed": "Não foi possível adiar a mensagem",
+ "thread.messagesCollapsed.older.one": "{count} mensagem mais antiga",
+ "thread.messagesCollapsed.older.other": "{count} mensagens mais antigas",
+ "thread.messagesCollapsed.newer.one": "{count} mensagem mais recente",
+ "thread.messagesCollapsed.newer.other": "{count} mensagens mais recentes",
+ "thread.earlier": "Mensagens anteriores desta conversa",
+ "thread.later": "Mensagens posteriores desta conversa",
+ "thread.expand": "Expandir {label}",
+ "thread.to": "para {recipients}",
+ "thread.noPreview": "Sem prévia",
+ "thread.attachmentCount.one": "{count} anexo",
+ "thread.attachmentCount.other": "{count} anexos",
+ "snooze.tomorrow": "Amanhã",
+ "snooze.nextWeek": "Próxima semana",
+ "snooze.nextMonth": "Próximo mês",
+ "message.reply": "Responder",
+ "message.replyAll": "Responder a todos",
+ "message.forward": "Encaminhar",
+ "message.showOriginal": "Mostrar original",
+ "message.blockContact": "Bloquear contato",
+ "message.star": "Marcar com estrela",
+ "message.removeStar": "Remover estrela",
+ "message.error.star": "Não foi possível atualizar a estrela",
+ "message.error.reply": "Não foi possível iniciar a resposta",
+ "message.error.forward": "Não foi possível iniciar o encaminhamento",
+ "message.error.update": "Não foi possível atualizar a mensagem",
+ "message.error.block": "Não foi possível bloquear o contato",
+ "message.nav.newer": "E-mail mais recente",
+ "message.nav.older": "E-mail mais antigo",
+ "message.nav.unreadPosition": "{position} de {total} não lidas",
+ "message.nav.backTo": "Voltar para {folder}",
+ "message.nav.hideList": "Ocultar lista de e-mails",
+ "message.nav.showList": "Mostrar lista de e-mails",
+ "message.nav.listUnavailable": "Lista de e-mails indisponível",
+ "message.quote.toggle": "Alternar e-mail citado",
+ "message.quote.title": "Mostrar ou ocultar e-mail citado",
+ "message.spam.unavailable": "Análise de spam indisponível",
+ "message.spam.score": "Pontuação de spam: {score} · {verdict}",
+ "message.spam.inbox": "caixa de entrada",
+ "message.spam.failed": "O filtro não conseguiu analisar esta mensagem. Ela foi entregue normalmente.",
+ "message.spam.why": "Por que o Mailflare deu esta pontuação",
+ "message.spam.none": "Nenhum sinal significativo de spam foi encontrado.",
+ "source.title": "Mensagem original",
+ "source.description": "Detalhes da mensagem e código-fonte completo, incluindo cabeçalhos e corpo MIME.",
+ "source.loading": "Carregando código-fonte…",
+ "source.loadFailed": "Não foi possível carregar a mensagem original",
+ "source.messageId": "ID da mensagem",
+ "source.createdAt": "Criada em",
+ "source.from": "De",
+ "source.to": "Para",
+ "source.subject": "Assunto",
+ "source.unavailable": "Indisponível",
+ "source.passed": "{method} aprovado",
+ "source.noResult": "Nenhum resultado nos cabeçalhos da mensagem",
+ "source.download": "Baixar original",
+ "source.couldNotCopy": "Não foi possível copiar",
+ "source.copied": "Copiado",
+ "source.copy": "Copiar para a área de transferência",
+ "common.notSpamOrInbox": "Não é spam",
+ "actions.error.update": "Não foi possível atualizar a mensagem",
+ "actions.error.delete": "Não foi possível excluir a mensagem",
+ "actions.error.trashRule": "Não foi possível criar a regra de lixeira",
+ "actions.moveToTrash": "Mover para a lixeira",
+ "actions.moveToTrashHint": "Mover para a lixeira (#)",
+ "actions.archiveHint": "Arquivar (e)",
+ "actions.reportSpamHint": "Denunciar spam (!)",
+ "actions.deleteHint": "Excluir (#)",
+ "actions.replyHint": "Responder (r)",
+ "actions.unsubscribe": "Cancelar inscrição",
+ "shortcut.archiveMessage": "Arquivar mensagem",
+ "shortcut.moveToTrash": "Mover para a lixeira",
+ "shortcut.replyToMessage": "Responder à mensagem",
+ "shortcut.reportSpam": "Denunciar spam",
+ "shortcut.backToList": "Voltar à lista",
+ "folder.empty.inbox": "Nenhum e-mail",
+ "folder.empty.starred": "Nenhum e-mail com estrela",
+ "folder.empty.snoozed": "Nenhum e-mail adiado",
+ "folder.empty.archived": "Nenhum e-mail arquivado",
+ "folder.empty.spam": "Nenhum spam",
+ "folder.empty.trash": "Nenhum e-mail na lixeira",
+ "folder.empty.custom": "Nenhum e-mail",
+ "list.noMatch": "Nenhuma mensagem corresponde a estes filtros",
+ "list.draft": "Rascunho",
+ "list.unknownSender": "Remetente desconhecido",
+ "list.noRecipient": "Sem destinatário",
+ "list.noContent": "Sem conteúdo",
+ "list.noSubject": "(sem assunto)",
+ "list.markUnread": "Marcar como não lida",
+ "list.markRead": "Marcar como lida",
+ "list.starred": "Com estrela",
+ "list.notStarred": "Sem estrela",
+ "list.selectFrom": "Selecionar mensagem de {sender}",
+ "list.selectMessage": "Selecionar mensagem",
+ "list.selectAll": "Selecionar todas as mensagens visíveis",
+ "list.range": "{start} - {end} de {total}",
+ "list.previousPage": "Página anterior",
+ "list.nextPage": "Próxima página",
+ "list.showingUnread": "Mostrando e-mails não lidos",
+ "list.showUnreadOnly": "Mostrar somente e-mails não lidos",
+ "list.emptying": "Esvaziando…",
+ "list.emptyFolder": "Esvaziar {folder}",
+ "list.emptyFailed": "Não foi possível esvaziar {folder}. Tente novamente.",
+ "delete.confirm.one": "Excluir esta mensagem permanentemente? Esta ação não pode ser desfeita.",
+ "delete.confirm.other": "Excluir estas {count} mensagens permanentemente? Esta ação não pode ser desfeita.",
+ "empty.confirm.one": "Excluir permanentemente a única mensagem em {folder}? Esta ação não pode ser desfeita.",
+ "empty.confirm.many": "Excluir permanentemente todas as {count} mensagens em {folder}? Esta ação não pode ser desfeita.",
+ "empty.confirm.all": "Excluir permanentemente todas as mensagens em {folder}? Esta ação não pode ser desfeita.",
+ "error.updateSelected": "Não foi possível atualizar as mensagens selecionadas",
+ "error.emptyFolder": "Não foi possível esvaziar a pasta",
+ "list.resize": "Redimensionar lista de mensagens"
}
diff --git a/src/lib/i18n/server.ts b/src/lib/i18n/server.ts
new file mode 100644
index 0000000..8637aef
--- /dev/null
+++ b/src/lib/i18n/server.ts
@@ -0,0 +1,7 @@
+import { cookies } from "next/headers";
+import { LOCALE_COOKIE, createTranslator, resolveLocale } from "./utils";
+
+// For server components and route handlers; client components use `useLanguage()`.
+export async function getServerTranslator() {
+ return createTranslator(resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value));
+}
diff --git a/src/lib/i18n/types.d.ts b/src/lib/i18n/types.d.ts
index 0120a04..5d80961 100644
--- a/src/lib/i18n/types.d.ts
+++ b/src/lib/i18n/types.d.ts
@@ -3,3 +3,7 @@ import type en from "./en.json";
export type { Locale } from "./locales";
export type TranslationKey = keyof typeof en;
export type Messages = Record<TranslationKey, string>;
+
+type PluralCategory = "zero" | "one" | "two" | "few" | "many" | "other";
+/** A key whose catalog entries are `key.one`, `key.other`, etc.; pass `{ count }` to pick the variant. */
+export type PluralKey = TranslationKey extends infer K ? (K extends `${infer Base}.${PluralCategory}` ? Base : never) : never;
diff --git a/src/lib/i18n/utils.ts b/src/lib/i18n/utils.ts
index 3d9ce2a..0497ca7 100644
--- a/src/lib/i18n/utils.ts
+++ b/src/lib/i18n/utils.ts
@@ -1,6 +1,6 @@
import en from "./en.json";
import { DEFAULT_LOCALE, locales } from "./locales";
-import type { Locale, Messages, TranslationKey } from "./types";
+import type { Locale, Messages, PluralKey, TranslationKey } from "./types";
export { DEFAULT_LOCALE } from "./locales";
export const LOCALE_COOKIE = "mailflare-locale";
@@ -19,7 +19,7 @@ export function getMessages(locale: Locale): Messages {
}
export type TranslationVars = Record<string, string | number>;
-export type Translator = (key: TranslationKey, vars?: TranslationVars) => string;
+export type Translator = (key: TranslationKey | PluralKey, vars?: TranslationVars) => string;
function interpolate(template: string, vars?: TranslationVars): string {
if (!vars) return template;
@@ -27,25 +27,31 @@ function interpolate(template: string, vars?: TranslationVars): string {
}
export function translate(messages: Partial<Messages>, key: TranslationKey, vars?: TranslationVars): string {
- return interpolate(messages[key] ?? en[key], vars);
+ return interpolate(messages[key] ?? en[key] ?? key, vars);
}
// Server-safe translator. A numeric `count` var selects a plural variant: with
// `inbox.unread.one` / `inbox.unread.other` catalog entries, `t("inbox.unread", { count })`
// uses the locale's CLDR category and falls back to the bare key when no variant exists.
export function createTranslator(locale: Locale): Translator {
- const messages: Partial<Record<string, string>> = getMessages(locale);
+ const messages = getMessages(locale);
const rules = new Intl.PluralRules(locale);
+ const known = (key: string) => key in messages || key in en;
return (key, vars) => {
const count = vars?.count;
if (typeof count === "number") {
- const variant = `${key}.${rules.select(count)}` as TranslationKey;
- if (messages[variant] !== undefined || (en as Record<string, string>)[variant] !== undefined) return translate(getMessages(locale), variant, vars);
+ for (const category of [rules.select(count), "other"]) {
+ const variant = `${key}.${category}`;
+ if (known(variant)) return translate(messages, variant as TranslationKey, vars);
+ }
}
- return translate(getMessages(locale), key, vars);
+ return translate(messages, key as TranslationKey, vars);
};
}
export function serializeLocaleCookie(locale: Locale, secure: boolean): string {
return `${LOCALE_COOKIE}=${resolveLocale(locale)}; Path=/; Max-Age=${LOCALE_COOKIE_MAX_AGE}; SameSite=Lax${secure ? "; Secure" : ""}`;
}
+
+/** Default for pure helpers that take an optional translator, so callers without one (and tests) get English. */
+export const defaultTranslator: Translator = createTranslator(DEFAULT_LOCALE);
diff --git a/src/lib/messages/permanent-delete-utils.ts b/src/lib/messages/permanent-delete-utils.ts
index 657da8a..f741689 100644
--- a/src/lib/messages/permanent-delete-utils.ts
+++ b/src/lib/messages/permanent-delete-utils.ts
@@ -1,22 +1,27 @@
import type { PermanentDeleteFolder } from "@/app/api/messages/bulk/types";
+import { defaultTranslator, type Translator } from "../i18n/utils";
-const folderLabels: Record<PermanentDeleteFolder, string> = { trash: "Trash", spam: "Spam" };
+const folderLabelKeys = { trash: "navigation.trash", spam: "navigation.spam" } as const;
+
+export function getPermanentDeleteFolderLabel(folder: PermanentDeleteFolder, t: Translator = defaultTranslator): string {
+ return t(folderLabelKeys[folder]);
+}
/** Whether the folder being viewed offers "Delete forever" and "Empty …". */
export function supportsPermanentDelete(folder: string | null | undefined): folder is PermanentDeleteFolder {
return folder === "trash" || folder === "spam";
}
-export function getEmptyFolderLabel(folder: PermanentDeleteFolder): string {
- return `Empty ${folderLabels[folder]}`;
+export function getEmptyFolderLabel(folder: PermanentDeleteFolder, t: Translator = defaultTranslator): string {
+ return t("list.emptyFolder", { folder: getPermanentDeleteFolderLabel(folder, t) });
}
-export function getPermanentDeleteConfirmText(count: number): string {
- const subject = count === 1 ? "this message" : `these ${count} messages`;
- return `Permanently delete ${subject}? This cannot be undone.`;
+export function getPermanentDeleteConfirmText(count: number, t: Translator = defaultTranslator): string {
+ return t("delete.confirm", { count });
}
-export function getEmptyFolderConfirmText(folder: PermanentDeleteFolder, total?: number): string {
- const what = total === 1 ? "the 1 message" : total && total > 1 ? `all ${total} messages` : "every message";
- return `Permanently delete ${what} in ${folderLabels[folder]}? This cannot be undone.`;
+export function getEmptyFolderConfirmText(folder: PermanentDeleteFolder, total?: number, t: Translator = defaultTranslator): string {
+ const vars = { count: total ?? 0, folder: getPermanentDeleteFolderLabel(folder, t) };
+ if (total === 1) return t("empty.confirm.one", vars);
+ return total && total > 1 ? t("empty.confirm.many", vars) : t("empty.confirm.all", vars);
}