@iconfu/svg-inject
Version:
A tiny, intuitive, robust, caching solution for injecting SVG files inline into the DOM.
2 lines • 8.45 kB
JavaScript
;var V=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var B=Object.getOwnPropertyNames;var X=Object.prototype.hasOwnProperty;var Y=(e,n)=>{for(var r in n)V(e,r,{get:n[r],enumerable:!0})},$=(e,n,r,d)=>{if(n&&typeof n=="object"||typeof n=="function")for(let u of B(n))!X.call(e,u)&&u!==r&&V(e,u,{get:()=>n[u],enumerable:!(d=H(n,u))||d.enumerable});return e};var J=e=>$(V({},"__esModule",{value:!0}),e);var dt={};Y(dt,{SVGInject:()=>E,createSVGInject:()=>T,default:()=>E});module.exports=J(dt);var W={viewbox:"viewBox",preserveaspectratio:"preserveAspectRatio",basefrequency:"baseFrequency",baseprofile:"baseProfile",calcmode:"calcMode",clippathunits:"clipPathUnits",diffuseconstant:"diffuseConstant",edgemode:"edgeMode",filterunits:"filterUnits",glyphref:"glyphRef",gradienttransform:"gradientTransform",gradientunits:"gradientUnits",kernelmatrix:"kernelMatrix",kernelunitlength:"kernelUnitLength",keypoints:"keyPoints",keysplines:"keySplines",keytimes:"keyTimes",lengthadjust:"lengthAdjust",limitingconeangle:"limitingConeAngle",markerheight:"markerHeight",markerunits:"markerUnits",markerwidth:"markerWidth",maskcontentunits:"maskContentUnits",maskunits:"maskUnits",numoctaves:"numOctaves",pathlength:"pathLength",patterncontentunits:"patternContentUnits",patterntransform:"patternTransform",patternunits:"patternUnits",pointsatx:"pointsAtX",pointsaty:"pointsAtY",pointsatz:"pointsAtZ",primitiveunits:"primitiveUnits",refx:"refX",refy:"refY",repeatcount:"repeatCount",repeatdur:"repeatDur",requiredextensions:"requiredExtensions",requiredfeatures:"requiredFeatures",specularconstant:"specularConstant",specularexponent:"specularExponent",spreadmethod:"spreadMethod",startoffset:"startOffset",stddeviation:"stdDeviation",stitchtiles:"stitchTiles",surfacescale:"surfaceScale",systemlanguage:"systemLanguage",tablevalues:"tableValues",targetx:"targetX",targety:"targetY",textlength:"textLength",xchannelselector:"xChannelSelector",ychannelselector:"yChannelSelector",zoomandpan:"zoomAndPan"},Z=new Set(["src","alt","onload","onerror"]);function K(e,n){let r=new Map;for(let d of[e,n])if(d)for(let u of d.split(";")){let o=u.indexOf(":");if(o===-1)continue;let m=u.substring(0,o).trim(),g=u.substring(o+1).trim();m&&r.set(m,g)}return r.size===0?"":Array.from(r.entries()).map(([d,u])=>`${d}: ${u}`).join("; ")}function L(e,n){let r=e.getAttribute("alt");r===""?(n.setAttribute("role","none"),n.setAttribute("aria-hidden","true")):(n.setAttribute("role","img"),r!==null&&n.setAttribute("aria-label",r));let d=e.attributes;for(let u=0;u<d.length;u++){let o=d[u],m=o.name;if(Z.has(m))continue;let g=o.value;if(m==="title"){let i=n.firstElementChild,a;i&&i.localName.toLowerCase()==="title"?a=i:(a=(n.ownerDocument||document).createElementNS("http://www.w3.org/2000/svg","title"),n.insertBefore(a,i)),a.textContent=g}else if(m==="style"){let i=n.getAttribute("style")||"",a=K(i,g);a&&n.setAttribute("style",a)}else m=W[m]||m,n.setAttribute(m,g)}}var Q="--inject-",N={clipPath:["clip-path"],"color-profile":null,cursor:null,filter:null,linearGradient:["fill","stroke"],marker:["marker","marker-end","marker-mid","marker-start"],mask:null,pattern:["fill","stroke"],radialGradient:["fill","stroke"]},tt=["aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-flowto","aria-activedescendant","aria-errormessage","aria-details"],O=/url\(["']?#([a-zA-Z][\w:.-]*)["']?\)/g,et=1;function P(e){let n=Q+et++,r=e.querySelectorAll("[id]");if(r.length===0)return!1;let d=new Set,u=new Set;for(let i=0;i<r.length;i++){d.add(r[i].id);let a=r[i].localName;a in N&&u.add(a)}let o=[];for(let i of u){let a=N[i]||[i];for(let f of a)o.includes(f)||o.push(f)}o.length>0&&o.push("style");let m=(i,a)=>"url(#"+a+n+")",g=e.getElementsByTagName("*");for(let i=-1;i<g.length;i++){let a=i===-1?e:g[i];if(a.localName==="style"){let f=a.textContent;if(f){let t=f.replace(O,m);t!==f&&(a.textContent=t)}}else if(a.hasAttributes()){for(let f of o){let t=a.getAttribute(f);if(t){let s=t.replace(O,m);s!==t&&a.setAttribute(f,s)}}for(let f of["xlink:href","href"]){let t=a.getAttribute(f);t&&/^\s*#/.test(t)&&a.setAttribute(f,t.trim()+n)}for(let f of tt){let t=a.getAttribute(f);if(t){let p=t.split(/\s+/).map(l=>d.has(l)?l+n:l).join(" ");p!==t&&a.setAttribute(f,p)}}}}for(let i=0;i<r.length;i++)r[i].id+=n;return!0}var nt=new Set(["script","foreignobject"]),rt=/^\s*(javascript|data|vbscript)\s*:/i;function _(e){var u;let n=e.getElementsByTagName("*"),r=[];for(let o=0;o<n.length;o++)nt.has(n[o].localName.toLowerCase())&&r.push(n[o]);for(let o of r)(u=o.parentNode)==null||u.removeChild(o);let d=e.getElementsByTagName("*");for(let o=-1;o<d.length;o++){let m=o===-1?e:d[o];if(!m.hasAttributes())continue;let g=[];for(let i=0;i<m.attributes.length;i++){let a=m.attributes[i],f=a.name.toLowerCase();if(f.startsWith("on")){g.push(a.name);continue}(f==="href"||f==="xlink:href")&&rt.test(a.value)&&g.push(a.name)}for(let i of g)m.removeAttribute(i)}}var b="LOAD_FAIL",M="SVG_NOT_SUPPORTED",F="SVG_INVALID",v="__svgInject",it=1,U=2,st={useCache:!0,copyAttributes:!0,makeIdsUnique:!0,sanitize:!1,injectStyleTag:!0},k=null,G=null,w=null;function ot(e){return w=w||document.createElement("a"),w.href=e,w.href}function at(e){return k=k||new DOMParser,k.parseFromString(e,"text/xml")}function D(e){return G=G||new XMLSerializer,G.serializeToString(e)}function R(e,n){let r;try{r=at(e)}catch(d){return null}return n&&r.getElementsByTagName("parsererror").length?null:document.adoptNode(r.documentElement)}async function ct(e){let n=await fetch(e);if(!n.ok)throw new Error(`Failed to load SVG: ${n.status}`);return(await n.text()).trim()}function x(e,n){return n?{...e,...n}:e}function lt(e){let n=document.getElementsByTagName("head")[0];if(n){let r=document.createElement("style");r.appendChild(document.createTextNode(e)),n.appendChild(r)}}function ut(e){return e!=null&&typeof e=="object"&&"localName"in e&&e.localName==="svg"}function C(e){console.error("SVGInject: "+e)}function T(e,n,r=!0){let d=x({...st},n),u=new Map;d.injectStyleTag&&typeof document!="undefined"&<('img[onload^="'+e+'("]{visibility:hidden;}');function o(t,s,c){t[v]=U,c.onFail?c.onFail(t,s):C(s)}function m(t,s,c,p){if(!s){t.removeAttribute("onload"),o(t,F,p);return}s.setAttribute("data-inject-url",c);let l=t.parentNode;if(!l)return;p.copyAttributes&&L(t,s);let h=p.beforeInject&&p.beforeInject(t,s)||s;l.replaceChild(h,t),t[v]=it,t.removeAttribute("onload"),p.afterInject&&p.afterInject(t,h)}async function g(t,s){if(!t){C("no img element");return}let c=t[v];if(c||(t.onload=null,t.onerror=null),c){c instanceof Promise&&await c;return}if(typeof SVGRect=="undefined"){t.removeAttribute("onload"),o(t,M,s);return}let p=s.beforeLoad,l=p&&p(t)||t.getAttribute("src");if(l==null)return;if(l===""){o(t,b,s);return}let h=ot(l),S=s.useCache,j=s.makeIdsUnique,{promise:q,resolve:z}=ft();t[v]=q;try{let I;S?I=await a(h,s):I=await i(h,s);let A=R(I,!1);A&&(s.sanitize&&_(A),j&&P(A)),m(t,A,h,s)}catch(I){let A=I instanceof y?I.status:b;t.removeAttribute("onload"),o(t,A,s)}finally{z()}}async function i(t,s){let c;try{c=await ct(t)}catch(l){throw new y(b)}let p=R(c,!0);if(!p||!ut(p))throw new y(F);if(s.afterLoad){let l=s.afterLoad(p,c);l?typeof l=="string"?c=l:c=D(l):c=D(p)}return c}async function a(t,s){let c=u.get(t);if(c){if(c.type==="loaded")return c.svgString;if(c.type==="failed")throw new y(c.status);return new Promise((l,h)=>{c.callbacks.push(S=>{S.type==="loaded"?l(S.svgString):S.type==="failed"&&h(new y(S.status))})})}let p={type:"pending",callbacks:[]};u.set(t,p);try{let l=await i(t,s),h={type:"loaded",svgString:l};return u.set(t,h),p.callbacks.forEach(S=>S(h)),l}catch(l){let S={type:"failed",status:l instanceof y?l.status:b};throw u.set(t,S),p.callbacks.forEach(j=>j(S)),l}}function f(t,s){let c=x(d,s),l=(t instanceof HTMLImageElement?[t]:Array.from(t)).map(h=>g(h,c));return Promise.all(l).then(()=>{c.onAllFinish&&c.onAllFinish()})}return f.setOptions=function(t){d=x(d,t)},f.create=T,f.err=function(t,s){if(!t){C("no img element");return}t[v]!==U&&(t.onload=null,t.onerror=null,t.removeAttribute("onload"),typeof SVGRect=="undefined"?o(t,M,d):o(t,b,d),s&&(t.src=s))},r&&typeof window!="undefined"&&(window[e]=f),f}var y=class extends Error{constructor(r){super(r);this.status=r}};function ft(){let e;return{promise:new Promise(r=>{e=r}),resolve:e}}var E=T("SVGInject",void 0,!1);0&&(module.exports={SVGInject,createSVGInject});
//# sourceMappingURL=svg-inject.cjs.map