Translate composer

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Hieu Nguyen (Jack)andClaude Sonnet 5.5 committed 2026-10-07 12:31:22 +07:00
1 parent 23e49056b4
commit d535cd3132
11 files changed
+273 -90

No files matched your search

+51 -49
View File
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import type { DragEvent } from "react";
import { ChevronUp, FileText, Forward, Maximize2, Minimize2, Minus, Paperclip, Reply, Trash2, X } from "lucide-react";
import { useRouter } from "next/navigation";
import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
@@ -42,6 +43,7 @@ export function ComposeForm({
draftIdToLoad?: string | null;
onClose?: () => void;
}) {
const { t } = useLanguage();
const router = useRouter();
const { selectedMailbox, setSelectedMailbox, mailboxes } = useSelectedMailbox();
const [draftId, setDraftId] = useState<string | null>(null);
@@ -161,7 +163,7 @@ export function ComposeForm({
})
.catch((err) => {
if (cancelled) return;
const message = err instanceof Error ? err.message : "Failed to load draft";
const message = err instanceof Error ? err.message : t("compose.error.loadDraft");
setToast({ type: "error", message });
})
.finally(() => {
@@ -239,16 +241,16 @@ export function ComposeForm({
async function onSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
if (to.length === 0) {
setToast({ type: "error", message: "Add at least one recipient" });
setToast({ type: "error", message: t("compose.error.noRecipient") });
return;
}
const invalid = [...to, ...cc, ...bcc].find((entry) => !isValidRecipient(entry));
if (invalid) {
setToast({ type: "error", message: `"${invalid}" is not a valid email address` });
setToast({ type: "error", message: t("compose.error.invalidAddress", { address: invalid }) });
return;
}
if (!hasMeaningfulHtml(html) && !quotedHtml) {
setToast({ type: "error", message: "Write a message before sending" });
setToast({ type: "error", message: t("compose.error.emptyBody") });
return;
}
setLoading(true);
@@ -261,20 +263,20 @@ export function ComposeForm({
for (const attachment of attachments) form.append("attachments", attachment.file);
const uploaded = await authFetch(`/api/drafts/${draftId}/attachments`, { method: "POST", body: form });
const result = await uploaded.json() as { attachments?: ComposeStoredAttachment[]; error?: string };
if (!uploaded.ok) throw new Error(result.error || "Could not add attachments to the draft");
if (!uploaded.ok) throw new Error(result.error || t("compose.error.draftAttachments"));
setStoredAttachments((current) => [...current, ...(result.attachments ?? [])]);
setAttachments([]);
}
const updated = await authFetch(`/api/drafts/${draftId}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mailboxId: selectedMailbox?.id, from: fromAddr, to: recipientsToHeader(to), cc: recipientsToHeader(cc), bcc: recipientsToHeader(bcc), subject, html: fullHtml, text: htmlToPlainText(fullHtml), inReplyTo: threading?.inReplyTo ?? null, references: threading?.references ?? null, threadId: threading?.threadId ?? null, scheduledAt: scheduledAt?.toISOString() ?? null }) });
if (!updated.ok) throw new Error("Could not save the draft for review");
if (!updated.ok) throw new Error(t("compose.error.saveForReview"));
const current = await fetchDraft(draftId);
if (!current.agent) throw new Error("AI draft metadata is missing");
if (!current.agent) throw new Error(t("compose.error.aiMetadata"));
setAgentRevision(current.agent.revision);
const response = await authFetch("/api/agent/approvals", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ draftId, expectedRevision: current.agent.revision }) });
const result = await response.json() as { approvalId?: string; snapshot?: ReviewSnapshot; error?: string };
if (!response.ok || !result.approvalId || !result.snapshot) throw new Error(result.error || "Could not create review");
if (!response.ok || !result.approvalId || !result.snapshot) throw new Error(result.error || t("compose.error.createReview"));
setAgentReview({ approvalId: result.approvalId, snapshot: result.snapshot });
} catch (cause) { setToast({ type: "error", message: cause instanceof Error ? cause.message : "Could not review draft" }); }
} catch (cause) { setToast({ type: "error", message: cause instanceof Error ? cause.message : t("compose.error.reviewDraft") }); }
finally { setLoading(false); }
return;
}
@@ -299,7 +301,7 @@ export function ComposeForm({
setLoading(false);
if (!res.ok) {
setToast({ type: "error", message: data.error ?? "Send failed" });
setToast({ type: "error", message: data.error ?? t("compose.error.sendFailed") });
return;
}
@@ -321,7 +323,7 @@ export function ComposeForm({
setQuotedHtml(null);
setAttachments([]);
setScheduledAt(null);
setToast({ type: "success", message: data.scheduled ? "Message scheduled" : "Message sent" });
setToast({ type: "success", message: data.scheduled ? t("compose.scheduled") : t("compose.sent") });
window.dispatchEvent(new Event("mailflare:messages-changed"));
}
@@ -334,7 +336,7 @@ export function ComposeForm({
const res = await authFetch(`/api/drafts/${draftId}`, { method: "DELETE" });
if (!res.ok) {
setDeletingDraft(false);
setToast({ type: "error", message: "Could not delete draft" });
setToast({ type: "error", message: t("compose.error.deleteDraft") });
return;
}
}
@@ -366,7 +368,7 @@ export function ComposeForm({
if (!draftId) return;
const res = await authFetch(`/api/drafts/${draftId}/attachments/${attachmentId}`, { method: "DELETE" });
if (!res.ok) {
setToast({ type: "error", message: "Could not remove attachment" });
setToast({ type: "error", message: t("compose.error.removeAttachment") });
return;
}
setStoredAttachments((current) => current.filter((item) => item.id !== attachmentId));
@@ -384,15 +386,15 @@ export function ComposeForm({
);
if (nextCount > 10) {
setToast({ type: "error", message: "A message can include at most 10 attachments" });
setToast({ type: "error", message: t("compose.error.maxAttachments") });
return;
}
if (nextFiles.some((file) => file.size > attachmentPolicy.maxMb * 1_000_000)) {
setToast({ type: "error", message: `Each attachment must be ${attachmentPolicy.maxMb} MB or smaller` });
setToast({ type: "error", message: t("compose.error.attachmentSize", { max: attachmentPolicy.maxMb }) });
return;
}
if (totalSize > attachmentPolicy.maxMb * 1_000_000) {
setToast({ type: "error", message: `Attachments must total ${attachmentPolicy.maxMb} MB or less` });
setToast({ type: "error", message: t("compose.error.totalSize", { max: attachmentPolicy.maxMb }) });
return;
}
@@ -443,7 +445,7 @@ export function ComposeForm({
<div
key={attachment.id}
className="flex max-w-full shrink-0 items-center gap-2 rounded-lg bg-neutral-100 px-2 py-1 text-xs"
title="Carried over from the forwarded message"
title={t("compose.carriedOver")}
>
<FileText className="h-4 w-4 shrink-0 text-neutral-500" />
<span className="max-w-48 truncate">{attachment.filename}</span>
@@ -454,7 +456,7 @@ export function ComposeForm({
className="rounded-full p-1 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700"
>
<X className="h-3.5 w-3.5" />
<span className="sr-only">Remove attachment</span>
<span className="sr-only">{t("compose.removeAttachment")}</span>
</button>
</div>
))}
@@ -478,12 +480,12 @@ export function ComposeForm({
className="rounded-full p-1 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700"
>
<X className="h-3.5 w-3.5" />
<span className="sr-only">Remove attachment</span>
<span className="sr-only">{t("compose.removeAttachment")}</span>
</button>
</div>
))}
</div>
<p className="px-3 pb-2 text-xs text-amber-700">Cloudflare limits general email messages to 5 MiB including encoding. Files over 3 MB{([...attachments.map((item) => item.file.size), ...storedAttachments.map((item) => item.size)].some((size) => size > attachmentPolicy.cloudThresholdBytes)) ? " here will" : " or files that exceed the message budget may"} be sent as 30-day R2 download links.</p>
<p className="px-3 pb-2 text-xs text-amber-700">{[...attachments.map((item) => item.file.size), ...storedAttachments.map((item) => item.size)].some((size) => size > attachmentPolicy.cloudThresholdBytes) ? t("compose.cloudWarning.will") : t("compose.cloudWarning.may")}</p>
</div>
);
@@ -510,10 +512,10 @@ export function ComposeForm({
{toast.message}
</div>
)}
<form onSubmit={onSubmit} className={frameClass} role={modalMode && !minimized ? "dialog" : undefined} aria-modal={modalMode && !minimized || undefined} aria-label={modalMode && !minimized ? "Compose message" : undefined} onKeyDown={(event) => { if (modalMode && !minimized && event.key === "Escape") { event.preventDefault(); setModalMode(false); } }} onDragEnterCapture={minimized ? undefined : onFileDragEnter} onDragOverCapture={minimized ? undefined : onFileDragOver} onDragLeaveCapture={minimized ? undefined : onFileDragLeave} onDropCapture={minimized ? undefined : onFileDrop}>
<form onSubmit={onSubmit} className={frameClass} role={modalMode && !minimized ? "dialog" : undefined} aria-modal={modalMode && !minimized || undefined} aria-label={modalMode && !minimized ? t("compose.dialogLabel") : undefined} onKeyDown={(event) => { if (modalMode && !minimized && event.key === "Escape") { event.preventDefault(); setModalMode(false); } }} onDragEnterCapture={minimized ? undefined : onFileDragEnter} onDragOverCapture={minimized ? undefined : onFileDragOver} onDragLeaveCapture={minimized ? undefined : onFileDragLeave} onDropCapture={minimized ? undefined : onFileDrop}>
{draggingFiles && !minimized && (
<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center border-2 border-dashed border-blue-400 bg-blue-50/90 text-sm font-medium text-blue-700" aria-hidden="true">
Drop files to attach
{t("compose.dropFiles")}
</div>
)}
<div className="flex h-9 shrink-0 items-center justify-between bg-neutral-800 text-white dark:bg-neutral-100 px-4 text-sm font-medium">
@@ -521,24 +523,24 @@ export function ComposeForm({
{threading?.inReplyTo && <Reply className="h-3.5 w-3.5 text-neutral-300" />}
{!threading?.inReplyTo && /^fwd?:/i.test(subject) && <Forward className="h-3.5 w-3.5 text-neutral-300" />}
{loadingDraft
? "Loading draft"
? t("compose.title.loading")
: threading?.inReplyTo
? "Reply"
? t("compose.title.reply")
: /^fwd?:/i.test(subject)
? "Forward"
? t("compose.title.forward")
: draftId
? "Draft saved"
: "New Message"}
? t("compose.title.saved")
: t("compose.title.new")}
</span>
{mode === "popup" && (
<div className="flex shrink-0 items-center gap-3 text-neutral-300">
<button type="button" onClick={() => { setMinimized((current) => !current); setDraggingFiles(false); }} aria-label={minimized ? "Restore composer" : "Minimize composer"} title={minimized ? "Restore composer" : "Minimize composer"} className="rounded p-1 hover:bg-neutral-700 dark:hover:bg-neutral-200 hover:text-white">
<button type="button" onClick={() => { setMinimized((current) => !current); setDraggingFiles(false); }} aria-label={minimized ? t("compose.restore") : t("compose.minimize")} title={minimized ? t("compose.restore") : t("compose.minimize")} className="rounded p-1 hover:bg-neutral-700 dark:hover:bg-neutral-200 hover:text-white">
{minimized ? <ChevronUp className="h-4 w-4" /> : <Minus className="h-4 w-4" />}
</button>
<button type="button" onClick={() => { if (minimized) setMinimized(false); setModalMode((current) => !current); }} aria-label={modalMode ? "Restore floating composer" : "Open composer as modal"} title={modalMode ? "Restore floating composer" : "Open composer as modal"} className="rounded p-1 dark:hover:bg-neutral-200 hover:bg-neutral-700 hover:text-white">
<button type="button" onClick={() => { if (minimized) setMinimized(false); setModalMode((current) => !current); }} aria-label={modalMode ? t("compose.restoreFloating") : t("compose.openModal")} title={modalMode ? t("compose.restoreFloating") : t("compose.openModal")} className="rounded p-1 dark:hover:bg-neutral-200 hover:bg-neutral-700 hover:text-white">
{modalMode ? <Minimize2 className="h-4 w-4" /> : <Maximize2 className="h-4 w-4" />}
</button>
<button type="button" onClick={onClose} aria-label="Close composer" className="rounded p-1 hover:bg-neutral-700 dark:hover:bg-neutral-200 hover:text-white">
<button type="button" onClick={onClose} aria-label={t("compose.close")} className="rounded p-1 hover:bg-neutral-700 dark:hover:bg-neutral-200 hover:text-white">
<X className="h-4 w-4" />
</button>
</div>
@@ -546,7 +548,7 @@ export function ComposeForm({
</div>
<div className={cn("flex min-h-0 flex-1 flex-col", minimized && "hidden")}>
<div className="border-b border-neutral-100 px-4 py-1 flex flex-row items-center">
<Label htmlFor={`${mode}-from`} className="text-sm text-neutral-500">From</Label>
<Label htmlFor={`${mode}-from`} className="text-sm text-neutral-500">{t("compose.from")}</Label>
<Select
id={`${mode}-from`}
value={selectedMailbox && selectedFrom ? `${selectedMailbox.id}|${selectedFrom}` : ""}
@@ -557,7 +559,7 @@ export function ComposeForm({
className="h-8 px-0 py-1 text-sm shadow-none focus-visible:ring-0"
containerClassName="border-0 flex-1"
>
{senderOptions.length === 0 && <option value="">Select a mailbox first</option>}
{senderOptions.length === 0 && <option value="">{t("compose.selectMailboxFirst")}</option>}
{senderOptions.map(({ mailbox, address }) => (
<option key={`${mailbox.id}|${address}`} value={`${mailbox.id}|${address}`}>{address}</option>
))}
@@ -565,22 +567,22 @@ export function ComposeForm({
</div>
<RecipientInput
id={`${mode}-to`}
label="To"
label={t("compose.to")}
value={to}
onChange={setTo}
placeholder='Recipients, or "Maya Chen" <maya@example.com>'
placeholder={t("compose.toPlaceholder")}
required
disabled={loadingDraft}
trailing={
<>
{!showCc && (
<button type="button" className="rounded px-1 hover:text-neutral-800" onClick={() => setShowCc(true)}>
Cc
{t("compose.cc")}
</button>
)}
{!showBcc && (
<button type="button" className="rounded px-1 hover:text-neutral-800" onClick={() => setShowBcc(true)}>
Bcc
{t("compose.bcc")}
</button>
)}
</>
@@ -589,10 +591,10 @@ export function ComposeForm({
{showCc && (
<RecipientInput
id={`${mode}-cc`}
label="Cc"
label={t("compose.cc")}
value={cc}
onChange={setCc}
placeholder="Carbon copy"
placeholder={t("compose.ccPlaceholder")}
disabled={loadingDraft}
autoFocus={!loadingDraft && cc.length === 0}
/>
@@ -600,34 +602,34 @@ export function ComposeForm({
{showBcc && (
<RecipientInput
id={`${mode}-bcc`}
label="Bcc"
label={t("compose.bcc")}
value={bcc}
onChange={setBcc}
placeholder="Blind carbon copy, hidden from other recipients"
placeholder={t("compose.bccPlaceholder")}
disabled={loadingDraft}
autoFocus={!loadingDraft && bcc.length === 0}
/>
)}
<div className="border-b border-neutral-100 px-4 py-1">
<Label htmlFor={`${mode}-subject`} className="sr-only">Subject</Label>
<Label htmlFor={`${mode}-subject`} className="sr-only">{t("compose.subject")}</Label>
<Input
id={`${mode}-subject`}
value={subject}
onChange={(event) => setSubject(event.target.value)}
placeholder="Subject"
placeholder={t("compose.subject")}
required
disabled={loadingDraft}
className="h-8 border-0 px-0 py-1 shadow-none focus-visible:ring-0"
/>
</div>
<Label htmlFor={`${mode}-text`} className="sr-only">Body</Label>
<Label htmlFor={`${mode}-text`} className="sr-only">{t("compose.body")}</Label>
<RichTextEditor
id={`${mode}-text`}
value={html}
onChange={setHtml}
quotedHtml={quotedHtml}
disabled={loadingDraft}
placeholder="Write your message"
placeholder={t("compose.bodyPlaceholder")}
footerContent={attachmentContent}
toolbarStart={
<>
@@ -638,7 +640,7 @@ export function ComposeForm({
disabled={loading || loadingDraft || !fromAddr}
className="rounded-r-none px-4"
>
{loading ? "Preparing…" : scheduledAt ? "Schedule" : agentRevision !== null ? "Review send" : "Send"}
{loading ? t("compose.preparing") : scheduledAt ? t("compose.schedule") : agentRevision !== null ? t("compose.reviewSend") : t("compose.send")}
</Button>
<ScheduleSendMenu
disabled={loading || loadingDraft || !fromAddr}
@@ -664,10 +666,10 @@ export function ComposeForm({
className="hidden"
onChange={(event) => addAttachments(event.target.files)}
/>
<Tooltip label={`Attach files (up to ${attachmentPolicy.maxMb} MB total). Files over 3 MB are sent as 30-day R2 download links.`}>
<Tooltip label={t("compose.attachTooltip", { max: attachmentPolicy.maxMb })}>
<button
type="button"
aria-label="Attach files"
aria-label={t("compose.attachFiles")}
onClick={() => attachmentInput.current?.click()}
disabled={loading || loadingDraft}
className="rounded-md p-1.5 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900 disabled:pointer-events-none disabled:opacity-50"
@@ -676,10 +678,10 @@ export function ComposeForm({
</button>
</Tooltip>
<span className="flex-1" />
<Tooltip label="Delete draft">
<Tooltip label={t("compose.deleteDraft")}>
<button
type="button"
aria-label="Delete draft"
aria-label={t("compose.deleteDraft")}
onClick={() => void deleteDraftAndClose()}
disabled={loading || loadingDraft || deletingDraft}
className="rounded-md p-1.5 text-neutral-500 hover:bg-red-50 hover:text-red-600 disabled:pointer-events-none disabled:opacity-50"
@@ -1,6 +1,7 @@
"use client";
import { useState } from "react";
import { useLanguage } from "@/components/language-provider";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
@@ -11,6 +12,7 @@ import { textToHtml } from "./rich-text-utils";
import type { NewTemplateDialogProps } from "./template-types";
export function NewTemplateDialog({ open, onOpenChange, mailboxId, from }: NewTemplateDialogProps) {
const { t } = useLanguage();
const [title, setTitle] = useState("");
const [content, setContent] = useState("");
const [saving, setSaving] = useState(false);
@@ -26,14 +28,14 @@ export function NewTemplateDialog({ open, onOpenChange, mailboxId, from }: NewTe
body: JSON.stringify({ mailboxId, from, title, text: content, html: textToHtml(content) }),
});
if (!response.ok) {
setError(((await response.json().catch(() => null)) as { error?: string } | null)?.error ?? "Could not save template");
setError(((await response.json().catch(() => null)) as { error?: string } | null)?.error ?? t("template.saveFailed"));
return;
}
onOpenChange(false);
setTitle("");
setContent("");
} catch {
setError("Could not save template");
setError(t("template.saveFailed"));
} finally {
setSaving(false);
}
@@ -42,22 +44,22 @@ export function NewTemplateDialog({ open, onOpenChange, mailboxId, from }: NewTe
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[calc(100vh-4rem)] overflow-y-auto">
<DialogHeader><DialogTitle>New template</DialogTitle></DialogHeader>
<DialogHeader><DialogTitle>{t("template.new")}</DialogTitle></DialogHeader>
<form
className="space-y-4"
onSubmit={(event) => { event.preventDefault(); void save(); }}
>
<div className="space-y-1.5">
<Label htmlFor="template-title">Title</Label>
<Label htmlFor="template-title">{t("template.title")}</Label>
<Input id="template-title" value={title} onChange={(event) => setTitle(event.target.value)} maxLength={200} required />
</div>
<div className="space-y-1.5">
<Label htmlFor="template-content">Content</Label>
<Label htmlFor="template-content">{t("template.content")}</Label>
<Textarea id="template-content" value={content} onChange={(event) => setContent(event.target.value)} rows={8} required />
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
<Button type="submit" disabled={saving || !title.trim() || !content.trim()}>
{saving ? "Saving…" : "Save template"}
{saving ? t("template.saving") : t("template.save")}
</Button>
</form>
</DialogContent>
+3 -1
View File
@@ -3,6 +3,7 @@
import { useRef, useState } from "react";
import type { KeyboardEvent } from "react";
import { X } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { Label } from "@/components/ui/label";
import { getEmailAddress } from "@/lib/email/address";
import { cn } from "@/lib/utils";
@@ -25,6 +26,7 @@ export function RecipientInput({
autoFocus,
trailing,
}: RecipientInputProps) {
const { t } = useLanguage();
const [draft, setDraft] = useState("");
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -74,7 +76,7 @@ export function RecipientInput({
{!disabled && (
<button
type="button"
aria-label={`Remove ${getEmailAddress(entry)}`}
aria-label={t("recipient.remove", { address: getEmailAddress(entry) })}
className="rounded-full p-0.5 text-neutral-400 hover:bg-neutral-200 hover:text-neutral-700"
onClick={(event) => {
event.stopPropagation();
+2 -1
View File
@@ -1,3 +1,4 @@
import type { TranslationKey } from "@/lib/i18n/types";
export type RichTextEditorProps = {
id: string;
/** Editable HTML. */
@@ -15,7 +16,7 @@ export type RichTextEditorProps = {
export type ToolbarCommand = {
command: string;
label: string;
labelKey: TranslationKey;
icon: React.ComponentType<{ className?: string }>;
value?: string;
};
+18 -16
View File
@@ -13,6 +13,7 @@ import {
Strikethrough,
Underline,
} from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { Tooltip } from "@/components/ui/tooltip";
import { cn } from "@/lib/utils";
import { EmailHtmlRenderer } from "@/components/messages/email-html-renderer";
@@ -20,13 +21,13 @@ import { sanitizeEmailHtml, sanitizeEditorHtml } from "@/lib/email/html";
import type { RichTextEditorProps, ToolbarCommand } from "./rich-text-editor-types";
const COMMANDS: ToolbarCommand[] = [
{ command: "bold", label: "Bold (⌘B)", icon: Bold },
{ command: "italic", label: "Italic (⌘I)", icon: Italic },
{ command: "underline", label: "Underline (⌘U)", icon: Underline },
{ command: "strikeThrough", label: "Strikethrough", icon: Strikethrough },
{ command: "insertUnorderedList", label: "Bulleted list", icon: List },
{ command: "insertOrderedList", label: "Numbered list", icon: ListOrdered },
{ command: "formatBlock", label: "Quote", icon: Quote, value: "blockquote" },
{ command: "bold", labelKey: "editor.bold", icon: Bold },
{ command: "italic", labelKey: "editor.italic", icon: Italic },
{ command: "underline", labelKey: "editor.underline", icon: Underline },
{ command: "strikeThrough", labelKey: "editor.strikethrough", icon: Strikethrough },
{ command: "insertUnorderedList", labelKey: "editor.bulletedList", icon: List },
{ command: "insertOrderedList", labelKey: "editor.numberedList", icon: ListOrdered },
{ command: "formatBlock", labelKey: "editor.quote", icon: Quote, value: "blockquote" },
];
/**
@@ -46,6 +47,7 @@ export function RichTextEditor({
toolbarEnd,
footerContent,
}: RichTextEditorProps) {
const { t } = useLanguage();
const editorRef = useRef<HTMLDivElement | null>(null);
const [active, setActive] = useState<Record<string, boolean>>({});
const [linkOpen, setLinkOpen] = useState(false);
@@ -141,7 +143,7 @@ export function RichTextEditor({
id={id}
role="textbox"
aria-multiline="true"
aria-label="Message body"
aria-label={t("editor.messageBody")}
contentEditable={!disabled}
suppressContentEditableWarning
data-placeholder={placeholder}
@@ -162,7 +164,7 @@ export function RichTextEditor({
onClick={() => setShowQuoted((open) => !open)}
aria-expanded={showQuoted}
className="rounded-full border border-neutral-200 bg-neutral-100 px-2 text-xs leading-5 text-neutral-500 hover:bg-neutral-200"
title={showQuoted ? "Hide quoted text" : "Show quoted text"}
title={showQuoted ? t("editor.hideQuoted") : t("editor.showQuoted")}
>
•••
</button>
@@ -176,10 +178,10 @@ export function RichTextEditor({
<div className="relative flex items-center gap-0.5 border-t border-neutral-100 px-4 py-3">
{toolbarStart}
{COMMANDS.map((item) => (
<Tooltip key={item.command} label={item.label}>
<Tooltip key={item.command} label={t(item.labelKey)}>
<button
type="button"
aria-label={item.label}
aria-label={t(item.labelKey)}
aria-pressed={!!active[item.command]}
disabled={disabled}
onMouseDown={(event) => event.preventDefault()}
@@ -193,10 +195,10 @@ export function RichTextEditor({
</button>
</Tooltip>
))}
<Tooltip label="Insert link (⌘K)">
<Tooltip label={t("editor.insertLinkHint")}>
<button
type="button"
aria-label="Insert link"
aria-label={t("editor.insertLink")}
disabled={disabled}
onMouseDown={(event) => event.preventDefault()}
onClick={openLink}
@@ -205,10 +207,10 @@ export function RichTextEditor({
<Link2 className="h-4 w-4" />
</button>
</Tooltip>
<Tooltip label="Clear formatting">
<Tooltip label={t("editor.clearFormatting")}>
<button
type="button"
aria-label="Clear formatting"
aria-label={t("editor.clearFormatting")}
disabled={disabled}
onMouseDown={(event) => event.preventDefault()}
onClick={() => run("removeFormat")}
@@ -237,7 +239,7 @@ export function RichTextEditor({
className="h-8 w-64 rounded-md border border-neutral-200 px-2 text-sm outline-none focus:border-blue-400"
/>
<button type="submit" className="rounded-md bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700">
Apply
{t("editor.apply")}
</button>
</form>
)}
@@ -3,6 +3,7 @@
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { useState } from "react";
import { ChevronDown, X } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { NewTemplateDialog } from "./new-template-dialog";
import { TemplateMenu } from "./template-menu";
import {
@@ -15,6 +16,7 @@ import type { ScheduleSendMenuProps } from "./schedule-send-types";
import { getUserTimeZone } from "@/lib/time/utils";
export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, onApplyTemplate }: ScheduleSendMenuProps) {
const { t } = useLanguage();
const [newTemplateOpen, setNewTemplateOpen] = useState(false);
const options = getScheduleSendOptions();
const minimum = new Date(Date.now() + 5 * 60 * 1000);
@@ -25,7 +27,7 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, o
<DropdownMenu.Trigger
type="button"
disabled={disabled}
aria-label="Schedule send options"
aria-label={t("schedule.optionsLabel")}
className="inline-flex h-8 items-center justify-center rounded-r-lg border-l border-blue-500 bg-blue-600 px-2 text-white transition-colors hover:bg-blue-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
>
<ChevronDown className="h-4 w-4" />
@@ -38,7 +40,7 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, o
>
<TemplateMenu onApply={onApplyTemplate} onNew={() => setNewTemplateOpen(true)} />
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
<DropdownMenu.Label className="px-3 pb-1 pt-2 text-xs font-medium text-neutral-500">Schedule</DropdownMenu.Label>
<DropdownMenu.Label className="px-3 pb-1 pt-2 text-xs font-medium text-neutral-500">{t("schedule.heading")}</DropdownMenu.Label>
{value && (
<>
<DropdownMenu.Item
@@ -46,18 +48,18 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, o
className="flex cursor-pointer items-center rounded-md px-3 py-2 outline-none hover:bg-neutral-100 focus:bg-neutral-100"
>
<X className="mr-2 h-4 w-4" />
Clear schedule
{t("schedule.clear")}
</DropdownMenu.Item>
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
</>
)}
{options.map((option) => (
<DropdownMenu.Item
key={option.label}
key={option.labelKey}
onSelect={() => onChange(option.value)}
className="cursor-pointer rounded-md px-3 py-2 outline-none hover:bg-neutral-100 focus:bg-neutral-100"
>
{option.label}
{t(option.labelKey)}
<span className="ml-2 text-xs text-neutral-400">
{option.value && formatScheduledSend(option.value)}
</span>
@@ -65,7 +67,7 @@ export function ScheduleSendMenu({ disabled, value, onChange, mailboxId, from, o
))}
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
<DropdownMenu.Label className="px-3 pb-1 pt-2 text-xs font-medium text-neutral-500">
Pick date &amp; time ({getUserTimeZone()})
{t("schedule.pick", { timeZone: getUserTimeZone() })}
</DropdownMenu.Label>
<input
type="datetime-local"
+3 -1
View File
@@ -1,5 +1,7 @@
import type { TranslationKey } from "@/lib/i18n/types";
export type ScheduleSendOption = {
label: string;
labelKey: TranslationKey;
value: Date | null;
};
@@ -17,9 +17,9 @@ export function getScheduleSendOptions(now = new Date()): ScheduleSendOption[] {
monday.setUTCDate(monday.getUTCDate() + daysUntilMonday);
return [
{ label: zonedDateFields(laterToday, getUserTimeZone()).toISOString().slice(0, 10) === today.toISOString().slice(0, 10) ? "Later today" : "In 3 hours", value: laterToday },
{ label: "Tomorrow morning", value: atTime(tomorrow, 8) },
{ label: "Monday morning", value: atTime(monday, 8) },
{ labelKey: zonedDateFields(laterToday, getUserTimeZone()).toISOString().slice(0, 10) === today.toISOString().slice(0, 10) ? "schedule.laterToday" : "schedule.in3Hours", value: laterToday },
{ labelKey: "schedule.tomorrowMorning", value: atTime(tomorrow, 8) },
{ labelKey: "schedule.mondayMorning", value: atTime(monday, 8) },
];
}
+7 -5
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react";
import * as DropdownMenu from "@radix-ui/react-dropdown-menu";
import { ChevronRight, FileText, Plus, Trash2 } from "lucide-react";
import { useLanguage } from "@/components/language-provider";
import { authFetch } from "@/lib/auth/client";
import { textToHtml } from "./rich-text-utils";
import type { ComposeTemplate, TemplateMenuProps } from "./template-types";
@@ -10,6 +11,7 @@ import type { ComposeTemplate, TemplateMenuProps } from "./template-types";
const itemClass = "flex cursor-pointer items-center rounded-md px-3 py-2 outline-none hover:bg-neutral-100 focus:bg-neutral-100";
export function TemplateMenu({ onApply, onNew }: TemplateMenuProps) {
const { t } = useLanguage();
const [templates, setTemplates] = useState<ComposeTemplate[]>([]);
useEffect(() => {
@@ -27,7 +29,7 @@ export function TemplateMenu({ onApply, onNew }: TemplateMenuProps) {
return (
<DropdownMenu.Sub>
<DropdownMenu.SubTrigger className={`${itemClass} justify-between data-[state=open]:bg-neutral-100`}>
<span className="flex items-center"><FileText className="mr-2 h-4 w-4" />Template</span>
<span className="flex items-center"><FileText className="mr-2 h-4 w-4" />{t("template.menu")}</span>
<ChevronRight className="ml-4 h-4 w-4 text-neutral-400" />
</DropdownMenu.SubTrigger>
<DropdownMenu.Portal>
@@ -36,17 +38,17 @@ export function TemplateMenu({ onApply, onNew }: TemplateMenuProps) {
className="z-50 flex max-h-80 w-64 flex-col rounded-lg border border-neutral-200 bg-white p-1 text-sm shadow-lg"
>
<div className="min-h-0 flex-1 overflow-y-auto">
{templates.length === 0 && <p className="px-3 py-2 text-xs text-neutral-400">No templates yet</p>}
{templates.length === 0 && <p className="px-3 py-2 text-xs text-neutral-400">{t("template.none")}</p>}
{templates.map((template) => (
<DropdownMenu.Item
key={template.id}
onSelect={() => onApply({ title: template.subject ?? "", html: template.htmlBody ?? textToHtml(template.textBody ?? "") })}
className={`${itemClass} group justify-between gap-2`}
>
<span className="whitespace-normal break-words">{template.subject || "Untitled"}</span>
<span className="whitespace-normal break-words">{template.subject || t("template.untitled")}</span>
<button
type="button"
aria-label="Delete template"
aria-label={t("template.delete")}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => { event.stopPropagation(); void remove(template.id); }}
className="shrink-0 rounded p-1 text-neutral-400 opacity-0 hover:text-red-600 group-hover:opacity-100 group-focus:opacity-100"
@@ -58,7 +60,7 @@ export function TemplateMenu({ onApply, onNew }: TemplateMenuProps) {
</div>
<DropdownMenu.Separator className="my-1 h-px bg-neutral-100" />
<DropdownMenu.Item onSelect={onNew} className={`${itemClass} text-blue-600`}>
<Plus className="mr-2 h-4 w-4" />New template
<Plus className="mr-2 h-4 w-4" />{t("template.new")}
</DropdownMenu.Item>
</DropdownMenu.SubContent>
</DropdownMenu.Portal>
+85 -1
View File
@@ -165,5 +165,89 @@
"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"
"list.resize": "Resize message list",
"compose.error.loadDraft": "Failed to load draft",
"compose.error.noRecipient": "Add at least one recipient",
"compose.error.invalidAddress": "\"{address}\" is not a valid email address",
"compose.error.emptyBody": "Write a message before sending",
"compose.error.draftAttachments": "Could not add attachments to the draft",
"compose.error.saveForReview": "Could not save the draft for review",
"compose.error.aiMetadata": "AI draft metadata is missing",
"compose.error.createReview": "Could not create review",
"compose.error.reviewDraft": "Could not review draft",
"compose.error.sendFailed": "Send failed",
"compose.error.deleteDraft": "Could not delete draft",
"compose.error.removeAttachment": "Could not remove attachment",
"compose.error.maxAttachments": "A message can include at most 10 attachments",
"compose.error.attachmentSize": "Each attachment must be {max} MB or smaller",
"compose.error.totalSize": "Attachments must total {max} MB or less",
"compose.scheduled": "Message scheduled",
"compose.sent": "Message sent",
"compose.carriedOver": "Carried over from the forwarded message",
"compose.removeAttachment": "Remove attachment",
"compose.cloudWarning.will": "Cloudflare limits general email messages to 5 MiB including encoding. Files over 3 MB here will be sent as 30-day R2 download links.",
"compose.cloudWarning.may": "Cloudflare limits general email messages to 5 MiB including encoding. Files over 3 MB or files that exceed the message budget may be sent as 30-day R2 download links.",
"compose.dialogLabel": "Compose message",
"compose.dropFiles": "Drop files to attach",
"compose.title.loading": "Loading draft",
"compose.title.reply": "Reply",
"compose.title.forward": "Forward",
"compose.title.saved": "Draft saved",
"compose.title.new": "New Message",
"compose.restore": "Restore composer",
"compose.minimize": "Minimize composer",
"compose.restoreFloating": "Restore floating composer",
"compose.openModal": "Open composer as modal",
"compose.close": "Close composer",
"compose.from": "From",
"compose.selectMailboxFirst": "Select a mailbox first",
"compose.to": "To",
"compose.toPlaceholder": "Recipients, or \"Maya Chen\" <maya@example.com>",
"compose.cc": "Cc",
"compose.bcc": "Bcc",
"compose.ccPlaceholder": "Carbon copy",
"compose.bccPlaceholder": "Blind carbon copy, hidden from other recipients",
"compose.subject": "Subject",
"compose.body": "Body",
"compose.bodyPlaceholder": "Write your message",
"compose.preparing": "Preparing…",
"compose.schedule": "Schedule",
"compose.reviewSend": "Review send",
"compose.send": "Send",
"compose.attachTooltip": "Attach files (up to {max} MB total). Files over 3 MB are sent as 30-day R2 download links.",
"compose.attachFiles": "Attach files",
"compose.deleteDraft": "Delete draft",
"editor.bold": "Bold (⌘B)",
"editor.italic": "Italic (⌘I)",
"editor.underline": "Underline (⌘U)",
"editor.strikethrough": "Strikethrough",
"editor.bulletedList": "Bulleted list",
"editor.numberedList": "Numbered list",
"editor.quote": "Quote",
"editor.messageBody": "Message body",
"editor.hideQuoted": "Hide quoted text",
"editor.showQuoted": "Show quoted text",
"editor.insertLinkHint": "Insert link (⌘K)",
"editor.insertLink": "Insert link",
"editor.clearFormatting": "Clear formatting",
"editor.apply": "Apply",
"schedule.optionsLabel": "Schedule send options",
"schedule.heading": "Schedule",
"schedule.clear": "Clear schedule",
"schedule.pick": "Pick date & time ({timeZone})",
"schedule.laterToday": "Later today",
"schedule.in3Hours": "In 3 hours",
"schedule.tomorrowMorning": "Tomorrow morning",
"schedule.mondayMorning": "Monday morning",
"template.menu": "Template",
"template.none": "No templates yet",
"template.untitled": "Untitled",
"template.delete": "Delete template",
"template.new": "New template",
"template.title": "Title",
"template.content": "Content",
"template.saving": "Saving…",
"template.save": "Save template",
"template.saveFailed": "Could not save template",
"recipient.remove": "Remove {address}"
}
+85 -1
View File
@@ -165,5 +165,89 @@
"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"
"list.resize": "Redimensionar lista de mensagens",
"compose.error.loadDraft": "Falha ao carregar o rascunho",
"compose.error.noRecipient": "Adicione pelo menos um destinatário",
"compose.error.invalidAddress": "\"{address}\" não é um endereço de e-mail válido",
"compose.error.emptyBody": "Escreva uma mensagem antes de enviar",
"compose.error.draftAttachments": "Não foi possível adicionar anexos ao rascunho",
"compose.error.saveForReview": "Não foi possível salvar o rascunho para revisão",
"compose.error.aiMetadata": "Faltam os metadados do rascunho de IA",
"compose.error.createReview": "Não foi possível criar a revisão",
"compose.error.reviewDraft": "Não foi possível revisar o rascunho",
"compose.error.sendFailed": "Falha no envio",
"compose.error.deleteDraft": "Não foi possível excluir o rascunho",
"compose.error.removeAttachment": "Não foi possível remover o anexo",
"compose.error.maxAttachments": "Uma mensagem pode ter no máximo 10 anexos",
"compose.error.attachmentSize": "Cada anexo deve ter {max} MB ou menos",
"compose.error.totalSize": "Os anexos devem somar {max} MB ou menos",
"compose.scheduled": "Mensagem agendada",
"compose.sent": "Mensagem enviada",
"compose.carriedOver": "Trazido da mensagem encaminhada",
"compose.removeAttachment": "Remover anexo",
"compose.cloudWarning.will": "A Cloudflare limita e-mails comuns a 5 MiB, incluindo a codificação. Arquivos acima de 3 MB aqui serão enviados como links de download R2 válidos por 30 dias.",
"compose.cloudWarning.may": "A Cloudflare limita e-mails comuns a 5 MiB, incluindo a codificação. Arquivos acima de 3 MB ou que excedam o limite da mensagem podem ser enviados como links de download R2 válidos por 30 dias.",
"compose.dialogLabel": "Escrever mensagem",
"compose.dropFiles": "Solte arquivos para anexar",
"compose.title.loading": "Carregando rascunho",
"compose.title.reply": "Resposta",
"compose.title.forward": "Encaminhamento",
"compose.title.saved": "Rascunho salvo",
"compose.title.new": "Nova mensagem",
"compose.restore": "Restaurar editor",
"compose.minimize": "Minimizar editor",
"compose.restoreFloating": "Restaurar editor flutuante",
"compose.openModal": "Abrir editor em janela modal",
"compose.close": "Fechar editor",
"compose.from": "De",
"compose.selectMailboxFirst": "Selecione uma caixa de correio primeiro",
"compose.to": "Para",
"compose.toPlaceholder": "Destinatários, ou \"Maya Chen\" <maya@example.com>",
"compose.cc": "Cc",
"compose.bcc": "Cco",
"compose.ccPlaceholder": "Cópia",
"compose.bccPlaceholder": "Cópia oculta, invisível para os outros destinatários",
"compose.subject": "Assunto",
"compose.body": "Corpo",
"compose.bodyPlaceholder": "Escreva sua mensagem",
"compose.preparing": "Preparando…",
"compose.schedule": "Agendar",
"compose.reviewSend": "Revisar envio",
"compose.send": "Enviar",
"compose.attachTooltip": "Anexar arquivos (até {max} MB no total). Arquivos acima de 3 MB são enviados como links de download R2 válidos por 30 dias.",
"compose.attachFiles": "Anexar arquivos",
"compose.deleteDraft": "Excluir rascunho",
"editor.bold": "Negrito (⌘B)",
"editor.italic": "Itálico (⌘I)",
"editor.underline": "Sublinhado (⌘U)",
"editor.strikethrough": "Tachado",
"editor.bulletedList": "Lista com marcadores",
"editor.numberedList": "Lista numerada",
"editor.quote": "Citação",
"editor.messageBody": "Corpo da mensagem",
"editor.hideQuoted": "Ocultar texto citado",
"editor.showQuoted": "Mostrar texto citado",
"editor.insertLinkHint": "Inserir link (⌘K)",
"editor.insertLink": "Inserir link",
"editor.clearFormatting": "Limpar formatação",
"editor.apply": "Aplicar",
"schedule.optionsLabel": "Opções de agendamento de envio",
"schedule.heading": "Agendar",
"schedule.clear": "Limpar agendamento",
"schedule.pick": "Escolher data e hora ({timeZone})",
"schedule.laterToday": "Mais tarde hoje",
"schedule.in3Hours": "Em 3 horas",
"schedule.tomorrowMorning": "Amanhã de manhã",
"schedule.mondayMorning": "Segunda-feira de manhã",
"template.menu": "Modelo",
"template.none": "Nenhum modelo ainda",
"template.untitled": "Sem título",
"template.delete": "Excluir modelo",
"template.new": "Novo modelo",
"template.title": "Título",
"template.content": "Conteúdo",
"template.saving": "Salvando…",
"template.save": "Salvar modelo",
"template.saveFailed": "Não foi possível salvar o modelo",
"recipient.remove": "Remover {address}"
}