UNPKG

vue-inline-svg

Version:

Replace SVG images with inline SVG element

2 lines (1 loc) 2.76 kB
"use strict";const f=require("vue"),h={};function C(n){return n.getIsPending!==void 0}function _(n){if(C(n))return n;let u=!0,r=n.then(t=>(u=!1,t),t=>{throw u=!1,t});return r.getIsPending=function(){return u},r}function E(n){let u={};const r=n.attributes;if(!r)return u;for(let t=r.length-1;t>=0;t--)u[r[t].name]=r[t].value;return u}function L(n){return Object.keys(n).reduce((u,r)=>(n[r]!==!1&&n[r]!==null&&n[r]!==void 0&&(u[r]=n[r]),u),{})}function M(n,u){const{class:r,style:t,...g}=E(n),{class:S,style:i,...p}=L(u);return{class:[r,S],style:[t,i],...g,...p}}const $=f.defineComponent({inheritAttrs:!1,__name:"InlineSvg",props:{src:{},title:{default:void 0},transformSource:{type:Function,default:n=>n},keepDuringLoading:{type:Boolean,default:!0},uniqueIds:{type:[Boolean,String],default:!1},uniqueIdsBase:{default:""}},emits:["loaded","unloaded","error"],setup(n,{expose:u,emit:r}){const t=n,g=r,S=f.useAttrs(),i=f.ref(),p=f.ref(),x=f.ref(),b=Math.random().toString(36).substring(2);u({svgElSource:i,request:x}),f.watch(()=>t.src,e=>{q(e)}),q(t.src);function y(e){if(e=e.cloneNode(!0),t.uniqueIds){const s=typeof t.uniqueIds=="string"?t.uniqueIds:b;e=I(e,s,t.uniqueIdsBase)}return e=t.transformSource(e),t.title&&P(e,t.title),e.innerHTML}function q(e){h[e]||(h[e]=A(e)),i.value&&h[e].getIsPending()&&!t.keepDuringLoading&&(i.value=null,g("unloaded")),h[e].then(s=>{i.value=s,f.nextTick(()=>{g("loaded",p.value)})}).catch(s=>{i.value&&(i.value=void 0,g("unloaded")),delete h[e],g("error",s)})}function A(e){return _(new Promise((s,l)=>{const o=new XMLHttpRequest;o.open("GET",e,!0),x.value=o,o.onload=()=>{if(o.status>=200&&o.status<400)try{let a=new DOMParser().parseFromString(o.responseText,"text/xml").getElementsByTagName("svg")[0];a?s(a):l(new Error('Loaded file is not valid SVG"'))}catch(m){l(m)}else l(new Error("Error loading SVG"))},o.onerror=l,o.send()}))}const B=()=>i.value?f.h("svg",{...M(i.value,S),innerHTML:y(i.value),ref:p}):null;function P(e,s){const l=e.getElementsByTagName("title");if(l.length)l[0].textContent=s;else{const o=document.createElementNS("http://www.w3.org/2000/svg","title");o.textContent=s,e.insertBefore(o,e.firstChild)}}function I(e,s,l=""){const o=["id","href","xlink:href","xlink:role","xlink:arcrole"],m=["href","xlink:href"],w=(a,v)=>m.includes(a)&&(v?!v.includes("#"):!1);return[...e.children].forEach(a=>{var v;if((v=a.attributes)!=null&&v.length){const T=Object.values(a.attributes).map(d=>{const c=/url\((.*?)\)/.exec(d.value);return c!=null&&c[1]&&(d.value=d.value.replace(c[0],`url(${l}${c[1]}_${s})`)),d});o.forEach(d=>{const c=T.find(k=>k.name===d);c&&!w(d,c.value)&&(c.value=`${c.value}_${s}`)})}return a.children.length?I(a,s,l):a}),e}return(e,s)=>(f.openBlock(),f.createBlock(B))}});module.exports=$;