You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

customNavigatorDetector.js 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* @flow */
  2. declare var navigator: Object;
  3. /**
  4. * Custom language detection, just returns the config property if any.
  5. */
  6. export default {
  7. /**
  8. * Does not support caching.
  9. *
  10. * @returns {void}
  11. */
  12. cacheUserLanguage: Function.prototype,
  13. /**
  14. * Looks the language up in the config.
  15. *
  16. * @returns {string} The default language if any.
  17. */
  18. lookup() {
  19. let found = [];
  20. if (typeof navigator !== 'undefined') {
  21. if (navigator.languages) {
  22. // chrome only; not an array, so can't use .push.apply instead of iterating
  23. for (let i = 0; i < navigator.languages.length; i++) {
  24. found.push(navigator.languages[i]);
  25. }
  26. }
  27. if (navigator.userLanguage) {
  28. found.push(navigator.userLanguage);
  29. }
  30. if (navigator.language) {
  31. found.push(navigator.language);
  32. }
  33. }
  34. found = found.map<string>(normalizeLanguage);
  35. return found.length > 0 ? found : undefined;
  36. },
  37. /**
  38. * Name of the language detector.
  39. */
  40. name: 'customNavigatorDetector'
  41. };
  42. /**
  43. * Normalize language format.
  44. *
  45. * (en-US => enUS)
  46. * (en-gb => enGB)
  47. * (es-es => es).
  48. *
  49. * @param {string} language - Language.
  50. * @returns {string} The normalized language.
  51. */
  52. function normalizeLanguage(language) {
  53. const [ lang, variant ] = language.replace('_', '-').split('-');
  54. if (!variant || lang === variant) {
  55. return lang;
  56. }
  57. return lang + variant.toUpperCase();
  58. }