Email for professionals and teams
Centralize locale registration for extensible localization
forge-zdb5a39362a3c
diff --git a/docs/localization.md b/docs/localization.mdindex 7a6b9d4..dddab63 100644--- a/docs/localization.md+++ b/docs/localization.md@@ -12,12 +12,26 @@ The rest of the interface is still in English, including account menus, login, mThe 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.+The root layout reads the cookie with `await cookies()`, validates it against the locale registry, 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.+Catalogs are flat JSON objects in `src/lib/i18n/`. English (`en.json`) defines `TranslationKey` and `Messages`; registered catalogs must contain all English keys with string values. Add new English keys and update registered translations together. `translate()` retains a per-key English fallback.++To add another language:++1. Copy `en.json` to a new catalog, for example `es.json`, and translate its values without changing the keys.+2. Import the catalog in `src/lib/i18n/locales.ts` and add one registry entry with its BCP 47 locale code and native display name:++ ```ts+ import es from "./es.json";++ // Inside locales:+ es: { label: "Español", messages: es },+ ```++That is the only registration point. The `Locale` type, supported-locale validation, cookie handling, server-rendered HTML and selector options all derive from it. No provider, layout, selector or utility changes are needed. English remains the default. Catalogs are currently bundled eagerly; this small initial scope does not add lazy loading, pluralization or locale-specific date formatting.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.+Run `node --test tests/i18n.test.mjs` for catalog parity, fallback, cookie attributes, selector labels, server rendering and root-layout locale agreement. An isolated test registers a third language and verifies that resolution, translations, cookie persistence, selector options and SSR pick it up without changing any consumers. Also run lint, `npx tsc --noEmit` and the applicable build when changing the integration.diff --git a/src/components/language-selector.tsx b/src/components/language-selector.tsxindex 699fdaa..03f55f1 100644--- a/src/components/language-selector.tsx+++ b/src/components/language-selector.tsx@@ -1,6 +1,7 @@"use client";import { useId } from "react";+import { locales, supportedLocales } from "@/lib/i18n/locales";import { resolveLocale } from "@/lib/i18n/utils";import { useLanguage } from "./language-provider";@@ -11,8 +12,9 @@ export function LanguageSelector() {<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>+ {supportedLocales.map((value) => (+ <option key={value} value={value} lang={value}>{locales[value].label}</option>+ ))}</select></div>);diff --git a/src/lib/i18n/locales.ts b/src/lib/i18n/locales.tsnew file mode 100644index 0000000..6d4b739--- /dev/null+++ b/src/lib/i18n/locales.ts@@ -0,0 +1,14 @@+import en from "./en.json";+import ptBR from "./pt-BR.json";+import type { Messages } from "./types";++// Register a catalog and its native display name here. All locale consumers+// (types, validation, cookies, SSR and the selector) derive from this registry.+export const locales = {+ en: { label: "English", messages: en },+ "pt-BR": { label: "Português (Brasil)", messages: ptBR },+} satisfies Record<string, { label: string; messages: Messages }>;++export type Locale = keyof typeof locales;+export const DEFAULT_LOCALE = "en" satisfies Locale;+export const supportedLocales = Object.keys(locales) as Locale[];diff --git a/src/lib/i18n/types.d.ts b/src/lib/i18n/types.d.tsindex c2fe27a..0120a04 100644--- a/src/lib/i18n/types.d.ts+++ b/src/lib/i18n/types.d.ts@@ -1,5 +1,5 @@import type en from "./en.json";-export type Locale = "en" | "pt-BR";+export type { Locale } from "./locales";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.tsindex 03c0d77..bd3fe56 100644--- a/src/lib/i18n/utils.ts+++ b/src/lib/i18n/utils.ts@@ -1,19 +1,17 @@import en from "./en.json";-import ptBR from "./pt-BR.json";+import { DEFAULT_LOCALE, locales } from "./locales";import type { Locale, Messages, TranslationKey } from "./types";-export const DEFAULT_LOCALE: Locale = "en";+export { DEFAULT_LOCALE } from "./locales";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;+ return typeof value === "string" && Object.hasOwn(locales, value) ? value as Locale : DEFAULT_LOCALE;}export function getMessages(locale: Locale): Messages {- return catalogs[locale];+ return locales[locale].messages;}export function translate(messages: Partial<Messages>, key: TranslationKey): string {diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjsindex 67c4a0b..1c91acc 100644--- a/tests/i18n.test.mjs+++ b/tests/i18n.test.mjs@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import test, { after } from "node:test";@@ -11,62 +11,71 @@ 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" }));+async function bundleI18n(outfile, extraLocale = false) {+ 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";+ export * from "./src/lib/i18n/locales";+ 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) {+ if (extraLocale) builder.onLoad({ filter: /\/i18n\/locales\.ts$/ }, ({ path }) => ({+ contents: readFileSync(path, "utf8").replace("export const locales = {", `export const locales = {+ es: { label: "Español", messages: { ...en, "navigation.inbox": "Entrada", "language.label": "Idioma" } },`),+ loader: "ts",+ }));+ 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" }));+ },+ }],+ });+}+await bundleI18n(outfile);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]) {+test("every registered catalog has the English keys and nonempty messages and label", () => {+ for (const { messages: catalog, label } of Object.values(i18n.locales)) {+ assert.ok(label.trim().length > 0);+ assert.deepEqual(Object.keys(catalog).sort(), Object.keys(en).sort());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");+ for (const value of [undefined, null, "", "not-a-registered-locale", "pt-BR; Path=/", {}]) assert.equal(i18n.resolveLocale(value), "en");assert.equal(i18n.resolveLocale("en"), "en");assert.equal(i18n.resolveLocale("pt-BR"), "pt-BR");});@@ -101,3 +110,22 @@ test("root layout passes the same cookie locale to HTML and provider on first reassert.match(english, />Inbox<\/span>/);}});++test("a locale registered once reaches resolution, translation, cookie, selector and SSR", async () => {+ assert.ok(existsSync(join(root, "src/lib/i18n/locales.ts")), "locales must have one shared registry");+ const extraFile = join(outDir, "with-spanish.mjs");+ await bundleI18n(extraFile, true);+ const extended = await import(pathToFileURL(extraFile).href);+ assert.equal(extended.resolveLocale("es"), "es");+ assert.equal(extended.translate(extended.getMessages("es"), "navigation.inbox"), "Entrada");+ assert.match(extended.serializeLocaleCookie("es", true), /^mailflare-locale=es;/);+ const selector = extended.renderLanguage("es");+ assert.match(selector, /value="es" lang="es" selected="">Español<\/option>/);+ assert.match(selector, />Entrada<\/span>/);+ const layout = await extended.renderLayout("es");+ assert.match(layout, /<html lang="es"/);+ assert.match(layout, />Entrada<\/span>/);+ for (const invalid of ["constructor", "toString", "__proto__"]) {+ assert.equal(extended.resolveLocale(invalid), "en");+ }+});