custom.mjs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import createDebugger from 'debug';
  2. import { mergeIconProps } from './utils.mjs';
  3. import { trimSVG } from '../svg/trim.mjs';
  4. import '../svg/build.mjs';
  5. import '../icon/defaults.mjs';
  6. import '../customisations/defaults.mjs';
  7. import '../svg/size.mjs';
  8. import '../svg/defs.mjs';
  9. const debug = createDebugger("@iconify-loader:custom");
  10. async function getCustomIcon(custom, collection, icon, options) {
  11. let result;
  12. debug(`${collection}:${icon}`);
  13. try {
  14. if (typeof custom === "function") {
  15. result = await custom(icon);
  16. } else {
  17. const inline = custom[icon];
  18. result = typeof inline === "function" ? await inline() : inline;
  19. }
  20. } catch (err) {
  21. console.warn(
  22. `Failed to load custom icon "${icon}" in "${collection}":`,
  23. err
  24. );
  25. return;
  26. }
  27. if (result) {
  28. const cleanupIdx = result.indexOf("<svg");
  29. if (cleanupIdx > 0)
  30. result = result.slice(cleanupIdx);
  31. const { transform } = options?.customizations ?? {};
  32. result = typeof transform === "function" ? await transform(result, collection, icon) : result;
  33. if (!result.startsWith("<svg")) {
  34. console.warn(
  35. `Custom icon "${icon}" in "${collection}" is not a valid SVG`
  36. );
  37. return result;
  38. }
  39. return await mergeIconProps(
  40. options?.customizations?.trimCustomSvg === true ? trimSVG(result) : result,
  41. collection,
  42. icon,
  43. options,
  44. void 0
  45. );
  46. }
  47. }
  48. export { getCustomIcon };