UNPKG

react-sketch-canvas

Version:

react-sketch-canvas - Freehand vector drawing tool for React using SVG as canvas

2 lines (1 loc) 23.8 kB
var mt=Object.defineProperty,pt=Object.defineProperties;var lt=Object.getOwnPropertyDescriptors;var fe=Object.getOwnPropertySymbols;var dt=Object.prototype.hasOwnProperty,ht=Object.prototype.propertyIsEnumerable;var Z=Math.pow,Pe=(t,e,r)=>e in t?mt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,g=(t,e)=>{for(var r in e||(e={}))dt.call(e,r)&&Pe(t,r,e[r]);if(fe)for(var r of fe(e))ht.call(e,r)&&Pe(t,r,e[r]);return t},P=(t,e)=>pt(t,lt(e));var T=(t,e,r)=>new Promise((n,o)=>{var a=c=>{try{i(r.next(c))}catch(u){o(u)}},s=c=>{try{i(r.throw(c))}catch(u){o(u)}},i=c=>c.done?n(c.value):Promise.resolve(c.value).then(a,s);i((r=r.apply(t,e)).next())});import*as I from"react";import*as Me from"react";function ue(t){var o;let e=(o=t.firstChild)==null?void 0:o.cloneNode(!0),r=t.offsetWidth,n=t.offsetHeight;return e.setAttribute("viewBox",`0 0 ${r} ${n}`),e.setAttribute("width",r.toString()),e.setAttribute("height",n.toString()),{svgCanvas:e,width:r,height:n}}function j(t){let e=new XMLSerializer().serializeToString(t),r=new TextEncoder().encode(e),n="";for(let a of r)n+=String.fromCharCode(a);return`data:image/svg+xml;base64,${btoa(n)}`}function gt(t){if(t.startsWith("data:")||t.startsWith("blob:"))return!1;try{let e=new URL(t,window.location.href);return/^https?:$/.test(e.protocol)?e.origin!==window.location.origin:!1}catch(e){return!1}}var V=t=>new Promise((e,r)=>{let n=new Image;gt(t)&&(n.crossOrigin="anonymous"),n.addEventListener("load",()=>{if(n.width>0){e(n);return}r(new Error("Image not found"))}),n.addEventListener("error",o=>r(o)),n.src=t});function ye({backgroundImage:t,exportWidth:e,exportHeight:r,preserveAspectRatio:n}){let o="http://www.w3.org/2000/svg",a=document.createElementNS(o,"svg"),s=document.createElementNS(o,"defs"),i=document.createElementNS(o,"pattern"),c=document.createElementNS(o,"image"),u=document.createElementNS(o,"rect");return a.setAttribute("xmlns",o),a.setAttribute("width",String(e)),a.setAttribute("height",String(r)),a.setAttribute("viewBox",`0 0 ${e} ${r}`),i.setAttribute("id","react-sketch-canvas-export-background"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("patternUnits","userSpaceOnUse"),c.setAttribute("x","0"),c.setAttribute("y","0"),c.setAttribute("width","100%"),c.setAttribute("height","100%"),c.setAttribute("href",t),n&&c.setAttribute("preserveAspectRatio",n),u.setAttribute("x","0"),u.setAttribute("y","0"),u.setAttribute("width","100%"),u.setAttribute("height","100%"),u.setAttribute("fill","url(#react-sketch-canvas-export-background)"),i.append(c),s.append(i),a.append(s,u),a}function vt(t){let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)r[n]=e.charCodeAt(n);return new TextDecoder("utf-8").decode(r)}function ft(t){let e=/^data:image\/svg\+xml([^,]*),(.*)$/i.exec(t);if(!e)return null;let[,r="",n=""]=e;try{return r.includes(";base64")?vt(n):decodeURIComponent(n)}catch(o){return null}}function ke(t){let e=ft(t);if(!e)return t;let n=new DOMParser().parseFromString(e,"image/svg+xml").documentElement;if(n.nodeName.toLowerCase()!=="svg"||n.hasAttribute("width")&&n.hasAttribute("height"))return t;let o=n.getAttribute("viewBox");if(!o)return t;let[,,a,s]=o.trim().split(/[\s,]+/).map(Number);if(!Number.isFinite(a)||!Number.isFinite(s))return t;n.hasAttribute("width")||n.setAttribute("width",String(a)),n.hasAttribute("height")||n.setAttribute("height",String(s));let i=new XMLSerializer().serializeToString(n);return`data:image/svg+xml;charset=utf-8,${encodeURIComponent(i)}`}function Se(t){var o,a;if(!t||t==="none")return null;let[e="xMidYMid",r="meet"]=t.split(/\s+/),n=/^x(Min|Mid|Max)Y(Min|Mid|Max)$/.exec(e);return{xAlign:(o=n==null?void 0:n[1])!=null?o:"Mid",yAlign:(a=n==null?void 0:n[2])!=null?a:"Mid",mode:r==="slice"?"slice":"meet"}}function Y(t,e,r){if(r==="Min")return 0;let n=t-e;return r==="Max"?n:n/2}function xe({context:t,backgroundLayer:e,exportWidth:r,exportHeight:n,preserveAspectRatio:o}){let a=Se(o),s=e.naturalWidth||e.width,i=e.naturalHeight||e.height;if(!a||s<=0||i<=0){t.drawImage(e,0,0,r,n);return}let c=r/s,u=n/i;if(a.mode==="slice"){let k=Math.max(c,u),x=r/k,B=n/k,y=Y(s,x,a.xAlign),w=Y(i,B,a.yAlign);t.drawImage(e,y,w,x,B,0,0,r,n);return}let v=Math.min(c,u),d=s*v,f=i*v,m=Y(r,d,a.xAlign),h=Y(n,f,a.yAlign);t.drawImage(e,m,h,d,f)}function Ce(t){return t.startsWith("data:")?"Cannot export: the background data URI could not be decoded as an image. Check that backgroundImage is a valid image data URL.":Pt(t)?"Cannot export: the cross-origin background image failed to load. Check the URL is reachable and that the server returns an Access-Control-Allow-Origin header so the image can be read into the export canvas.":"Cannot export: the background image failed to load. Check that backgroundImage points to a reachable image."}function Pt(t){try{let e=new URL(t,window.location.href);return/^https?:$/.test(e.protocol)?e.origin!==window.location.origin:!1}catch(e){return!1}}function Re(t){return T(this,null,function*(){if(t.kind==="none")return null;try{if(t.kind==="svg-wrapper"){let e=ye(t);return yield V(j(e))}return yield V(ke(t.backgroundImage))}catch(e){throw new Error(Ce(t.backgroundImage),{cause:e})}})}function be({context:t,backgroundLayer:e,plan:r,exportWidth:n,exportHeight:o}){if(r.kind==="svg-wrapper"){t.drawImage(e,0,0,n,o);return}xe({context:t,backgroundLayer:e,exportWidth:n,exportHeight:o,preserveAspectRatio:r.preserveAspectRatio})}function we({backgroundImage:t,exportWithBackgroundImage:e,exportWidth:r,exportHeight:n,preserveAspectRatio:o}){return!e||!t?{kind:"none"}:yt(t)?{kind:"svg-wrapper",backgroundImage:t,exportWidth:r,exportHeight:n,preserveAspectRatio:o}:{kind:"direct-image",backgroundImage:t,preserveAspectRatio:o}}function yt(t){return/^data:image\/svg\+xml(?:[;,]|$)/i.test(t)}var Ee=0;function z(t,e){return t.querySelector(`[id$="__${e}"]`)}function kt(t,e){Ee+=1;let r=`${e}__export-${Ee}`,n=new Map;for(let a of t.querySelectorAll("[id]")){let s=a.getAttribute("id");if(!(s!=null&&s.startsWith(`${e}__`)))continue;let i=s.replace(`${e}__`,`${r}__`);n.set(s,i),a.setAttribute("id",i)}let o=a=>{let s=a;for(let[i,c]of n)s=s.replaceAll(`url(#${i})`,`url(#${c})`),s===`#${i}`&&(s=`#${c}`);return s};for(let a of t.querySelectorAll("*"))for(let s of["fill","mask","href","xlink:href"]){let i=a.getAttribute(s);if(!i)continue;let c=o(i);c!==i&&a.setAttribute(s,c)}}function Ae(t){var e,r,n;return(e=z(t,"background"))==null||e.remove(),(r=z(t,"canvas-background-group"))==null||r.remove(),(n=z(t,"canvas-background"))==null||n.remove(),t}function K(t,{id:e,canvasColor:r,exportWithBackgroundImage:n}){var o,a;return n||((o=z(t,"background"))==null||o.remove(),(a=z(t,"canvas-background"))==null||a.setAttribute("fill",r)),kt(t,e),t}function St({id:t,svgCanvas:e,canvasColor:r,backgroundImage:n,exportWithBackgroundImage:o}){if(o&&n){let a=Ae(e);return K(a,{id:t,canvasColor:r,exportWithBackgroundImage:!0})}return K(e,{id:t,canvasColor:r,exportWithBackgroundImage:o})}function xt(t,e,r){let n=document.createElement("canvas");return n.width=Math.round(t*r),n.height=Math.round(e*r),n.style.width=`${t}px`,n.style.height=`${e}px`,n}function Ct(t){if((t==null?void 0:t.width)!==void 0||(t==null?void 0:t.height)!==void 0||typeof window=="undefined")return 1;let e=window.devicePixelRatio;return Number.isFinite(e)&&e>0?e:1}function Ie(v){return T(this,arguments,function*({id:t,svgCanvas:e,svgWidth:r,svgHeight:n,imageType:o,canvasColor:a,backgroundImage:s,exportWithBackgroundImage:i,preserveBackgroundImageAspectRatio:c,options:u}){var C,R;let d=(C=u==null?void 0:u.width)!=null?C:r,f=(R=u==null?void 0:u.height)!=null?R:n,m=we({backgroundImage:s,exportWithBackgroundImage:i,exportWidth:d,exportHeight:f,preserveAspectRatio:c}),h=St({id:t,svgCanvas:e,canvasColor:a,backgroundImage:s,exportWithBackgroundImage:i}),k=yield V(j(h)),x=Ct(u),B=xt(d,f,x),y=B.getContext("2d");if(!y)throw Error("Canvas not rendered yet");x!==1&&y.scale(x,x),(o==="jpeg"||!s||!i)&&(y.fillStyle=a,y.fillRect(0,0,d,f));let L=yield Re(m);return L&&m.kind!=="none"&&be({context:y,backgroundLayer:L,plan:m,exportWidth:d,exportHeight:f}),y.drawImage(k,0,0,d,f),B.toDataURL(`image/${o}`)})}function Be(t,{canvasRef:e,id:r,canvasColor:n,backgroundImage:o,exportWithBackgroundImage:a,preserveBackgroundImageAspectRatio:s}){Me.useImperativeHandle(t,()=>({exportImage:(i,c)=>T(null,null,function*(){let u=e.current;if(!u)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportImage().");let{svgCanvas:v,width:d,height:f}=ue(u);return Ie({id:r,svgCanvas:v,svgWidth:d,svgHeight:f,imageType:i,canvasColor:n,backgroundImage:o,exportWithBackgroundImage:a,preserveBackgroundImageAspectRatio:s,options:c})}),exportSvg:()=>T(null,null,function*(){let i=e.current;if(!i)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportSvg().");let{svgCanvas:c}=ue(i);return K(c,{id:r,canvasColor:n,exportWithBackgroundImage:a}).outerHTML})}))}import*as Te from"react";import{useCallback as W}from"react";var Rt=32,bt=(t,e)=>t==="all"||e===t,wt=(t,e)=>!(t==="mouse"&&e!==0),Et=(t,e)=>t==="pen"&&(e&Rt)!==0,At=(t,e,r)=>{let n=e.width>0&&r.offsetWidth>0?r.offsetWidth/e.width:1,o=e.height>0&&r.offsetHeight>0?r.offsetHeight/e.height:1;return{x:(t.clientX-e.left)*n,y:(t.clientY-e.top)*o}};function Le({canvasRef:t,isDrawing:e,allowOnlyPointerType:r,onPointerDown:n,onPointerMove:o,onPointerUp:a}){let s=Te.useRef(null),i=W(m=>{let h=t.current,k=h==null?void 0:h.getBoundingClientRect();return!h||!k?{x:0,y:0}:At(m,k,h)},[t]),c=W(m=>s.current===m.pointerId,[]),u=W(m=>{m.pointerType!=="touch"||!m.cancelable||m.preventDefault()},[]),v=W(m=>{c(m)&&(s.current=null,a())},[c,a]),d=W(m=>{if(bt(r,m.pointerType)&&wt(m.pointerType,m.button)){if(s.current!==null){s.current=null,a();return}u(m),m.isTrusted&&m.currentTarget.setPointerCapture(m.pointerId),s.current=m.pointerId,n(i(m),Et(m.pointerType,m.buttons))}},[r,i,n,a,u]),f=W(m=>{e&&c(m)&&(u(m),o(i(m)))},[i,c,e,o,u]);return{handlePointerDown:d,handlePointerMove:f,finishActivePointer:v}}import{jsx as ee}from"react/jsx-runtime";function _e({internalId:t,backgroundImage:e,preserveBackgroundImageAspectRatio:r}){return e?ee("pattern",{id:`${t}__background`,x:"0",y:"0",width:"100%",height:"100%",patternUnits:"userSpaceOnUse",children:ee("image",{x:"0",y:"0",width:"100%",height:"100%",xlinkHref:e,preserveAspectRatio:r})}):null}function $e({internalId:t,backgroundImage:e,canvasColor:r}){return ee("g",{id:`${t}__canvas-background-group`,children:ee("rect",{id:`${t}__canvas-background`,x:"0",y:"0",width:"100%",height:"100%",fill:e?`url(#${t}__background)`:r})})}import*as Fe from"react";var Oe=(t,e)=>{let r=e.x-t.x,n=e.y-t.y;return{length:Math.sqrt(Z(r,2)+Z(n,2)),angle:Math.atan2(n,r)}},te=t=>{let{current:e,next:r,previous:n,reverse:o}=t,a=n||e,s=r||e,i=.2,c=Oe(a,s),u=c.angle+(o?Math.PI:0),v=c.length*i;return[e.x+Math.cos(u)*v,e.y+Math.sin(u)*v]},ae=(t,e,r)=>{let n,o;switch(e){case 0:[n,o]=te({current:t});break;case 1:[n,o]=te({current:r[e-1],next:t});break;default:[n,o]=te({current:r[e-1],previous:r[e-2],next:t});break}let[a,s]=te({current:t,previous:r[e-1],next:r[e+1],reverse:!0});return`C ${n},${o} ${a},${s} ${t.x}, ${t.y}`},me=(t,e)=>Oe(t,e).length,re=(t,[e,r])=>{let n=Z(me(e,r),2);if(n===0)return me(t,e);let o=((t.x-e.x)*(r.x-e.x)+(t.y-e.y)*(r.y-e.y))/n,a=Math.max(0,Math.min(1,o)),s={x:e.x+a*(r.x-e.x),y:e.y+a*(r.y-e.y)};return me(t,s)},ne=(t,e,r)=>(e.y-t.y)*(r.x-e.x)-(e.x-t.x)*(r.y-e.y),oe=(t,[e,r])=>t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y),It=([t,e],[r,n])=>{let o=ne(t,e,r),a=ne(t,e,n),s=ne(r,n,t),i=ne(r,n,e);return(o>0&&a<0||o<0&&a>0)&&(s>0&&i<0||s<0&&i>0)?!0:o===0&&oe(r,[t,e])||a===0&&oe(n,[t,e])||s===0&&oe(t,[r,n])||i===0&&oe(e,[r,n])},Mt=(t,e)=>{if(It(t,e))return 0;let[r,n]=t,[o,a]=e;return Math.min(re(r,e),re(n,e),re(o,t),re(a,t))},De=t=>t.paths.length>1?t.paths.slice(1).map((e,r)=>[t.paths[r],e]):t.paths.map(e=>[e,e]);function He(t,e){let r=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(let s of t.paths)s.x<r&&(r=s.x),s.x>n&&(n=s.x),s.y<o&&(o=s.y),s.y>a&&(a=s.y);return{minX:r-e,maxX:n+e,minY:o-e,maxY:a+e}}function Bt(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Ue({eraser:t,stroke:e}){if(t.paths.length===0||e.paths.length===0)return!1;let r=t.strokeWidth/2+e.strokeWidth/2,n=He(t,t.strokeWidth/2),o=He(e,e.strokeWidth/2);if(!Bt(n,o))return!1;let a=De(t),s=De(e);return a.some(i=>s.some(c=>Mt(i,c)<=r))}import{jsx as We}from"react/jsx-runtime";function Tt({paths:t,id:e,strokeWidth:r,strokeColor:n,command:o=ae}){if(t.length===1){let{x:s,y:i}=t[0],c=r/2;return We("circle",{id:e,cx:s,cy:i,r:c,stroke:n,fill:n},e)}let a=t.reduce((s,i,c,u)=>c===0?`M ${i.x},${i.y}`:`${s} ${o(i,c,u)}`,"");return We("path",{id:e,d:a,fill:"none",strokeLinecap:"round",stroke:n,strokeWidth:r},e)}var q=Fe.memo(Tt);q.displayName="SvgPath";var se="#000000";import{Fragment as Lt,jsx as J,jsxs as Xe}from"react/jsx-runtime";function Ne({internalId:t,eraserPaths:e}){return Xe("g",{id:`${t}__eraser-stroke-group`,children:[J("rect",{id:`${t}__mask-background`,x:"0",y:"0",width:"100%",height:"100%",fill:"white"}),e.map((r,n)=>J(q,{id:`${t}__eraser-${n}`,paths:r.paths,strokeColor:se,strokeWidth:r.strokeWidth},`${t}__eraser-${n}`))]})}function Ge({internalId:t,eraserPaths:e}){return J(Lt,{children:e.map((r,n)=>Xe("mask",{id:`${t}__eraser-mask-${n}`,maskUnits:"userSpaceOnUse",children:[J("use",{href:`#${t}__mask-background`,xlinkHref:`#${t}__mask-background`}),Array.from({length:e.length-n},(o,a)=>a+n).map(o=>J("use",{href:`#${t}__eraser-${o.toString()}`,xlinkHref:`#${t}__eraser-${o.toString()}`},o.toString()))]},`${t}__eraser-mask-${n}`))})}var Ve=t=>t.filter(e=>!e.drawMode),Ye=t=>{let e=[[]],r=e[0];for(let n of t){if(!n.drawMode){r=[],e.push(r);continue}r.push(n)}for(;e.length>1&&e[e.length-1].length===0;)e.pop();return e};import{Fragment as $t,jsx as ze}from"react/jsx-runtime";function _t({id:t,paths:e}){return ze($t,{children:e.map((r,n)=>ze(q,{id:`${t}__${n}`,paths:r.paths,strokeWidth:r.strokeWidth,strokeColor:r.strokeColor,command:ae},`${t}__${n}`))})}var Ke=_t;import{Fragment as Dt,jsx as pe}from"react/jsx-runtime";function qe({internalId:t,pathGroups:e,eraserPaths:r}){return pe(Dt,{children:e.map((n,o)=>pe("g",P(g({id:`${t}__stroke-group-${o}`},r[o]?{mask:`url(#${t}__eraser-mask-${o})`}:{}),{children:pe(Ke,{id:`${t}__stroke-group-${o}__paths`,paths:n})}),`${t}__stroke-group-${o}`))})}import{jsx as Q,jsxs as Je}from"react/jsx-runtime";function Qe({id:t,internalId:e,paths:r,canvasColor:n,backgroundImage:o,preserveBackgroundImageAspectRatio:a,svgStyle:s,viewBox:i}){let c=Ve(r),u=Ye(r);return Je("svg",{version:"1.1",baseProfile:"full",xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink","aria-hidden":"true",style:g({width:"100%",height:"100%"},s),id:t,viewBox:i,children:[Je("defs",{children:[Q(Ne,{internalId:e,eraserPaths:c}),Q(_e,{internalId:e,backgroundImage:o,preserveBackgroundImageAspectRatio:a}),Q(Ge,{internalId:e,eraserPaths:c})]}),Q($e,{internalId:e,backgroundImage:o,canvasColor:n}),Q(qe,{internalId:e,pathGroups:u,eraserPaths:c})]})}import{jsx as Ze}from"react/jsx-runtime";var le=I.forwardRef((t,e)=>{let{paths:r,isDrawing:n,onPointerDown:o,onPointerMove:a,onPointerUp:s,id:i="react-sketch-canvas",width:c="100%",height:u="100%",className:v="react-sketch-canvas",canvasColor:d="white",backgroundImage:f="",exportWithBackgroundImage:m=!1,preserveBackgroundImageAspectRatio:h="none",allowOnlyPointerType:k="all",style:x={border:"0.0625rem solid #9c9c9c",borderRadius:"0.25rem"},svgStyle:B={},withViewBox:y=!1,readOnly:w=!1,touchAction:L}=t,C=I.useRef(null),[R,H]=I.useState(null),O=I.useId(),N=I.useMemo(()=>`${i}__${O.replaceAll(":","")}`,[i,O]);I.useLayoutEffect(()=>{if(!y||C.current===null)return;let A=C.current,_=()=>{let U=A.getBoundingClientRect(),ce=A.clientWidth||U.width,ve=A.clientHeight||U.height,ut={width:ce,height:ve};H(X=>(X==null?void 0:X.width)===ce&&X.height===ve?X:ut)};if(_(),typeof ResizeObserver=="undefined")return;let D=new ResizeObserver(_);return D.observe(A),()=>{D.disconnect()}},[y]),Be(e,{canvasRef:C,id:i,canvasColor:d,backgroundImage:f,exportWithBackgroundImage:m,preserveBackgroundImageAspectRatio:h});let{handlePointerDown:G,handlePointerMove:p,finishActivePointer:l}=Le({canvasRef:C,isDrawing:n,allowOnlyPointerType:k,onPointerDown:o,onPointerMove:a,onPointerUp:s}),E=k==="all"||k==="touch",S=L!=null?L:E?"none":"pan-x pan-y pinch-zoom",$=y&&R!==null?`0 0 ${R.width} ${R.height}`:void 0;return Ze("div",{role:"presentation",ref:C,className:v,style:g({touchAction:S,userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none",width:c,height:u},x),onPointerDown:w?void 0:G,onPointerMove:w?void 0:p,onPointerUp:w?void 0:l,onPointerCancel:w?void 0:l,children:Ze(Qe,{id:i,internalId:N,paths:r,canvasColor:d,backgroundImage:f,preserveBackgroundImageAspectRatio:h,svgStyle:B,viewBox:$})})});le.displayName="@react-sketch-canvas/Canvas";import*as ie from"react";import*as b from"react";import{useCallback as M}from"react";function de(){return{drawMode:!0,isDrawing:!1,history:[[]],historyPos:0,historySynced:!1,currentPaths:[],activeStroke:null,lastCompletedStroke:null}}function F(t){return t.historySynced?t:P(g({},t),{history:[...t.history.slice(0,t.historyPos),[...t.currentPaths]],historySynced:!0})}function je(t){if(t.historyPos<=0)return t;let e=F(t);return P(g({},e),{currentPaths:e.history[e.historyPos-1],historyPos:e.historyPos-1})}function et(t){if(t.historyPos>=t.history.length-1)return t;let e=F(t);return P(g({},e),{currentPaths:e.history[e.historyPos+1],historyPos:e.historyPos+1})}function tt(t){let e=F(t);return P(g({},e),{currentPaths:[],history:[...e.history.slice(0,e.historyPos+1),[]],historyPos:e.historyPos+1})}function rt(t,e){let r=F(t),n=[...r.currentPaths,...e],o=r.historyPos+1;return P(g({},r),{currentPaths:n,history:[...r.history.slice(0,o),n],historyPos:o})}function nt(){return P(g({},de()),{history:[]})}function ot({point:t,drawMode:e,strokeColor:r,strokeWidth:n,eraserWidth:o,withTimestamp:a,now:s}){let i={drawMode:e,strokeColor:e?r:se,strokeWidth:e?n:o,paths:[t]};return a?P(g({},i),{startTimestamp:s,endTimestamp:0}):i}function he(t,e){let r=t[t.length-1];if(!r||e.length===0)return t;let n=[],o=r.paths[r.paths.length-1];for(let s of e)(o==null?void 0:o.x)===s.x&&o.y===s.y||(n.push(s),o=s);if(n.length===0)return t;let a=P(g({},r),{paths:[...r.paths,...n]});return[...t.slice(0,-1),a]}function ge(t,e,r){var a,s;if(!e)return t;let n=(s=(a=t.slice(-1))==null?void 0:a[0])!=null?s:null;if(n===null)return t;let o=P(g({},n),{endTimestamp:r});return[...t.slice(0,-1),o]}function at({strokeColor:t,strokeWidth:e,eraserWidth:r,eraserMode:n,withTimestamp:o,onChange:a,onStroke:s}){let[i,c]=b.useState(de),u=i.currentPaths,v=i.isDrawing,d=b.useRef(a),f=b.useRef(s),m=b.useRef([]),h=b.useRef(null);b.useEffect(()=>{d.current=a},[a]),b.useEffect(()=>{f.current=s},[s]),b.useEffect(()=>{if(v||i.lastCompletedStroke===null)return;let p=i.lastCompletedStroke;f.current(p.path,p.isEraser),c(l=>l.lastCompletedStroke===p?P(g({},l),{lastCompletedStroke:null}):l)},[v,i.lastCompletedStroke]),b.useEffect(()=>{d.current(u)},[u]);let k=M(()=>{c(p=>je(p))},[]),x=M(()=>{c(p=>et(p))},[]),B=M(()=>{c(p=>tt(p))},[]),y=M(p=>{c(l=>rt(l,p))},[]),w=M(p=>{c(l=>P(g({},l),{drawMode:!p}))},[]),L=M(()=>{c(nt())},[]),C=M(p=>{p.length!==0&&c(l=>{if(!l.isDrawing)return l;if(l.activeStroke!==null){let S=he([l.activeStroke],p)[0];return S===l.activeStroke?l:P(g({},l),{activeStroke:S})}let E=he(l.currentPaths,p);return E===l.currentPaths?l:P(g({},l),{currentPaths:E})})},[]),R=M(()=>{h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null);let p=m.current;m.current=[],C(p)},[C]),H=M(()=>{h.current===null&&(h.current=window.requestAnimationFrame(()=>{R()}))},[R]);b.useEffect(()=>()=>{h.current!==null&&window.cancelAnimationFrame(h.current)},[]);let O=M((p,l=!1)=>{h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null),m.current=[],c(E=>{let S=F(E),$=!l&&S.drawMode,A=ot({point:p,drawMode:$,strokeColor:t,strokeWidth:e,eraserWidth:r,withTimestamp:o,now:Date.now()}),_=!$&&n==="stroke";return P(g({},S),{isDrawing:!0,historyPos:S.historyPos+1,historySynced:!1,activeStroke:_?A:null,currentPaths:_?S.currentPaths:[...S.currentPaths,A]})})},[n,r,t,e,o]),N=M(p=>{m.current.push(p),H()},[H]),G=M(()=>{R(),c(p=>{var S,$;if(!p.isDrawing)return p;if(p.activeStroke!==null){let[A]=ge([p.activeStroke],o,Date.now()),_=p.currentPaths.filter(U=>!U.drawMode||!Ue({eraser:A,stroke:U})),D=_.length<p.currentPaths.length;return P(g({},p),{isDrawing:!1,activeStroke:null,currentPaths:D?_:p.currentPaths,historyPos:D?p.historyPos:p.historyPos-1,historySynced:D?p.historySynced:!0,lastCompletedStroke:{path:A,isEraser:!0}})}let l=ge(p.currentPaths,o,Date.now()),E=($=(S=l.slice(-1))==null?void 0:S[0])!=null?$:null;return P(g({},p),{isDrawing:!1,currentPaths:l,lastCompletedStroke:E===null?null:{path:E,isEraser:!E.drawMode}})})},[R,o]);return{currentPaths:u,isDrawing:v,setEraseMode:w,undo:k,redo:x,clearCanvas:B,loadPaths:y,resetCanvas:L,handlePointerDown:O,handlePointerMove:N,handlePointerUp:G}}import*as it from"react";function st(t){return t.reduce((e,r)=>{var a,s;let n=(a=r.startTimestamp)!=null?a:0,o=(s=r.endTimestamp)!=null?s:0;return e+(o-n)},0)}function ct(t,{canvasRef:e,currentPaths:r,withTimestamp:n,setEraseMode:o,undo:a,redo:s,clearCanvas:i,loadPaths:c,resetCanvas:u}){it.useImperativeHandle(t,()=>({eraseMode:o,clearCanvas:()=>{i()},undo:()=>{a()},redo:()=>{s()},exportImage:(v,d)=>{var m;let f=(m=e.current)==null?void 0:m.exportImage;if(!f)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportImage().");return f(v,d)},exportSvg:()=>T(null,null,function*(){var d;let v=(d=e.current)==null?void 0:d.exportSvg;if(!v)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportSvg().");return v()}),exportPaths:()=>T(null,null,function*(){return r}),loadPaths:v=>{c(v)},getSketchingTime:()=>T(null,null,function*(){if(!n)throw new Error("Set 'withTimestamp' prop to get sketching time");return st(r)}),resetCanvas:u}),[e,r,a,s,i,c,u,o,n])}import{jsx as Ot}from"react/jsx-runtime";var Ht=ie.forwardRef((t,e)=>{let{id:r="react-sketch-canvas",width:n="100%",height:o="100%",className:a="",canvasColor:s="white",strokeColor:i="red",backgroundImage:c="",exportWithBackgroundImage:u=!1,preserveBackgroundImageAspectRatio:v="none",strokeWidth:d=4,eraserWidth:f=8,eraserMode:m="mask",allowOnlyPointerType:h="all",style:k={border:"0.0625rem solid lightgray",borderRadius:"0.25rem"},svgStyle:x={},onChange:B=U=>{},onStroke:y=(U,ce)=>{},withTimestamp:w=!1,withViewBox:L=!1,readOnly:C=!1,touchAction:R}=t,H=ie.useRef(null),{currentPaths:O,isDrawing:N,undo:G,redo:p,clearCanvas:l,loadPaths:E,resetCanvas:S,setEraseMode:$,handlePointerDown:A,handlePointerMove:_,handlePointerUp:D}=at({strokeColor:i,strokeWidth:d,eraserWidth:f,eraserMode:m,withTimestamp:w,onChange:B,onStroke:y});return ct(e,{canvasRef:H,currentPaths:O,withTimestamp:w,setEraseMode:$,undo:G,redo:p,clearCanvas:l,loadPaths:E,resetCanvas:S}),Ot(le,{ref:H,id:r,width:n,height:o,className:a,canvasColor:s,backgroundImage:c,exportWithBackgroundImage:u,preserveBackgroundImageAspectRatio:v,allowOnlyPointerType:h,style:k,svgStyle:x,paths:O,isDrawing:N,onPointerDown:A,onPointerMove:_,onPointerUp:D,withViewBox:L,readOnly:C,touchAction:R})});Ht.displayName="@react-sketch-canvas/ReactSketchCanvas";export{le as Canvas,Ht as ReactSketchCanvas};