UNPKG

react-svg

Version:

A React component that injects SVG into the DOM.

3 lines (2 loc) 14 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 l,s={};var u=function(){if(l)return s;l=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 u(e){this.parameters=Object.create(null),this.type=e}return s.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 l,s=Object.keys(t).sort(),u=0;u<s.length;u++){if(!r.test(l=s[u]))throw new TypeError("invalid parameter name");i+="; "+l+"="+a(t[l])}return i},s.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 l=new u(a.toLowerCase());if(-1!==i){var s,c,f;for(e.lastIndex=i;c=e.exec(r);){if(c.index!==i)throw new TypeError("invalid parameter format");i+=c[0].length,s=c[1].toLowerCase(),34===(f=c[2]).charCodeAt(0)&&-1!==(f=f.slice(1,-1)).indexOf("\\")&&(f=f.replace(n,"$1")),l.parameters[s]=f}if(i!==r.length)throw new TypeError("invalid parameter format")}return l},s}(),c=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=u.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("image/svg+xml"),n.send()},v={},h=function(e,t){var r;null!==(r=v[e])&&void 0!==r||(v[e]=[]),v[e].push(t)},m=function(e,t,r){if(c.has(e)){var n=c.get(e);if(void 0===n)return void h(e,r);if(n instanceof SVGSVGElement)return void r(null,f(n))}c.set(e,void 0),h(e,r),d(e,t,function(t,r){var n;t?c.set(e,t):(null===(n=r.responseXML)||void 0===n?void 0:n.documentElement)instanceof SVGSVGElement&&c.set(e,r.responseXML.documentElement),function(e){var t=v[e];if(t)for(var r=function(r,n){setTimeout(function(){if(Array.isArray(v[e])){var n=c.get(e),i=t[r];if(!i)return;n instanceof SVGSVGElement&&i(null,f(n)),n instanceof Error&&i(n),r===t.length-1&&delete v[e]}},0)},n=0,i=t.length;n<i;n++)r(n)}(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="data:image/svg+xml",w=0,b=function(){return++w},E=[],S={},A="http://www.w3.org/1999/xlink",x=function(e,t,r,n,i,o,l){var s,u=null!==(s=e.getAttribute("data-src"))&&void 0!==s?s:e.getAttribute("src");if(u){if(-1!==E.indexOf(e))return E.splice(E.indexOf(e),1),void(e=null);E.push(e),e.setAttribute("src","");var c=u.indexOf("#"),f=-1!==c?u.slice(0,c):u,p=-1!==c?u.slice(c+1):null,d=function(e){if(!e.startsWith(y))return null;var t,r=e.slice(18);if(r.startsWith(";base64,"))try{t=atob(r.slice(8))}catch(e){return new Error("Invalid base64 in data URL")}else if(r.startsWith(","))try{t=decodeURIComponent(r.slice(1))}catch(e){return new Error("Invalid encoding in data URL")}else{if(!r.startsWith(";charset=utf-8,"))return new Error("Unsupported data URL format");try{t=decodeURIComponent(r.slice(15))}catch(e){return new Error("Invalid encoding in data URL")}}var n=(new DOMParser).parseFromString(t,"image/svg+xml"),i=n.querySelector("parsererror");return i?new Error("Data URL SVG parse error: "+i.textContent.trim()):n.documentElement instanceof SVGSVGElement?n.documentElement:new Error("Data URL did not contain a valid SVG element")}(f);if(d instanceof Error)return E.splice(E.indexOf(e),1),e=null,void l(d);var v=function(n,i){var s,c;if(!i)return E.splice(E.indexOf(e),1),e=null,void l(n);var d=i;if(p){var v=function(e,t){var r=e.querySelector("#"+CSS.escape(t));if("symbol"!==(null==r?void 0:r.tagName.toLowerCase()))return null;for(var n=document.createElementNS("http://www.w3.org/2000/svg","svg"),i=r.attributes,o=0,a=i.length;o<a;o++){var l=i[o];"id"!==l.name&&n.setAttribute(l.name,l.value)}var s=r.childNodes;for(o=0,a=s.length;o<a;o++)n.appendChild(s[o].cloneNode(!0));return n}(i,p);if(!v)return E.splice(E.indexOf(e),1),e=null,void l(new Error('Symbol "'.concat(p,'" not found in ').concat(f)));d=v}var h=e.getAttribute("id");h&&d.setAttribute("id",h);var m=e.getAttribute("title");m&&d.setAttribute("title",m);var g=e.getAttribute("width");g&&d.setAttribute("width",g);var y=e.getAttribute("height");y&&d.setAttribute("height",y);var w=Array.from(new Set(a(a(a([],(null!==(s=d.getAttribute("class"))&&void 0!==s?s:"").split(" "),!0),["injected-svg"],!1),(null!==(c=e.getAttribute("class"))&&void 0!==c?c:"").split(" "),!0))).join(" ").trim();d.setAttribute("class",w);var x=e.getAttribute("style");x&&d.setAttribute("style",x),d.setAttribute("data-src",u);var j=[].filter.call(e.attributes,function(e){return/^data-\w[\w-]*$/.test(e.name)});if(Array.prototype.forEach.call(j,function(e){e.name&&e.value&&d.setAttribute(e.name,e.value)}),r){var C,R,O,q={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"]},G=function(e,t){return e.replace(/url\((['"]?)\s*#([^\s'"\)]+)\s*\1\)/g,function(e,r,n){var i=t[n];return i?"url(#".concat(i,")"):e})},I=function(e,t){if(!e.startsWith("#"))return e;var r=t[e.slice(1)];return r?"#"+r:e},k=[],V={};Object.keys(q).forEach(function(e){for(var t=0,r=(C=d.querySelectorAll(e+"[id]")).length;t<r;t++){var n=C[t];O=(R=n.id)+"-"+b(),V[R]=O,k.push({element:n,currentId:R,newId:O})}}),Object.keys(q).forEach(function(e){var t;Array.prototype.forEach.call(q[e],function(e){for(var r=0,n=(t=d.querySelectorAll("["+e+"]")).length;r<n;r++){var i=t[r],o=i.getAttribute(e);if(o){var a=G(o,V);a!==o&&i.setAttribute(e,a)}}})});for(var W=d.querySelectorAll("*"),T=0,L=W.length;T<L;T++){var M=W[T],N=M.getAttribute("href");if(N){var _=I(N,V);_!==N&&M.setAttribute("href",_)}var U=M.getAttributeNS(A,"href");if(U){var $=I(U,V);$!==U&&M.setAttributeNS(A,"href",$)}}for(var P=d.querySelectorAll("[style]"),D=0,X=P.length;D<X;D++){var z=P[D],Z=z.getAttribute("style");if(Z){var H=G(Z,V);H!==Z&&z.setAttribute("style",H)}}for(var F=d.querySelectorAll("style"),B=0,J=F.length;B<J;B++){var K=F[B],Q=K.textContent;if(Q){var Y=G(Q,V);Y!==Q&&(K.textContent=Y)}}for(var ee=0,te=k.length;ee<te;ee++)k[ee].element.id=k[ee].newId}d.removeAttribute("xmlns:a");for(var re,ne,ie=d.querySelectorAll("script"),oe=[],ae=0,le=ie.length;ae<le;ae++){var se=ie[ae];(ne=se.getAttribute("type"))&&"application/ecmascript"!==ne&&"application/javascript"!==ne&&"text/javascript"!==ne||((re=se.innerText||se.textContent)&&oe.push(re),d.removeChild(se))}if(oe.length>0&&("always"===t||"once"===t&&!S[u])){for(var ue=0,ce=oe.length;ue<ce;ue++)new Function(oe[ue])(window);S[u]=!0}var fe=d.querySelectorAll("style");if(Array.prototype.forEach.call(fe,function(e){e.textContent+=""}),d.setAttribute("xmlns","http://www.w3.org/2000/svg"),d.setAttribute("xmlns:xlink",A),o(d),!e.parentNode)return E.splice(E.indexOf(e),1),e=null,void l(new Error("Parent node is null"));e.parentNode.replaceChild(d,e),E.splice(E.indexOf(e),1),e=null,l(null,d)};if(d)setTimeout(function(){v(null,d)},0);else(n?m:g)(f,i,v)}else l(new Error("Invalid data-src or src attribute"))},j=["afterInjection","beforeInjection","desc","evalScripts","fallback","httpRequestWithCredentials","loading","renumerateIRIElements","src","title","useRequestCache","wrapper"],C="http://www.w3.org/2000/svg",R="http://www.w3.org/1999/xlink",O="react-svg-"+Math.random().toString(36).slice(2,6),q=0,G=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 l=t.prototype;return l.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,l=i.httpRequestWithCredentials,s=i.renumerateIRIElements,u=i.src,c=i.title,f=i.useRequestCache,p=this.props.onError,d=this.props.beforeInjection,v=this.props.afterInjection,h=this.props.wrapper;"svg"===h?((r=document.createElementNS(C,h)).setAttribute("xmlns",C),r.setAttribute("xmlns:xlink",R),n=document.createElementNS(C,h)):(r=document.createElement(h),n=document.createElement(h)),r.appendChild(n),n.dataset.src=u,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,l=r.beforeEach,s=void 0===l?function(){}:l,u=r.cacheRequests,c=void 0===u||u,f=r.evalScripts,p=void 0===f?"never":f,d=r.httpRequestWithCredentials,v=void 0!==d&&d,h=r.renumerateIRIElements,m=void 0===h||h;if(e&&"length"in e)for(var g=0,y=0,w=e.length;y<w;y++){var b=e[y];b&&x(b,p,m,c,v,s,function(t,r){a(t,r),e&&"length"in e&&e.length===++g&&i(g)})}else e?x(e,p,m,c,v,s,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{v(r)}catch(e){m(e)}})},beforeEach:function(e){e.setAttribute("role","img");var t=[],r=[];if(c){var n=e.querySelector(":scope > title");n&&e.removeChild(n);var i=O+"-title-"+ ++q,a=document.createElementNS(C,"title");a.id=i,a.textContent=c,e.prepend(a),t.push(i)}if(o){var l=e.querySelector(":scope > desc");l&&e.removeChild(l);var s=O+"-desc-"+ ++q,u=document.createElementNS(C,"desc");u.id=s,u.textContent=o;var f=e.querySelector(":scope > title");f?f.after(u):e.prepend(u),r.push(s)}t.length>0&&e.setAttribute("aria-labelledby",t.join(" ")),r.length>0&&e.setAttribute("aria-describedby",r.join(" "));try{d(e)}catch(e){m(e)}},cacheRequests:f,evalScripts:a,httpRequestWithCredentials:l,renumerateIRIElements:s})}},l.removeSVG=function(){var e;null!=(e=this.nonReactWrapper)&&e.parentNode&&(this.nonReactWrapper.parentNode.removeChild(this.nonReactWrapper),this.nonReactWrapper=null)},l.componentDidMount=function(){this._isMounted=!0,this.renderSVG()},l.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()})},l.componentWillUnmount=function(){this._isMounted=!1,this.removeSVG()},l.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(-1!==t.indexOf(n))continue;r[n]=e[n]}return r}(e,j);return n.createElement(o,i({},a,{ref:this.refCallback},"svg"===o?{xmlns:C,xmlnsXlink:R}:{}),this.state.isLoading&&r&&n.createElement(r,null),this.state.hasError&&t&&n.createElement(t,null))},t}(n.Component);G.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=G}); //# sourceMappingURL=react-svg.umd.production.js.map