Skip to content

Email for professionals and teams

Add English and Brazilian Portuguese language selection for email navigation

forge-z39bd23650227
diff --git a/docs/localization.md b/docs/localization.md
new file mode 100644
index 0000000..7a6b9d4
--- /dev/null
+++ b/docs/localization.md
@@ -0,0 +1,23 @@
+# Interface languages
+
+Mailflare defaults to English. The expanded sidebar has a **Language** selector with English and Português (Brasil). Expand the menu first if the sidebar is collapsed; on phones, open the menu to reach the selector.
+
+## Current coverage
+
+This first translation covers the email sidebar: system folders, expand/collapse controls, the custom-folder creation dialog, shortcut button, footer, and language selector. Custom folder names and mailbox names remain user content. Shared sidebar controls are also translated when used in other sections.
+
+The rest of the interface is still in English, including account menus, login, message lists, the composer, calendar, settings, administration pages, shortcut help, API errors, notifications and system emails. Selecting Portuguese does not translate email content, change routes or system-folder identifiers, or change date/time formatting.
+
+## Preference and rendering
+
+The selection applies immediately and is saved in the host-only `mailflare-locale` cookie for one year (`Path=/`, `SameSite=Lax`, `Secure` on HTTPS). It is a browser preference shared across accounts on the same installation. If cookies are blocked, the current selection works until the page is reloaded.
+
+The root layout reads the cookie with `await cookies()`, normalizes it to `en` or `pt-BR`, and uses the same value for `<html lang>` and the client language provider. This makes pages use request-time rendering, including otherwise static pages. A missing or unsupported cookie selects English. Client navigation preserves the provider state; reloading or opening a new tab restores the cookie selection. This version does not synchronize changes into tabs that are already open.
+
+## Adding translations
+
+Catalogs are flat JSON objects in `src/lib/i18n/en.json` and `src/lib/i18n/pt-BR.json`. Add the English key and the Portuguese translation together. `TranslationKey` derives from the English catalog, and each locale implements the same `Messages` type. `translate()` falls back to English for an absent entry.
+
+Client components use `useLanguage().t(key)`. Keep routes, storage keys, permission checks, API values and user content independent of translated display text. Extend coverage gradually rather than replacing strings throughout the app in one change.
+
+Run `node --test tests/i18n.test.mjs` for catalog parity, fallback, cookie attributes, selector labels, server rendering and root-layout locale agreement. Also run lint, `npx tsc --noEmit` and the applicable build when changing the integration.
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index c6238d5..445d350 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -1,6 +1,9 @@
import type { Metadata } from "next";
+import { cookies } from "next/headers";
import { Geist, Geist_Mono } from "next/font/google";
import { Providers } from "@/components/providers";
+import { LanguageProvider } from "@/components/language-provider";
+import { LOCALE_COOKIE, resolveLocale } from "@/lib/i18n/utils";
import { sidebarBootstrapScript } from "@/components/sidebar-state-utils";
import { themeBootstrapScript } from "@/components/theme-utils";
import "./globals.css";
@@ -35,16 +38,17 @@ export const metadata: Metadata = {
},
};
-export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
+export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
+ const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value);
return (
- <html lang="en" suppressHydrationWarning>
+ <html lang={locale} suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: sidebarBootstrapScript }} />
<script dangerouslySetInnerHTML={{ __html: themeBootstrapScript }} />
<link rel="icon" href="/api/branding/icon"></link>
</head>
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
- <Providers>{children}</Providers>
+ <LanguageProvider initialLocale={locale}><Providers>{children}</Providers></LanguageProvider>
</body>
</html>
);
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index 732bedc..144c65d 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -1,6 +1,8 @@
"use client";
import type { FormEvent } from "react";
+import { useLanguage } from "./language-provider";
+import type { TranslationKey } from "@/lib/i18n/types";
import { useEffect, useState } from "react";
import { usePathname } from "next/navigation";
import {
@@ -53,21 +55,32 @@ import { SidebarScaffold } from "./sidebar-scaffold";
import { useSidebar } from "./sidebar-state";
const links = [
- { href: "/compose", label: "Compose", icon: MailPlus, primary: true },
- { href: "/inbox", label: "Inbox", icon: Inbox, preloadMessages: true },
- { href: "/starred", label: "Starred", icon: Star, preloadMessages: true },
- { href: "/snoozed", label: "Snoozed", icon: Clock, preloadMessages: true },
- { href: "/sent", label: "Sent", icon: Send, preloadMessages: true },
- { href: "/drafts", label: "Drafts", icon: FileText, preloadMessages: true },
+ { href: "/compose", labelKey: "navigation.compose", icon: MailPlus, primary: true },
+ { href: "/inbox", labelKey: "navigation.inbox", icon: Inbox, preloadMessages: true },
+ { href: "/starred", labelKey: "navigation.starred", icon: Star, preloadMessages: true },
+ { href: "/snoozed", labelKey: "navigation.snoozed", icon: Clock, preloadMessages: true },
+ { href: "/sent", labelKey: "navigation.sent", icon: Send, preloadMessages: true },
+ { href: "/drafts", labelKey: "navigation.drafts", icon: FileText, preloadMessages: true },
{
href: "/archived",
- label: "Archived",
+ labelKey: "navigation.archived",
icon: Archive,
preloadMessages: true,
},
- { href: "/spam", label: "Spam", icon: ShieldAlert, preloadMessages: true },
- { href: "/trash", label: "Trash", icon: Trash2, preloadMessages: true },
-];
+ { href: "/spam", labelKey: "navigation.spam", icon: ShieldAlert, preloadMessages: true },
+ { href: "/trash", labelKey: "navigation.trash", icon: Trash2, preloadMessages: true },
+] satisfies (Omit<NavLink, "label"> & { labelKey: TranslationKey })[];
+
+const folderColorKeys = {
+ "#2563eb": "color.blue",
+ "#7c3aed": "color.purple",
+ "#db2777": "color.pink",
+ "#dc2626": "color.red",
+ "#ea580c": "color.orange",
+ "#d97706": "color.amber",
+ "#16a34a": "color.green",
+ "#0d9488": "color.teal",
+} satisfies Record<FolderColor, TranslationKey>;
// Drafts, Archived, Spam and Trash start tucked under "More...".
const MORE_LINK_HREFS = ["/drafts", "/archived", "/spam", "/trash"];
@@ -75,7 +88,8 @@ const MAX_VISIBLE_FOLDERS = 3;
const MORE_OPEN_KEY = "mailflare:nav:more-open";
const FOLDERS_OPEN_KEY = "mailflare:nav:folders-open";
-function NavToggle({ expanded, onClick, collapsedLabel = "More...", expandedLabel = "Show less..." }: { expanded: boolean; onClick: () => void; collapsedLabel?: string; expandedLabel?: string }) {
+function NavToggle({ expanded, onClick, collapsedLabel, expandedLabel }: { expanded: boolean; onClick: () => void; collapsedLabel?: string; expandedLabel?: string }) {
+ const { t } = useLanguage();
return (
<button
type="button"
@@ -83,12 +97,13 @@ function NavToggle({ expanded, onClick, collapsedLabel = "More...", expandedLabe
aria-expanded={expanded}
className="flex h-9 w-full items-center rounded-r-full pl-[52px] text-left text-sm text-neutral-700 transition-colors hover:bg-stone-200/60 max-md:min-h-11 max-md:pl-14 max-md:text-base"
>
- {expanded ? expandedLabel : collapsedLabel}
+ {expanded ? (expandedLabel ?? t("navigation.less")) : (collapsedLabel ?? t("navigation.more"))}
</button>
);
}
export function DashboardNav({ className }: { className?: string }) {
+ const { t } = useLanguage();
const { minimal } = useSidebar();
const pathname = usePathname();
const [moreOpen, setMoreOpen] = useState(false);
@@ -102,7 +117,7 @@ export function DashboardNav({ className }: { className?: string }) {
useState<FolderColor>(DEFAULT_FOLDER_COLOR);
const [addingFolder, setAddingFolder] = useState(false);
const [folderDialogOpen, setFolderDialogOpen] = useState(false);
- const linksWithCounts: NavLink[] = links.map((link): NavLink => {
+ const linksWithCounts: NavLink[] = links.map(({ labelKey, ...link }) => ({ ...link, label: t(labelKey) })).map((link): NavLink => {
if (link.href === "/inbox") {
return { ...link, count: getFolderNavCount("inbox", counts.folders) };
}
@@ -239,42 +254,42 @@ export function DashboardNav({ className }: { className?: string }) {
/>
{minimal && <hr className="mx-6 my-2 border-neutral-200/70" />}
{!minimal && (
- <NavSectionHeader label="Folders" open={foldersSectionOpen} onToggle={toggleFoldersSection}>
+ <NavSectionHeader label={t("navigation.folders")} open={foldersSectionOpen} onToggle={toggleFoldersSection}>
{selectedMailbox && (
<Dialog open={folderDialogOpen} onOpenChange={setFolderDialogOpen}>
<DialogTrigger asChild>
<button
type="button"
className="flex h-7 w-7 items-center justify-center rounded-lg text-neutral-500 hover:bg-blue-50 hover:text-blue-700"
- aria-label="Create folder"
+ aria-label={t("navigation.createFolder")}
>
<Plus className="h-4 w-4" />
</button>
</DialogTrigger>
- <DialogContent>
+ <DialogContent closeLabel={t("navigation.close")}>
<DialogHeader>
- <DialogTitle>Create folder</DialogTitle>
+ <DialogTitle>{t("navigation.createFolder")}</DialogTitle>
<DialogDescription>
- Add a folder to the selected mailbox.
+ {t("navigation.folderDescription")}
</DialogDescription>
</DialogHeader>
<form onSubmit={createFolder} className="space-y-4">
<div className="space-y-2">
- <Label htmlFor="folderName">Folder name</Label>
+ <Label htmlFor="folderName">{t("navigation.folderName")}</Label>
<Input
id="folderName"
value={newFolderName}
onChange={(event) => setNewFolderName(event.target.value)}
- placeholder="Receipts"
+ placeholder={t("navigation.folderExample")}
autoFocus
/>
</div>
<div className="space-y-2">
- <Label>Color</Label>
+ <Label>{t("navigation.color")}</Label>
<div
className="flex flex-wrap gap-2"
role="radiogroup"
- aria-label="Folder color"
+ aria-label={t("navigation.folderColor")}
>
{FOLDER_COLOR_OPTIONS.map((option) => (
<button
@@ -282,8 +297,8 @@ export function DashboardNav({ className }: { className?: string }) {
type="button"
role="radio"
aria-checked={newFolderColor === option.value}
- aria-label={option.label}
- title={option.label}
+ aria-label={t(folderColorKeys[option.value])}
+ title={t(folderColorKeys[option.value])}
onClick={() => setNewFolderColor(option.value)}
className={`h-8 w-8 rounded-full border-2 transition-transform hover:scale-110 ${
newFolderColor === option.value
@@ -299,7 +314,7 @@ export function DashboardNav({ className }: { className?: string }) {
type="submit"
disabled={addingFolder || !newFolderName.trim()}
>
- {addingFolder ? "Creating..." : "Create folder"}
+ {addingFolder ? t("navigation.creating") : t("navigation.createFolder")}
</Button>
</form>
</DialogContent>
@@ -309,7 +324,7 @@ export function DashboardNav({ className }: { className?: string }) {
)}
{!minimal && foldersSectionOpen && folders.length === 0 && (
<div className="mx-6 rounded-lg border border-dashed border-neutral-200 px-3 py-3 text-xs text-neutral-400">
- No folders yet
+ {t("navigation.noFolders")}
</div>
)}
{(minimal || foldersSectionOpen) && <ReorderableList
diff --git a/src/components/language-provider-types.d.ts b/src/components/language-provider-types.d.ts
new file mode 100644
index 0000000..5ada1d0
--- /dev/null
+++ b/src/components/language-provider-types.d.ts
@@ -0,0 +1,7 @@
+import type { Locale, TranslationKey } from "@/lib/i18n/types";
+
+export type LanguageState = {
+ locale: Locale;
+ setLocale: (locale: Locale) => void;
+ t: (key: TranslationKey) => string;
+};
diff --git a/src/components/language-provider.tsx b/src/components/language-provider.tsx
new file mode 100644
index 0000000..84ffa75
--- /dev/null
+++ b/src/components/language-provider.tsx
@@ -0,0 +1,38 @@
+"use client";
+
+import { createContext, useContext, useState, type ReactNode } from "react";
+import { DEFAULT_LOCALE, getMessages, resolveLocale, serializeLocaleCookie, translate } from "@/lib/i18n/utils";
+import type { Locale } from "@/lib/i18n/types";
+import type { LanguageState } from "./language-provider-types";
+
+const LanguageContext = createContext<LanguageState>({
+ locale: DEFAULT_LOCALE,
+ setLocale: () => undefined,
+ t: (key) => translate(getMessages(DEFAULT_LOCALE), key),
+});
+
+export function LanguageProvider({ initialLocale, children }: { initialLocale: Locale; children: ReactNode }) {
+ const [locale, updateLocale] = useState(initialLocale);
+
+ function setLocale(value: Locale) {
+ const nextLocale = resolveLocale(value);
+ // Preference cookies can be disabled; the selection still works for this session.
+ try {
+ document.cookie = serializeLocaleCookie(nextLocale, window.location.protocol === "https:");
+ } catch {
+ // Keep the in-memory preference when cookie storage is unavailable.
+ }
+ document.documentElement.lang = nextLocale;
+ updateLocale(nextLocale);
+ }
+
+ return (
+ <LanguageContext.Provider value={{ locale, setLocale, t: (key) => translate(getMessages(locale), key) }}>
+ {children}
+ </LanguageContext.Provider>
+ );
+}
+
+export function useLanguage() {
+ return useContext(LanguageContext);
+}
diff --git a/src/components/language-selector.tsx b/src/components/language-selector.tsx
new file mode 100644
index 0000000..699fdaa
--- /dev/null
+++ b/src/components/language-selector.tsx
@@ -0,0 +1,19 @@
+"use client";
+
+import { useId } from "react";
+import { resolveLocale } from "@/lib/i18n/utils";
+import { useLanguage } from "./language-provider";
+
+export function LanguageSelector() {
+ const id = useId();
+ const { locale, setLocale, t } = useLanguage();
+ return (
+ <div className="flex flex-col gap-1 px-1">
+ <label htmlFor={id} className="text-xs text-neutral-600">{t("language.label")}</label>
+ <select id={id} value={locale} onChange={(event) => setLocale(resolveLocale(event.target.value))} className="min-h-11 w-full rounded-lg border border-neutral-300 bg-white px-2 text-sm text-neutral-800 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600">
+ <option value="en" lang="en">English</option>
+ <option value="pt-BR" lang="pt-BR">Português (Brasil)</option>
+ </select>
+ </div>
+ );
+}
diff --git a/src/components/sidebar-aside.tsx b/src/components/sidebar-aside.tsx
index 3083f28..7ff1978 100644
--- a/src/components/sidebar-aside.tsx
+++ b/src/components/sidebar-aside.tsx
@@ -4,6 +4,7 @@ import clsx from "clsx";
import { Menu } from "lucide-react";
import type { ReactNode } from "react";
import { useSidebar } from "./sidebar-state";
+import { useLanguage } from "./language-provider";
export function SidebarAside({ children, className }: { children: ReactNode; className?: string }) {
const { mobile, mobileOpen, toggle } = useSidebar();
@@ -33,10 +34,11 @@ export function SidebarAside({ children, className }: { children: ReactNode; cla
}
export function MobileMenuButton({ className }: { className?: string }) {
+ const { t } = useLanguage();
const { mobile, mobileOpen, toggle } = useSidebar();
if (!mobile) return null;
return (
- <button type="button" onClick={toggle} aria-label="Open menu" aria-expanded={mobileOpen} className={clsx("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200 md:hidden", className)}>
+ <button type="button" onClick={toggle} aria-label={t("navigation.openMenu")} aria-expanded={mobileOpen} className={clsx("flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200 md:hidden", className)}>
<Menu size={20} />
</button>
);
diff --git a/src/components/sidebar-footer.tsx b/src/components/sidebar-footer.tsx
index b2b62ed..79eb7a3 100644
--- a/src/components/sidebar-footer.tsx
+++ b/src/components/sidebar-footer.tsx
@@ -4,14 +4,18 @@ import packageJson from "../../package.json";
import { useSidebar } from "./sidebar-state";
import { useShortcuts } from "./shortcuts";
import { Keyboard } from "lucide-react";
+import { LanguageSelector } from "./language-selector";
+import { useLanguage } from "./language-provider";
export function SidebarFooter() {
+ const { t } = useLanguage();
const { minimal } = useSidebar();
const { openHelpModal, shortcutsEnabled, shortcutsPreferenceLoading } = useShortcuts();
if (minimal) return null;
return (
<div className="px-3 pt-3 flex flex-col gap-2">
+ <LanguageSelector />
{shortcutsEnabled && !shortcutsPreferenceLoading && (
<button
type="button"
@@ -20,7 +24,7 @@ export function SidebarFooter() {
>
<span className="flex items-center gap-1.5">
<Keyboard className="w-3.5 h-3.5 text-neutral-400" />
- Shortcuts
+ {t("navigation.shortcuts")}
</span>
<kbd className="px-1.5 py-0.5 font-mono text-[10px] bg-white border border-neutral-200 rounded text-neutral-500 shadow-2xs">
?
@@ -28,7 +32,7 @@ export function SidebarFooter() {
</button>
)}
<p className="px-1 text-[11px] text-neutral-400">
- Powered by{" "}
+ {t("navigation.poweredBy")}{" "}
<a
href={`https://mailflare.co/?ref=${typeof window !== "undefined" ? location.hostname : ""}&v=${packageJson.version}`}
target="_blank"
diff --git a/src/components/sidebar-header.tsx b/src/components/sidebar-header.tsx
index 9f7e26e..ddb996f 100644
--- a/src/components/sidebar-header.tsx
+++ b/src/components/sidebar-header.tsx
@@ -6,16 +6,18 @@ import { useBranding } from "./branding-provider";
import { useSidebar } from "./sidebar-state";
import type { SidebarHeaderProps } from "./sidebar-state-types";
import { Tooltip } from "./ui/tooltip";
+import { useLanguage } from "./language-provider";
export function SidebarHeader({ href, label }: SidebarHeaderProps) {
+ const { t } = useLanguage();
const branding = useBranding();
const { minimal, toggle } = useSidebar();
- const toggleButton = <button type="button" onClick={toggle} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200" aria-label={minimal ? "Expand menu" : "Collapse menu"}>
+ const toggleButton = <button type="button" onClick={toggle} className="flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-neutral-600 hover:bg-neutral-200" aria-label={minimal ? t("navigation.expandMenu") : t("navigation.collapseMenu")}>
{minimal ? <img src={branding.iconUrl} height={32} width={32} alt="" /> : <TextAlignJustify size={18} />}
</button>;
return (
<div className={`mb-3 flex h-10 items-center ${minimal ? "" : "gap-2 px-1"}`}>
- {minimal ? <Tooltip label="Expand menu" placement="right">{toggleButton}</Tooltip> : toggleButton}
+ {minimal ? <Tooltip label={t("navigation.expandMenu")} placement="right">{toggleButton}</Tooltip> : toggleButton}
{!minimal && <Link href={href} className="flex min-w-0 items-center gap-3"><img src={branding.iconUrl} height={32} width={32} alt="" /><span className="truncate text-lg font-semibold text-neutral-800">{label ?? branding.appName}</span></Link>}
</div>
);
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index 2af0309..eb2d74a 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -12,8 +12,9 @@ export const DialogClose = DialogPrimitive.Close;
export function DialogContent({
className,
children,
+ closeLabel = "Close",
...props
-}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>) {
+}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { closeLabel?: string }) {
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="dialog-overlay fixed inset-0 z-50 bg-black/35" />
@@ -27,7 +28,7 @@ export function DialogContent({
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-full p-1 text-neutral-500 hover:bg-neutral-100 hover:text-neutral-900">
<X className="h-4 w-4" />
- <span className="sr-only">Close</span>
+ <span className="sr-only">{closeLabel}</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
diff --git a/src/lib/i18n/en.json b/src/lib/i18n/en.json
new file mode 100644
index 0000000..fdd152a
--- /dev/null
+++ b/src/lib/i18n/en.json
@@ -0,0 +1,37 @@
+{
+ "navigation.compose": "Compose",
+ "navigation.inbox": "Inbox",
+ "navigation.starred": "Starred",
+ "navigation.snoozed": "Snoozed",
+ "navigation.sent": "Sent",
+ "navigation.drafts": "Drafts",
+ "navigation.archived": "Archived",
+ "navigation.spam": "Spam",
+ "navigation.trash": "Trash",
+ "navigation.more": "More...",
+ "navigation.less": "Show less...",
+ "navigation.folders": "Folders",
+ "navigation.noFolders": "No folders yet",
+ "navigation.createFolder": "Create folder",
+ "navigation.folderDescription": "Add a folder to the selected mailbox.",
+ "navigation.folderName": "Folder name",
+ "navigation.folderExample": "Receipts",
+ "navigation.color": "Color",
+ "navigation.folderColor": "Folder color",
+ "navigation.creating": "Creating...",
+ "navigation.expandMenu": "Expand menu",
+ "navigation.collapseMenu": "Collapse menu",
+ "navigation.openMenu": "Open menu",
+ "navigation.close": "Close",
+ "navigation.shortcuts": "Shortcuts",
+ "navigation.poweredBy": "Powered by",
+ "color.blue": "Blue",
+ "color.purple": "Purple",
+ "color.pink": "Pink",
+ "color.red": "Red",
+ "color.orange": "Orange",
+ "color.amber": "Amber",
+ "color.green": "Green",
+ "color.teal": "Teal",
+ "language.label": "Language"
+}
diff --git a/src/lib/i18n/pt-BR.json b/src/lib/i18n/pt-BR.json
new file mode 100644
index 0000000..c640f08
--- /dev/null
+++ b/src/lib/i18n/pt-BR.json
@@ -0,0 +1,37 @@
+{
+ "navigation.compose": "Escrever",
+ "navigation.inbox": "Caixa de entrada",
+ "navigation.starred": "Com estrela",
+ "navigation.snoozed": "Adiados",
+ "navigation.sent": "Enviados",
+ "navigation.drafts": "Rascunhos",
+ "navigation.archived": "Arquivados",
+ "navigation.spam": "Spam",
+ "navigation.trash": "Lixeira",
+ "navigation.more": "Mais...",
+ "navigation.less": "Mostrar menos...",
+ "navigation.folders": "Pastas",
+ "navigation.noFolders": "Nenhuma pasta ainda",
+ "navigation.createFolder": "Criar pasta",
+ "navigation.folderDescription": "Adicione uma pasta à caixa de entrada selecionada.",
+ "navigation.folderName": "Nome da pasta",
+ "navigation.folderExample": "Recibos",
+ "navigation.color": "Cor",
+ "navigation.folderColor": "Cor da pasta",
+ "navigation.creating": "Criando...",
+ "navigation.expandMenu": "Expandir menu",
+ "navigation.collapseMenu": "Recolher menu",
+ "navigation.openMenu": "Abrir menu",
+ "navigation.close": "Fechar",
+ "navigation.shortcuts": "Atalhos",
+ "navigation.poweredBy": "Desenvolvido por",
+ "color.blue": "Azul",
+ "color.purple": "Roxo",
+ "color.pink": "Rosa",
+ "color.red": "Vermelho",
+ "color.orange": "Laranja",
+ "color.amber": "Âmbar",
+ "color.green": "Verde",
+ "color.teal": "Verde-azulado",
+ "language.label": "Idioma"
+}
diff --git a/src/lib/i18n/types.d.ts b/src/lib/i18n/types.d.ts
new file mode 100644
index 0000000..c2fe27a
--- /dev/null
+++ b/src/lib/i18n/types.d.ts
@@ -0,0 +1,5 @@
+import type en from "./en.json";
+
+export type Locale = "en" | "pt-BR";
+export type TranslationKey = keyof typeof en;
+export type Messages = Record<TranslationKey, string>;
diff --git a/src/lib/i18n/utils.ts b/src/lib/i18n/utils.ts
new file mode 100644
index 0000000..03c0d77
--- /dev/null
+++ b/src/lib/i18n/utils.ts
@@ -0,0 +1,25 @@
+import en from "./en.json";
+import ptBR from "./pt-BR.json";
+import type { Locale, Messages, TranslationKey } from "./types";
+
+export const DEFAULT_LOCALE: Locale = "en";
+export const LOCALE_COOKIE = "mailflare-locale";
+export const LOCALE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
+
+const catalogs: Record<Locale, Messages> = { en, "pt-BR": ptBR };
+
+export function resolveLocale(value: unknown): Locale {
+ return value === "pt-BR" ? "pt-BR" : DEFAULT_LOCALE;
+}
+
+export function getMessages(locale: Locale): Messages {
+ return catalogs[locale];
+}
+
+export function translate(messages: Partial<Messages>, key: TranslationKey): string {
+ return messages[key] ?? en[key];
+}
+
+export function serializeLocaleCookie(locale: Locale, secure: boolean): string {
+ return `${LOCALE_COOKIE}=${resolveLocale(locale)}; Path=/; Max-Age=${LOCALE_COOKIE_MAX_AGE}; SameSite=Lax${secure ? "; Secure" : ""}`;
+}
diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjs
new file mode 100644
index 0000000..67c4a0b
--- /dev/null
+++ b/tests/i18n.test.mjs
@@ -0,0 +1,103 @@
+import assert from "node:assert/strict";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test, { after } from "node:test";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { build } from "esbuild";
+
+const root = join(dirname(fileURLToPath(import.meta.url)), "..");
+const outDir = mkdtempSync(join(tmpdir(), "mailflare-i18n-"));
+after(() => rmSync(outDir, { recursive: true, force: true }));
+const outfile = join(outDir, "i18n.mjs");
+
+await build({
+ stdin: {
+ contents: `
+ import { createElement } from "react";
+ import { renderToStaticMarkup } from "react-dom/server";
+ import RootLayout from "./src/app/layout";
+ import { LanguageProvider, useLanguage } from "./src/components/language-provider";
+ import { LanguageSelector } from "./src/components/language-selector";
+ export * from "./src/lib/i18n/utils";
+ function Probe() { return createElement("span", null, useLanguage().t("navigation.inbox")); }
+ export function renderLanguage(locale) {
+ return renderToStaticMarkup(createElement(LanguageProvider, { initialLocale: locale }, createElement(Probe), createElement(LanguageSelector)));
+ }
+ export async function renderLayout(cookieValue) {
+ globalThis.testLocaleCookie = cookieValue;
+ return renderToStaticMarkup(await RootLayout({ children: createElement(Probe) }));
+ }
+ `,
+ resolveDir: root,
+ loader: "tsx",
+ },
+ outfile,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ target: "node22",
+ logLevel: "silent",
+ alias: { "@": join(root, "src") },
+ banner: { js: 'import { createRequire } from "node:module"; const require = createRequire(import.meta.url);' },
+ plugins: [{
+ name: "layout-runtime-stubs",
+ setup(builder) {
+ builder.onResolve({ filter: /^(next\/headers|next\/font\/google|@\/components\/providers)$/ }, (args) => ({ path: args.path, namespace: "stub" }));
+ builder.onLoad({ filter: /.*/, namespace: "stub" }, ({ path }) => ({ contents: path === "next/headers"
+ ? 'export async function cookies() { return { get(name) { return name === "mailflare-locale" && globalThis.testLocaleCookie !== undefined ? { value: globalThis.testLocaleCookie } : undefined; } }; }'
+ : path === "next/font/google"
+ ? 'export const Geist = () => ({ variable: "sans" }); export const Geist_Mono = () => ({ variable: "mono" });'
+ : 'export function Providers({ children }) { return children; }' }));
+ builder.onLoad({ filter: /\.css$/ }, () => ({ contents: "", loader: "js" }));
+ },
+ }],
+});
+
+const i18n = await import(pathToFileURL(outfile).href);
+const en = JSON.parse(readFileSync(join(root, "src/lib/i18n/en.json"), "utf8"));
+const ptBR = JSON.parse(readFileSync(join(root, "src/lib/i18n/pt-BR.json"), "utf8"));
+
+test("Portuguese has exactly the English keys and all messages are nonempty strings", () => {
+ assert.deepEqual(Object.keys(ptBR).sort(), Object.keys(en).sort());
+ for (const catalog of [en, ptBR]) {
+ for (const value of Object.values(catalog)) assert.ok(typeof value === "string" && value.trim().length > 0);
+ }
+});
+
+test("missing, invalid and unsupported locale values fall back to English", () => {
+ for (const value of [undefined, null, "", "pt", "pt-br", "fr", "pt-BR; Path=/", {}]) assert.equal(i18n.resolveLocale(value), "en");
+ assert.equal(i18n.resolveLocale("en"), "en");
+ assert.equal(i18n.resolveLocale("pt-BR"), "pt-BR");
+});
+
+test("translation uses the requested catalog and falls back per key", () => {
+ assert.equal(i18n.translate(i18n.getMessages("pt-BR"), "navigation.inbox"), "Caixa de entrada");
+ assert.equal(i18n.translate({}, "navigation.inbox"), "Inbox");
+});
+
+test("preference cookie persists for a year, covers every path and is Secure on HTTPS", () => {
+ assert.equal(i18n.serializeLocaleCookie("pt-BR", true), "mailflare-locale=pt-BR; Path=/; Max-Age=31536000; SameSite=Lax; Secure");
+ assert.equal(i18n.serializeLocaleCookie("en", false), "mailflare-locale=en; Path=/; Max-Age=31536000; SameSite=Lax");
+ assert.equal(i18n.serializeLocaleCookie("bad; Domain=example.com", true), "mailflare-locale=en; Path=/; Max-Age=31536000; SameSite=Lax; Secure");
+});
+
+test("provider server rendering uses initial locale and labels the native language selector", () => {
+ const pt = i18n.renderLanguage("pt-BR");
+ assert.match(pt, /Caixa de entrada/);
+ assert.match(pt, /<label for="[^"]+"[^>]*>Idioma<\/label>/);
+ assert.match(pt, /<select id="[^"]+"/);
+ assert.match(pt, /value="pt-BR" lang="pt-BR" selected=""/);
+ assert.match(i18n.renderLanguage("en"), /value="en" lang="en" selected=""/);
+});
+
+test("root layout passes the same cookie locale to HTML and provider on first render", async () => {
+ const pt = await i18n.renderLayout("pt-BR");
+ assert.match(pt, /<html lang="pt-BR"/);
+ assert.match(pt, /Caixa de entrada/);
+ for (const value of [undefined, "bad"]) {
+ const english = await i18n.renderLayout(value);
+ assert.match(english, /<html lang="en"/);
+ assert.match(english, />Inbox<\/span>/);
+ }
+});