UNPKG

react-sketch-canvas

Version:

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

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