react-sketch-canvas
Version:
react-sketch-canvas - Freehand vector drawing tool for React using SVG as canvas
26 lines (23 loc) • 33.1 kB
JavaScript
;(()=>{var Ft=Object.create;var ke=Object.defineProperty,Gt=Object.defineProperties,Xt=Object.getOwnPropertyDescriptor,jt=Object.getOwnPropertyDescriptors,Vt=Object.getOwnPropertyNames,Oe=Object.getOwnPropertySymbols,zt=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty,qt=Object.prototype.propertyIsEnumerable;var ce=Math.pow,Ue=(e,t,r)=>t in e?ke(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,g=(e,t)=>{for(var r in t||(t={}))Ne.call(t,r)&&Ue(e,r,t[r]);if(Oe)for(var r of Oe(t))qt.call(t,r)&&Ue(e,r,t[r]);return e},k=(e,t)=>Gt(e,jt(t));var ue=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Jt=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vt(t))!Ne.call(e,o)&&o!==r&&ke(e,o,{get:()=>t[o],enumerable:!(n=Xt(t,o))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?Ft(zt(e)):{},Jt(t||!e||!e.__esModule?ke(r,"default",{value:e,enumerable:!0}):r,e));var B=(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 Ke=ue(l=>{"use strict";var Ce=Symbol.for("react.transitional.element"),Kt=Symbol.for("react.portal"),Qt=Symbol.for("react.fragment"),Zt=Symbol.for("react.strict_mode"),er=Symbol.for("react.profiler"),tr=Symbol.for("react.consumer"),rr=Symbol.for("react.context"),nr=Symbol.for("react.forward_ref"),or=Symbol.for("react.suspense"),ar=Symbol.for("react.memo"),Xe=Symbol.for("react.lazy"),sr=Symbol.for("react.activity"),We=Symbol.iterator;function ir(e){return e===null||typeof e!="object"?null:(e=We&&e[We]||e["@@iterator"],typeof e=="function"?e:null)}var je={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ve=Object.assign,ze={};function q(e,t,r){this.props=e,this.context=t,this.refs=ze,this.updater=r||je}q.prototype.isReactComponent={};q.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};q.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function qe(){}qe.prototype=q.prototype;function Ee(e,t,r){this.props=e,this.context=t,this.refs=ze,this.updater=r||je}var we=Ee.prototype=new qe;we.constructor=Ee;Ve(we,q.prototype);we.isPureReactComponent=!0;var Ye=Array.isArray;function Re(){}var y={H:null,A:null,T:null,S:null},Je=Object.prototype.hasOwnProperty;function be(e,t,r){var n=r.ref;return{$$typeof:Ce,type:e,key:t,ref:n!==void 0?n:null,props:r}}function cr(e,t){return be(e.type,t,e.props)}function Ae(e){return typeof e=="object"&&e!==null&&e.$$typeof===Ce}function ur(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(r){return t[r]})}var Fe=/\/+/g;function xe(e,t){return typeof e=="object"&&e!==null&&e.key!=null?ur(""+e.key):t.toString(36)}function pr(e){switch(e.status){case"fulfilled":return e.value;case"rejected":throw e.reason;default:switch(typeof e.status=="string"?e.then(Re,Re):(e.status="pending",e.then(function(t){e.status==="pending"&&(e.status="fulfilled",e.value=t)},function(t){e.status==="pending"&&(e.status="rejected",e.reason=t)})),e.status){case"fulfilled":return e.value;case"rejected":throw e.reason}}throw e}function z(e,t,r,n,o){var a=typeof e;(a==="undefined"||a==="boolean")&&(e=null);var s=!1;if(e===null)s=!0;else switch(a){case"bigint":case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case Ce:case Kt:s=!0;break;case Xe:return s=e._init,z(s(e._payload),t,r,n,o)}}if(s)return o=o(e),s=n===""?"."+xe(e,0):n,Ye(o)?(r="",s!=null&&(r=s.replace(Fe,"$&/")+"/"),z(o,t,r,"",function(u){return u})):o!=null&&(Ae(o)&&(o=cr(o,r+(o.key==null||e&&e.key===o.key?"":(""+o.key).replace(Fe,"$&/")+"/")+s)),t.push(o)),1;s=0;var i=n===""?".":n+":";if(Ye(e))for(var c=0;c<e.length;c++)n=e[c],a=i+xe(n,c),s+=z(n,t,r,a,o);else if(c=ir(e),typeof c=="function")for(e=c.call(e),c=0;!(n=e.next()).done;)n=n.value,a=i+xe(n,c++),s+=z(n,t,r,a,o);else if(a==="object"){if(typeof e.then=="function")return z(pr(e),t,r,n,o);throw t=String(e),Error("Objects are not valid as a React child (found: "+(t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t)+"). If you meant to render a collection of children, use an array instead.")}return s}function pe(e,t,r){if(e==null)return e;var n=[],o=0;return z(e,n,"","",function(a){return t.call(r,a,o++)}),n}function lr(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(r){(e._status===0||e._status===-1)&&(e._status=1,e._result=r)},function(r){(e._status===0||e._status===-1)&&(e._status=2,e._result=r)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var Ge=typeof reportError=="function"?reportError:function(e){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof e=="object"&&e!==null&&typeof e.message=="string"?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",e);return}console.error(e)},mr={map:pe,forEach:function(e,t,r){pe(e,function(){t.apply(this,arguments)},r)},count:function(e){var t=0;return pe(e,function(){t++}),t},toArray:function(e){return pe(e,function(t){return t})||[]},only:function(e){if(!Ae(e))throw Error("React.Children.only expected to receive a single React element child.");return e}};l.Activity=sr;l.Children=mr;l.Component=q;l.Fragment=Qt;l.Profiler=er;l.PureComponent=Ee;l.StrictMode=Zt;l.Suspense=or;l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=y;l.__COMPILER_RUNTIME={__proto__:null,c:function(e){return y.H.useMemoCache(e)}};l.cache=function(e){return function(){return e.apply(null,arguments)}};l.cacheSignal=function(){return null};l.cloneElement=function(e,t,r){if(e==null)throw Error("The argument must be a React element, but you passed "+e+".");var n=Ve({},e.props),o=e.key;if(t!=null)for(a in t.key!==void 0&&(o=""+t.key),t)!Je.call(t,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&t.ref===void 0||(n[a]=t[a]);var a=arguments.length-2;if(a===1)n.children=r;else if(1<a){for(var s=Array(a),i=0;i<a;i++)s[i]=arguments[i+2];n.children=s}return be(e.type,o,n)};l.createContext=function(e){return e={$$typeof:rr,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:tr,_context:e},e};l.createElement=function(e,t,r){var n,o={},a=null;if(t!=null)for(n in t.key!==void 0&&(a=""+t.key),t)Je.call(t,n)&&n!=="key"&&n!=="__self"&&n!=="__source"&&(o[n]=t[n]);var s=arguments.length-2;if(s===1)o.children=r;else if(1<s){for(var i=Array(s),c=0;c<s;c++)i[c]=arguments[c+2];o.children=i}if(e&&e.defaultProps)for(n in s=e.defaultProps,s)o[n]===void 0&&(o[n]=s[n]);return be(e,a,o)};l.createRef=function(){return{current:null}};l.forwardRef=function(e){return{$$typeof:nr,render:e}};l.isValidElement=Ae;l.lazy=function(e){return{$$typeof:Xe,_payload:{_status:-1,_result:e},_init:lr}};l.memo=function(e,t){return{$$typeof:ar,type:e,compare:t===void 0?null:t}};l.startTransition=function(e){var t=y.T,r={};y.T=r;try{var n=e(),o=y.S;o!==null&&o(r,n),typeof n=="object"&&n!==null&&typeof n.then=="function"&&n.then(Re,Ge)}catch(a){Ge(a)}finally{t!==null&&r.types!==null&&(t.types=r.types),y.T=t}};l.unstable_useCacheRefresh=function(){return y.H.useCacheRefresh()};l.use=function(e){return y.H.use(e)};l.useActionState=function(e,t,r){return y.H.useActionState(e,t,r)};l.useCallback=function(e,t){return y.H.useCallback(e,t)};l.useContext=function(e){return y.H.useContext(e)};l.useDebugValue=function(){};l.useDeferredValue=function(e,t){return y.H.useDeferredValue(e,t)};l.useEffect=function(e,t){return y.H.useEffect(e,t)};l.useEffectEvent=function(e){return y.H.useEffectEvent(e)};l.useId=function(){return y.H.useId()};l.useImperativeHandle=function(e,t,r){return y.H.useImperativeHandle(e,t,r)};l.useInsertionEffect=function(e,t){return y.H.useInsertionEffect(e,t)};l.useLayoutEffect=function(e,t){return y.H.useLayoutEffect(e,t)};l.useMemo=function(e,t){return y.H.useMemo(e,t)};l.useOptimistic=function(e,t){return y.H.useOptimistic(e,t)};l.useReducer=function(e,t,r){return y.H.useReducer(e,t,r)};l.useRef=function(e){return y.H.useRef(e)};l.useState=function(e){return y.H.useState(e)};l.useSyncExternalStore=function(e,t,r){return y.H.useSyncExternalStore(e,t,r)};l.useTransition=function(){return y.H.useTransition()};l.version="19.2.6"});var N=ue((Dr,Qe)=>{"use strict";Qe.exports=Ke()});var ht=ue(me=>{"use strict";var br=Symbol.for("react.transitional.element"),Ar=Symbol.for("react.fragment");function ft(e,t,r){var n=null;if(r!==void 0&&(n=""+r),t.key!==void 0&&(n=""+t.key),"key"in t){r={};for(var o in t)o!=="key"&&(r[o]=t[o])}else r=t;return t=r.ref,{$$typeof:br,type:e,key:n,ref:t!==void 0?t:null,props:r}}me.Fragment=Ar;me.jsx=ft;me.jsxs=ft});var x=ue((yn,gt)=>{"use strict";gt.exports=ht()});var H=v(N());var pt=v(N());function _e(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 le(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 dr(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 te=e=>new Promise((t,r)=>{let n=new Image;dr(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 Ze({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 fr(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 hr(e){let t=/^data:image\/svg\+xml([^,]*),(.*)$/i.exec(e);if(!t)return null;let[,r="",n=""]=t;try{return r.includes(";base64")?fr(n):decodeURIComponent(n)}catch(o){return null}}function et(e){let t=hr(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 tt(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 re(e,t,r){if(r==="Min")return 0;let n=e-t;return r==="Max"?n:n/2}function rt({context:e,backgroundLayer:t,exportWidth:r,exportHeight:n,preserveAspectRatio:o}){let a=tt(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 C=Math.max(c,u),w=r/C,L=n/C,R=re(s,w,a.xAlign),T=re(i,L,a.yAlign);e.drawImage(t,R,T,w,L,0,0,r,n);return}let P=Math.min(c,u),f=s*P,S=i*P,p=re(r,f,a.xAlign),h=re(n,S,a.yAlign);e.drawImage(t,p,h,f,S)}function nt(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.":gr(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 gr(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 ot(e){return B(this,null,function*(){if(e.kind==="none")return null;try{if(e.kind==="svg-wrapper"){let t=Ze(e);return yield te(le(t))}return yield te(et(e.backgroundImage))}catch(t){throw new Error(nt(e.backgroundImage),{cause:t})}})}function at({context:e,backgroundLayer:t,plan:r,exportWidth:n,exportHeight:o}){if(r.kind==="svg-wrapper"){e.drawImage(t,0,0,n,o);return}rt({context:e,backgroundLayer:t,exportWidth:n,exportHeight:o,preserveAspectRatio:r.preserveAspectRatio})}function st({backgroundImage:e,exportWithBackgroundImage:t,exportWidth:r,exportHeight:n,preserveAspectRatio:o}){return!t||!e?{kind:"none"}:vr(e)?{kind:"svg-wrapper",backgroundImage:e,exportWidth:r,exportHeight:n,preserveAspectRatio:o}:{kind:"direct-image",backgroundImage:e,preserveAspectRatio:o}}function vr(e){return/^data:image\/svg\+xml(?:[;,]|$)/i.test(e)}var it=0;function ne(e,t){return e.querySelector(`[id$="__${t}"]`)}function yr(e,t){it+=1;let r=`${t}__export-${it}`,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 ct(e){var t,r,n;return(t=ne(e,"background"))==null||t.remove(),(r=ne(e,"canvas-background-group"))==null||r.remove(),(n=ne(e,"canvas-background"))==null||n.remove(),e}function oe(e,{id:t,canvasColor:r,exportWithBackgroundImage:n}){var o,a;return n||((o=ne(e,"background"))==null||o.remove(),(a=ne(e,"canvas-background"))==null||a.setAttribute("fill",r)),yr(e,t),e}function Pr({id:e,svgCanvas:t,canvasColor:r,backgroundImage:n,exportWithBackgroundImage:o}){if(o&&n){let a=ct(t);return oe(a,{id:e,canvasColor:r,exportWithBackgroundImage:!0})}return oe(t,{id:e,canvasColor:r,exportWithBackgroundImage:o})}function Sr(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 kr(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 ut(P){return B(this,arguments,function*({id:e,svgCanvas:t,svgWidth:r,svgHeight:n,imageType:o,canvasColor:a,backgroundImage:s,exportWithBackgroundImage:i,preserveBackgroundImageAspectRatio:c,options:u}){var b,A;let f=(b=u==null?void 0:u.width)!=null?b:r,S=(A=u==null?void 0:u.height)!=null?A:n,p=st({backgroundImage:s,exportWithBackgroundImage:i,exportWidth:f,exportHeight:S,preserveAspectRatio:c}),h=Pr({id:e,svgCanvas:t,canvasColor:a,backgroundImage:s,exportWithBackgroundImage:i}),C=yield te(le(h)),w=kr(u),L=Sr(f,S,w),R=L.getContext("2d");if(!R)throw Error("Canvas not rendered yet");w!==1&&R.scale(w,w),(o==="jpeg"||!s||!i)&&(R.fillStyle=a,R.fillRect(0,0,f,S));let O=yield ot(p);return O&&p.kind!=="none"&&at({context:R,backgroundLayer:O,plan:p,exportWidth:f,exportHeight:S}),R.drawImage(C,0,0,f,S),L.toDataURL(`image/${o}`)})}function lt(e,{canvasRef:t,id:r,canvasColor:n,backgroundImage:o,exportWithBackgroundImage:a,preserveBackgroundImageAspectRatio:s}){pt.useImperativeHandle(e,()=>({exportImage:(i,c)=>B(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:P,width:f,height:S}=_e(u);return ut({id:r,svgCanvas:P,svgWidth:f,svgHeight:S,imageType:i,canvasColor:n,backgroundImage:o,exportWithBackgroundImage:a,preserveBackgroundImageAspectRatio:s,options:c})}),exportSvg:()=>B(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}=_e(i);return oe(c,{id:r,canvasColor:n,exportWithBackgroundImage:a}).outerHTML})}))}var mt=v(N()),V=v(N()),xr=32,Rr=(e,t)=>e==="all"||t===e,Cr=(e,t)=>!(e==="mouse"&&t!==0),Er=(e,t)=>e==="pen"&&(t&xr)!==0,wr=(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 dt({canvasRef:e,isDrawing:t,allowOnlyPointerType:r,onPointerDown:n,onPointerMove:o,onPointerUp:a}){let s=mt.useRef(null),i=(0,V.useCallback)(p=>{let h=e.current,C=h==null?void 0:h.getBoundingClientRect();return!h||!C?{x:0,y:0}:wr(p,C,h)},[e]),c=(0,V.useCallback)(p=>s.current===p.pointerId,[]),u=(0,V.useCallback)(p=>{p.pointerType!=="touch"||!p.cancelable||p.preventDefault()},[]),P=(0,V.useCallback)(p=>{c(p)&&(s.current=null,a())},[c,a]),f=(0,V.useCallback)(p=>{if(Rr(r,p.pointerType)&&Cr(p.pointerType,p.button)){if(s.current!==null){s.current=null,a();return}u(p),p.isTrusted&&p.currentTarget.setPointerCapture(p.pointerId),s.current=p.pointerId,n(i(p),Er(p.pointerType,p.buttons))}},[r,i,n,a,u]),S=(0,V.useCallback)(p=>{t&&c(p)&&(u(p),o(i(p)))},[i,c,t,o,u]);return{handlePointerDown:f,handlePointerMove:S,finishActivePointer:P}}var ae=v(x());function vt({internalId:e,backgroundImage:t,preserveBackgroundImageAspectRatio:r}){return t?(0,ae.jsx)("pattern",{id:`${e}__background`,x:"0",y:"0",width:"100%",height:"100%",patternUnits:"userSpaceOnUse",children:(0,ae.jsx)("image",{x:"0",y:"0",width:"100%",height:"100%",xlinkHref:t,preserveAspectRatio:r})}):null}function yt({internalId:e,backgroundImage:t,canvasColor:r}){return(0,ae.jsx)("g",{id:`${e}__canvas-background-group`,children:(0,ae.jsx)("rect",{id:`${e}__canvas-background`,x:"0",y:"0",width:"100%",height:"100%",fill:t?`url(#${e}__background)`:r})})}var Rt=v(N());var kt=(e,t)=>{let r=t.x-e.x,n=t.y-e.y;return{length:Math.sqrt(ce(r,2)+ce(n,2)),angle:Math.atan2(n,r)}},de=e=>{let{current:t,next:r,previous:n,reverse:o}=e,a=n||t,s=r||t,i=.2,c=kt(a,s),u=c.angle+(o?Math.PI:0),P=c.length*i;return[t.x+Math.cos(u)*P,t.y+Math.sin(u)*P]},ve=(e,t,r)=>{let n,o;switch(t){case 0:[n,o]=de({current:e});break;case 1:[n,o]=de({current:r[t-1],next:e});break;default:[n,o]=de({current:r[t-1],previous:r[t-2],next:e});break}let[a,s]=de({current:e,previous:r[t-1],next:r[t+1],reverse:!0});return`C ${n},${o} ${a},${s} ${e.x}, ${e.y}`},Ie=(e,t)=>kt(e,t).length,fe=(e,[t,r])=>{let n=ce(Ie(t,r),2);if(n===0)return Ie(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 Ie(e,s)},he=(e,t,r)=>(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y),ge=(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),_r=([e,t],[r,n])=>{let o=he(e,t,r),a=he(e,t,n),s=he(r,n,e),i=he(r,n,t);return(o>0&&a<0||o<0&&a>0)&&(s>0&&i<0||s<0&&i>0)?!0:o===0&&ge(r,[e,t])||a===0&&ge(n,[e,t])||s===0&&ge(e,[r,n])||i===0&&ge(t,[r,n])},Ir=(e,t)=>{if(_r(e,t))return 0;let[r,n]=e,[o,a]=t;return Math.min(fe(r,t),fe(n,t),fe(o,e),fe(a,e))},Pt=e=>e.paths.length>1?e.paths.slice(1).map((t,r)=>[e.paths[r],t]):e.paths.map(t=>[t,t]);function St(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 Tr(e,t){return e.minX<=t.maxX&&e.maxX>=t.minX&&e.minY<=t.maxY&&e.maxY>=t.minY}function xt({eraser:e,stroke:t}){if(e.paths.length===0||t.paths.length===0)return!1;let r=e.strokeWidth/2+t.strokeWidth/2,n=St(e,e.strokeWidth/2),o=St(t,t.strokeWidth/2);if(!Tr(n,o))return!1;let a=Pt(e),s=Pt(t);return a.some(i=>s.some(c=>Ir(i,c)<=r))}var Te=v(x());function Mr({paths:e,id:t,strokeWidth:r,strokeColor:n,command:o=ve}){if(e.length===1){let{x:s,y:i}=e[0],c=r/2;return(0,Te.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,Te.jsx)("path",{id:t,d:a,fill:"none",strokeLinecap:"round",stroke:n,strokeWidth:r},t)}var se=Rt.memo(Mr);se.displayName="SvgPath";var ye="#000000";var D=v(x());function Ct({internalId:e,eraserPaths:t}){return(0,D.jsxs)("g",{id:`${e}__eraser-stroke-group`,children:[(0,D.jsx)("rect",{id:`${e}__mask-background`,x:"0",y:"0",width:"100%",height:"100%",fill:"white"}),t.map((r,n)=>(0,D.jsx)(se,{id:`${e}__eraser-${n}`,paths:r.paths,strokeColor:ye,strokeWidth:r.strokeWidth},`${e}__eraser-${n}`))]})}function Et({internalId:e,eraserPaths:t}){return(0,D.jsx)(D.Fragment,{children:t.map((r,n)=>(0,D.jsxs)("mask",{id:`${e}__eraser-mask-${n}`,maskUnits:"userSpaceOnUse",children:[(0,D.jsx)("use",{href:`#${e}__mask-background`,xlinkHref:`#${e}__mask-background`}),Array.from({length:t.length-n},(o,a)=>a+n).map(o=>(0,D.jsx)("use",{href:`#${e}__eraser-${o.toString()}`,xlinkHref:`#${e}__eraser-${o.toString()}`},o.toString()))]},`${e}__eraser-mask-${n}`))})}var wt=e=>e.filter(t=>!t.drawMode),bt=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 ie=v(x());function $r({id:e,paths:t}){return(0,ie.jsx)(ie.Fragment,{children:t.map((r,n)=>(0,ie.jsx)(se,{id:`${e}__${n}`,paths:r.paths,strokeWidth:r.strokeWidth,strokeColor:r.strokeColor,command:ve},`${e}__${n}`))})}var At=$r;var J=v(x());function _t({internalId:e,pathGroups:t,eraserPaths:r}){return(0,J.jsx)(J.Fragment,{children:t.map((n,o)=>(0,J.jsx)("g",k(g({id:`${e}__stroke-group-${o}`},r[o]?{mask:`url(#${e}__eraser-mask-${o})`}:{}),{children:(0,J.jsx)(At,{id:`${e}__stroke-group-${o}__paths`,paths:n})}),`${e}__stroke-group-${o}`))})}var Y=v(x());function It({id:e,internalId:t,paths:r,canvasColor:n,backgroundImage:o,preserveBackgroundImageAspectRatio:a,svgStyle:s,viewBox:i}){let c=wt(r),u=bt(r);return(0,Y.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,Y.jsxs)("defs",{children:[(0,Y.jsx)(Ct,{internalId:t,eraserPaths:c}),(0,Y.jsx)(vt,{internalId:t,backgroundImage:o,preserveBackgroundImageAspectRatio:a}),(0,Y.jsx)(Et,{internalId:t,eraserPaths:c})]}),(0,Y.jsx)(yt,{internalId:t,backgroundImage:o,canvasColor:n}),(0,Y.jsx)(_t,{internalId:t,pathGroups:u,eraserPaths:c})]})}var Me=v(x()),$e=H.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:P="react-sketch-canvas",canvasColor:f="white",backgroundImage:S="",exportWithBackgroundImage:p=!1,preserveBackgroundImageAspectRatio:h="none",allowOnlyPointerType:C="all",style:w={border:"0.0625rem solid #9c9c9c",borderRadius:"0.25rem"},svgStyle:L={},withViewBox:R=!1,readOnly:T=!1,touchAction:O}=e,b=H.useRef(null),[A,G]=H.useState(null),X=H.useId(),Q=H.useMemo(()=>`${i}__${X.replaceAll(":","")}`,[i,X]);H.useLayoutEffect(()=>{if(!R||b.current===null)return;let $=b.current,U=()=>{let j=$.getBoundingClientRect(),Se=$.clientWidth||j.width,De=$.clientHeight||j.height,Yt={width:Se,height:De};G(ee=>(ee==null?void 0:ee.width)===Se&&ee.height===De?ee:Yt)};if(U(),typeof ResizeObserver=="undefined")return;let F=new ResizeObserver(U);return F.observe($),()=>{F.disconnect()}},[R]),lt(t,{canvasRef:b,id:i,canvasColor:f,backgroundImage:S,exportWithBackgroundImage:p,preserveBackgroundImageAspectRatio:h});let{handlePointerDown:Z,handlePointerMove:m,finishActivePointer:d}=dt({canvasRef:b,isDrawing:n,allowOnlyPointerType:C,onPointerDown:o,onPointerMove:a,onPointerUp:s}),M=C==="all"||C==="touch",E=O!=null?O:M?"none":"pan-x pan-y pinch-zoom",W=R&&A!==null?`0 0 ${A.width} ${A.height}`:void 0;return(0,Me.jsx)("div",{role:"presentation",ref:b,className:P,style:g({touchAction:E,userSelect:"none",WebkitUserSelect:"none",WebkitTouchCallout:"none",width:c,height:u},w),onPointerDown:T?void 0:Z,onPointerMove:T?void 0:m,onPointerUp:T?void 0:d,onPointerCancel:T?void 0:d,children:(0,Me.jsx)(It,{id:i,internalId:Q,paths:r,canvasColor:f,backgroundImage:S,preserveBackgroundImageAspectRatio:h,svgStyle:L,viewBox:W})})});$e.displayName="@react-sketch-canvas/Canvas";var Pe=v(N());var I=v(N()),_=v(N());function He(){return{drawMode:!0,isDrawing:!1,history:[[]],historyPos:0,historySynced:!1,currentPaths:[],activeStroke:null,lastCompletedStroke:null}}function K(e){return e.historySynced?e:k(g({},e),{history:[...e.history.slice(0,e.historyPos),[...e.currentPaths]],historySynced:!0})}function Tt(e){if(e.historyPos<=0)return e;let t=K(e);return k(g({},t),{currentPaths:t.history[t.historyPos-1],historyPos:t.historyPos-1})}function Mt(e){if(e.historyPos>=e.history.length-1)return e;let t=K(e);return k(g({},t),{currentPaths:t.history[t.historyPos+1],historyPos:t.historyPos+1})}function $t(e){let t=K(e);return k(g({},t),{currentPaths:[],history:[...t.history.slice(0,t.historyPos+1),[]],historyPos:t.historyPos+1})}function Ht(e,t){let r=K(e),n=[...r.currentPaths,...t],o=r.historyPos+1;return k(g({},r),{currentPaths:n,history:[...r.history.slice(0,o),n],historyPos:o})}function Lt(){return k(g({},He()),{history:[]})}function Bt({point:e,drawMode:t,strokeColor:r,strokeWidth:n,eraserWidth:o,withTimestamp:a,now:s}){let i={drawMode:t,strokeColor:t?r:ye,strokeWidth:t?n:o,paths:[e]};return a?k(g({},i),{startTimestamp:s,endTimestamp:0}):i}function Le(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=k(g({},r),{paths:[...r.paths,...n]});return[...e.slice(0,-1),a]}function Be(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=k(g({},n),{endTimestamp:r});return[...e.slice(0,-1),o]}function Dt({strokeColor:e,strokeWidth:t,eraserWidth:r,eraserMode:n,withTimestamp:o,onChange:a,onStroke:s}){let[i,c]=I.useState(He),u=i.currentPaths,P=i.isDrawing,f=I.useRef(a),S=I.useRef(s),p=I.useRef([]),h=I.useRef(null);I.useEffect(()=>{f.current=a},[a]),I.useEffect(()=>{S.current=s},[s]),I.useEffect(()=>{if(P||i.lastCompletedStroke===null)return;let m=i.lastCompletedStroke;S.current(m.path,m.isEraser),c(d=>d.lastCompletedStroke===m?k(g({},d),{lastCompletedStroke:null}):d)},[P,i.lastCompletedStroke]),I.useEffect(()=>{f.current(u)},[u]);let C=(0,_.useCallback)(()=>{c(m=>Tt(m))},[]),w=(0,_.useCallback)(()=>{c(m=>Mt(m))},[]),L=(0,_.useCallback)(()=>{c(m=>$t(m))},[]),R=(0,_.useCallback)(m=>{c(d=>Ht(d,m))},[]),T=(0,_.useCallback)(m=>{c(d=>k(g({},d),{drawMode:!m}))},[]),O=(0,_.useCallback)(()=>{c(Lt())},[]),b=(0,_.useCallback)(m=>{m.length!==0&&c(d=>{if(!d.isDrawing)return d;if(d.activeStroke!==null){let E=Le([d.activeStroke],m)[0];return E===d.activeStroke?d:k(g({},d),{activeStroke:E})}let M=Le(d.currentPaths,m);return M===d.currentPaths?d:k(g({},d),{currentPaths:M})})},[]),A=(0,_.useCallback)(()=>{h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null);let m=p.current;p.current=[],b(m)},[b]),G=(0,_.useCallback)(()=>{h.current===null&&(h.current=window.requestAnimationFrame(()=>{A()}))},[A]);I.useEffect(()=>()=>{h.current!==null&&window.cancelAnimationFrame(h.current)},[]);let X=(0,_.useCallback)((m,d=!1)=>{h.current!==null&&(window.cancelAnimationFrame(h.current),h.current=null),p.current=[],c(M=>{let E=K(M),W=!d&&E.drawMode,$=Bt({point:m,drawMode:W,strokeColor:e,strokeWidth:t,eraserWidth:r,withTimestamp:o,now:Date.now()}),U=!W&&n==="stroke";return k(g({},E),{isDrawing:!0,historyPos:E.historyPos+1,historySynced:!1,activeStroke:U?$:null,currentPaths:U?E.currentPaths:[...E.currentPaths,$]})})},[n,r,e,t,o]),Q=(0,_.useCallback)(m=>{p.current.push(m),G()},[G]),Z=(0,_.useCallback)(()=>{A(),c(m=>{var E,W;if(!m.isDrawing)return m;if(m.activeStroke!==null){let[$]=Be([m.activeStroke],o,Date.now()),U=m.currentPaths.filter(j=>!j.drawMode||!xt({eraser:$,stroke:j})),F=U.length<m.currentPaths.length;return k(g({},m),{isDrawing:!1,activeStroke:null,currentPaths:F?U:m.currentPaths,historyPos:F?m.historyPos:m.historyPos-1,historySynced:F?m.historySynced:!0,lastCompletedStroke:{path:$,isEraser:!0}})}let d=Be(m.currentPaths,o,Date.now()),M=(W=(E=d.slice(-1))==null?void 0:E[0])!=null?W:null;return k(g({},m),{isDrawing:!1,currentPaths:d,lastCompletedStroke:M===null?null:{path:M,isEraser:!M.drawMode}})})},[A,o]);return{currentPaths:u,isDrawing:P,setEraseMode:T,undo:C,redo:w,clearCanvas:L,loadPaths:R,resetCanvas:O,handlePointerDown:X,handlePointerMove:Q,handlePointerUp:Z}}var Ut=v(N());function Ot(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 Nt(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:(P,f)=>{var p;let S=(p=t.current)==null?void 0:p.exportImage;if(!S)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportImage().");return S(P,f)},exportSvg:()=>B(null,null,function*(){var f;let P=(f=t.current)==null?void 0:f.exportSvg;if(!P)throw new Error("Cannot export: the canvas is not ready yet. Wait until the component has mounted before calling exportSvg().");return P()}),exportPaths:()=>B(null,null,function*(){return r}),loadPaths:P=>{c(P)},getSketchingTime:()=>B(null,null,function*(){if(!n)throw new Error("Set 'withTimestamp' prop to get sketching time");return Ot(r)}),resetCanvas:u}),[t,r,a,s,i,c,u,o,n])}var Wt=v(x()),Hr=Pe.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:P="none",strokeWidth:f=4,eraserWidth:S=8,eraserMode:p="mask",allowOnlyPointerType:h="all",style:C={border:"0.0625rem solid lightgray",borderRadius:"0.25rem"},svgStyle:w={},onChange:L=j=>{},onStroke:R=(j,Se)=>{},withTimestamp:T=!1,withViewBox:O=!1,readOnly:b=!1,touchAction:A}=e,G=Pe.useRef(null),{currentPaths:X,isDrawing:Q,undo:Z,redo:m,clearCanvas:d,loadPaths:M,resetCanvas:E,setEraseMode:W,handlePointerDown:$,handlePointerMove:U,handlePointerUp:F}=Dt({strokeColor:i,strokeWidth:f,eraserWidth:S,eraserMode:p,withTimestamp:T,onChange:L,onStroke:R});return Nt(t,{canvasRef:G,currentPaths:X,withTimestamp:T,setEraseMode:W,undo:Z,redo:m,clearCanvas:d,loadPaths:M,resetCanvas:E}),(0,Wt.jsx)($e,{ref:G,id:r,width:n,height:o,className:a,canvasColor:s,backgroundImage:c,exportWithBackgroundImage:u,preserveBackgroundImageAspectRatio:P,allowOnlyPointerType:h,style:C,svgStyle:w,paths:X,isDrawing:Q,onPointerDown:$,onPointerMove:U,onPointerUp:F,withViewBox:O,readOnly:b,touchAction:A})});Hr.displayName="@react-sketch-canvas/ReactSketchCanvas";})();
/*! Bundled license information:
react/cjs/react.production.js:
(**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.js:
(**
* @license React
* react-jsx-runtime.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
*/