All files / src/i18n index.ts

93.54% Statements 58/62
81.25% Branches 13/16
100% Functions 6/6
93.54% Lines 58/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 771x 1x 1x 1x   1x   1x   1x   115x 115x 115x 115x 115x 115x 115x 115x 115x 115x       1x 54x 54x   1x 43x 40x 43x 39x 39x   1x 48x 48x 48x 48x 11x 11x 48x   37x 37x 37x         1x 88x 88x   67x 67x 67x 67x 67x   1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x  
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import tr from './locales/tr.json';
 
export const SUPPORTED_LOCALES = ['en', 'tr'] as const;
export type Locale = (typeof SUPPORTED_LOCALES)[number];
export const LOCALE_STORAGE_KEY = 'sem_locale';
 
let currentLocale: Locale = 'en';
 
function getStorage(): Storage | null {
  if (typeof window === 'undefined') return null;
  const candidate = window.localStorage;
  if (
    candidate
    && typeof candidate.getItem === 'function'
    && typeof candidate.setItem === 'function'
  ) {
    return candidate;
  }
  return null;
}
 
export function isSupportedLocale(value: unknown): value is Locale {
  return value === 'en' || value === 'tr';
}
 
export function resolveLocale(deviceTag: string | null | undefined): Locale {
  if (!deviceTag) return 'en';
  const lower = deviceTag.toLowerCase();
  if (lower.startsWith('tr')) return 'tr';
  return 'en';
}
 
export function detectInitialLocale(): Locale {
  const storage = getStorage();
  if (storage) {
    const storedLocale = storage.getItem(LOCALE_STORAGE_KEY);
    if (isSupportedLocale(storedLocale)) {
      return storedLocale;
    }
  }
 
  if (typeof navigator !== 'undefined') {
    return resolveLocale(navigator.language);
  }
 
  return 'en';
}
 
export function getCurrentLocale(): Locale {
  return currentLocale;
}
 
export async function setCurrentLocale(locale: Locale): Promise<void> {
  currentLocale = locale;
  getStorage()?.setItem(LOCALE_STORAGE_KEY, locale);
  await i18n.changeLanguage(locale);
}
 
currentLocale = detectInitialLocale();
 
void i18n.use(initReactI18next).init({
  resources: {
    en: { translation: en },
    tr: { translation: tr },
  },
  lng: currentLocale,
  fallbackLng: 'en',
  interpolation: { escapeValue: false },
  returnNull: false,
  react: { useSuspense: false },
});
 
export default i18n;