aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/i18n.js
blob: 95bf7013bc8828105545497fbc022e426f887fe7 (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
import { register, init, getLocaleFromNavigator } from 'svelte-i18n';

// list of locales to load
const localeCodes = ['en', 'fr'];

// load locales
function addLocale(localeCode) {
  register(localeCode, () => import('../locales/' + localeCode + '.json'));
}

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

// setup internationalization
export function setupI18n() {
  localeCodes.forEach(addLocale);
  let initialLocale = pickLocale(getLocaleFromNavigator(), localeCodes);

  init({
    fallbackLocale: 'en',
    initialLocale: initialLocale,
  });
}