utils.js 1.7 KB

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