IconFont.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import _extends from "@babel/runtime/helpers/esm/extends";
  2. import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
  3. var _excluded = ["type", "children"];
  4. import * as React from 'react';
  5. import Icon from "./Icon";
  6. var customCache = new Set();
  7. function isValidCustomScriptUrl(scriptUrl) {
  8. return Boolean(typeof scriptUrl === 'string' && scriptUrl.length && !customCache.has(scriptUrl));
  9. }
  10. function createScriptUrlElements(scriptUrls) {
  11. var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
  12. var currentScriptUrl = scriptUrls[index];
  13. if (isValidCustomScriptUrl(currentScriptUrl)) {
  14. var script = document.createElement('script');
  15. script.setAttribute('src', currentScriptUrl);
  16. script.setAttribute('data-namespace', currentScriptUrl);
  17. if (scriptUrls.length > index + 1) {
  18. script.onload = function () {
  19. createScriptUrlElements(scriptUrls, index + 1);
  20. };
  21. script.onerror = function () {
  22. createScriptUrlElements(scriptUrls, index + 1);
  23. };
  24. }
  25. customCache.add(currentScriptUrl);
  26. document.body.appendChild(script);
  27. }
  28. }
  29. export default function create() {
  30. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  31. var scriptUrl = options.scriptUrl,
  32. _options$extraCommonP = options.extraCommonProps,
  33. extraCommonProps = _options$extraCommonP === void 0 ? {} : _options$extraCommonP;
  34. /**
  35. * DOM API required.
  36. * Make sure in browser environment.
  37. * The Custom Icon will create a <script/>
  38. * that loads SVG symbols and insert the SVG Element into the document body.
  39. */
  40. if (scriptUrl && typeof document !== 'undefined' && typeof window !== 'undefined' && typeof document.createElement === 'function') {
  41. if (Array.isArray(scriptUrl)) {
  42. // 因为iconfont资源会把svg插入before,所以前加载相同type会覆盖后加载,为了数组覆盖顺序,倒叙插入
  43. createScriptUrlElements(scriptUrl.reverse());
  44. } else {
  45. createScriptUrlElements([scriptUrl]);
  46. }
  47. }
  48. var Iconfont = /*#__PURE__*/React.forwardRef(function (props, ref) {
  49. var type = props.type,
  50. children = props.children,
  51. restProps = _objectWithoutProperties(props, _excluded);
  52. // children > type
  53. var content = null;
  54. if (props.type) {
  55. content = /*#__PURE__*/React.createElement("use", {
  56. xlinkHref: "#".concat(type)
  57. });
  58. }
  59. if (children) {
  60. content = children;
  61. }
  62. return /*#__PURE__*/React.createElement(Icon, _extends({}, extraCommonProps, restProps, {
  63. ref: ref
  64. }), content);
  65. });
  66. Iconfont.displayName = 'Iconfont';
  67. return Iconfont;
  68. }