|
| 1 | +/** |
| 2 | + * i18n entry point for open-codesign. |
| 3 | + * |
| 4 | + * Design notes: |
| 5 | + * - Two locales out of the gate: `en` and `zh-CN`. Adding a third means adding |
| 6 | + * a JSON file under `./locales/` and registering it in `resources` + `availableLocales`. |
| 7 | + * - We do NOT silently swallow missing keys. In dev they render as `⟦key⟧` so |
| 8 | + * they're visible in the UI; in any environment a `console.warn` records the |
| 9 | + * namespace + locale + key path. (Principle §10: no silent fallbacks.) |
| 10 | + * - `normalizeLocale` is intentionally narrow — we only widen aliases that we |
| 11 | + * are confident about (zh-Hans*, en-*). Anything else logs a warning and |
| 12 | + * falls back to `DEFAULT_LOCALE`. |
| 13 | + */ |
| 14 | + |
| 15 | +import i18next from 'i18next'; |
| 16 | +import { initReactI18next, useTranslation } from 'react-i18next'; |
| 17 | +import en from './locales/en.json'; |
| 18 | +import zhCN from './locales/zh-CN.json'; |
| 19 | + |
| 20 | +export const availableLocales = ['en', 'zh-CN'] as const; |
| 21 | +export type Locale = (typeof availableLocales)[number]; |
| 22 | + |
| 23 | +const DEFAULT_LOCALE: Locale = 'en'; |
| 24 | + |
| 25 | +const resources = { |
| 26 | + en: { translation: en }, |
| 27 | + 'zh-CN': { translation: zhCN }, |
| 28 | +} as const; |
| 29 | + |
| 30 | +export function isSupportedLocale(value: string | undefined | null): value is Locale { |
| 31 | + if (!value) return false; |
| 32 | + return (availableLocales as readonly string[]).includes(value); |
| 33 | +} |
| 34 | + |
| 35 | +export function normalizeLocale(value: string | undefined | null): Locale { |
| 36 | + if (!value) return DEFAULT_LOCALE; |
| 37 | + if (isSupportedLocale(value)) return value; |
| 38 | + const lower = value.toLowerCase(); |
| 39 | + if (lower === 'zh' || lower.startsWith('zh-hans') || lower === 'zh-cn' || lower === 'zh_cn') { |
| 40 | + return 'zh-CN'; |
| 41 | + } |
| 42 | + if (lower.startsWith('en')) return 'en'; |
| 43 | + console.warn( |
| 44 | + `[i18n] unsupported locale "${value}", falling back to "${DEFAULT_LOCALE}". ` + |
| 45 | + `Supported: ${availableLocales.join(', ')}`, |
| 46 | + ); |
| 47 | + return DEFAULT_LOCALE; |
| 48 | +} |
| 49 | + |
| 50 | +let initialized = false; |
| 51 | + |
| 52 | +function detectIsDev(): boolean { |
| 53 | + const proc = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process; |
| 54 | + return proc?.env?.['NODE_ENV'] !== 'production'; |
| 55 | +} |
| 56 | + |
| 57 | +export async function initI18n(locale: string | undefined): Promise<Locale> { |
| 58 | + const target = normalizeLocale(locale); |
| 59 | + if (initialized) { |
| 60 | + if (i18next.language !== target) { |
| 61 | + await i18next.changeLanguage(target); |
| 62 | + } |
| 63 | + return target; |
| 64 | + } |
| 65 | + |
| 66 | + const isDev = detectIsDev(); |
| 67 | + |
| 68 | + await i18next.use(initReactI18next).init({ |
| 69 | + resources, |
| 70 | + lng: target, |
| 71 | + fallbackLng: DEFAULT_LOCALE, |
| 72 | + supportedLngs: [...availableLocales], |
| 73 | + interpolation: { escapeValue: false }, |
| 74 | + returnNull: false, |
| 75 | + saveMissing: true, |
| 76 | + missingKeyHandler: (lngs, ns, key) => { |
| 77 | + const lang = Array.isArray(lngs) ? lngs.join(',') : String(lngs); |
| 78 | + console.warn( |
| 79 | + `[i18n] missing translation key "${key}" in namespace "${ns}" for locale "${lang}"`, |
| 80 | + ); |
| 81 | + }, |
| 82 | + parseMissingKeyHandler: (key) => { |
| 83 | + if (isDev) return `\u27E6${key}\u27E7`; |
| 84 | + return key; |
| 85 | + }, |
| 86 | + react: { useSuspense: false }, |
| 87 | + }); |
| 88 | + |
| 89 | + initialized = true; |
| 90 | + return target; |
| 91 | +} |
| 92 | + |
| 93 | +export async function setLocale(locale: string): Promise<Locale> { |
| 94 | + const target = normalizeLocale(locale); |
| 95 | + if (!initialized) { |
| 96 | + return initI18n(target); |
| 97 | + } |
| 98 | + await i18next.changeLanguage(target); |
| 99 | + return target; |
| 100 | +} |
| 101 | + |
| 102 | +export function getCurrentLocale(): Locale { |
| 103 | + return normalizeLocale(i18next.language); |
| 104 | +} |
| 105 | + |
| 106 | +export function useT(): (key: string, options?: Record<string, unknown>) => string { |
| 107 | + const { t } = useTranslation(); |
| 108 | + return (key, options) => t(key, options ?? {}) as string; |
| 109 | +} |
| 110 | + |
| 111 | +export { i18next as i18n }; |
| 112 | +export { useTranslation } from 'react-i18next'; |
0 commit comments