UNPKG

react-svg

Version:

A React component that injects SVG into the DOM.

3 lines (2 loc) 11.4 kB
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactSVG={},e.React)}(this,(function(e,t){"use strict";function r(e){var t=Object.create(null);return e&&Object.keys(e).forEach((function(r){if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:function(){return e[r]}})}})),t.default=e,Object.freeze(t)}var n=r(t);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i.apply(null,arguments)}function o(e,t){return o=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},o(e,t)}function a(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}"function"==typeof SuppressedError&&SuppressedError;var s,l={};var c=function(){if(s)return l;s=1;var e=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,t=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,n=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function a(e){var n=String(e);if(r.test(n))return n;if(n.length>0&&!t.test(n))throw new TypeError("invalid parameter value");return'"'+n.replace(i,"\\$1")+'"'}function c(e){this.parameters=Object.create(null),this.type=e}return l.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,n=e.type;if(!n||!o.test(n))throw new TypeError("invalid type");var i=n;if(t&&"object"==typeof t)for(var s,l=Object.keys(t).sort(),c=0;c<l.length;c++){if(!r.test(s=l[c]))throw new TypeError("invalid parameter name");i+="; "+s+"="+a(t[s])}return i},l.parse=function(t){if(!t)throw new TypeError("argument string is required");var r="object"==typeof t?function(e){var t;"function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]);if("string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(t):t;if("string"!=typeof r)throw new TypeError("argument string is required to be a string");var i=r.indexOf(";"),a=-1!==i?r.slice(0,i).trim():r.trim();if(!o.test(a))throw new TypeError("invalid media type");var s=new c(a.toLowerCase());if(-1!==i){var l,u,f;for(e.lastIndex=i;u=e.exec(r);){if(u.index!==i)throw new TypeError("invalid parameter format");i+=u[0].length,l=u[1].toLowerCase(),34===(f=u[2]).charCodeAt(0)&&-1!==(f=f.slice(1,-1)).indexOf("\\")&&(f=f.replace(n,"$1")),s.parameters[l]=f}if(i!==r.length)throw new TypeError("invalid parameter format")}return s},l}(),u=new Map,f=function(e){return e.cloneNode(!0)},p=function(){return"file:"===window.location.protocol},d=function(e,t,r){var n=new XMLHttpRequest;n.onreadystatechange=function(){try{if(!/\.svg/i.test(e)&&2===n.readyState){var t=n.getResponseHeader("Content-Type");if(!t)throw new Error("Content type not found");var i=c.parse(t).type;if("image/svg+xml"!==i&&"text/plain"!==i)throw new Error("Invalid content type: ".concat(i))}if(4===n.readyState){if(404===n.status||null===n.responseXML)throw new Error(p()?"Note: SVG injection ajax calls do not work locally without adjusting security settings in your browser. Or consider using a local webserver.":"Unable to load SVG file: "+e);if(!(200===n.status||p()&&0===n.status))throw new Error("There was a problem injecting the SVG: "+n.status+" "+n.statusText);r(null,n)}}catch(e){if(n.abort(),!(e instanceof Error))throw e;r(e,n)}},n.open("GET",e),n.withCredentials=t,n.overrideMimeType&&n.overrideMimeType("text/xml"),n.send()},h={},v=function(e,t){h[e]=h[e]||[],h[e].push(t)},m=function(e,t,r){if(u.has(e)){var n=u.get(e);if(void 0===n)return void v(e,r);if(n instanceof SVGSVGElement)return void r(null,f(n))}u.set(e,void 0),v(e,r),d(e,t,(function(t,r){var n;t?u.set(e,t):(null===(n=r.responseXML)||void 0===n?void 0:n.documentElement)instanceof SVGSVGElement&&u.set(e,r.responseXML.documentElement),function(e){for(var t=function(t,r){setTimeout((function(){if(Array.isArray(h[e])){var r=u.get(e),n=h[e][t];r instanceof SVGSVGElement&&n(null,f(r)),r instanceof Error&&n(r),t===h[e].length-1&&delete h[e]}}),0)},r=0,n=h[e].length;r<n;r++)t(r)}(e)}))},g=function(e,t,r){d(e,t,(function(e,t){var n;e?r(e):(null===(n=t.responseXML)||void 0===n?void 0:n.documentElement)instanceof SVGSVGElement&&r(null,t.responseXML.documentElement)}))},y=0,w=[],b={},E="http://www.w3.org/1999/xlink",A=function(e,t,r,n,i,o,s){var l=e.getAttribute("data-src")||e.getAttribute("src");if(l){if(-1!==w.indexOf(e))return w.splice(w.indexOf(e),1),void(e=null);w.push(e),e.setAttribute("src",""),(n?m:g)(l,i,(function(n,i){if(!i)return w.splice(w.indexOf(e),1),e=null,void s(n);var c=e.getAttribute("id");c&&i.setAttribute("id",c);var u=e.getAttribute("title");u&&i.setAttribute("title",u);var f=e.getAttribute("width");f&&i.setAttribute("width",f);var p=e.getAttribute("height");p&&i.setAttribute("height",p);var d=Array.from(new Set(a(a(a([],(i.getAttribute("class")||"").split(" "),!0),["injected-svg"],!1),(e.getAttribute("class")||"").split(" "),!0))).join(" ").trim();i.setAttribute("class",d);var h=e.getAttribute("style");h&&i.setAttribute("style",h),i.setAttribute("data-src",l);var v=[].filter.call(e.attributes,(function(e){return/^data-\w[\w-]*$/.test(e.name)}));if(Array.prototype.forEach.call(v,(function(e){e.name&&e.value&&i.setAttribute(e.name,e.value)})),r){var m,g,A,S,x={clipPath:["clip-path"],"color-profile":["color-profile"],cursor:["cursor"],filter:["filter"],linearGradient:["fill","stroke"],marker:["marker","marker-start","marker-mid","marker-end"],mask:["mask"],path:[],pattern:["fill","stroke"],radialGradient:["fill","stroke"]};Object.keys(x).forEach((function(e){g=x[e];for(var t=function(e,t){var r;S=(A=m[e].id)+"-"+ ++y,Array.prototype.forEach.call(g,(function(e){for(var t=0,n=(r=i.querySelectorAll("["+e+'*="'+A+'"]')).length;t<n;t++){var o=r[t].getAttribute(e);o&&!o.match(new RegExp('url\\("?#'+A+'"?\\)'))||r[t].setAttribute(e,"url(#"+S+")")}}));for(var n=i.querySelectorAll("[*|href]"),o=[],a=0,s=n.length;a<s;a++){var l=n[a].getAttributeNS(E,"href");l&&l.toString()==="#"+m[e].id&&o.push(n[a])}for(var c=0,u=o.length;c<u;c++)o[c].setAttributeNS(E,"href","#"+S);m[e].id=S},r=0,n=(m=i.querySelectorAll(e+"[id]")).length;r<n;r++)t(r)}))}i.removeAttribute("xmlns:a");for(var j,R,C=i.querySelectorAll("script"),O=[],k=0,G=C.length;k<G;k++)(R=C[k].getAttribute("type"))&&"application/ecmascript"!==R&&"application/javascript"!==R&&"text/javascript"!==R||((j=C[k].innerText||C[k].textContent)&&O.push(j),i.removeChild(C[k]));if(O.length>0&&("always"===t||"once"===t&&!b[l])){for(var q=0,T=O.length;q<T;q++)new Function(O[q])(window);b[l]=!0}var V=i.querySelectorAll("style");if(Array.prototype.forEach.call(V,(function(e){e.textContent+=""})),i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttribute("xmlns:xlink",E),o(i),!e.parentNode)return w.splice(w.indexOf(e),1),e=null,void s(new Error("Parent node is null"));e.parentNode.replaceChild(i,e),w.splice(w.indexOf(e),1),e=null,s(null,i)}))}else s(new Error("Invalid data-src or src attribute"))},S=["afterInjection","beforeInjection","desc","evalScripts","fallback","httpRequestWithCredentials","loading","renumerateIRIElements","src","title","useRequestCache","wrapper"],x="http://www.w3.org/2000/svg",j="http://www.w3.org/1999/xlink",R=function(e){function t(){for(var t,r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];return(t=e.call.apply(e,[this].concat(n))||this).initialState={hasError:!1,isLoading:!0},t.state=t.initialState,t._isMounted=!1,t.reactWrapper=void 0,t.nonReactWrapper=void 0,t.refCallback=function(e){t.reactWrapper=e},t}var r,a;a=e,(r=t).prototype=Object.create(a.prototype),r.prototype.constructor=r,o(r,a);var s=t.prototype;return s.renderSVG=function(){var e,t=this;if(this.reactWrapper instanceof(e=this.reactWrapper,((null==e?void 0:e.ownerDocument)||document).defaultView||window).Node){var r,n,i=this.props,o=i.desc,a=i.evalScripts,s=i.httpRequestWithCredentials,l=i.renumerateIRIElements,c=i.src,u=i.title,f=i.useRequestCache,p=this.props.onError,d=this.props.beforeInjection,h=this.props.afterInjection,v=this.props.wrapper;"svg"===v?((r=document.createElementNS(x,v)).setAttribute("xmlns",x),r.setAttribute("xmlns:xlink",j),n=document.createElementNS(x,v)):(r=document.createElement(v),n=document.createElement(v)),r.appendChild(n),n.dataset.src=c,this.nonReactWrapper=this.reactWrapper.appendChild(r);var m=function(e){t.removeSVG(),t._isMounted?t.setState((function(){return{hasError:!0,isLoading:!1}}),(function(){p(e)})):p(e)};!function(e,t){var r=void 0===t?{}:t,n=r.afterAll,i=void 0===n?function(){}:n,o=r.afterEach,a=void 0===o?function(){}:o,s=r.beforeEach,l=void 0===s?function(){}:s,c=r.cacheRequests,u=void 0===c||c,f=r.evalScripts,p=void 0===f?"never":f,d=r.httpRequestWithCredentials,h=void 0!==d&&d,v=r.renumerateIRIElements,m=void 0===v||v;if(e&&"length"in e)for(var g=0,y=0,w=e.length;y<w;y++)A(e[y],p,m,u,h,l,(function(t,r){a(t,r),e&&"length"in e&&e.length===++g&&i(g)}));else e?A(e,p,m,u,h,l,(function(t,r){a(t,r),i(1),e=null})):i(0)}(n,{afterEach:function(e,r){e?m(e):t._isMounted&&t.setState((function(){return{isLoading:!1}}),(function(){try{h(r)}catch(e){m(e)}}))},beforeEach:function(e){if(e.setAttribute("role","img"),o){var t=e.querySelector(":scope > desc");t&&e.removeChild(t);var r=document.createElement("desc");r.innerHTML=o,e.prepend(r)}if(u){var n=e.querySelector(":scope > title");n&&e.removeChild(n);var i=document.createElement("title");i.innerHTML=u,e.prepend(i)}try{d(e)}catch(e){m(e)}},cacheRequests:f,evalScripts:a,httpRequestWithCredentials:s,renumerateIRIElements:l})}},s.removeSVG=function(){var e;null!=(e=this.nonReactWrapper)&&e.parentNode&&(this.nonReactWrapper.parentNode.removeChild(this.nonReactWrapper),this.nonReactWrapper=null)},s.componentDidMount=function(){this._isMounted=!0,this.renderSVG()},s.componentDidUpdate=function(e){var t=this;(function(e,t){for(var r in e)if(!(r in t))return!0;for(var n in t)if(e[n]!==t[n])return!0;return!1})(i({},e),this.props)&&this.setState((function(){return t.initialState}),(function(){t.removeSVG(),t.renderSVG()}))},s.componentWillUnmount=function(){this._isMounted=!1,this.removeSVG()},s.render=function(){var e=this.props,t=e.fallback,r=e.loading,o=e.wrapper,a=function(e,t){if(null==e)return{};var r={};for(var n in e)if({}.hasOwnProperty.call(e,n)){if(t.includes(n))continue;r[n]=e[n]}return r}(e,S);return n.createElement(o,i({},a,{ref:this.refCallback},"svg"===o?{xmlns:x,xmlnsXlink:j}:{}),this.state.isLoading&&r&&n.createElement(r,null),this.state.hasError&&t&&n.createElement(t,null))},t}(n.Component);R.defaultProps={afterInjection:function(){},beforeInjection:function(){},desc:"",evalScripts:"never",fallback:null,httpRequestWithCredentials:!1,loading:null,onError:function(){},renumerateIRIElements:!0,title:"",useRequestCache:!0,wrapper:"div"},e.ReactSVG=R})); //# sourceMappingURL=react-svg.umd.production.js.map