import i18next from 'i18next' import { initReactI18next } from 'react-i18next' import { FALLBACK_LANGUAGE, SUPPORTED_LANGUAGES, normalizeLanguage } from './locale.js' import { NAMESPACES, resources } from './resources.js' import { BASE_OPTIONS } from './options.js' const DEV = typeof import.meta !== 'undefined' && !!import.meta.env?.DEV /** * One i18next instance per app, ready synchronously (resources are bundled). * * const i18n = createI18n({ language: resolveLanguage({ venue: 'el' }) }) * … * * A key missing in the current language falls back to English. A key missing in English * too renders the key itself and, in dev builds, warns in the console (and * scripts/check-i18n.mjs fails on it before it gets that far). * `extra` adds resources ({ el: { myns: {...} } }) on top of the bundled ones. */ export function createI18n({ language = FALLBACK_LANGUAGE, defaultNS = 'common', extra } = {}) { const i18n = i18next.createInstance() i18n.use(initReactI18next).init({ resources: mergeResources(resources, extra), lng: normalizeLanguage(language) || FALLBACK_LANGUAGE, ...BASE_OPTIONS, ns: NAMESPACES, defaultNS, saveMissing: DEV, missingKeyHandler: DEV ? (lngs, ns, key) => console.warn(`[i18n] missing key "${ns}:${key}" (${lngs.join(', ')})`) : undefined, react: { useSuspense: false }, }) const setHtmlLang = lng => { if (typeof document !== 'undefined') document.documentElement.lang = lng } setHtmlLang(i18n.language) i18n.on('languageChanged', setHtmlLang) return i18n } function mergeResources(base, extra) { if (!extra) return base const out = { ...base } for (const [lng, namespaces] of Object.entries(extra)) { out[lng] = { ...(out[lng] || {}) } for (const [ns, data] of Object.entries(namespaces)) out[lng][ns] = { ...(out[lng][ns] || {}), ...data } } return out }