blob: 2d39e29236811f84ca039a1face09c9079a8d3bd (
plain) (
blame)
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
|
import { register, init, getLocaleFromNavigator } from 'svelte-i18n';
/** The list of locales to look for */
const localeCodes = ['en', 'fr'];
/** The directory where locale files are stored */
const localeDirectory = "../locales";
/**
* Adds a new locale from the appropriate JSON file
* @param {string} localeCode - the code of the locale to add
*/
function addLocale(localeCode) {
register(localeCode, () => import(`${localeDirectory}/${localeCode}.json`));
}
/**
* Determines the default locale.
* @param {string} navigatorLocale - the locale given by the navigator
* @param {array<string>} avalableLocales - a list of the available locales
* @returns {string} chosen default locale
*/
function pickLocale(navigatorLocale, availableLocales) {
// determine langugage part of locale
// (e.g. if navigatorLocale is 'en-US', languageCode is 'en')
let dashIndex = navigatorLocale ? navigatorLocale.indexOf("-") : -1;
let languageCode; // navigator locale without the regional part
if (dashIndex === -1) {
languageCode = navigatorLocale;
} else {
languageCode = navigatorLocale.slice(0, dashIndex);
}
// get locale
if (availableLocales.includes(navigatorLocale)) {
return navigatorLocale;
} else if (availableLocales.includes(languageCode)) {
return languageCode;
} else {
return null;
}
}
/**
* Loads all of the locales, picks a default locale, and sets up internationalization in that locale.
*/
export function setupI18n() {
localeCodes.forEach(addLocale);
let initialLocale = pickLocale(getLocaleFromNavigator(), localeCodes);
init({
fallbackLocale: 'en',
initialLocale: initialLocale,
});
}
|