UNPKG

@mdast2docx/image

Version:

MDAST to DOCX plugin for resolving and embedding images. Supports base64, URLs, and custom resolvers for seamless DOCX image integration.

2 lines (1 loc) 1.91 kB
var y=n=>new Promise((t,c)=>{let i=new Blob([n],{type:"image/svg+xml"}),e=new FileReader;e.onloadend=()=>t(e.result),e.onerror=c,e.readAsDataURL(i)}),b=(n,t)=>new Promise((c,i)=>{let e=document.createElement("div");e.innerHTML=n,e.style="width:100%;height:100%;position:absolute;",t.appendChild(e);let a=e.querySelector("svg");if(!a||a.nodeType!==1)return i(new Error("No or invalid <svg> found"));requestAnimationFrame(()=>{try{let r=a.getBBox(),l=parseFloat(getComputedStyle(a).width)||0,u=parseFloat(getComputedStyle(a).height)||0,o=4,m=r.x-o,g=r.y-o,s=r.width+o*2,d=r.height+o*2,p=l>0?Math.min(s,l):s,w=u>0?Math.min(d,u):d,v=a.cloneNode(!0);v.setAttribute("viewBox",`${m} ${g} ${s} ${d}`),v.setAttribute("width",`${p}`),v.setAttribute("height",`${w}`),v.removeAttribute("style");let f=new XMLSerializer().serializeToString(v);e.remove(),c({svg:f,scale:Math.min(s/l,d/u,1)})}catch(r){e.remove(),i(r)}})}),h,x=n=>(h||(h=document.createElement("div"),h.style=`height:${n.maxH}in;width:${n.maxW}in;position:absolute;left:-2500vw;`,document.body.appendChild(h),n.dpi=parseFloat(getComputedStyle(h).width)/n.maxW),h),S=async(n,t)=>{var i;let c=n.value;try{let e=new Image,a=x(t);a.appendChild(e);let r=/(?:^|\n)\s*gantt\s*/.test((i=n.data)==null?void 0:i.mermaid),l=r?{svg:c,scale:1}:await b(c,a),u=await y(l.svg);e.src=u,await new Promise(w=>e.onload=w),r&&(t.scale*=2);let o=e.width*t.scale,m=e.height*t.scale,g=document.createElement("canvas"),s=g.getContext("2d");if(!s)throw new Error("Canvas context not available");g.width=o,g.height=m,s.drawImage(e,0,0,o,m);let d=g.toDataURL(`image/${t.fallbackImageType}`);e.remove();let p=Math.min(t.maxW*t.dpi/o,t.maxH*t.dpi/m,1)*l.scale;return{type:t.fallbackImageType,data:d,transformation:{width:o*p,height:m*p}}}catch(e){return console.error("Error resolving SVG image: ",e),{type:"png",data:Buffer.from([]),transformation:{width:100,height:100}}}};export{S as a};