Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
{
"name": "@toolctrl/i18n",
"version": "0.0.0",
"private": true,
"type": "module",
"sideEffects": false,
"exports": {
".": "./src/index.ts",
"./intl": "./src/intl/index.ts",
"./icu": "./src/icu/index.ts",
"./useTranslate": "./src/useTranslate.ts"
},
"scripts": {
"build": "pnpm run typecheck",
"test": "vitest run src",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"i18next": "^23.16.3",
"intl-messageformat": "^10.7.16"
},
"devDependencies": {
"typescript": "^5.3.2",
"vitest": "^3.2.4"
}
}
@@ -0,0 +1 @@
export { formatIcu, createIcuFormatter, type IcuValues, type IcuOptions, type IcuFormatter } from "./plural.js";
@@ -0,0 +1,38 @@
import { describe, expect, test } from "vitest";
import { createIcuFormatter, formatIcu } from "./plural.js";
describe("formatIcu (plurals)", () => {
test("renders English plural cases", () => {
const message = "{count, plural, =0 {No items} one {# item selected} other {# items selected}}";
expect(formatIcu(message, { count: 0 }, { locale: "en-US" })).toBe("No items");
expect(formatIcu(message, { count: 1 }, { locale: "en-US" })).toBe("1 item selected");
expect(formatIcu(message, { count: 5 }, { locale: "en-US" })).toBe("5 items selected");
});
test("renders German plural cases", () => {
const message = "{count, plural, =0 {Nichts ausgewählt} one {# Eintrag ausgewählt} other {# Einträge ausgewählt}}";
expect(formatIcu(message, { count: 0 }, { locale: "de-DE" })).toBe("Nichts ausgewählt");
expect(formatIcu(message, { count: 1 }, { locale: "de-DE" })).toBe("1 Eintrag ausgewählt");
expect(formatIcu(message, { count: 7 }, { locale: "de-DE" })).toBe("7 Einträge ausgewählt");
});
test("renders Polish plural cases (one/few/many)", () => {
const message =
"{count, plural, one {# element} few {# elementy} many {# elementów} other {# elementu}}";
expect(formatIcu(message, { count: 1 }, { locale: "pl-PL" })).toBe("1 element");
expect(formatIcu(message, { count: 2 }, { locale: "pl-PL" })).toBe("2 elementy");
expect(formatIcu(message, { count: 5 }, { locale: "pl-PL" })).toBe("5 elementów");
});
test("supports select rules", () => {
const message = "{role, select, admin {Administrator} member {Member} other {Guest}}";
expect(formatIcu(message, { role: "admin" }, { locale: "en-US" })).toBe("Administrator");
expect(formatIcu(message, { role: "external" }, { locale: "en-US" })).toBe("Guest");
});
test("createIcuFormatter memoises the parsed message", () => {
const fmt = createIcuFormatter("{count, plural, one {# day} other {# days}}", { locale: "en-US" });
expect(fmt({ count: 1 })).toBe("1 day");
expect(fmt({ count: 30 })).toBe("30 days");
});
});
@@ -0,0 +1,40 @@
// ICU-MessageFormat-based plural/select rendering. We rely on
// `intl-messageformat` (FormatJS) because it tracks the CLDR plural rule set
// for 60+ languages — re-implementing the rule cascade is exactly the kind of
// foot-gun we want to avoid in app code.
//
// Pattern example:
// formatIcu("{count, plural, =0 {No items} one {# item} other {# items}}",
// { count: 1 }, { locale: "en" }) // → "1 item"
//
// The helper is intentionally small. Heavy callsites (e.g. lists of plurals
// rendered in a loop) should memoise the `IntlMessageFormat` instance via
// `createIcuFormatter()` to avoid re-parsing the message on every call.
import { IntlMessageFormat } from "intl-messageformat";
export type IcuValues = Record<string, string | number | boolean | Date | null | undefined>;
export type IcuOptions = {
locale: string;
};
export function formatIcu(message: string, values: IcuValues, options: IcuOptions): string {
const formatter = new IntlMessageFormat(message, options.locale);
const formatted = formatter.format(values as Record<string, unknown>);
if (typeof formatted === "string") return formatted;
if (Array.isArray(formatted)) return formatted.join("");
return String(formatted ?? "");
}
export type IcuFormatter = (values: IcuValues) => string;
export function createIcuFormatter(message: string, options: IcuOptions): IcuFormatter {
const formatter = new IntlMessageFormat(message, options.locale);
return (values) => {
const out = formatter.format(values as Record<string, unknown>);
if (typeof out === "string") return out;
if (Array.isArray(out)) return out.join("");
return String(out ?? "");
};
}
@@ -0,0 +1,132 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { checkI18nParity } from "../../../scripts/i18n-check.ts";
import { defaultLocale, getDirection, i18nConfig, i18nNamespaces, isRTL, isSupportedLocale, supportedLocales } from "./index.js";
type JsonValue = boolean | null | number | string | JsonValue[] | { [key: string]: JsonValue };
type JsonObject = { [key: string]: JsonValue };
function readLocaleNamespace(locale: string, namespace: string): JsonObject {
return JSON.parse(
readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), `../../../apps/web/public/locales/${locale}/${namespace}.json`), "utf8"),
) as JsonObject;
}
function collectLeafKeys(value: JsonValue, prefix = ""): string[] {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return prefix ? [prefix] : [];
}
return Object.entries(value)
.flatMap(([key, nestedValue]) => collectLeafKeys(nestedValue, prefix ? `${prefix}.${key}` : key))
.sort();
}
describe("@toolctrl/i18n", () => {
test("keeps German as the default and fallback locale", () => {
expect(defaultLocale).toBe("de");
expect(i18nConfig.fallbackLng).toBe("de");
});
test("keeps German and English as maintained locale set", () => {
expect(supportedLocales).toEqual(["de", "en"]);
expect(i18nConfig.supportedLngs).toEqual(["de", "en"]);
});
test("checks supported locales", () => {
expect(isSupportedLocale("de")).toBe(true);
expect(isSupportedLocale("en")).toBe(true);
expect(isSupportedLocale("fr")).toBe(false);
});
test("keeps German and English translation keys in parity", () => {
for (const namespace of i18nNamespaces) {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", namespace));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", namespace));
expect(englishKeys).toEqual(germanKeys);
}
});
test("keeps static UI translation calls backed by locale entries", () => {
const result = checkI18nParity({ cwd: path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../") });
const missingKeysWithoutFallback = result.issues.filter((issue) => issue.type === "missing-source-key" && issue.fallback === "no-fallback");
expect(result.ok).toBe(true);
expect(missingKeysWithoutFallback).toEqual([]);
});
test("registers the legacy + per-area namespaces as loadable", () => {
// `translations` stays default for backwards-compat; `common`, `settings`,
// `billing`, `crm`, `auth` and `emailMarketing` are per-area namespaces
// split out of the legacy file. See #72.
const expected = ["translations", "errors", "mail", "common", "settings", "billing", "crm", "auth", "emailMarketing"];
expect(i18nNamespaces).toEqual(expected);
expect(i18nConfig.ns).toEqual(expected);
expect(i18nConfig.defaultNS).toBe("translations");
});
test("ships parity between de and en common namespace files", () => {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", "common"));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", "common"));
expect(englishKeys).toEqual(germanKeys);
expect(germanKeys.length).toBeGreaterThan(0);
});
test("ships parity between de and en settings namespace files", () => {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", "settings"));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", "settings"));
expect(englishKeys).toEqual(germanKeys);
expect(germanKeys.length).toBeGreaterThan(0);
});
test("ships parity between de and en for the per-area namespaces split from the legacy file", () => {
// #72 i18n namespace split — billing/crm/auth/emailMarketing moved out of
// translations.json into dedicated namespace files.
for (const namespace of ["billing", "crm", "auth", "emailMarketing"]) {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", namespace));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", namespace));
expect(englishKeys, namespace).toEqual(germanKeys);
expect(germanKeys.length, namespace).toBeGreaterThan(0);
}
});
test("keeps the errors namespace in parity between German and English", () => {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", "errors"));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", "errors"));
expect(englishKeys).toEqual(germanKeys);
for (const status of ["401", "403", "404", "500", "503"]) {
expect(germanKeys).toEqual(expect.arrayContaining([`${status}.eyebrow`, `${status}.title`, `${status}.description`]));
}
});
test("keeps the mail namespace in parity between German and English", () => {
const germanKeys = collectLeafKeys(readLocaleNamespace("de", "mail"));
const englishKeys = collectLeafKeys(readLocaleNamespace("en", "mail"));
expect(englishKeys).toEqual(germanKeys);
for (const template of ["welcome", "passwordReset", "userInvitation", "emailVerification", "accountSetup"]) {
expect(germanKeys).toEqual(expect.arrayContaining([`${template}.subject`]));
}
});
test("returns ltr for supported locales and rtl for known RTL languages", () => {
expect(getDirection("de")).toBe("ltr");
expect(getDirection("en")).toBe("ltr");
expect(getDirection("ar")).toBe("rtl");
expect(getDirection("he")).toBe("rtl");
expect(getDirection("fa")).toBe("rtl");
expect(getDirection("ur")).toBe("rtl");
expect(getDirection(undefined)).toBe("ltr");
expect(getDirection("xx-unknown")).toBe("ltr");
});
test("isRTL matches getDirection", () => {
expect(isRTL("de")).toBe(false);
expect(isRTL("ar")).toBe(true);
expect(isRTL(undefined)).toBe(false);
});
});
+70
View File
@@ -0,0 +1,70 @@
import type { InitOptions } from "i18next";
export const defaultLocale = "de";
export const supportedLocales = ["de", "en"];
export type SupportedLocale = (typeof supportedLocales)[number];
// Namespace order:
// - `translations` is the legacy single-file namespace that still holds the
// bulk of UI strings. New keys for *new* surfaces should land in a
// dedicated namespace.
// - `common` collects shared UI primitives — buttons, generic labels — and
// ICU-MessageFormat plural patterns (`itemsSelected`, `memberCount`).
// - `settings`/`billing`/`crm`/`auth`/`emailMarketing` are per-area
// namespaces split out of the legacy file. See `docs/contributing/i18n.md`.
export const i18nNamespaces = ["translations", "errors", "mail", "common", "settings", "billing", "crm", "auth", "emailMarketing"] as const;
export type I18nNamespace = (typeof i18nNamespaces)[number];
export const i18nConfig = {
supportedLngs: supportedLocales,
fallbackLng: defaultLocale,
defaultNS: "translations",
ns: [...i18nNamespaces],
react: {
useSuspense: false,
},
} satisfies InitOptions;
export function isSupportedLocale(locale: string | undefined): locale is SupportedLocale {
return Boolean(locale && supportedLocales.includes(locale));
}
const ltrLocales = new Set<string>(["de", "en"]);
const rtlLocales = new Set<string>(["ar", "he", "fa", "ur"]);
export type TextDirection = "ltr" | "rtl";
export function getDirection(locale: string | undefined): TextDirection {
if (!locale) return "ltr";
if (rtlLocales.has(locale)) return "rtl";
if (ltrLocales.has(locale)) return "ltr";
return "ltr";
}
export function isRTL(locale: string | undefined): boolean {
return getDirection(locale) === "rtl";
}
// Foundation extensions (#72 i18n-foundation). Exports are namespaced via
// `./intl` and `./icu` subpaths in `package.json#exports`, but we also
// re-export the helpers here so callers can `import { formatCurrency } from
// "@toolctrl/i18n"` without juggling subpaths.
export {
formatNumber,
formatPercent,
formatCompactNumber,
formatCurrency,
formatDate,
formatRelativeTime,
formatList,
type FormatNumberOptions,
type FormatCurrencyOptions,
type FormatDateOptions,
type FormatRelativeTimeOptions,
type FormatListOptions,
} from "./intl/index.js";
export { formatIcu, createIcuFormatter, type IcuValues, type IcuOptions, type IcuFormatter } from "./icu/index.js";
export { createUseTranslate, isIcuMessage, type Translator, type ReactI18nextLike, type UseTranslateOptions } from "./useTranslate.js";
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
import { getCachedFormatter } from "./cache.js";
describe("getCachedFormatter", () => {
it("reuses formatters for equivalent option objects", () => {
const cache = new Map<string, { readonly id: number }>();
const create = vi.fn(() => ({ id: create.mock.calls.length + 1 }));
const first = getCachedFormatter(cache, "de-DE", { style: "currency", currency: "EUR", unused: undefined }, create);
const second = getCachedFormatter(cache, "de-DE", { currency: "EUR", style: "currency" }, create);
expect(second).toBe(first);
expect(create).toHaveBeenCalledTimes(1);
});
it("evicts the oldest formatter after the bounded cache fills", () => {
const cache = new Map<string, { readonly locale: string }>();
const create = vi.fn((locale: string) => ({ locale }));
for (let index = 0; index < 130; index += 1) {
getCachedFormatter(cache, `x-${index}`, {}, create);
}
expect(cache.size).toBe(128);
expect(cache.has("x-0|[]")).toBe(false);
expect(cache.has("x-129|[]")).toBe(true);
});
});
@@ -0,0 +1,28 @@
const MAX_FORMATTER_CACHE_SIZE = 128;
export function getCachedFormatter<TFormatter>(
cache: Map<string, TFormatter>,
locale: string,
options: Record<string, unknown>,
create: (locale: string, options: Record<string, unknown>) => TFormatter
): TFormatter {
const key = `${locale}|${stableOptionsKey(options)}`;
const cached = cache.get(key);
if (cached) return cached;
const formatter = create(locale, options);
if (cache.size >= MAX_FORMATTER_CACHE_SIZE) {
const oldestKey = cache.keys().next().value;
if (oldestKey) cache.delete(oldestKey);
}
cache.set(key, formatter);
return formatter;
}
function stableOptionsKey(options: Record<string, unknown>): string {
return JSON.stringify(
Object.entries(options)
.filter(([, value]) => value !== undefined)
.sort(([left], [right]) => left.localeCompare(right))
);
}
@@ -0,0 +1,29 @@
import { describe, expect, test } from "vitest";
import { formatCurrency } from "./currency.js";
// String comparisons normalise whitespace because the ICU output uses U+00A0
// (NBSP) between digits and the currency symbol — depending on Node/ICU
// versions the *exact* code point can shift between regular space and NBSP.
// We only assert on the digits + currency token to keep the test stable.
function normalise(value: string) {
return value.replace(/\s+/g, " ");
}
describe("formatCurrency", () => {
test("renders EUR in German format", () => {
expect(normalise(formatCurrency(1234.5, { locale: "de-DE", currency: "EUR" }))).toBe("1.234,50 €");
});
test("renders USD in English format", () => {
expect(normalise(formatCurrency(1234.5, { locale: "en-US", currency: "USD" }))).toBe("$1,234.50");
});
test("respects minimumFractionDigits", () => {
const out = normalise(formatCurrency(10, { locale: "en-US", currency: "USD", minimumFractionDigits: 0 }));
expect(out).toBe("$10");
});
test("renders JPY without decimals by default", () => {
expect(normalise(formatCurrency(1500, { locale: "ja-JP", currency: "JPY" }))).toBe("¥1,500");
});
});
@@ -0,0 +1,20 @@
// Locale-aware currency formatter. Currency code is required (ISO-4217) so
// callers cannot accidentally render an amount without the symbol — matches
// billing/invoice surfaces that always know their currency.
import { getCachedFormatter } from "./cache.js";
export type FormatCurrencyOptions = {
locale: string;
currency: string;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
currencyDisplay?: Intl.NumberFormatOptions["currencyDisplay"];
};
const currencyFormatters = new Map<string, Intl.NumberFormat>();
export function formatCurrency(value: number, options: FormatCurrencyOptions): string {
const { locale, currency, ...rest } = options;
return getCachedFormatter(currencyFormatters, locale, { style: "currency", currency, ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
@@ -0,0 +1,34 @@
import { describe, expect, test } from "vitest";
import { formatDate, formatRelativeTime } from "./date.js";
describe("formatDate", () => {
test("renders an ISO date per locale", () => {
const out = formatDate("2026-05-17T12:00:00Z", { locale: "en-GB", timeZone: "UTC" });
expect(out).toBe("17/05/2026");
});
test("supports DateTimeFormat options", () => {
const out = formatDate("2026-05-17T12:00:00Z", { locale: "de-DE", year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });
expect(out).toBe("17. Mai 2026");
});
});
describe("formatRelativeTime", () => {
test("renders 'X days ago' for English", () => {
const now = new Date("2026-05-17T12:00:00Z");
const earlier = new Date("2026-05-14T12:00:00Z");
expect(formatRelativeTime(earlier, { locale: "en-US", relativeTo: now, numeric: "always" })).toBe("3 days ago");
});
test("renders 'vor X Tagen' for German", () => {
const now = new Date("2026-05-17T12:00:00Z");
const earlier = new Date("2026-05-14T12:00:00Z");
expect(formatRelativeTime(earlier, { locale: "de-DE", relativeTo: now, numeric: "always" })).toBe("vor 3 Tagen");
});
test("auto-derives the largest unit (minutes vs hours)", () => {
const now = new Date("2026-05-17T12:00:00Z");
const earlier = new Date("2026-05-17T11:00:00Z");
expect(formatRelativeTime(earlier, { locale: "en-US", relativeTo: now, numeric: "always" })).toBe("1 hour ago");
});
});
@@ -0,0 +1,51 @@
// Locale-aware date formatters. Provides both absolute (`formatDate`) and
// relative (`formatRelativeTime`) variants — relative-time auto-derives the
// largest sensible unit (years > months > days > hours > minutes > seconds).
import { getCachedFormatter } from "./cache.js";
export type FormatDateOptions = Intl.DateTimeFormatOptions & { locale: string };
const dateFormatters = new Map<string, Intl.DateTimeFormat>();
const relativeTimeFormatters = new Map<string, Intl.RelativeTimeFormat>();
export function formatDate(value: Date | number | string, options: FormatDateOptions): string {
const { locale, ...rest } = options;
const date = value instanceof Date ? value : new Date(value);
return getCachedFormatter(dateFormatters, locale, rest, (formatterLocale, formatterOptions) => new Intl.DateTimeFormat(formatterLocale, formatterOptions)).format(date);
}
export type FormatRelativeTimeOptions = {
locale: string;
relativeTo?: Date | number;
numeric?: Intl.RelativeTimeFormatOptions["numeric"];
style?: Intl.RelativeTimeFormatOptions["style"];
};
const RELATIVE_UNITS: Array<{ unit: Intl.RelativeTimeFormatUnit; ms: number }> = [
{ unit: "year", ms: 365.25 * 24 * 60 * 60 * 1000 },
{ unit: "month", ms: 30 * 24 * 60 * 60 * 1000 },
{ unit: "day", ms: 24 * 60 * 60 * 1000 },
{ unit: "hour", ms: 60 * 60 * 1000 },
{ unit: "minute", ms: 60 * 1000 },
{ unit: "second", ms: 1000 },
];
export function formatRelativeTime(value: Date | number | string, options: FormatRelativeTimeOptions): string {
const { locale, relativeTo, numeric = "auto", style = "long" } = options;
const target = value instanceof Date ? value.getTime() : new Date(value).getTime();
const anchor = relativeTo instanceof Date ? relativeTo.getTime() : typeof relativeTo === "number" ? relativeTo : Date.now();
const delta = target - anchor;
const formatter = getCachedFormatter(
relativeTimeFormatters,
locale,
{ numeric, style },
(formatterLocale, formatterOptions) => new Intl.RelativeTimeFormat(formatterLocale, formatterOptions)
);
for (const { unit, ms } of RELATIVE_UNITS) {
if (Math.abs(delta) >= ms || unit === "second") {
return formatter.format(Math.round(delta / ms), unit);
}
}
return formatter.format(0, "second");
}
@@ -0,0 +1,8 @@
// Barrel for the locale-aware Intl-API wrappers. All helpers are pure +
// SSR-safe (no DOM access) and accept an explicit `locale` so server code can
// render exactly what the client sees.
export { formatNumber, formatPercent, formatCompactNumber, type FormatNumberOptions } from "./number.js";
export { formatCurrency, type FormatCurrencyOptions } from "./currency.js";
export { formatDate, formatRelativeTime, type FormatDateOptions, type FormatRelativeTimeOptions } from "./date.js";
export { formatList, type FormatListOptions } from "./list.js";
@@ -0,0 +1,16 @@
import { describe, expect, test } from "vitest";
import { formatList } from "./list.js";
describe("formatList", () => {
test("joins with 'and' for English conjunction", () => {
expect(formatList(["Alpha", "Bravo", "Charlie"], { locale: "en-US" })).toBe("Alpha, Bravo, and Charlie");
});
test("joins with 'und' for German conjunction", () => {
expect(formatList(["Alpha", "Bravo", "Charlie"], { locale: "de-DE" })).toBe("Alpha, Bravo und Charlie");
});
test("supports disjunction", () => {
expect(formatList(["Alpha", "Bravo"], { locale: "en-US", type: "disjunction" })).toBe("Alpha or Bravo");
});
});
@@ -0,0 +1,16 @@
// Locale-aware list join (Oxford-comma/und-style). Wraps `Intl.ListFormat`.
import { getCachedFormatter } from "./cache.js";
export type FormatListOptions = {
locale: string;
type?: Intl.ListFormatOptions["type"];
style?: Intl.ListFormatOptions["style"];
};
const listFormatters = new Map<string, Intl.ListFormat>();
export function formatList(items: readonly string[], options: FormatListOptions): string {
const { locale, type = "conjunction", style = "long" } = options;
return getCachedFormatter(listFormatters, locale, { type, style }, (formatterLocale, formatterOptions) => new Intl.ListFormat(formatterLocale, formatterOptions)).format(items);
}
@@ -0,0 +1,27 @@
import { describe, expect, test } from "vitest";
import { formatCompactNumber, formatNumber, formatPercent } from "./number.js";
describe("formatNumber", () => {
test("formats decimals per locale", () => {
expect(formatNumber(1234.5, { locale: "de-DE" })).toBe("1.234,5");
expect(formatNumber(1234.5, { locale: "en-US" })).toBe("1,234.5");
});
test("respects fraction digits", () => {
expect(formatNumber(1, { locale: "en-US", minimumFractionDigits: 2 })).toBe("1.00");
});
});
describe("formatPercent", () => {
test("renders a percent sign per locale", () => {
expect(formatPercent(0.25, { locale: "en-US" })).toBe("25%");
// German uses non-breaking space U+00A0 between number and sign.
expect(formatPercent(0.25, { locale: "de-DE" })).toBe("25 %");
});
});
describe("formatCompactNumber", () => {
test("collapses large numbers", () => {
expect(formatCompactNumber(1500, { locale: "en-US" })).toBe("1.5K");
});
});
@@ -0,0 +1,24 @@
// Locale-aware number formatter wrapping `Intl.NumberFormat`. Centralised so
// every callsite shares a single contract — decimal/percent/compact derive
// from this helper to avoid drift between server/client.
import { getCachedFormatter } from "./cache.js";
export type FormatNumberOptions = Intl.NumberFormatOptions & { locale: string };
const numberFormatters = new Map<string, Intl.NumberFormat>();
export function formatNumber(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, rest, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
export function formatPercent(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, { style: "percent", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
export function formatCompactNumber(value: number, options: FormatNumberOptions): string {
const { locale, ...rest } = options;
return getCachedFormatter(numberFormatters, locale, { notation: "compact", ...rest }, (formatterLocale, formatterOptions) => new Intl.NumberFormat(formatterLocale, formatterOptions)).format(value);
}
@@ -0,0 +1,22 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import { describe, expect, test } from "vitest";
// Smoke test for the RTL/LTR variant registration in the root Tailwind config.
// We don't spin up the Tailwind compiler here — that's covered by the web
// app's build pipeline — but we *do* assert the variants are wired so the
// next config refactor can't silently delete them. Coupled with `<html
// dir={dir}>` in `apps/web/app/root.tsx`, this is the foundation for RTL
// support.
describe("RTL tailwind variants", () => {
test("root tailwind.config.ts registers rtl: and ltr: variants", () => {
const configPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "../../../tailwind.config.ts");
const source = readFileSync(configPath, "utf8");
expect(source).toMatch(/addVariant\("rtl",/);
expect(source).toMatch(/addVariant\("ltr",/);
expect(source).toContain('[dir="rtl"]');
expect(source).toContain('[dir="ltr"]');
});
});
@@ -0,0 +1,58 @@
import { describe, expect, test } from "vitest";
import { createUseTranslate, isIcuMessage, type ReactI18nextLike } from "./useTranslate.js";
// We stub the `react-i18next` surface — running the actual React renderer is
// out of scope here. The hook is a thin layer of glue logic so a stub gives us
// > 99 % of the value at < 1 % of the setup cost.
function makeDeps(translations: Record<string, string>, language: string): ReactI18nextLike {
return {
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) => {
const raw = translations[key] ?? key;
if (!values) return raw;
// mimic i18next's basic `{{name}}` interpolation so non-ICU messages
// still substitute values as callers expect.
return raw.replace(/\{\{(\w+)\}\}/g, (_, name) => String(values[name] ?? `{{${name}}}`));
},
i18n: { language },
}),
};
}
describe("isIcuMessage", () => {
test("detects plural and select messages", () => {
expect(isIcuMessage("{count, plural, one {# item} other {# items}}")).toBe(true);
expect(isIcuMessage("{role, select, admin {Admin} other {Guest}}")).toBe(true);
expect(isIcuMessage("Hello {{name}}")).toBe(false);
expect(isIcuMessage("Plain string")).toBe(false);
});
});
describe("createUseTranslate", () => {
test("routes ICU plurals through intl-messageformat", () => {
const deps = makeDeps(
{ itemsSelected: "{count, plural, =0 {Nothing selected} one {# item selected} other {# items selected}}" },
"en-US",
);
const useTranslate = createUseTranslate(deps);
const t = useTranslate();
expect(t("itemsSelected", { count: 0 })).toBe("Nothing selected");
expect(t("itemsSelected", { count: 1 })).toBe("1 item selected");
expect(t("itemsSelected", { count: 5 })).toBe("5 items selected");
});
test("falls through to i18next for non-ICU messages", () => {
const deps = makeDeps({ greet: "Hello {{name}}" }, "en-US");
const useTranslate = createUseTranslate(deps);
const t = useTranslate();
expect(t("greet", { name: "Ada" })).toBe("Hello Ada");
});
test("exposes the active language", () => {
const deps = makeDeps({ greet: "Moin" }, "de-DE");
const useTranslate = createUseTranslate(deps);
const t = useTranslate();
expect(t.language).toBe("de-DE");
});
});
@@ -0,0 +1,65 @@
// Tiny React hook layered on top of `react-i18next` that adds first-class
// support for ICU-MessageFormat plurals. The reason this lives in the i18n
// package and not in app-land: ICU detection logic is identical for every
// caller, and pulling it next to `formatIcu` keeps the contract consistent
// between server-rendered emails and client-rendered React surfaces.
//
// We do NOT import `react-i18next` directly — the package would then become
// a hard dependency. Callers pass the `useTranslation` import from their app
// once via `createUseTranslate`. App-side wiring lives in
// `apps/web/app/locale/useTranslate.ts`.
import { formatIcu, type IcuValues } from "./icu/plural.js";
export type Translator = (key: string, values?: IcuValues) => string;
export type ReactI18nextLike = {
useTranslation: (ns?: string | string[]) => {
t: (key: string, options?: Record<string, unknown>) => string;
i18n: { language: string };
};
};
export type UseTranslateOptions = {
/**
* If the raw message returned from `t()` contains ICU-syntax (`{count,
* plural,…}` / `{name, select,…}`), pass it through `intl-messageformat`
* instead of i18next's built-in pluralization. Default `true`.
*/
icu?: boolean;
};
const ICU_PATTERN = /\{[^{}]+,\s*(plural|select|selectordinal)\s*,/;
export function isIcuMessage(message: string): boolean {
return ICU_PATTERN.test(message);
}
/**
* Factory: produce a `useTranslate(namespace?)` hook bound to a particular
* `react-i18next` instance. The hook returns a translator that prefers the
* ICU formatter when the raw message has ICU syntax, otherwise falls back to
* the i18next `t()` value (preserves backwards compatibility with the legacy
* `count`-suffix pluralization used by older translation keys).
*/
export function createUseTranslate(deps: ReactI18nextLike, defaults: UseTranslateOptions = {}) {
const icuEnabled = defaults.icu !== false;
return function useTranslate(namespace?: string | string[]): Translator & { language: string } {
const { t, i18n } = deps.useTranslation(namespace);
const translator: Translator = (key, values) => {
// Pass values through to i18next first so existing `{{name}}` callsites
// and the `count`-suffix plural shorthand keep working.
const raw = t(key, values as Record<string, unknown>);
if (icuEnabled && typeof raw === "string" && isIcuMessage(raw)) {
try {
return formatIcu(raw, values ?? {}, { locale: i18n.language });
} catch {
// Fall through to raw message; better to ship the source than crash.
return raw;
}
}
return typeof raw === "string" ? raw : String(raw);
};
return Object.assign(translator, { language: i18n.language });
};
}
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"allowJs": false,
"allowImportingTsExtensions": true,
"lib": ["ES2022"],
"module": "NodeNext",
"moduleResolution": "NodeNext",
"noEmit": true,
"types": ["node"]
},
"include": ["src/**/*.ts"]
}