utils.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.82
  5. */
  6. import { getAssetPath } from "@stencil/core";
  7. import { locales } from "../../utils/locale";
  8. /**
  9. * Get supported locale code from raw user input
  10. * Exported for testing purposes.
  11. * @private
  12. */
  13. function getSupportedLocale(lang = "") {
  14. if (locales.indexOf(lang) > -1) {
  15. return lang;
  16. }
  17. lang = lang.toLowerCase();
  18. if (lang.includes("-")) {
  19. lang = lang.replace(/(\w+)-(\w+)/, (_match, language, region) => `${language}-${region.toUpperCase()}`);
  20. if (!locales.includes(lang)) {
  21. lang = lang.split("-")[0];
  22. }
  23. }
  24. return locales.includes(lang) ? lang : "en";
  25. }
  26. /**
  27. * CLDR cache.
  28. * Exported for testing purposes.
  29. * @private
  30. */
  31. export const translationCache = {};
  32. /**
  33. * CLDR request cache.
  34. * Exported for testing purposes.
  35. * @private
  36. */
  37. export const requestCache = {};
  38. /**
  39. * Fetch calendar data for a given locale from list of supported languages
  40. * @public
  41. */
  42. export async function getLocaleData(lang) {
  43. const locale = getSupportedLocale(lang);
  44. if (translationCache[locale]) {
  45. return translationCache[locale];
  46. }
  47. if (!requestCache[locale]) {
  48. requestCache[locale] = fetch(getAssetPath(`./assets/date-picker/nls/${locale}.json`))
  49. .then((resp) => resp.json())
  50. .catch(() => {
  51. console.error(`Translations for "${locale}" not found or invalid, falling back to english`);
  52. return getLocaleData("en");
  53. });
  54. }
  55. const data = await requestCache[locale];
  56. translationCache[locale] = data;
  57. return data;
  58. }