feat: implement core-i18n package with decentralized namespace support and integrate into landing and web apps
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import i18n from 'i18next';
|
||||
import { initReactI18next } from 'react-i18next';
|
||||
import { demoSecureStorage, StorageKey } from '@repo/core-storage';
|
||||
import commonEn from './locales/en/common.json';
|
||||
import commonId from './locales/id/common.json';
|
||||
|
||||
const DEFAULT_LANGUAGE = 'id';
|
||||
const SUPPORTED_LANGUAGES = ['en', 'id'] as const;
|
||||
|
||||
export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];
|
||||
|
||||
export const resources = {
|
||||
en: { common: commonEn.common },
|
||||
id: { common: commonId.common },
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Bootstraps the central i18n engine.
|
||||
*
|
||||
* This reads the preferred locale from secureStorage and initializes
|
||||
* i18next synchronously before React renders.
|
||||
*/
|
||||
export async function setupI18n(): Promise<void> {
|
||||
let initialLng = DEFAULT_LANGUAGE;
|
||||
try {
|
||||
const storedLng = await demoSecureStorage.getItem<string>(StorageKey.LOCALE);
|
||||
if (storedLng && SUPPORTED_LANGUAGES.includes(storedLng as SupportedLanguage)) {
|
||||
initialLng = storedLng;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[i18n] Failed to read locale from storage', err);
|
||||
}
|
||||
|
||||
await i18n
|
||||
.use(initReactI18next)
|
||||
.init({
|
||||
resources,
|
||||
lng: initialLng,
|
||||
fallbackLng: DEFAULT_LANGUAGE,
|
||||
defaultNS: 'common',
|
||||
interpolation: {
|
||||
escapeValue: false, // React already escapes values
|
||||
},
|
||||
});
|
||||
|
||||
// Apply initial language to the DOM for SEO/Accessibility
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = i18n.language;
|
||||
}
|
||||
|
||||
// Ensure DOM updates whenever the language changes later
|
||||
i18n.on('languageChanged', (lng) => {
|
||||
if (typeof document !== 'undefined') {
|
||||
document.documentElement.lang = lng;
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user