aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/i18n.js
blob: 4cbb9a5dcf8fce4b8d3fbc70ad5367a1b44f4fd6 (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
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";

// the default locale to use if none was found
const defaultLocale = "en";

// Adds a new locale based on its code
function addLocale(localeCode) {
  register(localeCode, () => import(`${localeDirectory}/${localeCode}.json`));
}

// Picks the default locale based on navigator locale and the list of available locales
function pickLocale(navigatorLocale, availableLocales) {
  // locale can be null the first time you load this
  // return the default locale in that case - reloading should fix this
  if (!navigatorLocale)
    return defaultLocale;

  // 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;
  }
}

// add locales
localeCodes.forEach(addLocale);

let initialLocale = pickLocale(getLocaleFromNavigator(), localeCodes);
init({
  fallbackLocale: defaultLocale,
  initialLocale: initialLocale,
});