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.ts 1.6KB

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