Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/i18n/src/useTranslate.ts
T

66 lines
2.7 KiB
TypeScript

// 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 });
};
}