summaryrefslogtreecommitdiff
path: root/public/js/locale.js
blob: ccc1d0e4537ca25bddad576dfb2d23171c753b03 (plain)
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
/* eslint-env browser, jquery */
/* global Cookies */
const supportedLanguages = require('../../locales/_supported.json')

function detectLang () {
  if (Cookies.get('locale')) {
    let lang = Cookies.get('locale')
    if (lang === 'zh') {
      lang = 'zh-TW'
    }
    return lang
  }
  const userLang = navigator.language || navigator.userLanguage
  const userLangCode = userLang.split('-')[0]
  const supportedLanguagesList = Object.keys(supportedLanguages)
  if (supportedLanguagesList.includes(userLangCode)) {
    return userLangCode
  } else if (supportedLanguagesList.includes(userLang)) {
    return userLang
  }
  return 'en'
}

const lang = detectLang()
const localeSelector = $('.ui-locale')
Object.entries(supportedLanguages).forEach(function ([isoCode, nativeName]) {
  localeSelector.append(`<option value="${isoCode}">${nativeName}</option>`)
})

// the following condition is needed as the selector is only available in the intro/history page
if (localeSelector.length > 0) {
  localeSelector.val(lang)
  $('select.ui-locale option[value="' + lang + '"]').attr('selected', 'selected')
  localeSelector.change(function () {
    Cookies.set('locale', $(this).val(), {
      expires: 365,
      sameSite: window.cookiePolicy
    })
    window.location.reload()
  })
}

window.moment.locale(lang)