utils.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. /**
  8. * Icon data cache.
  9. * Exported for testing purposes.
  10. * @private
  11. */
  12. export const iconCache = {};
  13. /**
  14. * Icon request cache.
  15. * Exported for testing purposes.
  16. * @private
  17. */
  18. export const requestCache = {};
  19. export const scaleToPx = {
  20. s: 16,
  21. m: 24,
  22. l: 32
  23. };
  24. export async function fetchIcon({ icon, scale }) {
  25. const size = scaleToPx[scale];
  26. const name = normalizeIconName(icon);
  27. const filled = name.charAt(name.length - 1) === "F";
  28. const iconName = filled ? name.substring(0, name.length - 1) : name;
  29. const id = `${iconName}${size}${filled ? "F" : ""}`;
  30. if (iconCache[id]) {
  31. return iconCache[id];
  32. }
  33. if (!requestCache[id]) {
  34. requestCache[id] = fetch(getAssetPath(`./assets/icon/${id}.json`))
  35. .then((resp) => resp.json())
  36. .catch(() => {
  37. console.error(`"${id}" is not a valid calcite-ui-icon name`);
  38. return "";
  39. });
  40. }
  41. const path = await requestCache[id];
  42. iconCache[id] = path;
  43. return path;
  44. }
  45. /**
  46. * Normalize the icon name to match the path data module exports.
  47. * Exported for testing purposes.
  48. * @private
  49. */
  50. export function normalizeIconName(name) {
  51. const numberLeadingName = !isNaN(Number(name.charAt(0)));
  52. const parts = name.split("-");
  53. if (parts.length === 1) {
  54. return numberLeadingName ? `i${name}` : name;
  55. }
  56. return parts
  57. .map((part, index) => {
  58. if (index === 0) {
  59. return numberLeadingName ? `i${part.toUpperCase()}` : part;
  60. }
  61. return part.charAt(0).toUpperCase() + part.slice(1);
  62. })
  63. .join("");
  64. }