i18n.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { createI18n } from 'vue-i18n';
  2. import en from './locales/en.json';
  3. import me from './locales/me.json';
  4. import ru from './locales/ru.json';
  5. import ua from './locales/ua.json';
  6. const savedLocale = localStorage.getItem('locale') || 'en';
  7. const i18n = createI18n({
  8. legacy: false,
  9. locale: savedLocale,
  10. fallbackLocale: 'en',
  11. messages: {
  12. en,
  13. me,
  14. ru,
  15. ua
  16. }
  17. });
  18. // Robust deep merge for locale objects
  19. const deepMerge = (target: any, source: any) => {
  20. if (!source) return target;
  21. Object.keys(source).forEach(key => {
  22. const sVal = source[key];
  23. const tVal = target[key];
  24. if (sVal !== null && typeof sVal === 'object' && !Array.isArray(sVal)) {
  25. if (!tVal || typeof tVal !== 'object') {
  26. target[key] = {};
  27. }
  28. deepMerge(target[key], sVal);
  29. } else {
  30. target[key] = sVal;
  31. }
  32. });
  33. return target;
  34. };
  35. export const loadAdminTranslations = async (lang?: string) => {
  36. const targetLang = lang || (i18n.global as any).locale.value;
  37. console.log(`[i18n] Loading admin translations for: ${targetLang}...`);
  38. try {
  39. const module = await import(`./locales/${targetLang}.admin.json`);
  40. let newMessages = module.default || module;
  41. // Ensure the structure is correct: { admin: { ... } }
  42. if (!newMessages.admin && (newMessages.tabs || newMessages.actions || newMessages.managementCenter)) {
  43. newMessages = { admin: newMessages };
  44. }
  45. // getLocaleMessage returns a copy in Composer mode
  46. const currentMessages = i18n.global.getLocaleMessage(targetLang);
  47. // Perform deep merge
  48. const merged = deepMerge({ ...currentMessages }, newMessages);
  49. // Explicitly set the updated message object back to the locale
  50. i18n.global.setLocaleMessage(targetLang, merged);
  51. console.log(`[i18n] Admin translations successfully loaded and merged for: ${targetLang}`);
  52. } catch (error) {
  53. console.error(`[i18n] Failed to load admin translations for ${targetLang}:`, error);
  54. }
  55. };
  56. export const setLanguage = async (lang: string) => {
  57. (i18n.global as any).locale.value = lang;
  58. localStorage.setItem('locale', lang);
  59. // If we are in an admin-related path, we might want to load admin translations for the new language
  60. if (window.location.pathname.startsWith('/admin')) {
  61. await loadAdminTranslations(lang);
  62. }
  63. };
  64. export const currentLanguage = () => (i18n.global as any).locale.value as string;
  65. export default i18n;