@iconfu/svg-inject
Version:
A tiny, intuitive, robust, caching solution for injecting SVG files inline into the DOM.
2 lines • 7.93 kB
JavaScript
var z={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"},H=new Set(["src","alt","onload","onerror"]);function B(e,n){let a=new Map;for(let d of[e,n])if(d)for(let p of d.split(";")){let s=p.indexOf(":");if(s===-1)continue;let m=p.substring(0,s).trim(),g=p.substring(s+1).trim();m&&a.set(m,g)}return a.size===0?"":Array.from(a.entries()).map(([d,p])=>`${d}: ${p}`).join("; ")}function C(e,n){let a=e.getAttribute("alt");a===""?(n.setAttribute("role","none"),n.setAttribute("aria-hidden","true")):(n.setAttribute("role","img"),a!==null&&n.setAttribute("aria-label",a));let d=e.attributes;for(let p=0;p<d.length;p++){let s=d[p],m=s.name;if(H.has(m))continue;let g=s.value;if(m==="title"){let r=n.firstElementChild,o;r&&r.localName.toLowerCase()==="title"?o=r:(o=(n.ownerDocument||document).createElementNS("http://www.w3.org/2000/svg","title"),n.insertBefore(o,r)),o.textContent=g}else if(m==="style"){let r=n.getAttribute("style")||"",o=B(r,g);o&&n.setAttribute("style",o)}else m=z[m]||m,n.setAttribute(m,g)}}var X="--inject-",E={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"]},Y=["aria-labelledby","aria-describedby","aria-controls","aria-owns","aria-flowto","aria-activedescendant","aria-errormessage","aria-details"],L=/url\(["']?#([a-zA-Z][\w:.-]*)["']?\)/g,$=1;function N(e){let n=X+$++,a=e.querySelectorAll("[id]");if(a.length===0)return!1;let d=new Set,p=new Set;for(let r=0;r<a.length;r++){d.add(a[r].id);let o=a[r].localName;o in E&&p.add(o)}let s=[];for(let r of p){let o=E[r]||[r];for(let u of o)s.includes(u)||s.push(u)}s.length>0&&s.push("style");let m=(r,o)=>"url(#"+o+n+")",g=e.getElementsByTagName("*");for(let r=-1;r<g.length;r++){let o=r===-1?e:g[r];if(o.localName==="style"){let u=o.textContent;if(u){let t=u.replace(L,m);t!==u&&(o.textContent=t)}}else if(o.hasAttributes()){for(let u of s){let t=o.getAttribute(u);if(t){let i=t.replace(L,m);i!==t&&o.setAttribute(u,i)}}for(let u of["xlink:href","href"]){let t=o.getAttribute(u);t&&/^\s*#/.test(t)&&o.setAttribute(u,t.trim()+n)}for(let u of Y){let t=o.getAttribute(u);if(t){let f=t.split(/\s+/).map(l=>d.has(l)?l+n:l).join(" ");f!==t&&o.setAttribute(u,f)}}}}for(let r=0;r<a.length;r++)a[r].id+=n;return!0}var J=new Set(["script","foreignobject"]),W=/^\s*(javascript|data|vbscript)\s*:/i;function O(e){var p;let n=e.getElementsByTagName("*"),a=[];for(let s=0;s<n.length;s++)J.has(n[s].localName.toLowerCase())&&a.push(n[s]);for(let s of a)(p=s.parentNode)==null||p.removeChild(s);let d=e.getElementsByTagName("*");for(let s=-1;s<d.length;s++){let m=s===-1?e:d[s];if(!m.hasAttributes())continue;let g=[];for(let r=0;r<m.attributes.length;r++){let o=m.attributes[r],u=o.name.toLowerCase();if(u.startsWith("on")){g.push(o.name);continue}(u==="href"||u==="xlink:href")&&W.test(o.value)&&g.push(o.name)}for(let r of g)m.removeAttribute(r)}}var b="LOAD_FAIL",P="SVG_NOT_SUPPORTED",_="SVG_INVALID",v="__svgInject",Z=1,M=2,K={useCache:!0,copyAttributes:!0,makeIdsUnique:!0,sanitize:!1,injectStyleTag:!0},j=null,V=null,w=null;function Q(e){return w=w||document.createElement("a"),w.href=e,w.href}function tt(e){return j=j||new DOMParser,j.parseFromString(e,"text/xml")}function F(e){return V=V||new XMLSerializer,V.serializeToString(e)}function U(e,n){let a;try{a=tt(e)}catch(d){return null}return n&&a.getElementsByTagName("parsererror").length?null:document.adoptNode(a.documentElement)}async function et(e){let n=await fetch(e);if(!n.ok)throw new Error(`Failed to load SVG: ${n.status}`);return(await n.text()).trim()}function k(e,n){return n?{...e,...n}:e}function nt(e){let n=document.getElementsByTagName("head")[0];if(n){let a=document.createElement("style");a.appendChild(document.createTextNode(e)),n.appendChild(a)}}function rt(e){return e!=null&&typeof e=="object"&&"localName"in e&&e.localName==="svg"}function G(e){console.error("SVGInject: "+e)}function x(e,n,a=!0){let d=k({...K},n),p=new Map;d.injectStyleTag&&typeof document!="undefined"&&nt('img[onload^="'+e+'("]{visibility:hidden;}');function s(t,i,c){t[v]=M,c.onFail?c.onFail(t,i):G(i)}function m(t,i,c,f){if(!i){t.removeAttribute("onload"),s(t,_,f);return}i.setAttribute("data-inject-url",c);let l=t.parentNode;if(!l)return;f.copyAttributes&&C(t,i);let h=f.beforeInject&&f.beforeInject(t,i)||i;l.replaceChild(h,t),t[v]=Z,t.removeAttribute("onload"),f.afterInject&&f.afterInject(t,h)}async function g(t,i){if(!t){G("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"),s(t,P,i);return}let f=i.beforeLoad,l=f&&f(t)||t.getAttribute("src");if(l==null)return;if(l===""){s(t,b,i);return}let h=Q(l),S=i.useCache,T=i.makeIdsUnique,{promise:R,resolve:q}=it();t[v]=R;try{let I;S?I=await o(h,i):I=await r(h,i);let A=U(I,!1);A&&(i.sanitize&&O(A),T&&N(A)),m(t,A,h,i)}catch(I){let A=I instanceof y?I.status:b;t.removeAttribute("onload"),s(t,A,i)}finally{q()}}async function r(t,i){let c;try{c=await et(t)}catch(l){throw new y(b)}let f=U(c,!0);if(!f||!rt(f))throw new y(_);if(i.afterLoad){let l=i.afterLoad(f,c);l?typeof l=="string"?c=l:c=F(l):c=F(f)}return c}async function o(t,i){let c=p.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 f={type:"pending",callbacks:[]};p.set(t,f);try{let l=await r(t,i),h={type:"loaded",svgString:l};return p.set(t,h),f.callbacks.forEach(S=>S(h)),l}catch(l){let S={type:"failed",status:l instanceof y?l.status:b};throw p.set(t,S),f.callbacks.forEach(T=>T(S)),l}}function u(t,i){let c=k(d,i),l=(t instanceof HTMLImageElement?[t]:Array.from(t)).map(h=>g(h,c));return Promise.all(l).then(()=>{c.onAllFinish&&c.onAllFinish()})}return u.setOptions=function(t){d=k(d,t)},u.create=x,u.err=function(t,i){if(!t){G("no img element");return}t[v]!==M&&(t.onload=null,t.onerror=null,t.removeAttribute("onload"),typeof SVGRect=="undefined"?s(t,P,d):s(t,b,d),i&&(t.src=i))},a&&typeof window!="undefined"&&(window[e]=u),u}var y=class extends Error{constructor(a){super(a);this.status=a}};function it(){let e;return{promise:new Promise(a=>{e=a}),resolve:e}}var D=x("SVGInject",void 0,!1);export{D as SVGInject,x as createSVGInject,D as default};
//# sourceMappingURL=svg-inject.esm.js.map