index.ts 2.17 KB
Newer Older
1
2
import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
3
import resourcesToBackend from 'i18next-resources-to-backend';
Ased Mammad's avatar
Ased Mammad committed
4
5
6
import type { i18n as i18nType } from 'i18next';
import { writable } from 'svelte/store';

Ased Mammad's avatar
Ased Mammad committed
7
const createI18nStore = (i18n: i18nType) => {
Ased Mammad's avatar
Ased Mammad committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
	const i18nWritable = writable(i18n);

	i18n.on('initialized', () => {
		i18nWritable.set(i18n);
	});
	i18n.on('loaded', () => {
		i18nWritable.set(i18n);
	});
	i18n.on('added', () => i18nWritable.set(i18n));
	i18n.on('languageChanged', () => {
		i18nWritable.set(i18n);
	});
	return i18nWritable;
};

Ased Mammad's avatar
Ased Mammad committed
23
const createIsLoadingStore = (i18n: i18nType) => {
Ased Mammad's avatar
Ased Mammad committed
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
	const isLoading = writable(false);

	// if loaded resources are empty || {}, set loading to true
	i18n.on('loaded', (resources) => {
		// console.log('loaded:', resources);
		Object.keys(resources).length !== 0 && isLoading.set(false);
	});

	// if resources failed loading, set loading to true
	i18n.on('failedLoading', () => {
		isLoading.set(true);
	});

	return isLoading;
};
39

40
41
42
43
44
45
46
47
48
export const initI18n = (defaultLocale?: string) => {
	// Use object destructuring for cleaner code
	const [defaultDetection, fallbackDetection] = defaultLocale ? ['querystring', 'localStorage'] : ['querystring', 'localStorage', 'navigator'];
  
	// Use nullish coalescing operator to simplify the ternary expression
	const fallbackDefaultLocale = defaultLocale ?? 'en-US';
  
	const loadResource = (language: string, namespace: string) => import(`./locales/${language}/${namespace}.json`);
  
49
	i18next
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
	  .use(resourcesToBackend(loadResource))
	  .use(LanguageDetector)
	  .init({
		debug: false,
		detection: {
		  order: [defaultDetection, fallbackDetection],
		  caches: ['localStorage'],
		  lookupQuerystring: 'lang',
		  lookupLocalStorage: 'locale'
		},
		fallbackLng: fallbackDefaultLocale,
		ns: 'translation',
		returnEmptyString: false,
		interpolation: { escapeValue: false }
	  });
  };
Ased Mammad's avatar
Ased Mammad committed
66

67
const i18n = createI18nStore(i18next);
Ased Mammad's avatar
Ased Mammad committed
68
const isLoadingStore = createIsLoadingStore(i18next);
Ased Mammad's avatar
Ased Mammad committed
69

70
71
72
73
export const getLanguages = async () => {
	const languages = (await import(`./locales/languages.json`)).default;
	return languages;
};
74
75
export default i18n;
export const isLoading = isLoadingStore;