Skip to content

Email for professionals and teams

Add translation vars, plurals, server translator and RTL support

Hieu Nguyen (Jack)eb64be1c560b
diff --git a/docs/localization.md b/docs/localization.md
index dddab63..6f51ff4 100644
--- a/docs/localization.md
+++ b/docs/localization.md
@@ -30,8 +30,10 @@ To add another language:
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.
+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. For a right-to-left language add `dir: "rtl"` to the entry; the layout and provider then set `<html dir>`. Catalogs are currently bundled eagerly; this small initial scope does not add lazy loading 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.
+Client components use `useLanguage().t(key, vars?)`; server code uses `createTranslator(locale)` from `src/lib/i18n/utils.ts`, which returns the same function. Strings interpolate `{name}` placeholders from `vars`. For plurals, add `key.one`, `key.other` (and any other CLDR categories the language needs) to **every** catalog, then call `t("key", { count })`; the variant is picked with `Intl.PluralRules`, falling back to the bare key. The dialog close button uses the translated `navigation.close` automatically.
+
+ 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. 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/app/layout.tsx b/src/app/layout.tsx
index 445d350..c719803 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -3,7 +3,7 @@ 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 { LOCALE_COOKIE, getDirection, resolveLocale } from "@/lib/i18n/utils";
import { sidebarBootstrapScript } from "@/components/sidebar-state-utils";
import { themeBootstrapScript } from "@/components/theme-utils";
import "./globals.css";
@@ -41,7 +41,7 @@ export const metadata: Metadata = {
export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
const locale = resolveLocale((await cookies()).get(LOCALE_COOKIE)?.value);
return (
- <html lang={locale} suppressHydrationWarning>
+ <html lang={locale} dir={getDirection(locale)} suppressHydrationWarning>
<head>
<script dangerouslySetInnerHTML={{ __html: sidebarBootstrapScript }} />
<script dangerouslySetInnerHTML={{ __html: themeBootstrapScript }} />
diff --git a/src/components/dashboard-nav.tsx b/src/components/dashboard-nav.tsx
index 144c65d..f4320f3 100644
--- a/src/components/dashboard-nav.tsx
+++ b/src/components/dashboard-nav.tsx
@@ -117,7 +117,8 @@ 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(({ labelKey, ...link }) => ({ ...link, label: t(labelKey) })).map((link): NavLink => {
+ const linksWithCounts: NavLink[] = links.map(({ labelKey, ...rest }): NavLink => {
+ const link = { ...rest, label: t(labelKey) };
if (link.href === "/inbox") {
return { ...link, count: getFolderNavCount("inbox", counts.folders) };
}
@@ -266,7 +267,7 @@ export function DashboardNav({ className }: { className?: string }) {
<Plus className="h-4 w-4" />
</button>
</DialogTrigger>
- <DialogContent closeLabel={t("navigation.close")}>
+ <DialogContent>
<DialogHeader>
<DialogTitle>{t("navigation.createFolder")}</DialogTitle>
<DialogDescription>
diff --git a/src/components/language-provider-types.d.ts b/src/components/language-provider-types.d.ts
index 5ada1d0..dca9f24 100644
--- a/src/components/language-provider-types.d.ts
+++ b/src/components/language-provider-types.d.ts
@@ -1,7 +1,8 @@
-import type { Locale, TranslationKey } from "@/lib/i18n/types";
+import type { Locale } from "@/lib/i18n/types";
+import type { Translator } from "@/lib/i18n/utils";
export type LanguageState = {
locale: Locale;
setLocale: (locale: Locale) => void;
- t: (key: TranslationKey) => string;
+ t: Translator;
};
diff --git a/src/components/language-provider.tsx b/src/components/language-provider.tsx
index 84ffa75..65db7b2 100644
--- a/src/components/language-provider.tsx
+++ b/src/components/language-provider.tsx
@@ -1,21 +1,22 @@
"use client";
-import { createContext, useContext, useState, type ReactNode } from "react";
-import { DEFAULT_LOCALE, getMessages, resolveLocale, serializeLocaleCookie, translate } from "@/lib/i18n/utils";
+import { createContext, useContext, useMemo, useState, type ReactNode } from "react";
+import { DEFAULT_LOCALE, createTranslator, getDirection, resolveLocale, serializeLocaleCookie } 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),
+ t: createTranslator(DEFAULT_LOCALE),
});
export function LanguageProvider({ initialLocale, children }: { initialLocale: Locale; children: ReactNode }) {
const [locale, updateLocale] = useState(initialLocale);
+ const value = useMemo<LanguageState>(() => ({ locale, setLocale, t: createTranslator(locale) }), [locale]);
- function setLocale(value: Locale) {
- const nextLocale = resolveLocale(value);
+ function setLocale(next: Locale) {
+ const nextLocale = resolveLocale(next);
// Preference cookies can be disabled; the selection still works for this session.
try {
document.cookie = serializeLocaleCookie(nextLocale, window.location.protocol === "https:");
@@ -23,11 +24,12 @@ export function LanguageProvider({ initialLocale, children }: { initialLocale: L
// Keep the in-memory preference when cookie storage is unavailable.
}
document.documentElement.lang = nextLocale;
+ document.documentElement.dir = getDirection(nextLocale);
updateLocale(nextLocale);
}
return (
- <LanguageContext.Provider value={{ locale, setLocale, t: (key) => translate(getMessages(locale), key) }}>
+ <LanguageContext.Provider value={value}>
{children}
</LanguageContext.Provider>
);
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index eb2d74a..d08c9ac 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -4,6 +4,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";
+import { useLanguage } from "@/components/language-provider";
export const Dialog = DialogPrimitive.Root;
export const DialogTrigger = DialogPrimitive.Trigger;
@@ -12,9 +13,10 @@ export const DialogClose = DialogPrimitive.Close;
export function DialogContent({
className,
children,
- closeLabel = "Close",
+ closeLabel,
...props
}: React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & { closeLabel?: string }) {
+ const { t } = useLanguage();
return (
<DialogPrimitive.Portal>
<DialogPrimitive.Overlay className="dialog-overlay fixed inset-0 z-50 bg-black/35" />
@@ -28,7 +30,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">{closeLabel}</span>
+ <span className="sr-only">{closeLabel ?? t("navigation.close")}</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPrimitive.Portal>
diff --git a/src/lib/i18n/locales.ts b/src/lib/i18n/locales.ts
index 6d4b739..c170a8a 100644
--- a/src/lib/i18n/locales.ts
+++ b/src/lib/i18n/locales.ts
@@ -2,12 +2,12 @@ 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
+// Register a catalog and its native display name here (add `dir: "rtl"` for right-to-left scripts). 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 }>;
+} satisfies Record<string, { label: string; messages: Messages; dir?: "rtl" }>;
export type Locale = keyof typeof locales;
export const DEFAULT_LOCALE = "en" satisfies Locale;
diff --git a/src/lib/i18n/utils.ts b/src/lib/i18n/utils.ts
index bd3fe56..3d9ce2a 100644
--- a/src/lib/i18n/utils.ts
+++ b/src/lib/i18n/utils.ts
@@ -10,12 +10,40 @@ export function resolveLocale(value: unknown): Locale {
return typeof value === "string" && Object.hasOwn(locales, value) ? value as Locale : DEFAULT_LOCALE;
}
+export function getDirection(locale: Locale): "ltr" | "rtl" {
+ return (locales[locale] as { dir?: "rtl" }).dir ?? "ltr";
+}
+
export function getMessages(locale: Locale): Messages {
return locales[locale].messages;
}
-export function translate(messages: Partial<Messages>, key: TranslationKey): string {
- return messages[key] ?? en[key];
+export type TranslationVars = Record<string, string | number>;
+export type Translator = (key: TranslationKey, vars?: TranslationVars) => string;
+
+function interpolate(template: string, vars?: TranslationVars): string {
+ if (!vars) return template;
+ return template.replace(/\{(\w+)\}/g, (match, name: string) => (Object.hasOwn(vars, name) ? String(vars[name]) : match));
+}
+
+export function translate(messages: Partial<Messages>, key: TranslationKey, vars?: TranslationVars): string {
+ return interpolate(messages[key] ?? en[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 rules = new Intl.PluralRules(locale);
+ 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);
+ }
+ return translate(getMessages(locale), key, vars);
+ };
}
export function serializeLocaleCookie(locale: Locale, secure: boolean): string {
diff --git a/tests/i18n.test.mjs b/tests/i18n.test.mjs
index 1c91acc..bb3111f 100644
--- a/tests/i18n.test.mjs
+++ b/tests/i18n.test.mjs
@@ -47,7 +47,7 @@ async function bundleI18n(outfile, extraLocale = false) {
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" } },`),
+ es: { label: "Español", dir: "rtl", messages: { ...en, "navigation.inbox": "Entrada", "navigation.inbox.one": "{count} entrada", "navigation.inbox.other": "{count} entradas", "language.label": "Idioma" } },`),
loader: "ts",
}));
builder.onResolve({ filter: /^(next\/headers|next\/font\/google|@\/components\/providers)$/ }, (args) => ({ path: args.path, namespace: "stub" }));
@@ -125,7 +125,19 @@ test("a locale registered once reaches resolution, translation, cookie, selector
const layout = await extended.renderLayout("es");
assert.match(layout, /<html lang="es"/);
assert.match(layout, />Entrada<\/span>/);
+ assert.match(layout, /<html lang="es" dir="rtl"/);
+ const t = extended.createTranslator("es");
+ assert.equal(t("navigation.inbox", { count: 1 }), "1 entrada");
+ assert.equal(t("navigation.inbox", { count: 3 }), "3 entradas");
+ assert.equal(t("navigation.inbox"), "Entrada");
for (const invalid of ["constructor", "toString", "__proto__"]) {
assert.equal(extended.resolveLocale(invalid), "en");
}
});
+
+test("translations interpolate {vars}, keep unknown placeholders and default to ltr", () => {
+ assert.equal(i18n.translate({ "navigation.inbox": "Hi {name}, {other}" }, "navigation.inbox", { name: "Ana", count: 2 }), "Hi Ana, {other}");
+ assert.equal(i18n.translate({}, "navigation.inbox", { name: "x" }), "Inbox");
+ assert.equal(i18n.createTranslator("pt-BR")("navigation.inbox", { count: 2 }), "Caixa de entrada");
+ assert.equal(i18n.getDirection("en"), "ltr");
+});