f1ow 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/README.md +32 -8
  2. package/dist/f1ow.js +4327 -3447
  3. package/dist/f1ow.umd.cjs +252 -7
  4. package/package.json +99 -94
package/dist/f1ow.umd.cjs CHANGED
@@ -1,11 +1,256 @@
1
- (function(x,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react/jsx-runtime"),require("react"),require("react-konva"),require("konva"),require("zustand"),require("nanoid"),require("react-dom"),require("lucide-react"),require("rbush"),require("yjs"),require("y-websocket")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-konva","konva","zustand","nanoid","react-dom","lucide-react","rbush","yjs","y-websocket"],g):(x=typeof globalThis<"u"?globalThis:x||self,g(x.FlowCanvas={},x.jsxRuntime,x.React,x.ReactKonva,x.Konva,x.zustand,x.nanoid,x.ReactDOM,x.LucideReact,x.RBush,x.Y,x.yWebsocket))})(this,(function(x,g,I,gt,qe,ws,ji,xs,It,Qi,qi,ks){"use strict";var ku=Object.defineProperty;var Su=(x,g,I)=>g in x?ku(x,g,{enumerable:!0,configurable:!0,writable:!0,value:I}):x[g]=I;var ct=(x,g,I)=>Su(x,typeof g!="symbol"?g+"":g,I);var qt=typeof document<"u"?document.currentScript:null;function tl(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Kt=tl(qi),wn={strokeColor:"#1e1e1e",fillColor:"transparent",strokeWidth:2,opacity:1,strokeStyle:"solid",roughness:0,fontSize:20,fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",freehandStyle:"standard"},tn=["#1a1a1a","#868e96","#b197fc","#7048e8","#4263eb","#f59f00","#e8590c","#2f9e44","#40c057","#f06595","#e03131"],en=["transparent","#e9ecef","#f3f0ff","#e5dbff","#edf2ff","#fff3bf","#ffe8cc","#d3f9d8","#ebfbee","#fcc2d7","#ffe3e3"],el=[1,2,3,4,6],co=[{type:"hand",label:"Hand (Pan)",shortcut:"H",icon:"Hand"},{type:"select",label:"Select",shortcut:"V",icon:"MousePointer2"},{type:"rectangle",label:"Rectangle",shortcut:"R",icon:"Square"},{type:"ellipse",label:"Ellipse",shortcut:"O",icon:"Circle"},{type:"diamond",label:"Diamond",shortcut:"D",icon:"Diamond"},{type:"line",label:"Line",shortcut:"L",icon:"Minus"},{type:"arrow",label:"Arrow",shortcut:"A",icon:"ArrowUpRight"},{type:"freedraw",label:"Pencil",shortcut:"P",icon:"Pencil"},{type:"text",label:"Text",shortcut:"T",icon:"Type"},{type:"image",label:"Image",shortcut:"I",icon:"ImageIcon"},{type:"eraser",label:"Eraser",shortcut:"E",icon:"Eraser"}],Xe=.1,Le=5,nl=[12,16,20,24,28,36,48,64],ol=[{label:"Sans-serif",value:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif"},{label:"Serif",value:"Georgia, Cambria, Times New Roman, Times, serif"},{label:"Monospace",value:"SF Mono, Menlo, Consolas, Liberation Mono, monospace"},{label:"Hand-drawn",value:"Segoe Print, Comic Sans MS, cursive"}],Tt={color:"#4f8df7",blur:6,opacity:.5},xe=20,sl=[{value:"standard",label:"Standard"},{value:"pen",label:"Pen"},{value:"pencil",label:"Pencil"},{value:"brush",label:"Brush"}],ao=[{type:null,label:"None",preview:"—"},{type:"arrow",label:"Arrow",preview:"▷"},{type:"triangle",label:"Triangle",preview:"▶"},{type:"triangle_outline",label:"Triangle Outline",preview:"△"},{type:"circle",label:"Circle",preview:"●"},{type:"circle_outline",label:"Circle Outline",preview:"○"},{type:"diamond",label:"Diamond",preview:"◆"},{type:"diamond_outline",label:"Diamond Outline",preview:"◇"},{type:"bar",label:"Bar",preview:"|"},{type:"crowfoot_one",label:"One",preview:"||"},{type:"crowfoot_many",label:"Many",preview:">|"},{type:"crowfoot_one_or_many",label:"One or Many",preview:">||"}],uo=[{type:"sharp",label:"Sharp",preview:"╱"},{type:"curved",label:"Curved",preview:"∿"},{type:"elbow",label:"Elbow",preview:"⌐"}],Ss=[{value:0,label:"Architect"},{value:1,label:"Artist"},{value:2,label:"Cartoonist"}],vs=20,Es=25,rl=36,Fe=40,Ws=1e4;function xn(t){switch(t){case"up":return{x:0,y:-1};case"down":return{x:0,y:1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}}function kn(t){return t==="up"||t==="down"}function Sn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=(t.width||1)/2,l=(t.height||1)/2,a=Math.abs(s)/i,c=Math.abs(r)/l;return a>c*3?s>=0?"right":"left":(c>a*3,r>=0?"down":"up")}function go(t){const[e,n]=t,o=n,s=1-n,r=e,i=1-e,l=Math.min(o,s,r,i);return l===o?"up":l===s?"down":l===r?"left":"right"}function nn(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>=Math.abs(o)?n>=0?"right":"left":o>=0?"down":"up"}function ho(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=t.width/2||1,l=t.height/2||1,a=s/i,c=r/l;return Math.abs(a)>=Math.abs(c)?s>=0?"right":"left":r>=0?"down":"up"}function il(t,e){const n=Math.abs(e.y-t.y),o=Math.abs(e.y-(t.y+t.height)),s=Math.abs(e.x-t.x),r=Math.abs(e.x-(t.x+t.width)),i=Math.min(n,o,s,r);return i===n?"up":i===o?"down":i===s?"left":"right"}function te(t){return t.left+t.width}function ee(t){return t.top+t.height}function ll(t,e){return e.x>t.left&&e.x<te(t)&&e.y>t.top&&e.y<ee(t)}function Ve(t,e,n){return{left:t.left-e,top:t.top-n,width:t.width+e*2,height:t.height+n*2}}function Ts(t,e,n){const o=Math.min(e,Es),s=n==="left"?o:e,r=n==="right"?o:e,i=n==="up"?o:e,l=n==="down"?o:e;return{left:t.left-s,top:t.top-i,width:t.width+s+r,height:t.height+i+l}}function Bs(t,e,n){const o=new Set(n),s=Math.min(e,Es),r=o.has("left")?s:e,i=o.has("right")?s:e,l=o.has("up")?s:e,a=o.has("down")?s:e;return{left:t.left-r,top:t.top-l,width:t.width+r+i,height:t.height+l+a}}function cl(t,e){const n=Math.min(t.left,e.left),o=Math.min(t.top,e.top),s=Math.max(te(t),te(e)),r=Math.max(ee(t),ee(e));return{left:n,top:o,width:s-n,height:r-o}}function fo(t){return{left:t.x,top:t.y,width:t.width,height:t.height}}function po(t){const e=t.rotation||0;if(e===0)return{x:t.x,y:t.y,width:t.width,height:t.height};const n=t.x+t.width/2,o=t.y+t.height/2,s=t.width/2,r=t.height/2,i=e*Math.PI/180,l=Math.cos(i),a=Math.sin(i),c=[{x:-s,y:-r},{x:s,y:-r},{x:s,y:r},{x:-s,y:r}].map(p=>({x:n+p.x*l-p.y*a,y:o+p.x*a+p.y*l}));let d=1/0,h=1/0,u=-1/0,f=-1/0;for(const p of c)p.x<d&&(d=p.x),p.y<h&&(h=p.y),p.x>u&&(u=p.x),p.y>f&&(f=p.y);return{x:d,y:h,width:u-d,height:f-h}}function al(t){switch(t){case"left":return"right";case"right":return"left";case"up":return"down";case"down":return"up"}}function dl(t,e){return e.x<t.x?"left":e.x>t.x?"right":e.y<t.y?"up":e.y>t.y?"down":null}function ul(t,e){return t===null||e===null?!1:(t==="left"||t==="right"?"h":"v")!==(e==="left"||e==="right"?"h":"v")}class gl{constructor(e){ct(this,"adjacent",new Map);this.pt=e}}class hl{constructor(){ct(this,"idx",{})}add(e){const n=String(e.x),o=String(e.y);n in this.idx||(this.idx[n]={}),o in this.idx[n]||(this.idx[n][o]=new gl(e))}get(e){var s;const n=String(e.x),o=String(e.y);return((s=this.idx[n])==null?void 0:s[o])??null}has(e){return this.get(e)!==null}connect(e,n){const o=this.get(e),s=this.get(n);if(!o||!s)return;const r=Math.abs(n.x-e.x)+Math.abs(n.y-e.y);o.adjacent.set(s,r),s.adjacent.set(o,r)}}class fl{constructor(){ct(this,"data",[])}get size(){return this.data.length}push(e,n){this.data.push({item:e,priority:n}),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;const e=this.data[0],n=this.data.pop();return this.data.length>0&&(this.data[0]=n,this.sinkDown(0)),e.item}bubbleUp(e){for(;e>0;){const n=e-1>>1;if(this.data[n].priority<=this.data[e].priority)break;[this.data[n],this.data[e]]=[this.data[e],this.data[n]],e=n}}sinkDown(e){const n=this.data.length;for(;;){let o=e;const s=2*e+1,r=2*e+2;if(s<n&&this.data[s].priority<this.data[o].priority&&(o=s),r<n&&this.data[r].priority<this.data[o].priority&&(o=r),o===e)break;[this.data[o],this.data[e]]=[this.data[e],this.data[o]],e=o}}}function pl(t,e,n){const o=t.get(e),s=t.get(n);if(!o||!s)return null;const r=u=>Math.abs(u.x-n.x)+Math.abs(u.y-n.y),i=(u,f)=>`${u.pt.x},${u.pt.y},${f??"n"}`,l=new Map,a=new Map,c=new fl,d={node:o,dir:null,g:0},h=i(o,null);for(l.set(h,0),a.set(h,null),c.push(d,r(o.pt));c.size>0;){const u=c.pop(),f=i(u.node,u.dir);if(!(u.g>(l.get(f)??1/0))){if(u.node===s){const p=[];let y=u;for(;y;){p.push(y.node.pt);const m=i(y.node,y.dir);if(y=a.get(m),y==null)break}return p[p.length-1]!==o.pt&&p.push(o.pt),p.reverse(),p}for(const[p,y]of u.node.adjacent){const m=dl(u.node.pt,p.pt);if(m===null)continue;const W=u.dir!==null&&m===al(u.dir),v=ul(u.dir,m),D=W?Ws*3:v?Ws:0,$=u.g+y+D,T=i(p,m);$<(l.get(T)??1/0)&&(l.set(T,$),a.set(T,u),c.push({node:p,dir:m,g:$},$+r(p.pt)))}}}return null}function yl(t){const e=new Map,n=[];for(const o of t){let s=e.get(o.x);s||(s=new Set,e.set(o.x,s)),s.has(o.y)||(s.add(o.y),n.push(o))}return n}function Il(t,e,n,o){const s=n.left,r=te(n),i=n.top,l=ee(n),a=[...new Set([s,...t.filter(u=>u>=s&&u<=r),r])].sort((u,f)=>u-f),c=[...new Set([i,...e.filter(u=>u>=i&&u<=l),l])].sort((u,f)=>u-f),d=u=>o.some(f=>ll(f,u)),h=[];for(const u of c)for(const f of a){const p={x:f,y:u};d(p)||h.push(p)}return h}function Zs(t,e,n){if(t.y===e.y){const o=t.y,s=Math.min(t.x,e.x),r=Math.max(t.x,e.x);for(const i of n)if(i.top<o&&o<ee(i)&&i.left<r&&te(i)>s)return!0}else if(t.x===e.x){const o=t.x,s=Math.min(t.y,e.y),r=Math.max(t.y,e.y);for(const i of n)if(i.left<o&&o<te(i)&&i.top<r&&ee(i)>s)return!0}return!1}function Cl(t,e){const n=new hl,o=new Set,s=new Set;for(const l of t)n.add(l),o.add(l.x),s.add(l.y);const r=[...o].sort((l,a)=>l-a),i=[...s].sort((l,a)=>l-a);for(let l=0;l<i.length;l++)for(let a=0;a<r.length;a++){const c={x:r[a],y:i[l]};if(n.has(c)){for(let d=a-1;d>=0;d--){const h={x:r[d],y:i[l]};if(n.has(h)){Zs(h,c,e)||n.connect(h,c);break}}for(let d=l-1;d>=0;d--){const h={x:r[a],y:i[d]};if(n.has(h)){Zs(h,c,e)||n.connect(h,c);break}}}}return n}function _s(t){if(t.length<=2)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;i||l||o.x===s.x&&o.y===s.y||e.push(s)}return e.push(t[t.length-1]),e}function Ms(t){if(t.length<=2)return 0;let e=0;for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;!i&&!l&&e++}return e}function Gs(t){let e=0;for(let n=1;n<t.length;n++)e+=Math.abs(t[n].x-t[n-1].x)+Math.abs(t[n].y-t[n-1].y);return e}function bl(t){let e=t[0],n=Ms(e),o=Gs(e);for(let s=1;s<t.length;s++){const r=Ms(t[s]),i=Gs(t[s]);(r<n||r===n&&i<o)&&(e=t[s],n=r,o=i)}return e}function yo(t,e,n,o,s,r){let i={left:Math.min(t.x,e.x),top:Math.min(t.y,e.y),width:Math.abs(e.x-t.x)||1,height:Math.abs(e.y-t.y)||1};for(const W of s)i=cl(i,W);i=Ve(i,Fe,Fe);const l=[],a=[];for(const W of s)l.push(W.left,te(W)),a.push(W.top,ee(W)),l.push(W.left+W.width/2),a.push(W.top+W.height/2);l.push(t.x,e.x),a.push(t.y,e.y);const c=xn(n),d=xn(o);let h={x:t.x+c.x*r,y:t.y+c.y*r},u={x:e.x+d.x*r,y:e.y+d.y*r};h=Xs(h,n,s),u=Xs(u,o,s),l.push(h.x,u.x),a.push(h.y,u.y),l.push((t.x+e.x)/2),a.push((t.y+e.y)/2);const f=Il(l,a,i,s),p=yl([h,u,...f]),y=Cl(p,s),m=pl(y,h,u);if(m){const W=[t,...m,e];return _s(W)}return null}function Ds(t,e,n,o,s,r,i,l){if(t.x===e.x&&t.y===e.y)return[t,e];const a=s?fo(s):{left:t.x,top:t.y,width:0,height:0},c=r?fo(r):{left:e.x,top:e.y,width:0,height:0},d=vs,h=Math.max(rl,i??0),u=(l??[]).map(O=>Ve(fo(O),d,d)),f=s?Ts(a,d,n):Ve(a,d,d),p=r?Ts(c,d,o):Ve(c,d,d),y=[n],m=[o];let W=!1;if(s){const O=ho(s,e);O!==n&&(y.push(O),W=!0)}if(r){const O=ho(r,t);O!==o&&(m.push(O),W=!0)}const v=s?Bs(a,d,y):Ve(a,d,d),D=r?Bs(c,d,m):Ve(c,d,d),$=[],T=yo(t,e,n,o,[f,p,...u],h);if(T&&$.push(T),W){const O=yo(t,e,n,o,[v,D,...u],h);O&&$.push(O)}if($.length>0)return bl($);if(u.length>0){const O=yo(t,e,n,o,[f,p],h);if(O)return O}return _s(ml(t,e,n,o,h))}function Xs(t,e,n){let{x:o,y:s}=t;for(let r=0;r<n.length;r++){let i=!0;for(const l of n)if(!(o<=l.left||o>=te(l)||s<=l.top||s>=ee(l)))switch(i=!1,e){case"left":o=l.left-1;break;case"right":o=te(l)+1;break;case"up":s=l.top-1;break;case"down":s=ee(l)+1;break}if(i)break}return{x:o,y:s}}function ml(t,e,n,o,s){const r=Math.max(s,vs),i=xn(n),l=xn(o),a={x:t.x+i.x*r,y:t.y+i.y*r},c={x:e.x+l.x*r,y:e.y+l.y*r};if(kn(n)===kn(o))if(kn(n)){const d=(a.y+c.y)/2;return[t,a,{x:a.x,y:d},{x:c.x,y:d},c,e]}else{const d=(a.x+c.x)/2;return[t,a,{x:d,y:a.y},{x:d,y:c.y},c,e]}else return kn(n)?[t,a,{x:a.x,y:c.y},c,e]:[t,a,{x:c.x,y:a.y},c,e]}const Al=new Set(["rectangle","ellipse","diamond","text","image"]),wl=256,Pe=new Map;function xl(t,e,n,o,s,r,i,l){const a=c=>Math.round(c*2)/2;return[a(t.x),a(t.y),a(e.x),a(e.y),n,o,s?`${a(s.x)},${a(s.y)},${a(s.width)},${a(s.height)}`:"n",r?`${a(r.x)},${a(r.y)},${a(r.width)},${a(r.height)}`:"n",i,l??0].join("|")}function kl(){Pe.clear()}function on(t,e,n,o,s,r){const i=new Map(s.map(F=>[F.id,F])),l=F=>!F.isPrecise||F.fixedPoint[0]===.5&&F.fixedPoint[1]===.5;let a;if(n)if(l(n)){const F=i.get(n.elementId);a=F?Sn(F,e):nn(t,e)}else a=go(n.fixedPoint);else a=nn(t,e);let c;if(o)if(l(o)){const F=i.get(o.elementId);c=F?Sn(F,t):nn(e,t)}else c=go(o.fixedPoint);else c=nn(e,t);const d=n?i.get(n.elementId)??null:null,h=o?i.get(o.elementId)??null:null,u=d?po(d):null,f=h?po(h):null,p=n==null?void 0:n.elementId,y=o==null?void 0:o.elementId,m=[],W=[],v=F=>Math.round(F*2)/2;for(const F of s){if(!Al.has(F.type)||F.id===p||F.id===y||!F.isVisible)continue;const J=po(F),Y=Math.min(t.x,e.x)-Fe*3,Q=Math.max(t.x,e.x)+Fe*3,M=Math.min(t.y,e.y)-Fe*3,k=Math.max(t.y,e.y)+Fe*3;J.x+J.width<Y||J.x>Q||J.y+J.height<M||J.y>k||(m.push(J),W.push(`${F.id}:${v(J.x)},${v(J.y)},${v(J.width)},${v(J.height)}`))}W.sort();const D=W.join(";"),$=xl(t,e,a,c,u,f,D,r),T=Pe.get($);if(T)return T;const O=Ds(t,e,a,c,u,f,r,m),ot=[];for(const F of O)ot.push(F.x-t.x,F.y-t.y);if(Pe.size>=wl){const F=Pe.keys().next().value;F!==void 0&&Pe.delete(F)}return Pe.set($,ot),ot}function sn(t){if(t.length<=4)return t;const e=[t[0],t[1]];for(let n=2;n<t.length-2;n+=2){const o=e[e.length-2],s=e[e.length-1],r=t[n],i=t[n+1],l=t[n+2],a=t[n+3];s===i&&i===a||o===r&&r===l||o===r&&s===i||e.push(r,i)}return e.push(t[t.length-2],t[t.length-1]),e}const Sl=new Set(["rectangle","ellipse","diamond","text","image"]);function Io(t){return Sl.has(t.type)}function Ls(t){return t*Math.PI/180}function Fs(t,e,n){if(n===0)return{x:t,y:e};const o=Math.cos(n),s=Math.sin(n);return{x:t*o-e*s,y:t*s+e*o}}function rn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=Ls(t.rotation||0);return i===0?{x:s,y:r}:Fs(s,r,-i)}function vn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=Ls(t.rotation||0),r=Fs(e.x,e.y,s);return{x:n+r.x,y:o+r.y}}function Vs(t){const{x:e,y:n,width:o,height:s}=t,r=e+o/2,i=n+s/2;return{top:{x:r,y:n},bottom:{x:r,y:n+s},left:{x:e,y:i},right:{x:e+o,y:i},center:{x:r,y:i}}}function vl(t,e){return Vs(t)[e]}const Ps=4;function ce(t){return Ps+t/2}function Ys(t,e){const n=t.width||1,o=t.height||1,s=rn(t,e),r=Math.max(0,Math.min(1,(s.x+n/2)/n)),i=Math.max(0,Math.min(1,(s.y+o/2)/o));return[r,i]}function ae(t,e,n=0){const o=(e[0]-.5)*t.width,s=(e[1]-.5)*t.height;if(o===0&&s===0)return vn(t,{x:0,y:0});const r=vn(t,{x:o,y:s});return de(t,r,n)}function de(t,e,n=0){const o=rn(t,e),s=o.x,r=o.y;if(s===0&&r===0)return vn(t,{x:0,y:-(t.height/2+n)});let i;switch(t.type){case"ellipse":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s);i={x:(l+n)*Math.cos(c),y:(a+n)*Math.sin(c)};break}case"diamond":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.cos(c),h=Math.sin(c),u=Math.abs(d),f=Math.abs(h),p=1/(u/l+f/a),y=p*d,m=p*h;if(n===0)i={x:y,y:m};else{const W=(d>=0?1:-1)/l,v=(h>=0?1:-1)/a,D=Math.sqrt(W*W+v*v);i={x:y+W/D*n,y:m+v/D*n}}break}default:{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.abs(Math.tan(c));let h,u;d<=a/l?(h=s>0?l:-l,u=h*Math.tan(c)):(u=r>0?a:-a,h=u/Math.tan(c)),n===0?i={x:h,y:u}:d<=a/l?i={x:h+(s>0?n:-n),y:u}:i={x:h,y:u+(r>0?n:-n)};break}}return vn(t,i)}const El=24,Wl=20,Hs=6;function Tl(t,e){const n=rn(t,e),o=t.width/2||1,s=t.height/2||1;switch(t.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)>=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(c-n.x,d-n.y)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s>=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(d-n.x,h-n.y)}default:{const r=o+n.x,i=o-n.x,l=s+n.y,a=s-n.y,c=Math.min(r,i,l,a);return c>0?c:0}}}function Bl(t,e){const n=rn(e,t),o=e.width/2,s=e.height/2;switch(e.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)<=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(n.x-c,n.y-d)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s<=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(n.x-d,n.y-h)}default:{const r=Math.max(-o-n.x,0,n.x-o),i=Math.max(-s-n.y,0,n.y-s);return Math.hypot(r,i)}}}function ke(t,e,n=El,o=new Set,s,r,i=Ps,l){let a=null,c=1/0;for(const d of e){if(!Io(d)||o.has(d.id))continue;const h=Bl(t,d);if(h>n)continue;const u=h===0,f=d.x+d.width/2,p=d.y+d.height/2,y=Math.hypot(f-t.x,p-t.y),m=u?-1e6+y:h*1e3+y;if(m<c){c=m;let W;if(r!==void 0)W=r;else if(h===0){const T=Math.min(d.width,d.height)/2,O=Math.min(Wl,T*.6),ot=Tl(d,t);l===!0?W=ot<=O+Hs:l===!1?W=ot<=Math.max(0,O-Hs):W=ot<=O}else W=!0;let v,D;if(W)v=Ys(d,t),D=ae(d,v,i);else{v=[.5,.5];const $=rn(d,t);Math.abs($.x)+Math.abs($.y)<2?D=s?de(d,s,i):de(d,{x:f+d.width,y:p},i):D=de(d,t,i)}a={elementId:d.id,fixedPoint:v,position:D,isPrecise:W}}}return a}function Se(t,e){const{startBinding:n,endBinding:o}=t;if(!n&&!o)return null;const s=new Map(e.map(v=>[v.id,v])),r=t.points,i=r.length/2;let l={x:t.x+r[0],y:t.y+r[1]},a={x:t.x+r[r.length-2],y:t.y+r[r.length-1]};const c=n?s.get(n.elementId):void 0,d=o?s.get(o.elementId):void 0,h=(v,D)=>v.isPrecise?ae(D,v.fixedPoint,0):{x:D.x+D.width/2,y:D.y+D.height/2},u=t.lineType==="elbow",f=(v,D,$)=>{const T=Sn(v,D),O=v.x+v.width/2,ot=v.y+v.height/2,F=Math.max(v.width,v.height)*10;let J;switch(T){case"up":J={x:O,y:ot-F};break;case"down":J={x:O,y:ot+F};break;case"left":J={x:O-F,y:ot};break;case"right":J={x:O+F,y:ot};break}return de(v,J,$)},p=u?(v,D,$)=>f(v,D,$):de;if(n&&c&&o&&d){if(n.isPrecise)l=ae(c,n.fixedPoint,n.gap);else{const v=h(o,d);l=p(c,v,n.gap)}if(o.isPrecise)a=ae(d,o.fixedPoint,o.gap);else{const v=h(n,c);a=p(d,v,o.gap)}n.isPrecise||(l=p(c,a,n.gap)),o.isPrecise||(a=p(d,l,o.gap))}else n&&c&&(n.isPrecise?l=ae(c,n.fixedPoint,n.gap):l=p(c,a,n.gap)),o&&d&&(o.isPrecise?a=ae(d,o.fixedPoint,o.gap):a=p(d,l,o.gap));const y=[0,0];for(let v=1;v<i-1;v++){const D=t.x+r[v*2],$=t.y+r[v*2+1];y.push(D-l.x,$-l.y)}y.push(a.x-l.x,a.y-l.y);const m=a.x-l.x,W=a.y-l.y;return{x:l.x,y:l.y,points:y,width:Math.abs(m),height:Math.abs(W)}}function ln(t,e){return e.filter(n=>{var s,r;if(n.type!=="line"&&n.type!=="arrow")return!1;const o=n;return((s=o.startBinding)==null?void 0:s.elementId)===t||((r=o.endBinding)==null?void 0:r.elementId)===t})}function Zl(t,e){return e.map(n=>{let o=!1;if(n.boundElements&&n.boundElements.length>0){const l=n.boundElements.filter(a=>!t.has(a.id));l.length!==n.boundElements.length&&(n={...n,boundElements:l.length>0?l:null},o=!0)}if(n.type!=="line"&&n.type!=="arrow")return n;const s=n;let r=s.startBinding,i=s.endBinding;return r&&t.has(r.elementId)&&(r=null,o=!0),i&&t.has(i.elementId)&&(i=null,o=!0),o?{...n,startBinding:r,endBinding:i}:n})}function Os(t,e){const n=t.boundElements??[];return n.some(o=>o.id===e.id)?t:{...t,boundElements:[...n,e]}}function Ns(t,e){const n=t.boundElements;if(!n||n.length===0)return t;const o=n.filter(s=>s.id!==e);return{...t,boundElements:o.length>0?o:null}}function ve(t,e,n,o,s,r){if(n&&n.elementId!==(o==null?void 0:o.elementId)){const i=s.find(l=>l.id===n.elementId);if(i){const l=Ns(i,t);l!==i&&r(i.id,{boundElements:l.boundElements})}}if(o&&o.elementId!==(n==null?void 0:n.elementId)){const i=s.find(l=>l.id===o.elementId);if(i){const l=Os(i,{id:t,type:e});l!==i&&r(i.id,{boundElements:l.boundElements})}}}function Pt(){return ji.nanoid(12)}function _l(t){const e={...t};return e.style&&(e.style={...e.style}),e.boundElements&&(e.boundElements=e.boundElements.map(n=>({...n}))),e.startBinding&&(e.startBinding={...e.startBinding}),e.endBinding&&(e.endBinding={...e.endBinding}),e.groupIds&&(e.groupIds=[...e.groupIds]),Array.isArray(e.points)&&(e.points=[...e.points]),Array.isArray(e.pressures)&&(e.pressures=[...e.pressures]),e.crop&&(e.crop={...e.crop}),e}function En(t,e,n=20){const o=new Set(t.map(d=>d.id)),s=new Set;for(const d of t)if(d.boundElements)for(const h of d.boundElements)h.type==="text"&&!o.has(h.id)&&s.add(h.id);const r=[...t,...e.filter(d=>s.has(d.id))],i=new Map;for(const d of r)i.set(d.id,Pt());const l=new Map;for(const d of r)if(d.groupIds)for(const h of d.groupIds)l.has(h)||l.set(h,Pt());const a=r.map(d=>{const h=i.get(d.id),u=_l(d);return u.id=h,u.x=d.x+n,u.y=d.y+n,u.containerId&&i.has(u.containerId)?u.containerId=i.get(u.containerId):u.containerId&&(u.containerId=null),u.boundElements&&(u.boundElements=u.boundElements.map(f=>i.has(f.id)?{...f,id:i.get(f.id)}:null).filter(Boolean),u.boundElements.length===0&&(u.boundElements=null)),u.startBinding&&i.has(u.startBinding.elementId)?u.startBinding={...u.startBinding,elementId:i.get(u.startBinding.elementId)}:u.startBinding&&(u.startBinding=null),u.endBinding&&i.has(u.endBinding.elementId)?u.endBinding={...u.endBinding,elementId:i.get(u.endBinding.elementId)}:u.endBinding&&(u.endBinding=null),u.groupIds&&u.groupIds.length>0&&(u.groupIds=u.groupIds.map(f=>l.get(f)??f)),u}),c=a.filter(d=>{var u;const h=(u=[...i.entries()].find(([,f])=>f===d.id))==null?void 0:u[0];return h?o.has(h):!1}).map(d=>d.id);return{clones:a,idMap:i,selectedCloneIds:c}}function Us(t,e){const n=new Set(t),o=new Set;for(const s of e)if(n.has(s.id)&&s.groupIds)for(const r of s.groupIds)o.add(r);if(o.size>0){for(const s of e)if(!n.has(s.id)&&s.groupIds){for(const r of s.groupIds)if(o.has(r)){n.add(s.id);break}}}for(const s of e)if(n.has(s.id)&&s.boundElements)for(const r of s.boundElements)r.type==="text"&&!n.has(r.id)&&n.add(r.id);return e.filter(s=>n.has(s.id))}function Ks(t,e,n,o=200){const{x:s,y:r,scale:i}=t,l=-s/i-o,a=-r/i-o,c=(-s+e)/i+o,d=(-r+n)/i+o;return{minX:l,minY:a,maxX:c,maxY:d}}function cn(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r}}if(t.type==="freedraw"&&"points"in t){if(t.isComplete===!1){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return n===1/0?{minX:t.x,minY:t.y,maxX:t.x+1,maxY:t.y+1}:{minX:n,minY:s,maxX:o,maxY:r}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}function zs(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Js(t,e,n,o,s,r){if(t.length<=100)return t;const i=Ks(e,n,o,r);return t.filter(l=>{if(s.has(l.id))return!0;const a=cn(l);return zs(i,a)})}function Ml(t){const e=new Map;for(const n of t)e.set(n.id,n);return e}function Gl(t){if(typeof structuredClone=="function"){const e=new Map,n=new Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s.type==="image"&&"src"in s){const r=s;e.has(r.id)||e.set(r.id,r.src);const{src:i,...l}=r,a=structuredClone(l);a.src=e.get(r.id),n[o]=a}else n[o]=structuredClone(s)}return n}return JSON.parse(JSON.stringify(t))}function $s(t){let e=null,n=null;const o=(...s)=>{n=s,e===null&&(e=requestAnimationFrame(()=>{e=null,n&&(t(...n),n=null)}))};return o.cancel=()=>{e!==null&&(cancelAnimationFrame(e),e=null),n=null},o}function Dl(t,e){if(e.length===0)return t;const n=new Map;for(const o of e){const s=n.get(o.id);n.set(o.id,s?{...s,...o.changes}:o.changes)}return t.map(o=>{const s=n.get(o.id);return s?{...o,...s}:o})}function Rs(t){return new Set(t)}const an=[.1,.25,.5,.75,1,1.5,2,3,4,5],js=280;function Wn({viewport:t,point:e,targetScale:n}){const o=Math.min(Le,Math.max(Xe,n)),s=(e.x-t.x)/t.scale,r=(e.y-t.y)/t.scale;return{scale:o,x:e.x-s*o,y:e.y-r*o}}function Qs(t){for(const e of an)if(e>t+.01)return e;return Le}function qs(t){for(let e=an.length-1;e>=0;e--)if(an[e]<t-.01)return an[e];return Xe}function Co(t){if(t.length===0)return null;let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const r of t){const i=cn(r);i.minX<e&&(e=i.minX),i.minY<n&&(n=i.minY),i.maxX>o&&(o=i.maxX),i.maxY>s&&(s=i.maxY)}return{minX:e,minY:n,maxX:o,maxY:s}}function bo(t,e,n,o={}){const s=o.padding??50,r=o.maxZoom??2,i=t.maxX-t.minX,l=t.maxY-t.minY;if(i===0&&l===0)return{scale:1,x:e/2-t.minX,y:n/2-t.minY};const a=(e-s*2)/(i||1),c=(n-s*2)/(l||1),d=Math.min(Math.min(a,c),r),h=Math.min(Le,Math.max(Xe,d)),u=(t.minX+t.maxX)/2,f=(t.minY+t.maxY)/2;return{scale:h,x:e/2-u*h,y:n/2-f*h}}function Xl(t){return 1-Math.pow(1-t,3)}let Yt=null;function Ee(t,e,n,o=js){Yt!==null&&(cancelAnimationFrame(Yt),Yt=null);const s=performance.now(),r=i=>{const l=i-s,a=Math.min(l/o,1),c=Xl(a),d={x:t.x+(e.x-t.x)*c,y:t.y+(e.y-t.y)*c,scale:t.scale+(e.scale-t.scale)*c};n(d),a<1?Yt=requestAnimationFrame(r):(Yt=null,n(e))};return Yt=requestAnimationFrame(r),()=>{Yt!==null&&(cancelAnimationFrame(Yt),Yt=null)}}function We(){Yt!==null&&(cancelAnimationFrame(Yt),Yt=null)}const Ll=100;function ue(t){if(t.type==="image"&&"src"in t){const{src:e,...n}=t,o=structuredClone(n);return o.src=e,o}return structuredClone(t)}const B=ws.create((t,e)=>({elements:[],selectedIds:[],activeTool:"select",currentStyle:{...wn},currentLineType:"sharp",currentStartArrowhead:null,currentEndArrowhead:"arrow",viewport:{x:0,y:0,scale:1},isDrawing:!1,drawStart:null,history:[],historyIndex:-1,_historyBaseline:new Map,_historyPaused:!1,showGrid:!1,addElement:n=>{t(o=>({elements:[...o.elements,n]})),e().pushHistory()},updateElement:(n,o)=>{t(s=>{const r=s.elements,i=r.findIndex(c=>c.id===n);if(i===-1)return s;const l={...r[i],...o};if(l===r[i])return s;const a=r.slice();return a[i]=l,{elements:a}})},batchUpdateElements:n=>{if(n.length!==0){if(n.length===1){e().updateElement(n[0].id,n[0].updates);return}t(o=>{const s=o.elements,r=new Map;for(let l=0;l<s.length;l++)r.set(s[l].id,l);let i=null;for(const{id:l,updates:a}of n){const c=r.get(l);if(c===void 0)continue;const d=i?i[c]:s[c],h={...d,...a};h!==d&&(i||(i=s.slice()),i[c]=h)}return i?{elements:i}:o})}},deleteElements:n=>{const o=new Set(n),{elements:s}=e();for(const r of s)if(o.has(r.id)&&r.boundElements)for(const i of r.boundElements)i.type==="text"&&o.add(i.id);for(const r of s)r.type==="text"&&"containerId"in r&&r.containerId&&o.has(r.containerId)&&o.add(r.id);t(r=>{const i=r.elements.filter(a=>!o.has(a.id));return{elements:Zl(o,i),selectedIds:r.selectedIds.filter(a=>!o.has(a))}}),e().pushHistory()},setElements:n=>{const o=new Map;for(const s of n)o.set(s.id,s);t({elements:n,_historyBaseline:o})},duplicateElements:n=>{const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),{clones:r,selectedCloneIds:i}=En(s,o);t(l=>({elements:[...l.elements,...r],selectedIds:i.length>0?i:r.map(a=>a.id)})),e().pushHistory()},convertElementType:(n,o)=>{const s=new Set(["rectangle","ellipse","diamond"]);s.has(o)&&(t(r=>({elements:r.elements.map(i=>{if(!n.includes(i.id)||!s.has(i.type)||i.type===o)return i;const l={...i,type:o};return o==="rectangle"?{...l,cornerRadius:0}:l})})),e().pushHistory())},bringToFront:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id)),r=o.elements.filter(i=>n.includes(i.id));return{elements:[...s,...r]}}),e().pushHistory()},sendToBack:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id));return{elements:[...o.elements.filter(i=>n.includes(i.id)),...s]}}),e().pushHistory()},bringForward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=s.length-2;i>=0;i--)r.has(s[i].id)&&!r.has(s[i+1].id)&&([s[i],s[i+1]]=[s[i+1],s[i]]);return{elements:s}}),e().pushHistory()},sendBackward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=1;i<s.length;i++)r.has(s[i].id)&&!r.has(s[i-1].id)&&([s[i],s[i-1]]=[s[i-1],s[i]]);return{elements:s}}),e().pushHistory()},toggleLockElements:n=>{t(o=>({elements:o.elements.map(s=>n.includes(s.id)?{...s,isLocked:!s.isLocked}:s)})),e().pushHistory()},groupElements:n=>{if(n.length<2)return;const o=Pt(),s=new Set(n),{elements:r}=e();for(const i of r)if(s.has(i.id)&&i.boundElements)for(const l of i.boundElements)l.type==="text"&&s.add(l.id);t(i=>({elements:i.elements.map(l=>s.has(l.id)?{...l,groupIds:[...l.groupIds??[],o]}:l)})),e().pushHistory()},ungroupElements:n=>{var i;const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),r=new Set;for(const l of s)(i=l.groupIds)!=null&&i.length&&r.add(l.groupIds[l.groupIds.length-1]);r.size!==0&&(t(l=>({elements:l.elements.map(a=>{var d;if(!((d=a.groupIds)!=null&&d.length))return a;const c=a.groupIds.filter(h=>!r.has(h));return{...a,groupIds:c.length>0?c:void 0}})})),e().pushHistory())},setSelectedIds:n=>t({selectedIds:n}),clearSelection:()=>t({selectedIds:[]}),setActiveTool:n=>t(o=>({activeTool:n,selectedIds:n==="select"?o.selectedIds:[]})),setCurrentStyle:n=>t(o=>({currentStyle:{...o.currentStyle,...n}})),setCurrentLineType:n=>t({currentLineType:n}),setCurrentStartArrowhead:n=>t({currentStartArrowhead:n}),setCurrentEndArrowhead:n=>t({currentEndArrowhead:n}),setViewport:n=>{We(),t(o=>({viewport:{...o.viewport,...n}}))},zoomIn:(n,o)=>{const{viewport:s}=e(),r=Qs(s.scale),l=Wn({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},zoomOut:(n,o)=>{const{viewport:s}=e(),r=qs(s.scale),l=Wn({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},resetZoom:n=>{const{viewport:o}=e(),s={x:0,y:0,scale:1};n!=null&&n.animate?Ee(o,s,r=>t(i=>({viewport:{...i.viewport,...r}}))):(We(),t({viewport:s}))},zoomToFit:(n,o,s,r)=>{const{elements:i,viewport:l}=e(),a=s?i.filter(h=>s.includes(h.id)):i,c=Co(a);if(!c)return;const d=bo(c,n,o,{padding:r==null?void 0:r.padding,maxZoom:r==null?void 0:r.maxZoom});r!=null&&r.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},zoomToSelection:(n,o,s)=>{const{elements:r,selectedIds:i,viewport:l}=e();if(i.length===0)return;const a=r.filter(h=>i.includes(h.id)),c=Co(a);if(!c)return;const d=bo(c,n,o,{padding:(s==null?void 0:s.padding)??80,maxZoom:(s==null?void 0:s.maxZoom)??2});s!=null&&s.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},setIsDrawing:n=>t({isDrawing:n}),setDrawStart:n=>t({drawStart:n}),pushHistory:n=>{const{elements:o,_historyBaseline:s,_historyPaused:r}=e();if(r)return;const i=[],l=new Map;for(const a of o)l.set(a.id,a);for(const a of o){const c=s.get(a.id);c?c!==a&&i.push({type:"modify",elementId:a.id,before:ue(c),after:ue(a)}):i.push({type:"add",elementId:a.id,after:ue(a)})}for(const[a,c]of s)l.has(a)||i.push({type:"delete",elementId:a,before:ue(c)});i.length!==0&&t(a=>{const c=a.history.slice(0,a.historyIndex+1);return c.push({diffs:i,mark:n,timestamp:Date.now()}),c.length>Ll&&c.shift(),{history:c,historyIndex:c.length-1,_historyBaseline:new Map(l)}})},undo:()=>{const{historyIndex:n,history:o}=e();if(n<0)return;const s=o[n];t(r=>{let i=[...r.elements];for(let a=s.diffs.length-1;a>=0;a--){const c=s.diffs[a];switch(c.type){case"add":i=i.filter(d=>d.id!==c.elementId);break;case"modify":i=i.map(d=>d.id===c.elementId?ue(c.before):d);break;case"delete":i.push(ue(c.before));break}}const l=new Map;for(const a of i)l.set(a.id,a);return{historyIndex:n-1,elements:i,selectedIds:[],_historyBaseline:l}})},redo:()=>{const{historyIndex:n,history:o}=e();if(n>=o.length-1)return;const s=n+1,r=o[s];t(i=>{let l=[...i.elements];for(const c of r.diffs)switch(c.type){case"add":l.push(ue(c.after));break;case"modify":l=l.map(d=>d.id===c.elementId?ue(c.after):d);break;case"delete":l=l.filter(d=>d.id!==c.elementId);break}const a=new Map;for(const c of l)a.set(c.id,c);return{historyIndex:s,elements:l,selectedIds:[],_historyBaseline:a}})},squashHistory:(n=2)=>{t(o=>{if(o.history.length<n)return o;const s=Math.max(0,o.history.length-n),r=o.history.slice(s),i=new Map;for(const c of r)for(const d of c.diffs){const h=i.get(d.elementId);h?d.type==="delete"?h.type==="add"?i.delete(d.elementId):i.set(d.elementId,{type:"delete",elementId:d.elementId,before:h.before}):d.type==="modify"&&i.set(d.elementId,{type:h.type==="add"?"add":"modify",elementId:d.elementId,before:h.before,after:d.after}):i.set(d.elementId,{...d})}const l={diffs:Array.from(i.values()),mark:r[r.length-1].mark,timestamp:Date.now()},a=[...o.history.slice(0,s),l];return{history:a,historyIndex:a.length-1}})},pauseHistory:()=>t({_historyPaused:!0}),resumeHistory:()=>t({_historyPaused:!1}),canUndo:()=>e().historyIndex>=0,canRedo:()=>{const{historyIndex:n,history:o}=e();return n<o.length-1},toggleGrid:()=>t(n=>({showGrid:!n.showGrid}))})),mo={elementId:null,isEditing:!1,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1},dn=ws.create(t=>({...mo,enterEditMode:e=>t({elementId:e,isEditing:!0,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1}),exitEditMode:()=>t({...mo}),setSelectedPoints:e=>t({selectedPointIndices:e}),togglePointSelection:e=>t(n=>({selectedPointIndices:n.selectedPointIndices.includes(e)?n.selectedPointIndices.filter(s=>s!==e):[...n.selectedPointIndices,e]})),setHoveredPoint:e=>t({hoveredPointIndex:e}),setHoveredMidpoint:e=>t({hoveredMidpointIndex:e}),setIsDraggingPoint:e=>t({isDraggingPoint:e}),reset:()=>t({...mo})}));function At(t,e){return Math.round(t/e)*e}function Fl(t,e){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Ao(t,e){return{x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)}}function tr(t,e,n){const o=Math.cos(n),s=Math.sin(n),r=t.x-e.x,i=t.y-e.y;return{x:e.x+r*o-i*s,y:e.y+r*s+i*o}}function Vl(t,e){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function un(t,e){return[t/2,0,t,e/2,t/2,e,0,e/2]}function Pl(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.max(Math.abs(n),Math.abs(o)),r=n>=0?1:-1,i=o>=0?1:-1,l=r>=0?t.x:t.x-s,a=i>=0?t.y:t.y-s;return{x:l,y:a,width:s,height:s}}const er=[0,45,90,135,180,225,270,315,360],Yl=Math.PI/180;function Hl(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.sqrt(n*n+o*o);if(s===0)return{...e};let r=Math.atan2(o,n)*180/Math.PI;r<0&&(r+=360);let i=er[0],l=999;for(const c of er){const d=Math.abs(r-c);d<l&&(l=d,i=c)}i===360&&(i=0);const a=i*Yl;return{x:t.x+s*Math.cos(a),y:t.y+s*Math.sin(a)}}function Tn(t){let e=0,n=0,o=0,s=0;for(let r=0;r<t.length;r+=2)e=Math.min(e,t[r]),n=Math.max(n,t[r]),o=Math.min(o,t[r+1]),s=Math.max(s,t[r+1]);return{width:n-e,height:s-o}}function _t(t,e){switch(t){case"dashed":return[e*4,e*4];case"dotted":return[e,e*2];case"solid":default:return[]}}const zt=.2;function Jt(t,e,n=zt){const o=(t.x+e.x)/2,s=(t.y+e.y)/2,r=e.x-t.x,i=e.y-t.y,l=Math.sqrt(r*r+i*i);if(l===0)return{x:o,y:s};const a=-i/l,c=r/l,d=l*n;return{x:o+a*d,y:s+c*d}}function Ye(t,e,n,o){const s=1-o;return{x:s*s*t.x+2*s*o*e.x+o*o*n.x,y:s*s*t.y+2*s*o*e.y+o*o*n.y}}function wo(t,e,n,o){const s=1-o;return{x:2*s*(e.x-t.x)+2*o*(n.x-e.x),y:2*s*(e.y-t.y)+2*o*(n.y-e.y)}}function xo(t,e,n,o){if(o){const s=wo(t,e,n,1),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:n.x-s.x/r*20,y:n.y-s.y/r*20}}else{const s=wo(t,e,n,0),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:t.x+s.x/r*20,y:t.y+s.y/r*20}}}function nr(t,e,n){const o=e.x-t.x,s=e.y-t.y,r=Math.sqrt(o*o+s*s);if(r===0)return zt;const i=-s/r,l=o/r,a=(t.x+e.x)/2,c=(t.y+e.y)/2,d=n.x-a,h=n.y-c;return 2*(d*i+h*l)/r}const Ol={name:"select",onMouseDown(t,e,n){t.target===t.target.getStage()&&(n.linearEdit.isEditing&&n.linearEdit.exitEditMode(),n.clearSelection(),n.setIsDrawing(!0),n.setDrawStart(e),n.setSelectionBox({x:e.x,y:e.y,width:0,height:0}))},onMouseMove(t,e,n){!n.isDrawing||!n.drawStart||n.setSelectionBox(Ao(n.drawStart,e))},onMouseUp(t){if(!t.isDrawing)return;const e=t.selectionBox;if(e&&(e.width>2||e.height>2)){const n=t.elements.filter(r=>{let i=r.x,l=r.y,a=r.width,c=r.height;if((r.type==="arrow"||r.type==="line")&&"points"in r){const p=r.points,y=[],m=[];for(let W=0;W<p.length;W+=2)y.push(r.x+p[W]),m.push(r.y+p[W+1]);i=Math.min(...y),l=Math.min(...m),a=Math.max(...y)-i,c=Math.max(...m)-l}const d=i+a,h=l+c,u=e.x+e.width,f=e.y+e.height;return i<u&&d>e.x&&l<f&&h>e.y}).map(r=>r.id),o=new Set(n),s=new Set;for(const r of n){const i=t.elements.find(l=>l.id===r);if(i!=null&&i.groupIds)for(const l of i.groupIds)s.add(l)}if(s.size>0){for(const r of t.elements)if(!o.has(r.id)&&r.groupIds){for(const i of r.groupIds)if(s.has(i)){o.add(r.id);break}}}t.setSelectedIds([...o])}t.setSelectionBox(null),t.setIsDrawing(!1),t.setDrawStart(null)}};let ko=!1;const Nl={name:"eraser",onMouseDown(t,e,n){var s;ko=!0;const o=t.target.id();o&&(n.deleteElements([o]),(s=n.onElementDelete)==null||s.call(n,[o]))},onMouseMove(t,e,n){var r,i;if(!ko)return;const o=t.target,s=(r=o.id)==null?void 0:r.call(o);s&&o!==o.getStage()&&(n.deleteElements([s]),(i=n.onElementDelete)==null||i.call(n,[s]))},onMouseUp(t){ko=!1},getCursor(){return"not-allowed"}},So={name:"rectangle",onMouseDown(t,e,n){var l;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt();n.currentElementIdRef.current=s;const r={id:s,type:n.activeTool,x:o.x,y:o.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null},i=n.activeTool==="rectangle"?{...r,type:"rectangle",cornerRadius:0}:r;B.getState().pauseHistory(),n.addElement(i),(l=n.onElementCreate)==null||l.call(n,i)},onMouseMove(t,e,n){if(!n.isDrawing||!n.drawStart||!n.currentElementIdRef.current)return;const o=n.snapPos(e),s=n.shiftKeyRef.current?Pl(n.drawStart,o):Ao(n.drawStart,o);n.updateElement(n.currentElementIdRef.current,s)},onMouseUp(t){B.getState().resumeHistory(),t.currentElementIdRef.current&&(t.setSelectedIds([t.currentElementIdRef.current]),t.pushHistory()),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},{PI:Ul}=Math,Kl=.275,gn=Ul+1e-4,or=13,zl=29,Jl=13,$l=3,Rl=.15,jl=.85,Ql=.01,ql=.25,sr=.5,rr=[1,1];function tc(t){return[-t[0],-t[1]]}function $t(t,e){return[t[0]+e[0],t[1]+e[1]]}function ir(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function ge(t,e){return[t[0]-e[0],t[1]-e[1]]}function vo(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function he(t,e){return[t[0]*e,t[1]*e]}function Eo(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function ec(t,e){return[t[0]/e,t[1]/e]}function lr(t){return[t[1],-t[0]]}function Wo(t,e){const n=e[0];return t[0]=e[1],t[1]=-n,t}function cr(t,e){return t[0]*e[0]+t[1]*e[1]}function nc(t,e){return t[0]===e[0]&&t[1]===e[1]}function oc(t){return Math.hypot(t[0],t[1])}function ar(t,e){const n=t[0]-e[0],o=t[1]-e[1];return n*n+o*o}function dr(t){return ec(t,oc(t))}function sc(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function To(t,e,n){const o=Math.sin(n),s=Math.cos(n),r=t[0]-e[0],i=t[1]-e[1];return[r*s-i*o+e[0],r*o+i*s+e[1]]}function ur(t,e,n,o){const s=Math.sin(o),r=Math.cos(o),i=e[0]-n[0],l=e[1]-n[1];return t[0]=i*r-l*s+n[0],t[1]=i*s+l*r+n[1],t}function gr(t,e,n){return $t(t,he(ge(e,t),n))}function rc(t,e,n,o){return t[0]=e[0]+(n[0]-e[0])*o,t[1]=e[1]+(n[1]-e[1])*o,t}function hr(t,e,n){return $t(t,he(e,n))}function fr(t,e,n){const o=Math.min(1,e/n),s=Math.min(1,1-o);return Math.min(1,t+(s-t)*(o*Kl))}function pr(t,e,n,o=s=>s){return t*o(.5-e*(.5-n))}const yr=[0,0];function Ir(t){return t!=null&&t>=0}function ic(t,e={}){var u;const{streamline:n=.5,size:o=16,last:s=!1}=e;if(t.length===0)return[];const r=Rl+(1-n)*jl;let i=t.map(({x:f,y:p,pressure:y=sr})=>[f,p,y]);if(i.length===2){const f=i[1];i=i.slice(0,-1);for(let p=1;p<5;p++)i.push([...gr(i[0],f,p/4)])}i.length===1&&(i=[...i,[...$t(i[0],rr),...i[0].slice(2)]]);const l=[{point:[i[0][0],i[0][1]],pressure:Ir(i[0][2])?i[0][2]:ql,vector:[...rr],distance:0,runningLength:0}];let a=!1,c=0,d=l[0];const h=i.length-1;for(let f=1;f<i.length;f++){const p=s&&f===h?[i[f][0],i[f][1]]:gr(d.point,i[f],r);if(nc(d.point,p))continue;const y=sc(p,d.point);if(c+=y,f<h&&!a){if(c<o)continue;a=!0}vo(yr,d.point,p),d={point:p,pressure:Ir(i[f][2])?i[f][2]:sr,vector:dr(yr),distance:y,runningLength:c},l.push(d)}return l[0].vector=((u=l[1])==null?void 0:u.vector)||[0,0],l}const Zt=[0,0],fe=[0,0],pe=[0,0];function lc(t,e){const n=$t(t,[1,1]),o=hr(t,dr(lr(ge(t,n))),-e),s=[],r=1/or;for(let i=r;i<=1;i+=r)s.push(To(o,t,gn*2*i));return s}function cc(t,e,n){const o=[],s=1/n;for(let r=s;r<=1;r+=s)o.push(To(e,t,gn*r));return o}function ac(t,e,n){const o=ge(e,n),s=he(o,.5),r=he(o,.51);return[ge(t,s),ge(t,r),$t(t,r),$t(t,s)]}function dc(t,e,n,o){const s=[],r=hr(t,e,n),i=1/o;for(let l=i;l<1;l+=i)s.push(To(r,t,gn*3*l));return s}function uc(t,e,n){return[$t(t,he(e,n)),$t(t,he(e,n*.99)),ge(t,he(e,n*.99)),ge(t,he(e,n))]}function Cr(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function gc(t,e,n){return t.slice(0,10).reduce((o,s)=>{let r=s.pressure;return e&&(r=fr(o,s.distance,n)),(o+r)/2},t[0].pressure)}function hc(t,e={}){const{size:n=16,smoothing:o=.5,thinning:s=.5,simulatePressure:r=!0,easing:i=Z=>Z,start:l={},end:a={},last:c=!1}=e,{cap:d=!0,easing:h=Z=>Z*(2-Z)}=l,{cap:u=!0,easing:f=Z=>--Z*Z*Z+1}=a;if(t.length===0||n<=0)return[];const p=t[t.length-1].runningLength,y=Cr(l.taper,n,p),m=Cr(a.taper,n,p),W=Math.pow(n*o,2),v=[],D=[];let $=gc(t,r,n),T=pr(n,s,t[t.length-1].pressure,i),O,ot=t[0].vector,F=t[0].point,J=F,Y=F,Q=J,M=!1;for(let Z=0;Z<t.length;Z++){let{pressure:G}=t[Z];const{point:U,vector:X,distance:L,runningLength:at}=t[Z],tt=Z===t.length-1;if(!tt&&p-at<$l)continue;s?(r&&(G=fr($,L,n)),T=pr(n,s,G,i)):T=n/2,O===void 0&&(O=T);const E=at<y?h(at/y):1,V=p-at<m?f((p-at)/m):1;T=Math.max(Ql,T*Math.min(E,V));const dt=(tt?t[Z]:t[Z+1]).vector,R=tt?1:cr(X,dt),et=cr(X,ot)<0&&!M,Ct=R!==null&&R<0;if(et||Ct){Wo(Zt,ot),Eo(Zt,Zt,T);const bt=1/Jl;for(let rt=0;rt<=1;rt+=bt)vo(fe,U,Zt),ur(fe,fe,U,gn*rt),Y=[fe[0],fe[1]],v.push(Y),ir(pe,U,Zt),ur(pe,pe,U,gn*-rt),Q=[pe[0],pe[1]],D.push(Q);F=Y,J=Q,Ct&&(M=!0);continue}if(M=!1,tt){Wo(Zt,X),Eo(Zt,Zt,T),v.push(ge(U,Zt)),D.push($t(U,Zt));continue}rc(Zt,dt,X,R),Wo(Zt,Zt),Eo(Zt,Zt,T),vo(fe,U,Zt),Y=[fe[0],fe[1]],(Z<=1||ar(F,Y)>W)&&(v.push(Y),F=Y),ir(pe,U,Zt),Q=[pe[0],pe[1]],(Z<=1||ar(J,Q)>W)&&(D.push(Q),J=Q),$=G,ot=X}const k=[t[0].point[0],t[0].point[1]],C=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:$t(t[0].point,[1,1]),w=[],S=[];if(t.length===1){if(!(y||m)||c)return lc(k,O||T)}else{y||m&&t.length===1||(d?w.push(...cc(k,D[0],or)):w.push(...ac(k,v[0],D[0])));const Z=lr(tc(t[t.length-1].vector));m||y&&t.length===1?S.push(C):u?S.push(...dc(C,Z,T,zl)):S.push(...uc(C,Z,T))}return v.concat(S,D.reverse(),w)}function fc(t,e={}){return hc(ic(t,e),e)}const Bn=(t,e)=>(t+e)/2;function pc(t,e=!0){const n=t.length;if(n<4)return"";let o=t[0],s=t[1];const r=t[2];let i=`M${o[0].toFixed(2)},${o[1].toFixed(2)} Q${s[0].toFixed(2)},${s[1].toFixed(2)} ${Bn(s[0],r[0]).toFixed(2)},${Bn(s[1],r[1]).toFixed(2)} T`;for(let l=2,a=n-1;l<a;l++)o=t[l],s=t[l+1],i+=`${Bn(o[0],s[0]).toFixed(2)},${Bn(o[1],s[1]).toFixed(2)} `;return e&&(i+="Z"),i}function Bo(t){let e=1/0,n=1/0,o=-1/0,s=-1/0;for(let r=0;r<t.length;r+=2){const i=t[r],l=t[r+1];i<e&&(e=i),i>o&&(o=i),l<n&&(n=l),l>s&&(s=l)}return isFinite(e)||(e=0,o=0,n=0,s=0),{minX:e,minY:n,maxX:o,maxY:s,width:Math.max(1,o-e),height:Math.max(1,s-n)}}function br(t,e,n={}){if(t.length<4)return"";const o=[];for(let r=0;r<t.length;r+=2)o.push({x:t[r],y:t[r+1],pressure:e&&e[r/2]!==void 0?e[r/2]:.5});const s=fc(o,n);return pc(s)}const yc=9,Ic={name:"freedraw",onMouseDown(t,e,n){var i;n.setIsDrawing(!0),n.setDrawStart(e),n.clearSelection();let o=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(o=t.evt.pressure===0?.5:t.evt.pressure);const s=Pt();n.currentElementIdRef.current=s;const r={id:s,type:"freedraw",x:e.x,y:e.y,width:1,height:1,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[e.x,e.y],pressures:[o],isComplete:!1};B.getState().pauseHistory(),n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r)},onMouseMove(t,e,n){if(!n.isDrawing||!n.currentElementIdRef.current)return;const o=n.elements.find(s=>s.id===n.currentElementIdRef.current);if(o){let s=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(s=t.evt.pressure===0?.5:t.evt.pressure);const r=o.points;if(r.length>=2){const h=r[r.length-2],u=r[r.length-1],f=e.x-h,p=e.y-u;if(f*f+p*p<yc)return}const i=[...o.points,e.x,e.y],{minX:l,minY:a,width:c,height:d}=Bo(i);n.updateElement(o.id,{points:i,pressures:o.pressures?[...o.pressures,s]:[s],isComplete:!1,x:l,y:a,width:c,height:d})}},onMouseUp(t){if(t.currentElementIdRef.current){const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const{minX:n,minY:o,width:s,height:r}=Bo(e.points);t.updateElement(e.id,{x:n,y:o,width:s,height:r,points:e.points.map((i,l)=>l%2===0?i-n:i-o),isComplete:!0})}B.getState().resumeHistory(),t.pushHistory()}t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null},getCursor(){return"crosshair"}},Cc={name:"text",onMouseDown(t,e,n){var i;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt(),r={id:s,type:"text",x:o.x,y:o.y,width:10,height:30,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:null,textAlign:"left",verticalAlign:"top"};n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r),n.setSelectedIds([s]),n.setActiveTool("select"),n.setIsDrawing(!1),n.setAutoEditTextId(s)},onMouseMove(){},onMouseUp(){},getCursor(){return"text"}},bc=800,mc=600;function Zn(t){return new Promise((e,n)=>{const o=new FileReader;o.onload=()=>e(o.result),o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function hn(t){return new Promise((e,n)=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>e(o),o.onerror=()=>n(new Error("Failed to load image")),o.src=t})}function mr(t,e,n=bc,o=mc){if(t<=n&&e<=o)return{width:t,height:e};const s=t/e,r=n/o;return s>r?{width:n,height:n/s}:{width:o*s,height:o}}function _n(t,e,n,o,s,r={...wn}){const i=mr(e,n);return{id:Pt(),type:"image",x:o-i.width/2,y:s-i.height/2,width:i.width,height:i.height,rotation:0,style:{...r,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,src:t,naturalWidth:e,naturalHeight:n,scaleMode:"stretch",crop:null,cornerRadius:0,alt:""}}function Zo(t){const e=[];if(t.files)for(let n=0;n<t.files.length;n++){const o=t.files[n];o.type.startsWith("image/")&&e.push(o)}return e}function _o(t){const e=t.clipboardData;if(!e)return{file:null,imgUrl:null};const n=Zo(e);if(n.length>0)return{file:n[0],imgUrl:null};const o=e.getData("text/html");if(o){const s=o.match(/<img[^>]+src=["']([^"']+)["']/i);if(s!=null&&s[1])return{file:null,imgUrl:s[1]}}return{file:null,imgUrl:null}}function Ac(t){const{file:e,imgUrl:n}=_o(t);return e!==null||n!==null}async function Ar(t){if(t.file)return Zn(t.file);if(t.imgUrl)try{const e=await hn(t.imgUrl),n=document.createElement("canvas");n.width=e.naturalWidth,n.height=e.naturalHeight;const o=n.getContext("2d");if(o)return o.drawImage(e,0,0),n.toDataURL("image/png")}catch{return t.imgUrl}return null}function wr(){return new Promise(t=>{const e=document.createElement("input");e.type="file",e.accept="image/*",e.multiple=!0,e.style.display="none",e.onchange=()=>{const n=[];if(e.files)for(let o=0;o<e.files.length;o++)n.push(e.files[o]);t(n),document.body.removeChild(e)},e.oncancel=()=>{t([]),document.body.removeChild(e)},document.body.appendChild(e),e.click()})}const wc={name:"image",onMouseDown(t,e,n){n.setIsDrawing(!1);const o=n.snapPos(e);n.clearSelection(),wr().then(async s=>{var r;for(const i of s)try{const l=await Zn(i),a=await hn(l),c=_n(l,a.naturalWidth,a.naturalHeight,o.x,o.y,{...n.currentStyle});n.addElement(c),(r=n.onElementCreate)==null||r.call(n,c),n.setSelectedIds([c.id]),n.pushHistory()}catch{}n.setActiveTool("select")})},onMouseMove(){},onMouseUp(){},getCursor(){return"copy"}};let Mn=null,He;const xr={name:"line",onMouseDown(t,e,n){var p;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt();n.currentElementIdRef.current=s;const r=ce(n.currentStyle.strokeWidth??2),i=ke(e,n.elements,24,void 0,void 0,void 0,r);let l=e,a=null;He=void 0,i?(l=i.position,a={elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}):l=o,n.startBindingRef.current=a,B.getState().pauseHistory();const c={id:s,x:l.x,y:l.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[0,0,0,0],startBinding:a,endBinding:null},{currentLineType:d,currentStartArrowhead:h,currentEndArrowhead:u}=B.getState(),f=n.activeTool==="arrow"?{...c,type:"arrow",startArrowhead:h,endArrowhead:u,lineType:d}:{...c,type:"line",lineType:d};n.addElement(f),(p=n.onElementCreate)==null||p.call(n,f)},onMouseMove(t,e,n){if(!n.isDrawing){const h=ce(n.currentStyle.strokeWidth??2),u=ke(e,n.elements,24,void 0,void 0,void 0,h);n.setSnapTarget(u);return}if(!n.currentElementIdRef.current)return;const o=n.elements.find(h=>h.id===n.currentElementIdRef.current);if(!o)return;Mn=e;const s=new Set([o.id]);o.startBinding&&s.add(o.startBinding.elementId);const r=ce(o.style.strokeWidth??2),i=ke(e,n.elements,24,s,{x:o.x,y:o.y},void 0,r,He);n.setSnapTarget(i),He=i==null?void 0:i.isPrecise;let l=i?i.position:n.snapPos(e);!i&&n.shiftKeyRef.current&&(l=Hl({x:o.x,y:o.y},l));const a=i?{elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}:null,c=l.x-o.x,d=l.y-o.y;if(o.startBinding){const h=n.elements.find(u=>u.id===o.startBinding.elementId);if(h){let u;o.startBinding.isPrecise?u=ae(h,o.startBinding.fixedPoint,o.startBinding.gap):u=de(h,l,o.startBinding.gap);const f=l.x-u.x,p=l.y-u.y;n.updateElement(o.id,{x:u.x,y:u.y,points:[0,0,f,p],width:Math.abs(f),height:Math.abs(p),endBinding:a});return}}n.updateElement(o.id,{points:[0,0,c,d],width:Math.abs(c),height:Math.abs(d),endBinding:a})},onMouseUp(t){if(!t.currentElementIdRef.current)return;const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const n=e.points;if(Math.sqrt((n[n.length-2]-n[0])**2+(n[n.length-1]-n[1])**2)<2)B.getState().resumeHistory(),t.deleteElements([t.currentElementIdRef.current]),t.currentElementIdRef.current=null,t.startBindingRef.current=null,t.setSnapTarget(null),Mn=null,He=void 0;else{const s=Mn??{x:e.x+n[n.length-2],y:e.y+n[n.length-1]},r=new Set([e.id]);e.startBinding&&r.add(e.startBinding.elementId);const i=ce(e.style.strokeWidth??2),l=ke(s,t.elements,24,r,void 0,void 0,i,He),a=ce(e.style.strokeWidth??2),c=l?{elementId:l.elementId,fixedPoint:l.fixedPoint,gap:a,isPrecise:l.isPrecise}:null,d=e.startBinding??t.startBindingRef.current,h=c&&d&&c.elementId===d.elementId?null:c,u=[...n];l&&(u[u.length-2]=l.position.x-e.x,u[u.length-1]=l.position.y-e.y);const f={points:u,width:Math.abs(u[u.length-2]-u[0]),height:Math.abs(u[u.length-1]-u[1]),startBinding:d,endBinding:h},p={...e,...f},y=Se(p,t.elements);y&&Object.assign(f,y),t.updateElement(e.id,f);const m=e.type,W=B.getState().elements;ve(e.id,m,null,d,W,t.updateElement);const v=B.getState().elements;ve(e.id,m,null,h,v,t.updateElement),t.startBindingRef.current=null,t.setSnapTarget(null),t.setSelectedIds([t.currentElementIdRef.current]),B.getState().resumeHistory(),t.pushHistory()}}Mn=null,He=void 0,B.getState().resumeHistory(),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},xc={select:Ol,rectangle:So,ellipse:So,diamond:So,line:xr,arrow:xr,freedraw:Ic,text:Cc,image:wc,eraser:Nl};function fn(t){return xc[t]}function ye(t){const e=typeof t=="number"?String(t):t;let n=0,o=0,s=0,r=0;function i(){const l=n^n<<11;return n=o,o=s,s=r,r^=(r>>>19^l^l>>>8)>>>0,r/4294967296*2}for(let l=0;l<e.length+64;l++)n^=e.charCodeAt(l)|0,i();return i}function pn(t,e){if(t===0)return 0;const n=t===1?.8:1.5,o=e*(t===1?.4:.8);return Math.max(n,o)}function kr(t,e){return t===0?0:Math.max(e*(t===1?1.2:2),t===1?1.5:3)}function kc(t,e,n,o){const s=n-t,r=o-e;return Math.sqrt(s*s+r*r)}function Sc(t,e,n,o){const s=t*n+e*o,r=Math.sqrt(t*t+e*e),i=Math.sqrt(n*n+o*o);return r<1e-6||i<1e-6?0:Math.acos(Math.max(-1,Math.min(1,s/(r*i))))}function vc(t,e,n,o,s,r,i,l=!0){const a=o-e,c=s-n,d=Math.sqrt(a*a+c*c);if(d<.5){l&&t.moveTo(e,n),t.lineTo(o,s);return}const h=-c/d,u=a/d,f=Math.min(r,d*.25),p=f*.15,y=e+i()*p,m=n+i()*p,W=o+i()*p,v=s+i()*p,D=y+a*.33+h*i()*f,$=m+c*.33+u*i()*f,T=y+a*.67+h*i()*f,O=m+c*.67+u*i()*f;l&&t.moveTo(y,m),t.bezierCurveTo(D,$,T,O,W,v)}function Sr(t,e,n,o,s){const r=e.length;if(r<3)return;const i=[];for(let l=0;l<r;l++){const[a,c]=e[l],[d,h]=e[(l+1)%r];i.push(kc(a,c,d,h))}for(let l=0;l<r;l++){const a=e[(l-1+r)%r],c=e[l],d=e[(l+1)%r],h=i[(l-1+r)%r],u=i[l],f=c[0]-a[0],p=c[1]-a[1],y=d[0]-c[0],m=d[1]-c[1],v=1-Sc(-f,-p,y,m)/Math.PI;let D=o*v;const $=Math.min(h,u);D=Math.min(D,$*.4),D=Math.max(D,0);const T=h>1e-6?D/h:0,O=u>1e-6?D/u:0,ot=c[0]-f*T,F=c[1]-p*T,J=c[0]+y*O,Y=c[1]+m*O,Q=ot+s()*n,M=F+s()*n,k=J+s()*n,C=Y+s()*n,w=c[0]+s()*n,S=c[1]+s()*n;l===0?t.moveTo(Q,M):t.lineTo(Q,M),D>.5?t.quadraticCurveTo(w,S,k,C):t.lineTo(k,C)}t.closePath()}function Oe(t){return t>=2?2:1}function Ec(t,e,n,o,s,r,i,l=1,a=2){const c=pn(r,a),d=kr(r,a),h=[[e,n],[e+o,n],[e+o,n+s],[e,n+s]];for(let u=0;u<l;u++)t.beginPath(),Sr(t,h,c,d,i)}function Wc(t,e,n,o,s,r,i,l=1,a=2){const c=pn(r,a),d=Math.PI*2*Math.sqrt((o*o+s*s)/2),h=Math.max(16,Math.min(64,Math.floor(d*.08))),u=Math.PI*2/h,f=4/3*Math.tan(u/4);for(let p=0;p<l;p++){const y=[];for(let m=0;m<=h;m++){const W=m*u,v=i()*c*1.8;y.push({x:e+(o+v)*Math.cos(W),y:n+(s+v)*Math.sin(W),angle:W})}t.moveTo(y[0].x,y[0].y);for(let m=0;m<h;m++){const W=y[m],v=y[m+1],D=Math.cos(W.angle),$=Math.sin(W.angle),T=Math.cos(v.angle),O=Math.sin(v.angle),ot=-$,F=D,J=-O,Y=T;o+i()*c,s+i()*c;const Q=W.x+ot*o*f+i()*c*.8,M=W.y+F*s*f+i()*c*.8,k=v.x-J*o*f+i()*c*.8,C=v.y-Y*s*f+i()*c*.8;t.bezierCurveTo(Q,M,k,C,v.x,v.y)}}}function Tc(t,e,n,o,s,r=1,i=2){const l=pn(o,i),a=kr(o,i),c=[[e/2,0],[e,n/2],[e/2,n],[0,n/2]];for(let d=0;d<r;d++)t.beginPath(),Sr(t,c,l,a,s)}function Mo(t,e,n,o,s=1,r=2){if(e.length<4)return;const i=pn(n,r);for(let l=0;l<s;l++)for(let a=0;a<e.length-2;a+=2)vc(t,e[a],e[a+1],e[a+2],e[a+3],i,o,!0)}function vr(t,e,n,o,s,r,i=1,l=2){const a=pn(s,l),c=a*2;for(let d=0;d<i;d++){const h=e.x+r()*a*.6,u=e.y+r()*a*.6,f=o.x+r()*a*.6,p=o.y+r()*a*.6,y=n.x+r()*c,m=n.y+r()*c;t.moveTo(h,u),t.quadraticCurveTo(y,m,f,p)}}function Bc(t,e,n,o,s,r){const i=Math.min(r,o/2,s/2);t.beginPath(),t.moveTo(e+i,n),t.lineTo(e+o-i,n),t.arcTo(e+o,n,e+o,n+i,i),t.lineTo(e+o,n+s-i),t.arcTo(e+o,n+s,e+o-i,n+s,i),t.lineTo(e+i,n+s),t.arcTo(e,n+s,e,n+s-i,i),t.lineTo(e,n+i),t.arcTo(e,n,e+i,n,i),t.closePath()}const Zc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,cornerRadius:y,style:m,isLocked:W}=t,v=!W&&!n,D=m.roughness,$=I.useCallback(()=>o(c),[o,c]),T=I.useCallback(()=>i==null?void 0:i(c),[i,c]),O=I.useCallback(k=>{let C=k.target.x(),w=k.target.y();if(l&&(C=At(C,l),w=At(w,l),k.target.x(C),k.target.y(w)),!l&&a){const S=a(c,{x:C,y:w,width:u,height:f});S&&(C=S.x,w=S.y,k.target.x(C),k.target.y(w))}r==null||r(c,{x:C,y:w})},[c,l,u,f,r,a]),ot=I.useCallback(k=>{let C=k.target.x(),w=k.target.y();l&&(C=At(C,l),w=At(w,l)),s(c,{x:C,y:w})},[c,l,s]),F=I.useCallback(k=>{const C=k.target,w=C.scaleX(),S=C.scaleY(),Z=Math.max(5,C.width()*w),G=Math.max(5,C.height()*S);C.setAttrs({scaleX:1,scaleY:1,width:Z,height:G}),r==null||r(c,{x:C.x(),y:C.y(),width:Z,height:G})},[c,r]),J=I.useCallback(k=>{const C=k.target,w=Math.max(5,C.width()*C.scaleX()),S=Math.max(5,C.height()*C.scaleY());C.setAttrs({scaleX:1,scaleY:1,width:w,height:S}),s(c,{x:C.x(),y:C.y(),width:w,height:S,rotation:C.rotation()})},[c,s]),Y=e?Tt.color:void 0,Q=e?Tt.blur:0,M=e?Tt.opacity:0;if(D>0){const k=Oe(D),C=_t(m.strokeStyle,m.strokeWidth);return g.jsx(gt.Shape,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{y>0?Bc(w,0,0,u,f,y):(w.beginPath(),w.rect(0,0,u,f)),w.fillShape(S);for(let Z=0;Z<k;Z++){const G=ye(c+":"+Z);w.beginPath(),Ec(w,0,0,u,f,D,G,1,m.strokeWidth),w.strokeShape(S)}},fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:C,lineCap:"round",lineJoin:"round",draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:Y,shadowBlur:Q,shadowOpacity:M,onDragMove:O,onDragEnd:ot,onTransform:F,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Rect,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",cornerRadius:y,fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:_t(m.strokeStyle,m.strokeWidth),draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:Y,shadowBlur:Q,shadowOpacity:M,onDragMove:O,onDragEnd:ot,onTransform:F,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},_c=I.memo(Zc),Mc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:m}=t,W=!m&&!n,v=y.roughness,D=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l){const w=At(k-u/2,l),S=At(C-f/2,l);k=w+u/2,C=S+f/2,M.target.x(k),M.target.y(C)}if(!l&&a){const w=a(c,{x:k-u/2,y:C-f/2,width:u,height:f});w&&(k=w.x+u/2,C=w.y+f/2,M.target.x(k),M.target.y(C))}r==null||r(c,{x:k-u/2,y:C-f/2})},[c,l,u,f,r,a]),O=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l){const w=At(k-u/2,l),S=At(C-f/2,l);k=w+u/2,C=S+f/2}s(c,{x:k-u/2,y:C-f/2})},[c,l,u,f,s]),ot=I.useCallback(M=>{const k=M.target,C=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*C/2),Z=Math.max(5,f*w/2);k.setAttrs({scaleX:1,scaleY:1,radiusX:S,radiusY:Z});const G=S*2,U=Z*2;r==null||r(c,{x:k.x()-S,y:k.y()-Z,width:G,height:U})},[c,u,f,r]),F=I.useCallback(M=>{const k=M.target,C=k.getAttr("radiusX"),w=k.getAttr("radiusY");k.setAttrs({scaleX:1,scaleY:1});const S=Math.max(5,C*2),Z=Math.max(5,w*2);s(c,{x:k.x()-C,y:k.y()-w,width:S,height:Z,rotation:k.rotation()})},[c,s]),J=e?Tt.color:void 0,Y=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const M=Oe(v),k=u/2,C=f/2;return g.jsx(gt.Shape,{id:c,x:d+k,y:h+C,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{w.beginPath(),w.ellipse(0,0,k,C,0,0,Math.PI*2),w.fillShape(S);for(let Z=0;Z<M;Z++){const G=ye(c+":"+Z);w.beginPath(),Wc(w,0,0,k,C,v,G,1,y.strokeWidth),w.strokeShape(S)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Ellipse,{id:c,x:d+u/2,y:h+f/2,radiusX:u/2,radiusY:f/2,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Gc=I.memo(Mc),Dc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:m}=t,W=!m&&!n,v=y.roughness,D=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l&&(k=At(k,l),C=At(C,l),M.target.x(k),M.target.y(C)),!l&&a){const w=a(c,{x:k,y:C,width:u,height:f});w&&(k=w.x,C=w.y,M.target.x(k),M.target.y(C))}r==null||r(c,{x:k,y:C})},[c,l,u,f,r,a]),O=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();l&&(k=At(k,l),C=At(C,l)),s(c,{x:k,y:C})},[c,l,s]),ot=I.useCallback(M=>{const k=M.target,C=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*C),Z=Math.max(5,f*w);k.setAttrs({scaleX:1,scaleY:1,points:un(S,Z)}),r==null||r(c,{x:k.x(),y:k.y(),width:S,height:Z})},[c,u,f,r]),F=I.useCallback(M=>{const k=M.target;k.setAttrs({scaleX:1,scaleY:1});const C=k.getAttr("points"),w=C?C[2]:u,S=C?C[5]:f;s(c,{x:k.x(),y:k.y(),width:Math.max(5,w),height:Math.max(5,S),rotation:k.rotation()})},[c,u,f,s]),J=e?Tt.color:void 0,Y=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const M=Oe(v),k=_t(y.strokeStyle,y.strokeWidth);return g.jsx(gt.Shape,{id:c,x:d,y:h,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(C,w)=>{const S=un(u,f);C.beginPath(),C.moveTo(S[0],S[1]);for(let Z=2;Z<S.length;Z+=2)C.lineTo(S[Z],S[Z+1]);C.closePath(),C.fillShape(w);for(let Z=0;Z<M;Z++){const G=ye(c+":"+Z);C.beginPath(),Tc(C,u,f,v,G,1,y.strokeWidth),C.strokeShape(w)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:k,lineCap:"round",lineJoin:"round",draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Line,{id:c,x:d,y:h,points:un(u,f),closed:!0,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Xc=I.memo(Dc),Lc=new Set(["rectangle","ellipse","diamond","text","image"]);function Er(t){const e=I.useRef(t??[]);return e.current=t??[],{fingerprint:I.useMemo(()=>{if(!t||t.length===0)return"";const o=r=>Math.round(r*2)/2,s=[];for(const r of t)Lc.has(r.type)&&r.isVisible&&s.push(`${r.id}:${o(r.x)},${o(r.y)},${o(r.width)},${o(r.height)},${o(r.rotation||0)}`);return s.join(";")},[t]),elementsRef:e}}function Fc(t){const e=t.indexOf(",");if(e===-1)throw new Error("Invalid data URL");const o=t.slice(5,e).endsWith(";base64"),s=t.slice(e+1);let r;if(o){const l=atob(s);r=new Uint8Array(l.length);for(let a=0;a<l.length;a++)r[a]=l.charCodeAt(a)}else{const l=decodeURIComponent(s);r=new TextEncoder().encode(l)}const i=new Blob([r],{type:"application/javascript"});return URL.createObjectURL(i)}function Gn(t,e){if(typeof Worker>"u"||e!=null&&e.disabled)return null;if(e!=null&&e.url)try{return new Worker(e.url,{type:"module"})}catch(n){return console.warn("[workerFactory] Failed to create worker from custom URL:",e.url,n),null}try{const n=typeof t=="function"?t():t,o=n instanceof URL?n.href:String(n);if(o.startsWith("data:")){const s=Fc(o);return new Worker(s)}return new Worker(n instanceof URL?n:new URL(o),{type:"module"})}catch(n){return console.warn("[workerFactory] Worker creation failed, using sync fallback:",n),null}}function Vc(){return typeof Worker<"u"&&typeof URL<"u"}function Pc(t){const e=new Array(t.length);for(let n=0;n<t.length;n++){const o=t[n];e[n]={id:o.id,type:o.type,x:o.x,y:o.y,width:o.width,height:o.height,rotation:o.rotation,isVisible:o.isVisible}}return e}const Wr=50;class Yc{constructor(e){ct(this,"worker",null);ct(this,"requestIdCounter",0);ct(this,"pending",new Map);ct(this,"cachedElements",[]);ct(this,"workerSupported",!0);ct(this,"workerConfig");ct(this,"handleMessage",e=>{const{type:n,requestId:o,points:s}=e.data;if(n==="routeResult"){const r=this.pending.get(o);r&&(this.pending.delete(o),r.timerId!==void 0&&clearTimeout(r.timerId),r.resolve(s))}});this.workerConfig=e}_getWorker(){if(!this.workerSupported)return null;if(this.worker)return this.worker;try{return this.worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGVsYm93V29ya2VyLnRzIOKAlCBXZWIgV29ya2VyIGZvciBvZmYtbWFpbi10aHJlYWQgZWxib3cgY29ubmVjdG9yIHJvdXRpbmcuCiAqCiAqIFJ1bnMgdGhlIGV4cGVuc2l2ZSBBKiBncmlkLXNlYXJjaCBhbGdvcml0aG0gaW4gYSBiYWNrZ3JvdW5kIHRocmVhZCBzbwogKiB0aGUgbWFpbiB0aHJlYWQgc3RheXMgYXQgNjBmcHMgZHVyaW5nIGludGVuc2l2ZSBkcmFnIG9wZXJhdGlvbnMgdGhhdAogKiB0cmlnZ2VyIG1hbnkgc2ltdWx0YW5lb3VzIHJvdXRlIHJlY29tcHV0YXRpb25zLgogKgogKiBDb21tdW5pY2F0aW9uIHByb3RvY29sOgogKiAgIE1haW4g4oaSIFdvcmtlcjoKICogICAgIHsgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJywgZWxlbWVudHM6IFNlcmlhbGl6ZWRFbGVtZW50W10gfQogKiAgICAgeyB0eXBlOiAnY29tcHV0ZVJvdXRlJywgcmVxdWVzdElkLCBwYXJhbXM6IFJvdXRlUGFyYW1zIH0KICogICBXb3JrZXIg4oaSIE1haW46CiAqICAgICB7IHR5cGU6ICdyb3V0ZVJlc3VsdCcsIHJlcXVlc3RJZCwgcG9pbnRzOiBudW1iZXJbXSB9CiAqCiAqIFVzZXMgVml0ZSdzIG5hdGl2ZSBXb3JrZXIgbW9kdWxlIHN1cHBvcnQg4oCUIGltcG9ydGVkIHdpdGg6CiAqICAgbmV3IFdvcmtlcihuZXcgVVJMKCcuL2VsYm93V29ya2VyLnRzJywgaW1wb3J0Lm1ldGEudXJsKSwgeyB0eXBlOiAnbW9kdWxlJyB9KQogKi8KCi8vIE5PVEU6IFdlIGltcG9ydCB0aGUgZnVsbCBlbGJvdyBtb2R1bGUgaGVyZS4gIFZpdGUgYnVuZGxlcyBpdCBpbnRvIHRoZQovLyBXb3JrZXIgY2h1bmsgYXV0b21hdGljYWxseS4gIFRoZSBgQC9gIHBhdGggYWxpYXMgaXMgcmVzb2x2ZWQgYnkgVml0ZS4KaW1wb3J0IHsgY29tcHV0ZUVsYm93UG9pbnRzLCBzaW1wbGlmeUVsYm93UGF0aCB9IGZyb20gJ0AvdXRpbHMvZWxib3cnOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQsIEJpbmRpbmcsIFBvaW50IH0gZnJvbSAnQC90eXBlcyc7CgovLyDilIDilIDilIAgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgU2VyaWFsaXplZEVsZW1lbnQgewogICAgaWQ6IHN0cmluZzsKICAgIHR5cGU6IHN0cmluZzsKICAgIHg6IG51bWJlcjsKICAgIHk6IG51bWJlcjsKICAgIHdpZHRoOiBudW1iZXI7CiAgICBoZWlnaHQ6IG51bWJlcjsKICAgIHJvdGF0aW9uOiBudW1iZXI7CiAgICBpc1Zpc2libGU6IGJvb2xlYW47CiAgICAvLyBNaW5pbWFsIGZpZWxkcyBuZWVkZWQgZm9yIG9ic3RhY2xlIGRldGVjdGlvbiDigJQgc3R5bGUsIHRleHQsIGV0Yy4gYXJlIG9taXR0ZWQuCiAgICAvLyBXZSByZWNvbnN0cnVjdCBhICJwc2V1ZG8tQ2FudmFzRWxlbWVudCIgZnJvbSB0aGVzZSBmaWVsZHMuCn0KCmludGVyZmFjZSBSb3V0ZVBhcmFtcyB7CiAgICBzdGFydFdvcmxkOiBQb2ludDsKICAgIGVuZFdvcmxkOiBQb2ludDsKICAgIHN0YXJ0QmluZGluZzogQmluZGluZyB8IG51bGw7CiAgICBlbmRCaW5kaW5nOiBCaW5kaW5nIHwgbnVsbDsKICAgIG1pblN0dWJMZW5ndGg/OiBudW1iZXI7Cn0KCmludGVyZmFjZSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgewogICAgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJzsKICAgIGVsZW1lbnRzOiBTZXJpYWxpemVkRWxlbWVudFtdOwp9CgppbnRlcmZhY2UgQ29tcHV0ZVJvdXRlTWVzc2FnZSB7CiAgICB0eXBlOiAnY29tcHV0ZVJvdXRlJzsKICAgIHJlcXVlc3RJZDogbnVtYmVyOwogICAgcGFyYW1zOiBSb3V0ZVBhcmFtczsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgfCBDb21wdXRlUm91dGVNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBzdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCi8qKiBMaWdodHdlaWdodCBlbGVtZW50IHByb3hpZXMgdXNlZCBmb3Igb2JzdGFjbGUgZGV0ZWN0aW9uIGluIHJvdXRpbmcgKi8KbGV0IGNhY2hlZEVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gPSBbXTsKCi8qKgogKiBSZWNvbnN0cnVjdCBtaW5pbWFsIENhbnZhc0VsZW1lbnQtc2hhcGVkIG9iamVjdHMgZnJvbSBzZXJpYWxpemVkIGRhdGEuCiAqIE9ubHkgdGhlIGZpZWxkcyB1c2VkIGJ5IGNvbXB1dGVFbGJvd1BvaW50cyBhcmUgbmVlZGVkOgogKiAgIGlkLCB0eXBlLCB4LCB5LCB3aWR0aCwgaGVpZ2h0LCByb3RhdGlvbiwgaXNWaXNpYmxlCiAqLwpmdW5jdGlvbiBkZXNlcmlhbGl6ZUVsZW1lbnRzKHNlcmlhbGl6ZWQ6IFNlcmlhbGl6ZWRFbGVtZW50W10pOiBDYW52YXNFbGVtZW50W10gewogICAgLy8gQ2FzdCBpcyBzYWZlIGJlY2F1c2UgY29tcHV0ZUVsYm93UG9pbnRzIG9ubHkgcmVhZHMgc3BhdGlhbCBmaWVsZHMKICAgIC8vIGFuZCBjaGVja3MgYHR5cGVgIG1lbWJlcnNoaXAgaW4gT0JTVEFDTEVfVFlQRVMgc2V0LgogICAgcmV0dXJuIHNlcmlhbGl6ZWQgYXMgdW5rbm93biBhcyBDYW52YXNFbGVtZW50W107Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIGhhbmRsZXIg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpzZWxmLm9ubWVzc2FnZSA9IChlOiBNZXNzYWdlRXZlbnQ8SW5jb21pbmdNZXNzYWdlPikgPT4gewogICAgY29uc3QgbXNnID0gZS5kYXRhOwoKICAgIGlmIChtc2cudHlwZSA9PT0gJ3VwZGF0ZUVsZW1lbnRzJykgewogICAgICAgIGNhY2hlZEVsZW1lbnRzID0gZGVzZXJpYWxpemVFbGVtZW50cyhtc2cuZWxlbWVudHMpOwogICAgICAgIHJldHVybjsKICAgIH0KCiAgICBpZiAobXNnLnR5cGUgPT09ICdjb21wdXRlUm91dGUnKSB7CiAgICAgICAgY29uc3QgeyByZXF1ZXN0SWQsIHBhcmFtcyB9ID0gbXNnOwogICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHJhdyA9IGNvbXB1dGVFbGJvd1BvaW50cygKICAgICAgICAgICAgICAgIHBhcmFtcy5zdGFydFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLmVuZFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLnN0YXJ0QmluZGluZywKICAgICAgICAgICAgICAgIHBhcmFtcy5lbmRCaW5kaW5nLAogICAgICAgICAgICAgICAgY2FjaGVkRWxlbWVudHMsCiAgICAgICAgICAgICAgICBwYXJhbXMubWluU3R1Ykxlbmd0aCwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc2ltcGxpZmllZCA9IHNpbXBsaWZ5RWxib3dQYXRoKHJhdyk7CiAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UoeyB0eXBlOiAncm91dGVSZXN1bHQnLCByZXF1ZXN0SWQsIHBvaW50czogc2ltcGxpZmllZCB9KTsKICAgICAgICB9IGNhdGNoIHsKICAgICAgICAgICAgLy8gT24gZXJyb3IsIHJldHVybiBhIHN0cmFpZ2h0IGxpbmUgZmFsbGJhY2sKICAgICAgICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICB0eXBlOiAncm91dGVSZXN1bHQnLAogICAgICAgICAgICAgICAgcmVxdWVzdElkLAogICAgICAgICAgICAgICAgcG9pbnRzOiBbMCwgMCwgcGFyYW1zLmVuZFdvcmxkLnggLSBwYXJhbXMuc3RhcnRXb3JsZC54LCBwYXJhbXMuZW5kV29ybGQueSAtIHBhcmFtcy5zdGFydFdvcmxkLnldLAogICAgICAgICAgICB9KTsKICAgICAgICB9CiAgICB9Cn07Cg==",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this.workerConfig),this.worker?(this.worker.onmessage=this.handleMessage,this.worker.onerror=()=>{this.workerSupported=!1,this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker failed"));this.pending.clear()},this.worker):(this.workerSupported=!1,null)}catch{return this.workerSupported=!1,null}}updateElements(e){this.cachedElements=e;const n=this._getWorker();n&&e.length>=Wr&&n.postMessage({type:"updateElements",elements:Pc(e)})}async computeRoute(e){const n=this._getWorker();if(!n||this.cachedElements.length<Wr)return this.computeSync(e);const o=++this.requestIdCounter;return new Promise((s,r)=>{const i=setTimeout(()=>{this.pending.has(o)&&(this.pending.delete(o),s(this.computeSync(e)))},100);this.pending.set(o,{resolve:s,reject:r,timerId:i}),n.postMessage({type:"computeRoute",requestId:o,params:e})})}computeSync(e){const n=on(e.startWorld,e.endWorld,e.startBinding,e.endBinding,this.cachedElements,e.minStubLength);return sn(n)}dispose(){this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker disposed"));this.pending.clear()}get isWorkerActive(){return this.workerSupported}}let ne=null,Go;function Do(t){return ne&&t&&JSON.stringify(t)!==JSON.stringify(Go)&&(ne.dispose(),ne=null),ne||(Go=t,ne=new Yc(t)),ne}function Tr(){ne&&(ne.dispose(),ne=null,Go=void 0)}const Xo=I.createContext(void 0);function Br(){return I.useContext(Xo)}function Zr(t,e,n,o){const[s,r]=I.useState(null),i=I.useRef(n),l=Br(),a=l==null?void 0:l.elbowWorkerConfig;return i.current=n,I.useEffect(()=>{Do(a).updateElements(n)},[o,a]),I.useEffect(()=>()=>{},[]),I.useEffect(()=>{if(!t){r(null);return}const c=Do(a);let d=!1;const h={startWorld:e.startWorld,endWorld:e.endWorld,startBinding:e.startBinding,endBinding:e.endBinding,minStubLength:e.minStubLength};if(c.isWorkerActive)c.computeRoute(h).then(u=>{d||r(u)});else{const u=on(e.startWorld,e.endWorld,e.startBinding,e.endBinding,i.current,e.minStubLength),f=sn(u);r(f)}return()=>{d=!0}},[t,e.startWorld.x,e.startWorld.y,e.endWorld.x,e.endWorld.y,e.startBinding,e.endBinding,e.minStubLength,o]),s}const Hc=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:m,endBinding:W,lineType:v,isLocked:D}=t,$=!D&&!o,T=I.useRef(null),O=y.roughness,ot=v==="curved",F=v==="elbow",{fingerprint:J,elementsRef:Y}=Er(c),Q=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),M=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),k=Zr(F,{startWorld:Q,endWorld:M,startBinding:m,endBinding:W},c??[],J),C=I.useMemo(()=>{if(!F)return f;const R=on(Q,M,m,W,Y.current);return sn(R)},[F,h,u,f,m,W,J]),w=F?k??C:f,S=I.useMemo(()=>{if(!F)return f;const R=[...w],K=f[0],et=f[1];if(K!==0||et!==0)for(let Ct=0;Ct<R.length;Ct+=2)R[Ct]+=K,R[Ct+1]+=et;return R},[F,w,f]),Z=I.useMemo(()=>{if(!ot)return null;const R={x:f[0],y:f[1]},K={x:f[f.length-2],y:f[f.length-1]},et=Jt(R,K,t.curvature??zt);return{start:R,end:K,cp:et}},[ot,f,t.curvature]),G=I.useCallback(()=>s(d),[s,d]),U=I.useCallback(()=>l==null?void 0:l(d),[l,d]),X=I.useCallback(R=>{let K=R.target.x(),et=R.target.y();a&&(K=At(K,a),et=At(et,a),R.target.x(K),R.target.y(et)),i==null||i(d,{x:K,y:et})},[d,a,i]),L=I.useCallback(R=>{let K=R.target.x(),et=R.target.y();a&&(K=At(K,a),et=At(et,a)),r(d,{x:K,y:et})},[d,a,r]),at=I.useCallback(R=>{const K=R.target,et=K.scaleX(),Ct=K.scaleY();K.setAttrs({scaleX:1,scaleY:1});const bt=f.map((st,pt)=>pt%2===0?st*et:st*Ct),rt=Tn(bt);r(d,{x:K.x(),y:K.y(),points:bt,rotation:K.rotation(),width:rt.width,height:rt.height})},[d,f,r]),tt=Oe(O),E=e?Tt.color:void 0,V=e?Tt.blur:0,dt=e?Tt.opacity:0;return g.jsx(gt.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:G,onTap:G,onDblClick:U,onDblTap:U,onDragMove:X,onDragEnd:L,onTransformEnd:at,children:F?g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:S,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:S,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]}):ot?g.jsx(gt.Shape,{sceneFunc:(R,K)=>{if(Z){if(R.beginPath(),O>0){const et=ye(d);vr(R,Z.start,Z.cp,Z.end,O,et,tt,y.strokeWidth)}else R.moveTo(Z.start.x,Z.start.y),R.quadraticCurveTo(Z.cp.x,Z.cp.y,Z.end.x,Z.end.y);R.fillStrokeShape(K)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):O>0?g.jsx(gt.Shape,{sceneFunc:(R,K)=>{const et=ye(d);R.beginPath(),Mo(R,f,O,et,tt,y.strokeWidth),R.fillStrokeShape(K)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]})})},Oc=I.memo(Hc);function Nc(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function Uc(t){return{x:-t.y,y:t.x}}function Lo(t){return Math.max(10,t*4)}function oe(t,e,n,o,s,r,i){const l=Nc(n,o),a=Uc(l),c=s*.45,d=t._context;switch(d.save(),d.strokeStyle=r,d.fillStyle=r,d.lineWidth=i,d.lineJoin="round",d.lineCap="round",e){case"arrow":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(h.x,h.y),d.lineTo(n.x,n.y),d.lineTo(u.x,u.y),d.stroke();break}case"triangle":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"triangle_outline":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"circle":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"circle_outline":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.fillStyle="#ffffff",d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"diamond":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"diamond_outline":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"bar":{const h=c*1.2;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one":{const h=c*1,u=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.stroke();break}case"crowfoot_many":{const h=c*1,u=s*.6;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(f.x,f.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one_or_many":{const h=c*1,u=s*.6,f=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const p={x:n.x-l.x*f,y:n.y-l.y*f};d.beginPath(),d.moveTo(p.x+a.x*h,p.y+a.y*h),d.lineTo(p.x-a.x*h,p.y-a.y*h),d.stroke();const y={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(y.x,y.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}}d.restore()}function Dn(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Kc(t){let e=t.startArrowhead??null,n=t.endArrowhead??null;return e===null&&t.startArrow&&(e="arrow"),n===null&&t.endArrow&&(n="arrow"),{start:e,end:n}}const zc=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:m,endBinding:W,lineType:v,isLocked:D}=t,$=!D&&!o,T=I.useRef(null),O=y.roughness,{start:ot,end:F}=Kc(t),J=ot!=null||F!=null,Y=v==="curved",Q=v==="elbow",M=Lo(y.strokeWidth),k=Oe(O),{fingerprint:C,elementsRef:w}=Er(c),S=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),Z=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),G=J?Math.ceil(M*1.5):void 0,U=Zr(Q,{startWorld:S,endWorld:Z,startBinding:m,endBinding:W,minStubLength:G},c??[],C),X=I.useMemo(()=>{if(!Q)return f;const rt=on(S,Z,m,W,w.current,G);return sn(rt)},[Q,h,u,f,m,W,C]),L=Q?U??X:f,at=I.useMemo(()=>{if(!Q)return f;const rt=[...L],st=f[0],pt=f[1];if(st!==0||pt!==0)for(let A=0;A<rt.length;A+=2)rt[A]+=st,rt[A+1]+=pt;return rt},[Q,L,f]),tt=I.useMemo(()=>{if(!Y)return null;const rt={x:f[0],y:f[1]},st={x:f[f.length-2],y:f[f.length-1]},pt=Jt(rt,st,t.curvature??zt);return{start:rt,end:st,cp:pt}},[Y,f,t.curvature]),E=I.useCallback(()=>s(d),[s,d]),V=I.useCallback(()=>l==null?void 0:l(d),[l,d]),dt=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a),rt.target.x(st),rt.target.y(pt)),i==null||i(d,{x:st,y:pt})},[d,a,i]),R=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a)),r(d,{x:st,y:pt})},[d,a,r]),K=I.useCallback(rt=>{const st=rt.target,pt=st.scaleX(),A=st.scaleY();st.setAttrs({scaleX:1,scaleY:1});const lt=f.map((j,Dt)=>Dt%2===0?j*pt:j*A),mt=Tn(lt);r(d,{x:st.x(),y:st.y(),points:lt,rotation:st.rotation(),width:mt.width,height:mt.height})},[d,f,r]),et=e?Tt.color:void 0,Ct=e?Tt.blur:0,bt=e?Tt.opacity:0;return g.jsx(gt.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:E,onTap:E,onDblClick:V,onDblTap:V,onDragMove:dt,onDragEnd:R,onTransformEnd:K,children:Q?g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:at,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:at,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(at);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):Y?g.jsxs(g.Fragment,{children:[g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{if(tt){if(rt.beginPath(),O>0){const pt=ye(d);vr(rt,tt.start,tt.cp,tt.end,O,pt,k,y.strokeWidth)}else rt.moveTo(tt.start.x,tt.start.y),rt.quadraticCurveTo(tt.cp.x,tt.cp.y,tt.end.x,tt.end.y);rt.fillStrokeShape(st)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&tt&&g.jsx(gt.Shape,{sceneFunc:rt=>{if(ot){const st=xo(tt.start,tt.cp,tt.end,!1);oe(rt,ot,tt.start,st,M,y.strokeColor,y.strokeWidth)}if(F){const st=xo(tt.start,tt.cp,tt.end,!0);oe(rt,F,tt.end,st,M,y.strokeColor,y.strokeWidth)}},listening:!1,opacity:y.opacity})]}):O>0?g.jsxs(g.Fragment,{children:[g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=ye(d);rt.beginPath(),Mo(rt,f,O,pt,k,y.strokeWidth),rt.fillStrokeShape(st)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]})})},Jc=I.memo(zc),$c=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,points:u,rotation:f,style:p,isLocked:y}=t,m=!y&&!n,W=I.useCallback(()=>o(c),[o,c]),v=I.useCallback(()=>i==null?void 0:i(c),[i,c]),D=I.useCallback(G=>{let U=G.target.x(),X=G.target.y();if(l&&(U=At(U,l),X=At(X,l),G.target.x(U),G.target.y(X)),!l&&a){const{minX:L,minY:at,width:tt,height:E}=Bo(u),V=a(c,{x:U+L,y:X+at,width:tt,height:E});V&&(U=V.x-L,X=V.y-at,G.target.x(U),G.target.y(X))}r==null||r(c,{x:U,y:X})},[c,l,u,r,a]),$=I.useCallback(G=>{let U=G.target.x(),X=G.target.y();l&&(U=At(U,l),X=At(X,l)),s(c,{x:U,y:X})},[c,l,s]),T=I.useCallback(G=>{const U=G.target,X=U.scaleX(),L=U.scaleY();U.setAttrs({scaleX:1,scaleY:1});const at=u.map((tt,E)=>E%2===0?tt*X:tt*L);s(c,{x:U.x(),y:U.y(),points:at,rotation:U.rotation()})},[c,u,s]),O=e?Tt.color:void 0,ot=e?Tt.blur:0,F=e?Tt.opacity:0,J=p.freehandStyle||"standard",Y=t.isComplete===!1,Q=Y?0:d,M=Y?0:h,k=J==="pen"||J==="brush",C=J==="pencil",w=I.useMemo(()=>{if(!k)return"";const G=!Y;if(J==="brush"){const U=p.strokeWidth*4;return br(u,t.pressures,{size:U,thinning:.7,smoothing:.5,streamline:.5,simulatePressure:!0,last:G,start:{cap:!0},end:{cap:!0}})}return br(u,t.pressures,{size:p.strokeWidth*1.8,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:!0,last:G,start:{cap:!0,taper:0},end:{cap:!0,taper:0}})},[u,t.pressures,k,J,p.strokeWidth,Y]),S=I.useMemo(()=>{if(!C||u.length===0)return[];const G=[u[0],u[1]];let U=u[0],X=u[1];for(let L=2;L<u.length;L+=2){const at=u[L],tt=u[L+1],E=at-U,V=tt-X;(E*E+V*V>2.25||L===u.length-2)&&(G.push(at,tt),U=at,X=tt)}return G},[C,u]),Z=I.useCallback((G,U)=>{const X=p.roughness,L=ye(c);G.beginPath(),Mo(G,S,X,L,Oe(X),p.strokeWidth),G.fillStrokeShape(U)},[c,S,p.roughness,p.strokeWidth]);return k&&w?g.jsx(gt.Path,{id:c,x:Q,y:M,data:w,rotation:f,transformsEnabled:f?"all":"position",fill:p.strokeColor,opacity:p.opacity,draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:20,onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):C?g.jsx(gt.Shape,{id:c,x:Q,y:M,width:Y?void 0:t.width,height:Y?void 0:t.height,rotation:f,transformsEnabled:f?"all":"position",sceneFunc:Z,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:Math.max(20,p.strokeWidth+16),onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsx(gt.Line,{id:c,x:Q,y:M,points:u,rotation:f,transformsEnabled:f?"all":"position",stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",tension:.5,globalCompositeOperation:"source-over",draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:20,onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Rc=I.memo($c),Xn=1.18,jc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,autoEdit:i,onEditStart:l,onEditEnd:a,allElements:c,gridSnap:d})=>{const{id:h,x:u,y:f,width:p,height:y,rotation:m,style:W,text:v,containerId:D,textAlign:$,verticalAlign:T,isLocked:O}=t,ot=I.useRef(null),F=I.useRef(!1),J=I.useRef(!1),Y=!!D,Q=!Y&&!O&&!n,M=I.useMemo(()=>!D||!c?null:c.find(X=>X.id===D)??null,[D,c]),k=I.useMemo(()=>{var dt,R;if(!M)return{x:u,y:f};if(M.type==="arrow"||M.type==="line"){const K=M,et=K.points,Ct={x:et[0],y:et[1]},bt={x:et[et.length-2],y:et[et.length-1]};let rt,st;if(K.lineType==="curved"){const lt=Jt(Ct,bt,K.curvature??zt),mt=Ye(Ct,lt,bt,.5);rt=K.x+mt.x,st=K.y+mt.y}else rt=K.x+(Ct.x+bt.x)/2,st=K.y+(Ct.y+bt.y)/2;const pt=Math.max(80,p||80),A=((dt=ot.current)==null?void 0:dt.height())??y;return{x:rt-pt/2,y:st-A/2,width:pt}}const X=4,L=M.width-X*2,at=Math.max(20,L),tt=M.x+X,E=((R=ot.current)==null?void 0:R.height())??y;let V;return T==="top"?V=M.y+X:T==="bottom"?V=M.y+M.height-E-X:V=M.y+(M.height-E)/2,{x:tt,y:V,width:at}},[M,u,f,y,T]),C=I.useCallback(()=>{const X=ot.current;if(!X||F.current)return;const L=X.height(),at={};let tt=!1;if(Math.abs(L-y)>1&&(at.height=L,tt=!0),!Y){const E=Math.ceil(X.getTextWidth());Math.abs(E-p)>1&&(at.width=E,tt=!0)}tt&&s(h,at)},[h,y,p,Y,s]);I.useEffect(()=>{requestAnimationFrame(C)},[v,W.fontSize,W.fontFamily,C]);const w=I.useCallback(()=>{const X=ot.current;if(!X||F.current)return;const L=X.getStage();if(!L)return;F.current=!0,l==null||l(h);const at=L.container(),E=X.getAbsoluteTransform().copy().point({x:0,y:0}),V=L.scaleX(),dt=W.fontSize*V,R=dt*(Xn-1.07)/2;let K=0,et=0,Ct=0,bt=0;const st=4*V;if(Y&&M){const Ft=L.getAbsoluteTransform().copy().point({x:M.x,y:M.y});K=Ft.x,et=Ft.y,Ct=M.width*V,bt=M.height*V}const pt=X.width(),A=Y?Ct-st*2:Math.max(pt,100)*V,lt=Y?K+st:E.x,mt=v,j=document.createElement("textarea");if(at.appendChild(j),j.value=v,j.style.position="absolute",Y&&M){const vt=T||"middle",Ft=X.height()*V;let Ut;vt==="top"?Ut=et+st-R:vt==="bottom"?Ut=et+bt-Ft-st-R:Ut=et+(bt-Ft)/2-R,j.style.top=`${Ut}px`}else j.style.top=`${E.y-R}px`;j.style.left=`${lt}px`,j.style.width=`${A}px`,j.style.fontSize=`${dt}px`,j.style.fontFamily=W.fontFamily,j.style.color=W.strokeColor,j.style.lineHeight=`${Xn}`,j.style.border="none",j.style.borderRadius="0",j.style.padding="0",j.style.margin="0",j.style.outline="none",j.style.resize="none",j.style.overflow="hidden",j.style.background="transparent",j.style.zIndex="1000",j.rows=1,j.style.minHeight=`${Math.max(20,dt*Xn)}px`,j.style.boxSizing="border-box",j.style.transformOrigin="left top",j.style.letterSpacing="normal",j.style.caretColor=W.strokeColor;const Dt=Y?$||"center":"left";j.style.textAlign=Dt,Y?(j.style.whiteSpace="pre-wrap",j.style.wordBreak="break-word"):(j.style.whiteSpace="pre",j.style.wordBreak="normal");const Gt=Y?(M==null?void 0:M.rotation)??m:m;Gt&&(j.style.transform=`rotateZ(${Gt}deg)`);const Ot=()=>{j.style.height="auto";const vt=j.scrollHeight;if(j.style.height=`${vt}px`,Y&&M){const Ft=T||"middle";let Ut;Ft==="top"?Ut=et+st-R:Ft==="bottom"?Ut=et+bt-vt-st-R:Ut=et+(bt-vt)/2-R,j.style.top=`${Ut}px`}Y||(j.style.width="auto",j.style.width=`${Math.max(j.scrollWidth,100*V)}px`)};j.addEventListener("input",Ot),requestAnimationFrame(Ot),X.hide(),L.batchDraw(),j.focus(),j.select();let Ge=!1;const jt=()=>{if(!F.current)return;F.current=!1;const vt=Ge?mt:j.value,Ft=vt.trim()==="";j.removeEventListener("input",Ot),j.removeEventListener("blur",mn),j.removeEventListener("keydown",Nt),j.parentNode&&j.parentNode.removeChild(j),X.show(),L.batchDraw(),Ge||s(h,{text:vt}),a==null||a(h,Ft)},mn=()=>{jt()},Nt=vt=>{vt.stopPropagation(),vt.key==="Escape"&&(Ge=!0,j.blur()),vt.key==="Enter"&&!vt.shiftKey&&(vt.preventDefault(),j.blur()),vt.key==="Tab"&&(vt.preventDefault(),j.blur())};j.addEventListener("blur",mn),j.addEventListener("keydown",Nt)},[h,v,m,W,Y,M,$,T,s,l,a]);I.useEffect(()=>{i||(J.current=!1)},[i]),I.useEffect(()=>{i&&!J.current&&ot.current&&(J.current=!0,w())},[i,w]);const S=Y?k.x:u,Z=Y?k.y:f,G=Y&&k.width?k.width:void 0,U=Y?$||"center":void 0;return g.jsx(gt.Text,{ref:ot,id:h,x:S,y:Z,text:v||(Y?"":"Double-click to edit"),fontSize:W.fontSize,fontFamily:W.fontFamily,fill:W.strokeColor,lineHeight:Xn,width:G,align:U,wrap:Y?"word":"none",rotation:Y?(M==null?void 0:M.rotation)??m:m,transformsEnabled:(Y?(M==null?void 0:M.rotation)??m:m)?"all":"position",visible:!(i&&!F.current&&!v),opacity:v?W.opacity:Y?0:.4,draggable:Q,listening:!Y,onClick:Y?void 0:()=>o(h),onTap:Y?void 0:()=>o(h),onDblClick:w,onDblTap:w,shadowColor:!Y&&e?"#4f8df7":void 0,shadowBlur:!Y&&e?6:0,shadowOpacity:!Y&&e?.5:0,hitStrokeWidth:Y?0:10,perfectDrawEnabled:!1,onDragMove:Y?void 0:X=>{let L=X.target.x(),at=X.target.y();d&&(L=At(L,d),at=At(at,d),X.target.x(L),X.target.y(at)),r==null||r(h,{x:L,y:at})},onDragEnd:Y?void 0:X=>{let L=X.target.x(),at=X.target.y();d&&(L=At(L,d),at=At(at,d)),s(h,{x:L,y:at})},onTransformEnd:Y?void 0:X=>{const L=X.target,at=L.scaleX(),tt=L.scaleY(),E=Math.max(Math.abs(at),Math.abs(tt)),V=Math.max(8,Math.round(W.fontSize*E));L.scaleX(1),L.scaleY(1),s(h,{x:L.x(),y:L.y(),rotation:L.rotation(),style:{...W,fontSize:V}})}})},Qc=I.memo(jc),qc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,src:y,style:m,crop:W,cornerRadius:v,scaleMode:D,isLocked:$}=t,[T,O]=I.useState(null),[ot,F]=I.useState(!1),[J,Y]=I.useState({w:u,h:f});I.useEffect(()=>{Y({w:u,h:f})},[u,f]);const Q=J.w,M=J.h;I.useEffect(()=>{if(!y){O(null),F(!0);return}const E=new window.Image;return E.crossOrigin="anonymous",E.onload=()=>{O(E),F(!1)},E.onerror=()=>{O(null),F(!0)},E.src=y,()=>{E.onload=null,E.onerror=null}},[y]);const k=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();if(l&&(V=At(V,l),dt=At(dt,l),E.target.x(V),E.target.y(dt)),!l&&a){const R=a(c,{x:V,y:dt,width:u,height:f});R&&(V=R.x,dt=R.y,E.target.x(V),E.target.y(dt))}r==null||r(c,{x:V,y:dt})},[c,u,f,l,a,r]),C=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();l&&(V=At(V,l),dt=At(dt,l)),s(c,{x:V,y:dt})},[c,l,s]),w=I.useCallback(E=>{const V=E.target,dt=V.scaleX(),R=V.scaleY(),K=Math.max(10,V.width()*dt),et=Math.max(10,V.height()*R);V.setAttrs({scaleX:1,scaleY:1,width:K,height:et}),Y({w:K,h:et}),r==null||r(c,{x:V.x(),y:V.y(),width:K,height:et})},[c,r]),S=I.useCallback(E=>{const V=E.target;s(c,{x:V.x(),y:V.y(),width:Math.max(10,V.width()),height:Math.max(10,V.height()),rotation:V.rotation()})},[c,s]);let Z=0,G=0,U=Q,X=M,L;if(W&&(L={x:W.x,y:W.y,width:W.width,height:W.height}),T){const E=W?W.width:T.naturalWidth,V=W?W.height:T.naturalHeight;if(D==="fit"){const dt=E/V,R=Q/M;dt>R?(U=Q,X=Q/dt,G=(M-X)/2):(X=M,U=M*dt,Z=(Q-U)/2)}else if(D==="fill"&&!W){const dt=T.naturalWidth,R=T.naturalHeight,K=dt/R,et=Q/M;if(K>et){const Ct=R*et;L={x:(dt-Ct)/2,y:0,width:Ct,height:R}}else{const Ct=dt/et;L={x:0,y:(R-Ct)/2,width:dt,height:Ct}}U=Q,X=M}}const at=v>0?E=>{const V=Math.min(v,Q/2,M/2);E.beginPath(),E.moveTo(V,0),E.lineTo(Q-V,0),E.arcTo(Q,0,Q,V,V),E.lineTo(Q,M-V),E.arcTo(Q,M,Q-V,M,V),E.lineTo(V,M),E.arcTo(0,M,0,M-V,V),E.lineTo(0,V),E.arcTo(0,0,V,0,V),E.closePath()}:void 0,tt={id:c,x:d,y:h,width:Q,height:M,rotation:p,transformsEnabled:p?"all":"position",draggable:!$&&!n,clipFunc:at,onClick:()=>o(c),onTap:()=>o(c),onDblClick:()=>i==null?void 0:i(c),onDblTap:()=>i==null?void 0:i(c),onDragMove:k,onDragEnd:C,onTransform:w,onTransformEnd:S};return!T||ot?g.jsx(gt.Group,{...tt,children:g.jsx(gt.Rect,{width:Q,height:M,fill:"#f0f0f0",stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,opacity:m.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}):g.jsxs(gt.Group,{...tt,shadowColor:e?"#4f8df7":void 0,shadowBlur:e?6:0,shadowOpacity:e?.5:0,children:[D==="fit"&&g.jsx(gt.Rect,{width:Q,height:M,fill:m.fillColor==="transparent"?void 0:m.fillColor,cornerRadius:v}),g.jsx(gt.Image,{image:T,x:Z,y:G,width:U,height:X,crop:L,opacity:m.opacity,listening:!1,perfectDrawEnabled:!1}),m.strokeWidth>0&&m.strokeColor!=="transparent"&&g.jsx(gt.Rect,{width:Q,height:M,stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,listening:!1})]})},ta=I.memo(qc),ea=.5,na=1,oa=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,autoEditText:a,onTextEditStart:c,onTextEditEnd:d,allElements:h,gridSnap:u,onDragSnap:f,viewportScale:p})=>{var m,W,v;const y=I.useCallback(()=>s(t.id),[s,t.id]);if(!t.isVisible)return null;if(p!==void 0&&!e&&!n){const D=Math.max(t.width,t.height)*p;if(D<ea)return null;if(D<na)return g.jsx(gt.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:((m=t.style)==null?void 0:m.fillColor)||"#e0e0e0",stroke:((W=t.style)==null?void 0:W.strokeColor)||"#999",strokeWidth:1/p,opacity:((v=t.style)==null?void 0:v.opacity)??1,onClick:y,onTap:y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,transformsEnabled:"position"})}switch(t.type){case"rectangle":return g.jsx(_c,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"ellipse":return g.jsx(Gc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"diamond":return g.jsx(Xc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"line":return g.jsx(Oc,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"arrow":return g.jsx(Jc,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"freedraw":return g.jsx(Rc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"text":return g.jsx(Qc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,autoEdit:a,onEditStart:c,onEditEnd:d,allElements:h,gridSnap:u});case"image":return g.jsx(ta,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});default:return null}};function sa(t,e){return!(t.element!==e.element||t.isSelected!==e.isSelected||t.isEditing!==e.isEditing||t.isGrouped!==e.isGrouped||t.autoEditText!==e.autoEditText||t.viewportScale!==e.viewportScale||t.gridSnap!==e.gridSnap)}const Ln=I.memo(oa,sa);function ra(t,e){if(t.length===0)return"";const n=new Set(t),o=new Map;for(const r of e)if(n.has(r.id)&&(o.set(r.id,r),o.size===n.size))break;const s=[];for(const r of t){const i=o.get(r);i&&s.push(`${r}:${i.isLocked?1:0}:${i.type}`)}return s.join(",")}const ia=({selectedIds:t,selectionColor:e="#4f8df7"})=>{const n=I.useRef(null),o=B(c=>ra(t,c.elements)),{hasLocked:s,allLocked:r,allText:i}=I.useMemo(()=>{if(!o||t.length===0)return{hasLocked:!1,allLocked:!1,allText:!1};const c=o.split(",");let d=0,h=0;for(const u of c){const f=u.split(":");f[1]==="1"&&d++,f[2]==="text"&&h++}return{hasLocked:d>0,allLocked:d===c.length,allText:h===c.length}},[o,t.length]),l=i?["top-left","top-right","bottom-left","bottom-right"]:["top-left","top-right","bottom-left","bottom-right","middle-left","middle-right","top-center","bottom-center"];if(I.useEffect(()=>{var u;const c=n.current;if(!c)return;const d=c.getStage();if(!d)return;const h=t.map(f=>d.findOne(`#${f}`)).filter(Boolean);c.nodes(h),(u=c.getLayer())==null||u.batchDraw()},[t]),t.length===0)return null;const a=s?"#ff9500":e;return g.jsx(gt.Transformer,{ref:n,flipEnabled:!1,keepRatio:i,resizeEnabled:!r,rotateEnabled:!r,boundBoxFunc:(c,d)=>r||Math.abs(d.width)<5||Math.abs(d.height)<5?c:d,anchorFill:r?"#ff9500":"#ffffff",anchorStroke:a,anchorSize:r?0:8,anchorCornerRadius:2,borderStroke:a,borderStrokeWidth:1,borderDash:r?[6,3]:[4,4],rotateAnchorOffset:25,enabledAnchors:r?[]:l})},la=I.memo(ia),ca=({width:t,height:e,viewport:n,gridColor:o="#e5e5e5"})=>{const{x:s,y:r,scale:i}=n,l=xe,a=I.useMemo(()=>{const c=Math.floor((-s/i-l)/l)*l,d=Math.ceil((-s/i+t/i+l)/l)*l,h=Math.floor((-r/i-l)/l)*l,u=Math.ceil((-r/i+e/i+l)/l)*l;return{startX:c,endX:d,startY:h,endY:u}},[s,r,i,t,e,l]);return g.jsx(gt.Shape,{sceneFunc:c=>{const{startX:d,endX:h,startY:u,endY:f}=a,p=1/i,y=c._context;y.beginPath(),y.strokeStyle=o,y.lineWidth=p;for(let m=d;m<=h;m+=l)y.moveTo(m,u),y.lineTo(m,f);for(let m=u;m<=f;m+=l)y.moveTo(d,m),y.lineTo(h,m);y.stroke()},listening:!1,perfectDrawEnabled:!1})},aa=I.memo(ca),da=({box:t,selectionColor:e="#4f8df7",viewportScale:n=1})=>t?g.jsx(gt.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:`${e}14`,stroke:e,strokeWidth:1/n,dash:[4/n,4/n],listening:!1}):null,ua=I.memo(da),Ie=6,ga=({el:t,color:e,viewportScale:n})=>{const o=t.x+t.width/2,s=t.y+t.height/2,r=t.rotation||0;switch(t.type){case"ellipse":return g.jsx(gt.Ellipse,{x:o,y:s,radiusX:t.width/2+Ie,radiusY:t.height/2+Ie,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1});case"diamond":{const i=t.width+Ie*2,l=t.height+Ie*2,a=[i/2,0,i,l/2,i/2,l,0,l/2];return g.jsx(gt.Line,{x:o-i/2,y:s-l/2,points:a,closed:!0,rotation:r,offsetX:0,offsetY:0,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}default:return g.jsx(gt.Rect,{x:o,y:s,offsetX:t.width/2+Ie,offsetY:t.height/2+Ie,width:t.width+Ie*2,height:t.height+Ie*2,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],cornerRadius:6,fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}},ha=({elements:t,snapTarget:e,visible:n,color:o="#4f8df7",viewportScale:s=1})=>{if(!n||!e)return null;const r=t.find(i=>i.id===e.elementId&&Io(i));return r?g.jsxs(g.Fragment,{children:[g.jsx(ga,{el:r,color:o,viewportScale:s}),g.jsx(gt.Circle,{x:e.position.x,y:e.position.y,radius:6/s,fill:o,stroke:"white",strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1}),!e.isPrecise&&(()=>{const i=r.rotation||0,l={x:r.x+r.width/2,y:r.y+r.height/2},a=i!==0?tr(l,{x:r.x,y:r.y},i*Math.PI/180):l;return g.jsx(gt.Circle,{x:a.x,y:a.y,radius:4/s,fill:"white",stroke:o,strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1})})()]}):null},fa=I.memo(ha),_r=4,pa=3,ya="#ffffff",Ia="#4f8df7",Ca="#2563eb",ba="#4f8df7",ma=5,Aa="#ff6b35",wa="#ffffff";function xa(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Mr(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const ka=({element:t,allElements:e,onPointsChange:n,onPointDragMove:o,onSnapTargetChange:s,color:r="#4f8df7"})=>{const{selectedPointIndices:i,hoveredPointIndex:l,hoveredMidpointIndex:a,setSelectedPoints:c,togglePointSelection:d,setHoveredPoint:h,setHoveredMidpoint:u,setIsDraggingPoint:f}=dn(),{id:p,x:y,y:m,points:W}=t,v=xa(W),D=I.useRef(null),$=I.useRef(null),T=I.useRef(void 0),O="lineType"in t&&t.lineType==="curved",ot="lineType"in t&&t.lineType==="elbow",F=O||ot,J=I.useCallback(w=>w===0||w===v.length-1,[v.length]),Y=I.useCallback(w=>{f(!0),D.current={points:[...W],x:y,y:m},T.current=void 0,i.includes(w)||c([w])},[W,y,m,i,c,f]),Q=I.useCallback((w,S)=>{const Z=S.target,G=Z.x(),U=Z.y(),X=[...W];X[w*2]=G-y,X[w*2+1]=U-m;const L={};if(J(w)){const at=Z.getStage(),tt=at==null?void 0:at.getRelativePointerPosition(),E=(tt==null?void 0:tt.x)??G,V=(tt==null?void 0:tt.y)??U;$.current={x:E,y:V};const dt={x:E,y:V},R=new Set([p]),K=w===0?t.endBinding:t.startBinding;K&&R.add(K.elementId);const et=ce(t.style.strokeWidth??2),Ct=ke(dt,e,24,R,void 0,void 0,et,T.current);if(s==null||s(Ct),T.current=Ct==null?void 0:Ct.isPrecise,Ct){const bt=Ct.position;X[w*2]=bt.x-y,X[w*2+1]=bt.y-m,Z.x(bt.x),Z.y(bt.y);const rt={elementId:Ct.elementId,fixedPoint:Ct.fixedPoint,gap:et,isPrecise:Ct.isPrecise};w===0?L.startBinding=rt:L.endBinding=rt}else w===0?L.startBinding=null:L.endBinding=null}o==null||o(p,{points:X,x:y,y:m,...L})},[W,y,m,p,t,e,J,o,s]),M=I.useCallback((w,S)=>{f(!1);const Z=S.target;let G,U;J(w)&&$.current?(G=$.current.x,U=$.current.y):(G=Z.x(),U=Z.y()),$.current=null;const X=[...W];X[w*2]=G-y,X[w*2+1]=U-m;const L={points:X};if(J(w)){const R={x:G,y:U},K=new Set([p]),et=w===0?t.endBinding:t.startBinding;et&&K.add(et.elementId);const Ct=ce(t.style.strokeWidth??2),bt=ke(R,e,24,K,void 0,void 0,Ct,T.current);if(s==null||s(null),T.current=void 0,bt){const rt=ce(t.style.strokeWidth??2),st={elementId:bt.elementId,fixedPoint:bt.fixedPoint,gap:rt,isPrecise:bt.isPrecise};w===0?L.startBinding=st:L.endBinding=st,X[w*2]=bt.position.x-y,X[w*2+1]=bt.position.y-m,L.points=X}else w===0?L.startBinding=null:L.endBinding=null}const at=L.points??X,tt=at[0],E=at[1];if(tt!==0||E!==0){const R=[];for(let K=0;K<at.length;K+=2)R.push(at[K]-tt,at[K+1]-E);L.x=y+tt,L.y=m+E,L.points=R}const V=L.points??at,dt=Tn(V);L.width=dt.width,L.height=dt.height,n(p,L),D.current=null},[W,y,m,p,v,t,e,J,f,n,s]),k=I.useCallback((w,S)=>{S.cancelBubble=!0,S.evt.shiftKey?d(w):c([w])},[c,d]),C=I.useCallback((w,S)=>{S.cancelBubble=!0;const Z=v[w],G=v[w+1],U=Mr(Z,G),X=w+1,L=[];for(let tt=0;tt<v.length;tt++)L.push(v[tt].x,v[tt].y),tt===w&&L.push(U.x,U.y);const at=Tn(L);c([X]),u(null),n(p,{points:L,width:at.width,height:at.height})},[p,v,c,u,n]);return g.jsxs(gt.Group,{children:[!F&&v.length>=2&&v.slice(0,-1).map((w,S)=>{const Z=v[S+1],G=Mr(w,Z),U=a===S;return g.jsx(gt.Circle,{x:y+G.x,y:m+G.y,radius:pa,fill:U?Ca:Ia,opacity:U?.9:.5,stroke:"white",strokeWidth:1.5,onMouseEnter:()=>u(S),onMouseLeave:()=>u(null),onClick:X=>C(S,X),onTap:X=>C(S,X),hitStrokeWidth:10,perfectDrawEnabled:!1},`mid-${S}`)}),v.map((w,S)=>{const Z=J(S);if(F&&!Z)return null;const G=i.includes(S),U=l===S,X=Z?_r+1:_r;return g.jsx(gt.Circle,{x:y+w.x,y:m+w.y,radius:X,fill:G?ba:ya,stroke:U||G?"#2563eb":r,strokeWidth:G?2.5:2,draggable:!0,onMouseEnter:()=>h(S),onMouseLeave:()=>h(-1),onClick:L=>k(S,L),onTap:L=>k(S,L),onDragStart:()=>Y(S),onDragMove:L=>Q(S,L),onDragEnd:L=>M(S,L),hitStrokeWidth:10,perfectDrawEnabled:!1},`pt-${S}`)}),O&&v.length>=2&&(()=>{const w=v[0],S=v[v.length-1],Z=t.curvature??zt,G=Jt(w,S,Z),U=Ye(w,G,S,.5);return g.jsx(gt.Circle,{x:y+U.x,y:m+U.y,radius:ma,fill:Aa,stroke:wa,strokeWidth:2,draggable:!0,onDragStart:()=>f(!0),onDragMove:X=>{const L=X.target,at={x:y+w.x,y:m+w.y},tt={x:y+S.x,y:m+S.y},E={x:L.x(),y:L.y()},V=nr(at,tt,E),dt=Jt(w,S,V),R=Ye(w,dt,S,.5);L.x(y+R.x),L.y(m+R.y),o==null||o(p,{curvature:V})},onDragEnd:X=>{f(!1);const L=X.target,at={x:y+w.x,y:m+w.y},tt={x:y+S.x,y:m+S.y},E={x:L.x(),y:L.y()},V=nr(at,tt,E),dt=Jt(w,S,V),R=Ye(w,dt,S,.5);L.x(y+R.x),L.y(m+R.y),n(p,{curvature:V})},hitStrokeWidth:12,perfectDrawEnabled:!1},"curve-handle")})()]})},Sa=I.memo(ka),va={Hand:g.jsx(It.Hand,{size:18}),MousePointer2:g.jsx(It.MousePointer2,{size:18}),Square:g.jsx(It.Square,{size:18}),Circle:g.jsx(It.Circle,{size:18}),Diamond:g.jsx(It.Diamond,{size:18}),Minus:g.jsx(It.Minus,{size:18}),ArrowUpRight:g.jsx(It.ArrowUpRight,{size:18}),Pencil:g.jsx(It.Pencil,{size:18}),Type:g.jsx(It.Type,{size:18}),ImageIcon:g.jsx(It.ImageIcon,{size:18}),Eraser:g.jsx(It.Eraser,{size:18}),StickyNote:g.jsx(It.StickyNote,{size:18})},Ce=(t,e,n)=>({display:"flex",alignItems:"center",justifyContent:"center",width:34,height:34,borderRadius:8,border:"none",cursor:n?"not-allowed":"pointer",transition:"background 150ms, color 150ms",background:t?`${e.activeToolColor}20`:"transparent",color:t?e.activeToolColor:n?`${e.mutedTextColor}55`:e.mutedTextColor,outline:t?`1.5px solid ${e.activeToolColor}50`:"none",flexShrink:0,opacity:n?.45:1}),Fn=t=>({width:1,height:22,background:t.toolbarBorder,margin:"0 3px",flexShrink:0}),Gr=t=>({display:"flex",alignItems:"center",gap:1,background:t.toolbarBg,backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",boxShadow:"0 2px 10px rgba(0,0,0,0.08)",borderRadius:12,padding:"5px 8px",border:`1px solid ${t.toolbarBorder}`});function Ea(t,e,n){const[o,s]=I.useState(null),r=I.useRef(e);r.current=e;const i=I.useCallback(()=>{t.current&&s(r.current(t.current.getBoundingClientRect()))},[t]);return I.useEffect(()=>{if(!n){s(null);return}return i(),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0)}},[n,i]),o}const Fo=({anchorRef:t,onClose:e,theme:n,placement:o,computePos:s,transform:r,dataAttribute:i,style:l,children:a,isOpen:c})=>{const d=Ea(t,h=>s(h,o),c);return I.useEffect(()=>{if(!c)return;const h=f=>{t.current&&t.current.contains(f.target)||f.target.closest(`[${i}]`)||e()},u=()=>e();return document.addEventListener("mousedown",h),window.addEventListener("resize",u),()=>{document.removeEventListener("mousedown",h),window.removeEventListener("resize",u)}},[c,e,i,t]),!c||!d?null:xs.createPortal(g.jsx("div",{[i]:"true",style:{position:"fixed",top:d.top,left:d.left,transform:r,background:n.toolbarBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:`1px solid ${n.toolbarBorder}`,borderRadius:12,boxShadow:"0 8px 28px rgba(0,0,0,0.12)",zIndex:9999,...l},children:a}),document.body)},Dr=({icon:t,label:e,disabled:n,isActive:o,onClick:s,theme:r,size:i=36})=>g.jsx("button",{title:e,disabled:n,onClick:n?void 0:s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:i,height:i,borderRadius:8,border:`1px solid ${o?`${r.activeToolColor}50`:"transparent"}`,background:o?`${r.activeToolColor}18`:"transparent",cursor:n?"default":"pointer",color:o?r.activeToolColor:n?`${r.mutedTextColor}55`:r.mutedTextColor,opacity:n?.4:1,transition:"background 120ms, color 120ms, border-color 120ms"},onMouseEnter:l=>{!n&&!o&&(l.currentTarget.style.background=`${r.activeToolColor}14`,l.currentTarget.style.color=r.activeToolColor,l.currentTarget.style.borderColor=`${r.activeToolColor}30`)},onMouseLeave:l=>{o||(l.currentTarget.style.background="transparent",l.currentTarget.style.color=n?`${r.mutedTextColor}55`:r.mutedTextColor,l.currentTarget.style.borderColor="transparent")},children:t}),Wa=({actions:t,anchorRef:e,onClose:n,theme:o,placement:s="bottom"})=>g.jsx(Fo,{isOpen:!0,anchorRef:e,onClose:n,theme:o,placement:s,computePos:(r,i)=>i==="top"?{top:r.bottom+8,left:r.left+r.width/2}:{top:r.top-12,left:r.left+r.width/2},transform:s==="top"?"translate(-50%, 0)":"translate(-50%, -100%)",dataAttribute:"data-subtools-popup",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(4, 36px)",gap:4},children:t.map((r,i)=>g.jsx(Dr,{icon:r.icon,label:r.label,disabled:r.disabled,onClick:()=>{r.onClick(),n()},theme:o},i))}),Ta=({shapes:t,activeTool:e,anchorRef:n,onSelect:o,onClose:s,theme:r,placement:i="bottom"})=>g.jsx(Fo,{isOpen:!0,anchorRef:n,onClose:s,theme:r,placement:i,computePos:(l,a)=>a==="top"?{top:l.bottom+8,left:l.right}:{top:l.top-12,left:l.right},transform:i==="top"?"translate(-100%, 0)":"translate(-100%, -100%)",dataAttribute:"data-shape-picker",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(5, 40px)",gap:4},children:t.filter(l=>l.tool!==null).map((l,a)=>g.jsx(Dr,{icon:l.icon,label:l.label,disabled:l.tool===null,isActive:l.tool!==null&&e===l.tool,onClick:()=>{l.tool&&(o(l.tool),s())},theme:r,size:40},a))}),Ba=({scale:t,theme:e,onZoomIn:n,onZoomOut:o,onReset:s,placement:r="bottom"})=>{const[i,l]=I.useState(!1),a=I.useRef(null);return g.jsxs("div",{ref:a,style:{position:"relative"},children:[g.jsxs("button",{style:{...Ce(i,e),width:"auto",padding:"0 6px",gap:2,fontSize:11,minWidth:52},onClick:()=>l(!i),title:"Zoom",children:[g.jsxs("span",{style:{minWidth:32,textAlign:"center",userSelect:"none"},children:[Math.round(t*100),"%"]}),g.jsx(It.ChevronDown,{size:12})]}),g.jsx(Fo,{isOpen:i,anchorRef:a,onClose:()=>l(!1),theme:e,placement:r,computePos:(c,d)=>d==="top"?{top:c.bottom+6,left:c.left}:{top:c.top-6,left:c.left},transform:r==="top"?"translateY(0)":"translateY(-100%)",dataAttribute:"data-zoom-dropdown",style:{padding:4,minWidth:130},children:[{icon:g.jsx(It.ZoomIn,{size:14}),label:"Zoom In",fn:()=>{n(),l(!1)}},{icon:g.jsx(It.ZoomOut,{size:14}),label:"Zoom Out",fn:()=>{o(),l(!1)}},{icon:g.jsx(It.Maximize,{size:14}),label:"Reset Zoom",fn:()=>{s(),l(!1)}}].map(({icon:c,label:d,fn:h})=>g.jsxs("button",{onClick:h,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:"transparent",color:e.textColor,cursor:"pointer",borderRadius:4,fontSize:12},onMouseEnter:u=>{u.currentTarget.style.background=`${e.activeToolColor}14`},onMouseLeave:u=>{u.currentTarget.style.background="transparent"},children:[c,g.jsx("span",{children:d})]},d))})]})},Za=({visibleTools:t,theme:e,position:n="bottom"})=>{const o=B(E=>E.activeTool),s=B(E=>E.setActiveTool),r=B(E=>E.undo),i=B(E=>E.redo),l=B(E=>E.selectedIds),a=B(E=>E.elements),c=B(E=>E.deleteElements),d=B(E=>E.duplicateElements),h=B(E=>E.bringToFront),u=B(E=>E.bringForward),f=B(E=>E.sendBackward),p=B(E=>E.sendToBack),y=B(E=>E.toggleLockElements),m=B(E=>E.ungroupElements),W=B(E=>E.pushHistory),v=B(E=>E.showGrid),D=B(E=>E.toggleGrid),$=B(E=>E.zoomIn),T=B(E=>E.zoomOut),O=B(E=>E.resetZoom),ot=B(E=>E.viewport.scale),[F,J]=I.useState(!1),Y=I.useRef(null),[Q,M]=I.useState(!1),k=I.useRef(null),C=l.length>0,w=l.length>1,S=C&&a.filter(E=>l.includes(E.id)).every(E=>E.isLocked),Z=()=>{const E=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),V=URL.createObjectURL(E),dt=Object.assign(document.createElement("a"),{href:V,download:"canvas.json"});document.body.appendChild(dt),dt.click(),document.body.removeChild(dt),URL.revokeObjectURL(V)},G=[{icon:g.jsx(It.AlignLeft,{size:16}),label:"Align Left",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignCenter,{size:16}),label:"Align Center H",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignRight,{size:16}),label:"Align Right",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignCenterVertical,{size:16}),label:"Align Center V",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignStartVertical,{size:16}),label:"Align Top",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignEndVertical,{size:16}),label:"Align Bottom",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.FlipHorizontal,{size:16}),label:"Flip H",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.FlipVertical,{size:16}),label:"Flip V",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.ChevronsUp,{size:16}),label:"Bring to Front",disabled:!C,onClick:()=>{h(l),W()}},{icon:g.jsx(It.ArrowUp,{size:16}),label:"Bring Forward",disabled:!C,onClick:()=>{u(l),W()}},{icon:g.jsx(It.ArrowDown,{size:16}),label:"Send Backward",disabled:!C,onClick:()=>{f(l),W()}},{icon:g.jsx(It.ChevronsDown,{size:16}),label:"Send to Back",disabled:!C,onClick:()=>{p(l),W()}},{icon:g.jsx(It.RotateCcw,{size:16}),label:"Rotate Left 90°",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.RotateCw,{size:16}),label:"Rotate Right 90°",disabled:!C,onClick:()=>{}},{icon:S?g.jsx(It.Unlock,{size:16}):g.jsx(It.Lock,{size:16}),label:S?"Unlock":"Lock",disabled:!C,onClick:()=>{y(l),W()}},{icon:g.jsx(It.Ungroup,{size:16}),label:"Ungroup",disabled:!C,onClick:()=>{m(l),W()}},{icon:g.jsx(It.Grid3x3,{size:16}),label:v?"Hide Grid":"Show Grid",disabled:!1,onClick:D},{icon:g.jsx(It.Download,{size:16}),label:"Export JSON",disabled:!1,onClick:Z},{icon:g.jsx(It.Maximize,{size:16}),label:"Reset Zoom",disabled:!1,onClick:O},{icon:g.jsx(It.Group,{size:16}),label:"Select All",disabled:!1,onClick:()=>{}}],X=[{icon:g.jsx(It.Square,{size:16}),label:"Rectangle",tool:"rectangle"},{icon:g.jsx(It.Circle,{size:16}),label:"Ellipse",tool:"ellipse"},{icon:g.jsx(It.Diamond,{size:16}),label:"Diamond",tool:"diamond"},{icon:g.jsx(It.Minus,{size:16}),label:"Line",tool:"line"},{icon:g.jsx(It.ArrowUpRight,{size:16}),label:"Arrow",tool:"arrow"}].filter(E=>E.tool===null?!0:!t.some(V=>V.type===E.tool)),L=E=>s(E),at=G.filter(E=>!["Undo","Redo","Delete","Duplicate"].includes(E.label)),tt=n==="top";return g.jsx("div",{style:{position:"absolute",...tt?{top:16}:{bottom:16},left:0,right:0,zIndex:50,display:"flex",justifyContent:"center",alignItems:tt?"flex-start":"flex-end",pointerEvents:"none"},children:g.jsxs("div",{style:{display:"flex",flexDirection:tt?"column-reverse":"column",alignItems:"center",maxWidth:"calc(100% - 32px)",gap:0,pointerEvents:"none"},children:[g.jsxs("div",{style:{...Gr(e),pointerEvents:"auto",...tt?{borderRadius:"0 0 12px 12px",borderTop:"none"}:{borderRadius:"12px 12px 0 0",borderBottom:"none"}},children:[g.jsx("button",{style:Ce(!1,e),onClick:r,title:"Undo (⌘Z)",children:g.jsx(It.Undo2,{size:16})}),g.jsx("button",{style:Ce(!1,e),onClick:i,title:"Redo (⌘⇧Z)",children:g.jsx(It.Redo2,{size:16})}),g.jsx("div",{style:Fn(e)}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&c(l)},title:"Delete (⌫)",children:g.jsx(It.Trash2,{size:16})}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&d(l)},title:"Duplicate (⌘D)",children:g.jsx(It.Copy,{size:16})}),at.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:Fn(e)}),g.jsx("button",{ref:Y,style:Ce(F,e),onClick:()=>{J(!F),M(!1)},title:"More actions",children:g.jsx(It.MoreHorizontal,{size:16})})]})]}),g.jsxs("div",{style:{...Gr(e),pointerEvents:"auto",...tt?{borderRadius:"12px 12px 0 0",borderBottom:"none"}:{}},children:[t.map(E=>g.jsx("button",{style:Ce(o===E.type,e),onClick:()=>s(E.type),title:`${E.label} (${E.shortcut})`,children:va[E.icon]},E.type)),g.jsx("div",{style:Fn(e)}),g.jsx(Ba,{scale:ot,theme:e,onZoomIn:$,onZoomOut:T,onReset:O,placement:n}),X.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:Fn(e)}),g.jsx("button",{ref:k,style:Ce(Q,e),onClick:()=>{M(!Q),J(!1)},title:"More shapes",children:g.jsx(It.ChevronUp,{size:16})})]})]}),F&&at.length>0&&g.jsx(Wa,{actions:at,anchorRef:Y,onClose:()=>J(!1),theme:e,placement:n}),Q&&X.length>0&&g.jsx(Ta,{shapes:X,activeTool:o,anchorRef:k,onSelect:L,onClose:()=>M(!1),theme:e,placement:n})]})})},be=({theme:t,variant:e="toggle",isActive:n=!1,dangerHover:o=!1,onClick:s,title:r,disabled:i=!1,width:l=28,height:a=28,style:c,children:d})=>{const[h,u]=I.useState(!1),f=n||h,p=()=>e==="toggle"&&n?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",y=()=>e==="toggle"&&n?`${t.activeToolColor}10`:h?"#f3f4f6":"transparent";return g.jsx("button",{title:r,onClick:i?void 0:s,disabled:i,onMouseEnter:()=>!i&&u(!0),onMouseLeave:()=>u(!1),style:{width:l,height:a,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:5,border:p(),background:y(),cursor:i?"not-allowed":"pointer",color:n?t.activeToolColor:t.textColor,transition:"background 0.1s, border-color 0.1s",outline:"none",padding:0,opacity:i?.35:1,flexShrink:0,...c},children:typeof d=="function"?d(f):d})},Vo=({theme:t,isActive:e=!1,onClick:n,title:o,disabled:s,flex:r=1,width:i,children:l,style:a})=>g.jsx("button",{title:o,onClick:n,disabled:s,style:{flex:r,width:i,padding:"3px 0",borderRadius:4,border:e?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",background:e?`${t.activeToolColor}10`:"transparent",cursor:"pointer",fontSize:10,fontWeight:500,color:e?t.activeToolColor:t.textColor,textAlign:"center",outline:"none",...a},children:l}),Mt=({theme:t,label:e,headerAction:n,children:o,style:s})=>g.jsxs("div",{style:{marginBottom:10,...s},children:[e&&g.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:n?"space-between":"flex-start",marginBottom:n?0:5},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:e}),n]}),o]}),Te=({children:t,gap:e=5,wrap:n=!1,columns:o=4,style:s})=>g.jsx("div",{style:{display:o?"grid":"flex",gridTemplateColumns:o?`repeat(${o}, 1fr)`:void 0,gap:e,justifyContent:o?void 0:"flex-start",flexWrap:!o&&n?"wrap":"nowrap",...s},children:t}),Vn=({options:t,value:e,onChange:n,theme:o,label:s,isOpen:r,onToggle:i,pickerRef:l,columns:a,style:c})=>{const d=t.find(p=>p.value===e)??t[0],h=I.useRef(null),[u,f]=I.useState(null);return I.useEffect(()=>{if(r&&h.current){const p=h.current.getBoundingClientRect();f({top:p.bottom+3,left:p.left})}else f(null)},[r]),g.jsxs("div",{ref:l,style:{position:"relative",display:"inline-flex",...c},children:[g.jsx("button",{ref:h,title:`${s}: ${d.label}`,onClick:i,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",height:28,padding:"0 8px",borderRadius:6,border:r?`1.5px solid ${o.activeToolColor}`:"1px solid #e0e3e7",background:r?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:r?o.activeToolColor:o.textColor,outline:"none",transition:"background 0.15s, border-color 0.15s",boxShadow:r?`0 0 0 2px ${o.activeToolColor}20`:"none"},children:typeof d.icon=="function"?d.icon(r?o.activeToolColor:o.textColor):d.icon}),r&&u&&xs.createPortal(g.jsx("div",{"data-compact-dropdown":"true",style:{position:"fixed",top:u.top,left:u.left,background:o.panelBg,border:`1px solid ${o.toolbarBorder}`,borderRadius:6,padding:3,boxShadow:"0 3px 12px rgba(0,0,0,0.1)",zIndex:9999,display:"grid",gridTemplateColumns:a?`repeat(${a}, 26px)`:`repeat(${t.length}, 26px)`,gap:1},children:t.map(p=>{const y=p.value===e,m=y?o.activeToolColor:o.textColor;return g.jsx("button",{title:p.label,onClick:()=>{n(p.value),i()},style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,borderRadius:4,border:y?`1.5px solid ${o.activeToolColor}`:"1px solid transparent",background:y?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:m,outline:"none"},children:typeof p.icon=="function"?p.icon(m):p.icon},String(p.value))})}),document.body)]})},Po=20,_a=4,Ma=6,Ga=[{value:1,label:"Thin",thickness:1},{value:2,label:"Normal",thickness:2},{value:4,label:"Bold",thickness:3.5},{value:6,label:"Extra Bold",thickness:5.5}],Da=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],Xa=({thickness:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"2",y1:"7",x2:"12",y2:"7",stroke:e,strokeWidth:t,strokeLinecap:"round"})}),La=({style:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"1",y1:"7",x2:"13",y2:"7",stroke:e,strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:t==="dashed"?"3.5 2.5":t==="dotted"?"1 2.5":void 0})}),Fa=({level:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t===0?g.jsx("path",{d:"M2,9 Q5,5 7,7 Q9,9 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):t===1?g.jsx("path",{d:"M2,9 Q3.5,3 6,8 Q8,13 10,6 Q11,3 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):g.jsx("path",{d:"M1,8 Q3,3 4.5,9 Q6,13 7,6 Q8.5,1 10,9 Q11.5,13 13,6",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"})}),Va=({type:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t==="sharp"?g.jsx("polyline",{points:"2,11 7,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}):t==="elbow"?g.jsx("polyline",{points:"2,11 2,3 12,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"square",strokeLinejoin:"miter"}):g.jsx("path",{d:"M2,11 Q7,0 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round"})}),Xr={standard:({size:t,color:e,strokeWidth:n})=>g.jsx(It.PenLine,{size:t,color:e,strokeWidth:n}),pen:({size:t,color:e,strokeWidth:n})=>g.jsx(It.PenTool,{size:t,color:e,strokeWidth:n}),pencil:({size:t,color:e,strokeWidth:n})=>g.jsx(It.Pencil,{size:t,color:e,strokeWidth:n}),brush:({size:t,color:e,strokeWidth:n})=>g.jsx(It.Brush,{size:t,color:e,strokeWidth:n})},Pa=({style:t,color:e})=>{const n=Xr[t]??Xr.standard;return g.jsx(n,{size:16,color:e,strokeWidth:1.5})},Lr=({arrowhead:t,end:e,color:n})=>{let l=18,a=null;switch(t){case null:break;case"arrow":l=16,a=g.jsx("path",{d:`M12,${6-3.5} L18,6 L12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"});break;case"triangle":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:n});break;case"triangle_outline":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinejoin:"round"});break;case"circle":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:n});break;case"circle_outline":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"diamond":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:n});break;case"diamond_outline":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"bar":a=g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"});break;case"crowfoot_one":l=14,a=g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:14,y1:6-3.5,x2:14,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_one_or_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18-3.5,y1:6-3.5,x2:18-3.5,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break}const c=e==="start"?"scale(-1,1) translate(-20,0)":void 0;return g.jsx("svg",{width:14,height:12,viewBox:"0 0 20 12",fill:"none",children:g.jsxs("g",{transform:c,children:[g.jsx("line",{x1:2,y1:6,x2:l,y2:6,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"}),a]})})},me=({children:t,color:e,size:n=12})=>g.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t}),Pn={sendToBack:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 12 12 18"}),g.jsx("polyline",{points:"9 15 12 18 15 15"})]}),sendBackward:t=>g.jsxs(me,{color:t,children:[g.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),g.jsx("polyline",{points:"19 12 12 19 5 12"})]}),bringForward:t=>g.jsxs(me,{color:t,children:[g.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),g.jsx("polyline",{points:"5 12 12 5 19 12"})]}),bringToFront:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 18 12 12"}),g.jsx("polyline",{points:"9 15 12 12 15 15"})]})},Yn={duplicate:t=>g.jsxs(me,{color:t,children:[g.jsx("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"}),g.jsx("path",{d:"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"})]}),delete:t=>g.jsxs(me,{color:t,children:[g.jsx("polyline",{points:"3 6 5 6 21 6"}),g.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),g.jsx("path",{d:"M10 11v6"}),g.jsx("path",{d:"M14 11v6"}),g.jsx("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),link:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),g.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),ungroup:t=>g.jsxs(me,{color:t,children:[g.jsx("rect",{x:"2",y:"2",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("rect",{x:"14",y:"14",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("path",{d:"M14 2h4a2 2 0 0 1 2 2v4"}),g.jsx("path",{d:"M2 14v4a2 2 0 0 0 2 2h4"})]})},Ya=({theme:t})=>{const e=B(A=>A.currentStyle),n=B(A=>A.setCurrentStyle),o=B(A=>A.selectedIds),s=B(A=>A.elements),r=B(A=>A.updateElement),i=B(A=>A.pushHistory),l=B(A=>A.toggleLockElements),a=B(A=>A.deleteElements),c=B(A=>A.duplicateElements),d=B(A=>A.bringToFront),h=B(A=>A.sendToBack),u=B(A=>A.bringForward),f=B(A=>A.sendBackward),p=B(A=>A.activeTool),y=B(A=>A.currentLineType),m=B(A=>A.setCurrentLineType),W=B(A=>A.currentStartArrowhead),v=B(A=>A.setCurrentStartArrowhead),D=B(A=>A.currentEndArrowhead),$=B(A=>A.setCurrentEndArrowhead),[T,O]=I.useState(null),ot=I.useRef(null),F=I.useRef(null),[J,Y]=I.useState(null),Q=I.useRef(null),M=I.useRef(null),k=I.useRef(null),C=I.useRef(null);I.useEffect(()=>{if(!T)return;const A=lt=>{const mt=T==="start"?ot:F,j=mt.current&&mt.current.contains(lt.target),Dt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Dt&&O(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[T]),I.useEffect(()=>{if(!J)return;const A=lt=>{const mt=J==="sloppiness"?Q:M,j=mt.current&&mt.current.contains(lt.target),Dt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Dt&&Y(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[J]);const w=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(mt=>mt.id===A))==null?void 0:lt.type)==="text"}),[o,s]),S=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return A&&(A.type==="arrow"||A.type==="line")?A:null},[o,s]),Z=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return!A||A.type!=="image"?null:A},[o,s]),G=I.useMemo(()=>{if(o.length===0)return null;const A=s.filter(j=>o.includes(j.id)),lt=A.every(j=>j.isLocked),mt=A.some(j=>j.isLocked);return{allLocked:lt,anyLocked:mt}},[o,s]),U=(S==null?void 0:S.type)==="arrow",X=S!=null,L=o.length>0,at=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(mt=>mt.id===A))==null?void 0:lt.type)==="freedraw"}),[o,s]),tt=p==="arrow"||p==="line",E=p==="arrow",V=X||tt,dt=U||E,R=at||p==="freedraw",K=I.useMemo(()=>{if(o.length===0)return e;if(o.length===1){const lt=s.find(mt=>mt.id===o[0]);if(lt)return lt.style}const A=s.find(lt=>o.includes(lt.id));return A?A.style:e},[o,s,e]),et=A=>{n(A),o.length>0&&(o.forEach(lt=>{const mt=s.find(j=>j.id===lt);mt&&r(lt,{style:{...mt.style,...A}})}),i())},Ct=Math.round(K.opacity*100),bt={position:"absolute",left:12,top:64,zIndex:50,width:160,background:t.panelBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",boxShadow:"0 1px 4px rgba(0,0,0,0.05), 0 3px 12px rgba(0,0,0,0.07)",borderRadius:10,padding:"10px 10px 8px",border:`1px solid ${t.toolbarBorder}`,maxHeight:"calc(100vh - 90px)",overflowY:"auto",fontFamily:"system-ui, -apple-system, sans-serif"},rt=(A,lt)=>({width:Po,height:Po,borderRadius:4,border:lt?`2px solid ${t.activeToolColor}`:"1.5px solid #d5d8dc",cursor:"pointer",background:A==="transparent"?"repeating-conic-gradient(#d1d5db 0% 25%, transparent 0% 50%) 50%/6px 6px":A,boxShadow:lt?`0 0 0 1.5px ${t.activeToolColor}30`:"none",outline:"none",flexShrink:0,transition:"border-color 0.1s, box-shadow 0.1s",padding:0}),st={height:1,background:t.toolbarBorder,margin:"10px 0",border:"none"},pt={display:"grid",gridTemplateColumns:`repeat(${Ma}, ${Po}px)`,gap:_a};return g.jsxs("div",{style:bt,children:[g.jsx(Mt,{label:"Stroke",theme:t,children:g.jsxs("div",{style:pt,children:[tn.map(A=>g.jsx("button",{style:rt(A,K.strokeColor===A),onClick:()=>et({strokeColor:A}),title:A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=k.current)==null?void 0:A.click()},style:{...rt(K.strokeColor,!tn.includes(K.strokeColor)),background:tn.includes(K.strokeColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":K.strokeColor,border:tn.includes(K.strokeColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:k,type:"color",value:K.strokeColor.startsWith("#")?K.strokeColor:"#000000",onChange:A=>et({strokeColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),!X&&!tt&&!at&&p!=="freedraw"&&g.jsx(Mt,{label:"Background",theme:t,children:g.jsxs("div",{style:pt,children:[en.map(A=>g.jsx("button",{style:rt(A,K.fillColor===A),onClick:()=>et({fillColor:A}),title:A==="transparent"?"None":A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=C.current)==null?void 0:A.click()},style:{...rt(K.fillColor,!en.includes(K.fillColor)),background:en.includes(K.fillColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":K.fillColor,border:en.includes(K.fillColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:C,type:"color",value:K.fillColor.startsWith("#")?K.fillColor:"#ffffff",onChange:A=>et({fillColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),g.jsx(Mt,{label:"Stroke width",theme:t,children:g.jsx(Te,{columns:4,children:Ga.map(A=>g.jsx(be,{isActive:K.strokeWidth===A.value,theme:t,onClick:()=>et({strokeWidth:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Xa,{thickness:A.thickness,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(Mt,{label:"Stroke style",theme:t,children:g.jsx(Te,{columns:4,children:Da.map(A=>g.jsx(be,{isActive:K.strokeStyle===A.value,theme:t,onClick:()=>et({strokeStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(La,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(Mt,{label:"Sloppiness",theme:t,headerAction:g.jsx(Vn,{label:"Sloppiness",style:{width:32},value:K.roughness,options:Ss.map(A=>({value:A.value,label:A.label,icon:lt=>g.jsx(Fa,{level:A.value,color:lt})})),onChange:A=>{et({roughness:A})},theme:t,isOpen:J==="sloppiness",onToggle:()=>Y(J==="sloppiness"?null:"sloppiness"),pickerRef:Q})}),R&&g.jsx(Mt,{label:"Pen style",theme:t,children:g.jsx(Te,{columns:4,children:sl.map(A=>g.jsx(be,{isActive:(K.freehandStyle||"standard")===A.value,theme:t,onClick:()=>et({freehandStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Pa,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),V&&g.jsx(Mt,{label:U||E?"Arrow type":"Line type",theme:t,headerAction:g.jsx(Vn,{label:U||E?"Arrow type":"Line type",style:{width:32},value:S?S.lineType:y,options:uo.map(A=>({value:A.type,label:A.label,icon:lt=>g.jsx(Va,{type:A.type,color:lt})})),onChange:A=>{const lt=uo.find(mt=>mt.type===A);if(lt){if(S){const mt={lineType:lt.type};if(lt.type==="curved"||lt.type==="elbow"){const j=S;j.points.length>4&&(mt.points=[j.points[0],j.points[1],j.points[j.points.length-2],j.points[j.points.length-1]])}r(S.id,mt),i()}m(lt.type),Y(null)}},theme:t,isOpen:J==="lineType",onToggle:()=>Y(J==="lineType"?null:"lineType"),pickerRef:M})}),dt&&g.jsx(Mt,{label:"Arrows",theme:t,headerAction:g.jsxs("div",{style:{display:"flex",gap:4},children:[g.jsx(Vn,{label:"Start arrowhead",style:{width:32},value:(S?S.startArrowhead:W)??"__none__",options:ao.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(Lr,{arrowhead:A.type,end:"start",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{startArrowhead:lt}),i()),v(lt)},columns:4,theme:t,isOpen:T==="start",onToggle:()=>O(T==="start"?null:"start"),pickerRef:ot}),g.jsx(Vn,{label:"End arrowhead",style:{width:32},value:(S?S.endArrowhead:D)??"__none__",options:ao.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(Lr,{arrowhead:A.type,end:"end",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{endArrowhead:lt}),i()),$(lt)},columns:4,theme:t,isOpen:T==="end",onToggle:()=>O(T==="end"?null:"end"),pickerRef:F})]})}),g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsxs(Mt,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Opacity"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[Ct,"%"]})]}),g.jsx("input",{type:"range",min:"0",max:"100",step:"1",value:Ct,onChange:A=>et({opacity:parseInt(A.target.value)/100}),style:{width:"100%",accentColor:t.activeToolColor,height:4}})]})]}),w&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Font size",theme:t,children:g.jsx(Te,{columns:0,wrap:!0,gap:2,children:nl.map(A=>g.jsx(Vo,{isActive:K.fontSize===A,theme:t,onClick:()=>et({fontSize:A}),flex:"none",style:{width:28,padding:"2px 0"},children:A},A))})}),g.jsx(Mt,{label:"Font family",theme:t,children:g.jsx("select",{value:K.fontFamily,onChange:A=>et({fontFamily:A.target.value}),style:{width:"100%",padding:"4px 6px",borderRadius:4,border:`1px solid ${t.toolbarBorder}`,background:t.panelBg,color:t.textColor,fontSize:10,cursor:"pointer",outline:"none"},children:ol.map(A=>g.jsx("option",{value:A.value,children:A.label},A.value))})})]}),Z&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Scale mode",theme:t,children:g.jsx(Te,{columns:3,children:["stretch","fit","fill"].map(A=>g.jsx(Vo,{isActive:Z.scaleMode===A,theme:t,title:A==="stretch"?"Stretch to fill":A==="fit"?"Fit (contain)":"Fill (cover)",onClick:()=>{r(Z.id,{scaleMode:A}),i()},flex:"1",children:A.charAt(0).toUpperCase()+A.slice(1)},A))})}),g.jsxs(Mt,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Corner radius"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[Z.cornerRadius,"px"]})]}),g.jsx("input",{type:"range",min:"0",max:"50",step:"1",value:Z.cornerRadius,onChange:A=>{r(Z.id,{cornerRadius:parseInt(A.target.value)}),i()},style:{width:"100%",accentColor:t.activeToolColor,height:4}})]}),g.jsx(Mt,{theme:t,children:g.jsx(Vo,{theme:t,style:{width:"100%",padding:"5px 0",borderRadius:4},onClick:()=>{const A=document.createElement("input");A.type="file",A.accept="image/*",A.onchange=async()=>{var j;const lt=(j=A.files)==null?void 0:j[0];if(!lt)return;const mt=new FileReader;mt.onload=()=>{const Dt=mt.result,Gt=new window.Image;Gt.onload=()=>{r(Z.id,{src:Dt,naturalWidth:Gt.naturalWidth,naturalHeight:Gt.naturalHeight}),i()},Gt.src=Dt},mt.readAsDataURL(lt)},A.click()},children:"Replace Image…"})})]}),L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Layers",theme:t,children:g.jsx(Te,{columns:4,children:[{fn:h,icon:Pn.sendToBack,tip:"Send to back"},{fn:f,icon:Pn.sendBackward,tip:"Send backward"},{fn:u,icon:Pn.bringForward,tip:"Bring forward"},{fn:d,icon:Pn.bringToFront,tip:"Bring to front"}].map(({fn:A,icon:lt,tip:mt})=>g.jsx(be,{variant:"action",theme:t,title:mt,width:"100%",height:32,onClick:()=>{A(o),i()},children:j=>lt(j?t.activeToolColor:t.textColor)},mt))})}),g.jsx(Mt,{label:"Actions",theme:t,children:g.jsxs(Te,{columns:4,children:[g.jsx(be,{variant:"action",theme:t,title:"Duplicate (⌘D)",width:"100%",height:32,onClick:()=>c(o),children:A=>Yn.duplicate(A?t.activeToolColor:t.textColor)}),g.jsx(be,{variant:"action",theme:t,title:"Delete (⌫)",dangerHover:!0,width:"100%",height:32,onClick:()=>{a(o),i()},children:A=>Yn.delete(A?"#e03131":t.textColor)}),g.jsx(be,{variant:"action",theme:t,title:"Add link (coming soon)",width:"100%",height:32,disabled:!0,children:Yn.link(t.mutedTextColor)}),g.jsx(be,{variant:"action",theme:t,title:"Ungroup",width:"100%",height:32,onClick:()=>{B.getState().ungroupElements(o),i()},children:A=>Yn.ungroup(A?t.activeToolColor:t.textColor)})]})})]}),G&&L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx("button",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",padding:"5px 0",borderRadius:6,border:G.allLocked?"1.5px solid #ff9500":`1px solid ${t.toolbarBorder}`,background:G.allLocked?"#ff950010":"transparent",cursor:"pointer",fontSize:10,fontWeight:600,color:G.allLocked?"#ff9500":t.textColor,letterSpacing:.2,transition:"all 0.1s ease",outline:"none",marginBottom:2},title:G.allLocked?"Unlock position (⌘⇧L)":"Lock position (⌘⇧L)",onClick:()=>l(o),children:G.allLocked?g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}),"Unlock"]}):g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),"Lock Position"]})})]})]})},Ha=({x:t,y:e,items:n,onClose:o,theme:s})=>{const r=I.useRef(null),[i,l]=I.useState({x:t,y:e}),[a,c]=I.useState(!1),d=I.useRef(o);d.current=o,I.useEffect(()=>{const u=r.current;if(!u)return;const f=u.getBoundingClientRect(),p=u.parentElement;if(!p)return;const y=p.getBoundingClientRect();let m=t,W=e;t+f.width>y.width&&(m=Math.max(0,t-f.width)),e+f.height>y.height&&(W=Math.max(0,e-f.height)),l({x:m,y:W}),requestAnimationFrame(()=>c(!0))},[t,e]);const h=I.useCallback(()=>{d.current()},[]);return I.useEffect(()=>{const u=m=>{r.current&&!r.current.contains(m.target)&&h()},f=m=>{m.key==="Escape"&&h()},p=()=>h(),y=requestAnimationFrame(()=>{document.addEventListener("pointerdown",u,!0),document.addEventListener("keydown",f,!0),window.addEventListener("scroll",p,!0)});return()=>{cancelAnimationFrame(y),document.removeEventListener("pointerdown",u,!0),document.removeEventListener("keydown",f,!0),window.removeEventListener("scroll",p,!0)}},[h]),g.jsx("div",{ref:r,style:{position:"absolute",left:i.x,top:i.y,zIndex:1e3,background:s.panelBg,border:`1px solid ${s.toolbarBorder}`,borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.12)",padding:"4px 0",minWidth:180,backdropFilter:"blur(8px)",userSelect:"none",opacity:a?1:0,transform:a?"scale(1)":"scale(0.95)",transformOrigin:"top left",transition:"opacity 0.12s ease-out, transform 0.12s ease-out"},onContextMenu:u=>u.preventDefault(),children:n.map((u,f)=>g.jsxs(I.Fragment,{children:[u.divider&&g.jsx("div",{style:{height:1,background:s.toolbarBorder,margin:"4px 0"}}),g.jsxs("button",{onClick:()=>{u.disabled||(u.action(),o())},disabled:u.disabled,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"6px 12px",border:"none",background:"transparent",color:u.disabled?s.mutedTextColor:s.textColor,fontSize:13,cursor:u.disabled?"default":"pointer",textAlign:"left",fontFamily:"inherit",lineHeight:"20px"},onMouseEnter:p=>{u.disabled||(p.currentTarget.style.background=s.activeToolColor+"18")},onMouseLeave:p=>{p.currentTarget.style.background="transparent"},children:[g.jsx("span",{children:u.label}),u.shortcut&&g.jsx("span",{style:{color:s.mutedTextColor,fontSize:11,marginLeft:24,opacity:.8},children:u.shortcut})]})]},f))})},Oa=I.memo(Ha);let Yo=[];function yn(t){Yo=structuredClone(t)}function Ho(){return structuredClone(Yo)}function Na(){return Yo.length>0}function Fr(t){return t.toDataURL({pixelRatio:2})}function Ua(t,e="canvas.png"){const n=Fr(t),o=document.createElement("a");o.download=e,o.href=n,document.body.appendChild(o),o.click(),document.body.removeChild(o)}function Vr(t){return JSON.stringify(t,null,2)}function Ka(t,e="canvas.json"){const n=Vr(t),o=new Blob([n],{type:"application/json"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const Hn=20;function St(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function In(t,e){const n=_t(t,e);return n.length>0?n.join(","):"none"}function Oo(t){const{strokeColor:e,fillColor:n,strokeWidth:o,opacity:s,strokeStyle:r}=t.style,i=In(r,o),l=[`fill="${St(n==="transparent"?"none":n)}"`,`stroke="${St(e)}"`,`stroke-width="${o}"`,`opacity="${s}"`];return i!=="none"&&l.push(`stroke-dasharray="${i}"`),l.join(" ")}function On(t,e,n,o){return e.rotation?`<g transform="rotate(${e.rotation} ${n} ${o})">${t}</g>`:t}function za(t){const{x:e,y:n,width:o,height:s,cornerRadius:r}=t,i=r?` rx="${r}" ry="${r}"`:"",l=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${i} ${Oo(t)} />`;return On(l,t,e+o/2,n+s/2)}function Ja(t){const e=t.x+t.width/2,n=t.y+t.height/2,o=`<ellipse cx="${e}" cy="${n}" rx="${t.width/2}" ry="${t.height/2}" ${Oo(t)} />`;return On(o,t,e,n)}function $a(t){const e=un(t.width,t.height),n=[];for(let s=0;s<e.length;s+=2)n.push(`${t.x+e[s]},${t.y+e[s+1]}`);const o=`<polygon points="${n.join(" ")}" ${Oo(t)} />`;return On(o,t,t.x+t.width/2,t.y+t.height/2)}function Ra(t){const n=t.points.map((s,r)=>`${r%2===0?t.x+s:t.y+s}`),o=[];for(let s=0;s<n.length;s+=2)o.push(`${n[s]},${n[s+1]}`);return`<polyline points="${o.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round"${In(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${In(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function ja(t){const e=t.points,n={x:e[0],y:e[1]},o={x:e[e.length-2],y:e[e.length-1]},s=Jt(n,o,t.curvature??zt),r=t.x+n.x,i=t.y+n.y,l=t.x+s.x,a=t.y+s.y,c=t.x+o.x,d=t.y+o.y;return`<path d="M ${r} ${i} Q ${l} ${a} ${c} ${d}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round"${In(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${In(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function Qa(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function qa(t){return{x:-t.y,y:t.x}}function Nn(t,e,n,o,s,r){const i=Qa(e,n),l=qa(i),a=o*.45;switch(t){case"arrow":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polyline points="${c.x},${c.y} ${e.x},${e.y} ${d.x},${d.y}" fill="none" stroke="${St(s)}" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round" />`}case"triangle":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"triangle_outline":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"circle":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"circle_outline":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"bar":{const c=a*1.2;return`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`}case"diamond":case"diamond_outline":{const c=a*.7,d=o*.55,h={x:e.x-i.x*d,y:e.y-i.y*d},u=t==="diamond"?St(s):"#ffffff";return`<polygon points="${e.x},${e.y} ${h.x+l.x*c},${h.y+l.y*c} ${h.x-i.x*d},${h.y-i.y*d} ${h.x-l.x*c},${h.y-l.y*c}" fill="${u}" stroke="${St(s)}" stroke-width="${r}" />`}case"crowfoot_one":{const c=a*1,d=o*.25,h={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<line x1="${h.x+l.x*c}" y1="${h.y+l.y*c}" x2="${h.x-l.x*c}" y2="${h.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`].join(`
1
+ (function(k,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react/jsx-runtime"),require("react"),require("react-konva"),require("konva"),require("zustand"),require("react-dom"),require("yjs"),require("y-websocket")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-konva","konva","zustand","react-dom","yjs","y-websocket"],g):(k=typeof globalThis<"u"?globalThis:k||self,g(k.FlowCanvas={},k.jsxRuntime,k.React,k.ReactKonva,k.Konva,k.zustand,k.ReactDOM,k.Y,k.yWebsocket))})(this,(function(k,g,I,ht,en,Zs,Ms,yl,_s){"use strict";var Lh=Object.defineProperty;var Yh=(k,g,I)=>g in k?Lh(k,g,{enumerable:!0,configurable:!0,writable:!0,value:I}):k[g]=I;var ct=(k,g,I)=>Yh(k,typeof g!="symbol"?g+"":g,I);var qt=typeof document<"u"?document.currentScript:null;function Il(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const zt=Il(yl),En={strokeColor:"#1e1e1e",fillColor:"transparent",strokeWidth:2,opacity:1,strokeStyle:"solid",roughness:0,fontSize:20,fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",freehandStyle:"standard"},nn=["#1a1a1a","#868e96","#b197fc","#7048e8","#4263eb","#f59f00","#e8590c","#2f9e44","#40c057","#f06595","#e03131"],on=["transparent","#e9ecef","#f3f0ff","#e5dbff","#edf2ff","#fff3bf","#ffe8cc","#d3f9d8","#ebfbee","#fcc2d7","#ffe3e3"],Cl=[1,2,3,4,6],yo=[{type:"hand",label:"Hand (Pan)",shortcut:"H",icon:"Hand"},{type:"select",label:"Select",shortcut:"V",icon:"MousePointer2"},{type:"rectangle",label:"Rectangle",shortcut:"R",icon:"Square"},{type:"ellipse",label:"Ellipse",shortcut:"O",icon:"Circle"},{type:"diamond",label:"Diamond",shortcut:"D",icon:"Diamond"},{type:"line",label:"Line",shortcut:"L",icon:"Minus"},{type:"arrow",label:"Arrow",shortcut:"A",icon:"ArrowUpRight"},{type:"freedraw",label:"Pencil",shortcut:"P",icon:"Pencil"},{type:"text",label:"Text",shortcut:"T",icon:"Type"},{type:"image",label:"Image",shortcut:"I",icon:"ImageIcon"},{type:"eraser",label:"Eraser",shortcut:"E",icon:"Eraser"}],De=.1,Le=5,ml=[12,16,20,24,28,36,48,64],bl=[{label:"Sans-serif",value:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif"},{label:"Serif",value:"Georgia, Cambria, Times New Roman, Times, serif"},{label:"Monospace",value:"SF Mono, Menlo, Consolas, Liberation Mono, monospace"},{label:"Hand-drawn",value:"Segoe Print, Comic Sans MS, cursive"}],Tt={color:"#4f8df7",blur:6,opacity:.5},xe=20,Al=[{value:"standard",label:"Standard"},{value:"pen",label:"Pen"},{value:"pencil",label:"Pencil"},{value:"brush",label:"Brush"}],Io=[{type:null,label:"None",preview:"—"},{type:"arrow",label:"Arrow",preview:"▷"},{type:"triangle",label:"Triangle",preview:"▶"},{type:"triangle_outline",label:"Triangle Outline",preview:"△"},{type:"circle",label:"Circle",preview:"●"},{type:"circle_outline",label:"Circle Outline",preview:"○"},{type:"diamond",label:"Diamond",preview:"◆"},{type:"diamond_outline",label:"Diamond Outline",preview:"◇"},{type:"bar",label:"Bar",preview:"|"},{type:"crowfoot_one",label:"One",preview:"||"},{type:"crowfoot_many",label:"Many",preview:">|"},{type:"crowfoot_one_or_many",label:"One or Many",preview:">||"}],Co=[{type:"sharp",label:"Sharp",preview:"╱"},{type:"curved",label:"Curved",preview:"∿"},{type:"elbow",label:"Elbow",preview:"⌐"}],Xs=[{value:0,label:"Architect"},{value:1,label:"Artist"},{value:2,label:"Cartoonist"}],Gs=20,Ds=25,wl=36,Ye=40,Ls=1e4;function Wn(t){switch(t){case"up":return{x:0,y:-1};case"down":return{x:0,y:1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}}function Tn(t){return t==="up"||t==="down"}function Bn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=(t.width||1)/2,l=(t.height||1)/2,a=Math.abs(s)/i,c=Math.abs(r)/l;return a>c*3?s>=0?"right":"left":(c>a*3,r>=0?"down":"up")}function mo(t){const[e,n]=t,o=n,s=1-n,r=e,i=1-e,l=Math.min(o,s,r,i);return l===o?"up":l===s?"down":l===r?"left":"right"}function sn(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>=Math.abs(o)?n>=0?"right":"left":o>=0?"down":"up"}function bo(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=t.width/2||1,l=t.height/2||1,a=s/i,c=r/l;return Math.abs(a)>=Math.abs(c)?s>=0?"right":"left":r>=0?"down":"up"}function xl(t,e){const n=Math.abs(e.y-t.y),o=Math.abs(e.y-(t.y+t.height)),s=Math.abs(e.x-t.x),r=Math.abs(e.x-(t.x+t.width)),i=Math.min(n,o,s,r);return i===n?"up":i===o?"down":i===s?"left":"right"}function te(t){return t.left+t.width}function ee(t){return t.top+t.height}function kl(t,e){return e.x>t.left&&e.x<te(t)&&e.y>t.top&&e.y<ee(t)}function Ve(t,e,n){return{left:t.left-e,top:t.top-n,width:t.width+e*2,height:t.height+n*2}}function Ys(t,e,n){const o=Math.min(e,Ds),s=n==="left"?o:e,r=n==="right"?o:e,i=n==="up"?o:e,l=n==="down"?o:e;return{left:t.left-s,top:t.top-i,width:t.width+s+r,height:t.height+i+l}}function Vs(t,e,n){const o=new Set(n),s=Math.min(e,Ds),r=o.has("left")?s:e,i=o.has("right")?s:e,l=o.has("up")?s:e,a=o.has("down")?s:e;return{left:t.left-r,top:t.top-l,width:t.width+r+i,height:t.height+l+a}}function Sl(t,e){const n=Math.min(t.left,e.left),o=Math.min(t.top,e.top),s=Math.max(te(t),te(e)),r=Math.max(ee(t),ee(e));return{left:n,top:o,width:s-n,height:r-o}}function Ao(t){return{left:t.x,top:t.y,width:t.width,height:t.height}}function wo(t){const e=t.rotation||0;if(e===0)return{x:t.x,y:t.y,width:t.width,height:t.height};const n=t.x+t.width/2,o=t.y+t.height/2,s=t.width/2,r=t.height/2,i=e*Math.PI/180,l=Math.cos(i),a=Math.sin(i),c=[{x:-s,y:-r},{x:s,y:-r},{x:s,y:r},{x:-s,y:r}].map(p=>({x:n+p.x*l-p.y*a,y:o+p.x*a+p.y*l}));let d=1/0,h=1/0,u=-1/0,f=-1/0;for(const p of c)p.x<d&&(d=p.x),p.y<h&&(h=p.y),p.x>u&&(u=p.x),p.y>f&&(f=p.y);return{x:d,y:h,width:u-d,height:f-h}}function vl(t){switch(t){case"left":return"right";case"right":return"left";case"up":return"down";case"down":return"up"}}function El(t,e){return e.x<t.x?"left":e.x>t.x?"right":e.y<t.y?"up":e.y>t.y?"down":null}function Wl(t,e){return t===null||e===null?!1:(t==="left"||t==="right"?"h":"v")!==(e==="left"||e==="right"?"h":"v")}class Tl{constructor(e){ct(this,"adjacent",new Map);this.pt=e}}class Bl{constructor(){ct(this,"idx",{})}add(e){const n=String(e.x),o=String(e.y);n in this.idx||(this.idx[n]={}),o in this.idx[n]||(this.idx[n][o]=new Tl(e))}get(e){var s;const n=String(e.x),o=String(e.y);return((s=this.idx[n])==null?void 0:s[o])??null}has(e){return this.get(e)!==null}connect(e,n){const o=this.get(e),s=this.get(n);if(!o||!s)return;const r=Math.abs(n.x-e.x)+Math.abs(n.y-e.y);o.adjacent.set(s,r),s.adjacent.set(o,r)}}class Zl{constructor(){ct(this,"data",[])}get size(){return this.data.length}push(e,n){this.data.push({item:e,priority:n}),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;const e=this.data[0],n=this.data.pop();return this.data.length>0&&(this.data[0]=n,this.sinkDown(0)),e.item}bubbleUp(e){for(;e>0;){const n=e-1>>1;if(this.data[n].priority<=this.data[e].priority)break;[this.data[n],this.data[e]]=[this.data[e],this.data[n]],e=n}}sinkDown(e){const n=this.data.length;for(;;){let o=e;const s=2*e+1,r=2*e+2;if(s<n&&this.data[s].priority<this.data[o].priority&&(o=s),r<n&&this.data[r].priority<this.data[o].priority&&(o=r),o===e)break;[this.data[o],this.data[e]]=[this.data[e],this.data[o]],e=o}}}function Ml(t,e,n){const o=t.get(e),s=t.get(n);if(!o||!s)return null;const r=u=>Math.abs(u.x-n.x)+Math.abs(u.y-n.y),i=(u,f)=>`${u.pt.x},${u.pt.y},${f??"n"}`,l=new Map,a=new Map,c=new Zl,d={node:o,dir:null,g:0},h=i(o,null);for(l.set(h,0),a.set(h,null),c.push(d,r(o.pt));c.size>0;){const u=c.pop(),f=i(u.node,u.dir);if(!(u.g>(l.get(f)??1/0))){if(u.node===s){const p=[];let y=u;for(;y;){p.push(y.node.pt);const b=i(y.node,y.dir);if(y=a.get(b),y==null)break}return p[p.length-1]!==o.pt&&p.push(o.pt),p.reverse(),p}for(const[p,y]of u.node.adjacent){const b=El(u.node.pt,p.pt);if(b===null)continue;const W=u.dir!==null&&b===vl(u.dir),v=Wl(u.dir,b),G=W?Ls*3:v?Ls:0,$=u.g+y+G,T=i(p,b);$<(l.get(T)??1/0)&&(l.set(T,$),a.set(T,u),c.push({node:p,dir:b,g:$},$+r(p.pt)))}}}return null}function _l(t){const e=new Map,n=[];for(const o of t){let s=e.get(o.x);s||(s=new Set,e.set(o.x,s)),s.has(o.y)||(s.add(o.y),n.push(o))}return n}function Xl(t,e,n,o){const s=n.left,r=te(n),i=n.top,l=ee(n),a=[...new Set([s,...t.filter(u=>u>=s&&u<=r),r])].sort((u,f)=>u-f),c=[...new Set([i,...e.filter(u=>u>=i&&u<=l),l])].sort((u,f)=>u-f),d=u=>o.some(f=>kl(f,u)),h=[];for(const u of c)for(const f of a){const p={x:f,y:u};d(p)||h.push(p)}return h}function Fs(t,e,n){if(t.y===e.y){const o=t.y,s=Math.min(t.x,e.x),r=Math.max(t.x,e.x);for(const i of n)if(i.top<o&&o<ee(i)&&i.left<r&&te(i)>s)return!0}else if(t.x===e.x){const o=t.x,s=Math.min(t.y,e.y),r=Math.max(t.y,e.y);for(const i of n)if(i.left<o&&o<te(i)&&i.top<r&&ee(i)>s)return!0}return!1}function Gl(t,e){const n=new Bl,o=new Set,s=new Set;for(const l of t)n.add(l),o.add(l.x),s.add(l.y);const r=[...o].sort((l,a)=>l-a),i=[...s].sort((l,a)=>l-a);for(let l=0;l<i.length;l++)for(let a=0;a<r.length;a++){const c={x:r[a],y:i[l]};if(n.has(c)){for(let d=a-1;d>=0;d--){const h={x:r[d],y:i[l]};if(n.has(h)){Fs(h,c,e)||n.connect(h,c);break}}for(let d=l-1;d>=0;d--){const h={x:r[a],y:i[d]};if(n.has(h)){Fs(h,c,e)||n.connect(h,c);break}}}}return n}function Ps(t){if(t.length<=2)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;i||l||o.x===s.x&&o.y===s.y||e.push(s)}return e.push(t[t.length-1]),e}function Hs(t){if(t.length<=2)return 0;let e=0;for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;!i&&!l&&e++}return e}function Os(t){let e=0;for(let n=1;n<t.length;n++)e+=Math.abs(t[n].x-t[n-1].x)+Math.abs(t[n].y-t[n-1].y);return e}function Dl(t){let e=t[0],n=Hs(e),o=Os(e);for(let s=1;s<t.length;s++){const r=Hs(t[s]),i=Os(t[s]);(r<n||r===n&&i<o)&&(e=t[s],n=r,o=i)}return e}function xo(t,e,n,o,s,r){let i={left:Math.min(t.x,e.x),top:Math.min(t.y,e.y),width:Math.abs(e.x-t.x)||1,height:Math.abs(e.y-t.y)||1};for(const W of s)i=Sl(i,W);i=Ve(i,Ye,Ye);const l=[],a=[];for(const W of s)l.push(W.left,te(W)),a.push(W.top,ee(W)),l.push(W.left+W.width/2),a.push(W.top+W.height/2);l.push(t.x,e.x),a.push(t.y,e.y);const c=Wn(n),d=Wn(o);let h={x:t.x+c.x*r,y:t.y+c.y*r},u={x:e.x+d.x*r,y:e.y+d.y*r};h=Us(h,n,s),u=Us(u,o,s),l.push(h.x,u.x),a.push(h.y,u.y),l.push((t.x+e.x)/2),a.push((t.y+e.y)/2);const f=Xl(l,a,i,s),p=_l([h,u,...f]),y=Gl(p,s),b=Ml(y,h,u);if(b){const W=[t,...b,e];return Ps(W)}return null}function Ns(t,e,n,o,s,r,i,l){if(t.x===e.x&&t.y===e.y)return[t,e];const a=s?Ao(s):{left:t.x,top:t.y,width:0,height:0},c=r?Ao(r):{left:e.x,top:e.y,width:0,height:0},d=Gs,h=Math.max(wl,i??0),u=(l??[]).map(O=>Ve(Ao(O),d,d)),f=s?Ys(a,d,n):Ve(a,d,d),p=r?Ys(c,d,o):Ve(c,d,d),y=[n],b=[o];let W=!1;if(s){const O=bo(s,e);O!==n&&(y.push(O),W=!0)}if(r){const O=bo(r,t);O!==o&&(b.push(O),W=!0)}const v=s?Vs(a,d,y):Ve(a,d,d),G=r?Vs(c,d,b):Ve(c,d,d),$=[],T=xo(t,e,n,o,[f,p,...u],h);if(T&&$.push(T),W){const O=xo(t,e,n,o,[v,G,...u],h);O&&$.push(O)}if($.length>0)return Dl($);if(u.length>0){const O=xo(t,e,n,o,[f,p],h);if(O)return O}return Ps(Ll(t,e,n,o,h))}function Us(t,e,n){let{x:o,y:s}=t;for(let r=0;r<n.length;r++){let i=!0;for(const l of n)if(!(o<=l.left||o>=te(l)||s<=l.top||s>=ee(l)))switch(i=!1,e){case"left":o=l.left-1;break;case"right":o=te(l)+1;break;case"up":s=l.top-1;break;case"down":s=ee(l)+1;break}if(i)break}return{x:o,y:s}}function Ll(t,e,n,o,s){const r=Math.max(s,Gs),i=Wn(n),l=Wn(o),a={x:t.x+i.x*r,y:t.y+i.y*r},c={x:e.x+l.x*r,y:e.y+l.y*r};if(Tn(n)===Tn(o))if(Tn(n)){const d=(a.y+c.y)/2;return[t,a,{x:a.x,y:d},{x:c.x,y:d},c,e]}else{const d=(a.x+c.x)/2;return[t,a,{x:d,y:a.y},{x:d,y:c.y},c,e]}else return Tn(n)?[t,a,{x:a.x,y:c.y},c,e]:[t,a,{x:c.x,y:a.y},c,e]}const Yl=new Set(["rectangle","ellipse","diamond","text","image"]),Vl=256,Fe=new Map;function Fl(t,e,n,o,s,r,i,l){const a=c=>Math.round(c*2)/2;return[a(t.x),a(t.y),a(e.x),a(e.y),n,o,s?`${a(s.x)},${a(s.y)},${a(s.width)},${a(s.height)}`:"n",r?`${a(r.x)},${a(r.y)},${a(r.width)},${a(r.height)}`:"n",i,l??0].join("|")}function Pl(){Fe.clear()}function rn(t,e,n,o,s,r){const i=new Map(s.map(Y=>[Y.id,Y])),l=Y=>!Y.isPrecise||Y.fixedPoint[0]===.5&&Y.fixedPoint[1]===.5;let a;if(n)if(l(n)){const Y=i.get(n.elementId);a=Y?Bn(Y,e):sn(t,e)}else a=mo(n.fixedPoint);else a=sn(t,e);let c;if(o)if(l(o)){const Y=i.get(o.elementId);c=Y?Bn(Y,t):sn(e,t)}else c=mo(o.fixedPoint);else c=sn(e,t);const d=n?i.get(n.elementId)??null:null,h=o?i.get(o.elementId)??null:null,u=d?wo(d):null,f=h?wo(h):null,p=n==null?void 0:n.elementId,y=o==null?void 0:o.elementId,b=[],W=[],v=Y=>Math.round(Y*2)/2;for(const Y of s){if(!Yl.has(Y.type)||Y.id===p||Y.id===y||!Y.isVisible)continue;const J=wo(Y),P=Math.min(t.x,e.x)-Ye*3,Q=Math.max(t.x,e.x)+Ye*3,_=Math.min(t.y,e.y)-Ye*3,x=Math.max(t.y,e.y)+Ye*3;J.x+J.width<P||J.x>Q||J.y+J.height<_||J.y>x||(b.push(J),W.push(`${Y.id}:${v(J.x)},${v(J.y)},${v(J.width)},${v(J.height)}`))}W.sort();const G=W.join(";"),$=Fl(t,e,a,c,u,f,G,r),T=Fe.get($);if(T)return T;const O=Ns(t,e,a,c,u,f,r,b),ot=[];for(const Y of O)ot.push(Y.x-t.x,Y.y-t.y);if(Fe.size>=Vl){const Y=Fe.keys().next().value;Y!==void 0&&Fe.delete(Y)}return Fe.set($,ot),ot}function ln(t){if(t.length<=4)return t;const e=[t[0],t[1]];for(let n=2;n<t.length-2;n+=2){const o=e[e.length-2],s=e[e.length-1],r=t[n],i=t[n+1],l=t[n+2],a=t[n+3];s===i&&i===a||o===r&&r===l||o===r&&s===i||e.push(r,i)}return e.push(t[t.length-2],t[t.length-1]),e}const Hl=new Set(["rectangle","ellipse","diamond","text","image"]);function ko(t){return Hl.has(t.type)}function zs(t){return t*Math.PI/180}function Ks(t,e,n){if(n===0)return{x:t,y:e};const o=Math.cos(n),s=Math.sin(n);return{x:t*o-e*s,y:t*s+e*o}}function cn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=zs(t.rotation||0);return i===0?{x:s,y:r}:Ks(s,r,-i)}function Zn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=zs(t.rotation||0),r=Ks(e.x,e.y,s);return{x:n+r.x,y:o+r.y}}function Js(t){const{x:e,y:n,width:o,height:s}=t,r=e+o/2,i=n+s/2;return{top:{x:r,y:n},bottom:{x:r,y:n+s},left:{x:e,y:i},right:{x:e+o,y:i},center:{x:r,y:i}}}function Ol(t,e){return Js(t)[e]}const $s=4;function ce(t){return $s+t/2}function Rs(t,e){const n=t.width||1,o=t.height||1,s=cn(t,e),r=Math.max(0,Math.min(1,(s.x+n/2)/n)),i=Math.max(0,Math.min(1,(s.y+o/2)/o));return[r,i]}function ae(t,e,n=0){const o=(e[0]-.5)*t.width,s=(e[1]-.5)*t.height;if(o===0&&s===0)return Zn(t,{x:0,y:0});const r=Zn(t,{x:o,y:s});return de(t,r,n)}function de(t,e,n=0){const o=cn(t,e),s=o.x,r=o.y;if(s===0&&r===0)return Zn(t,{x:0,y:-(t.height/2+n)});let i;switch(t.type){case"ellipse":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s);i={x:(l+n)*Math.cos(c),y:(a+n)*Math.sin(c)};break}case"diamond":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.cos(c),h=Math.sin(c),u=Math.abs(d),f=Math.abs(h),p=1/(u/l+f/a),y=p*d,b=p*h;if(n===0)i={x:y,y:b};else{const W=(d>=0?1:-1)/l,v=(h>=0?1:-1)/a,G=Math.sqrt(W*W+v*v);i={x:y+W/G*n,y:b+v/G*n}}break}default:{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.abs(Math.tan(c));let h,u;d<=a/l?(h=s>0?l:-l,u=h*Math.tan(c)):(u=r>0?a:-a,h=u/Math.tan(c)),n===0?i={x:h,y:u}:d<=a/l?i={x:h+(s>0?n:-n),y:u}:i={x:h,y:u+(r>0?n:-n)};break}}return Zn(t,i)}const Nl=24,Ul=20,js=6;function zl(t,e){const n=cn(t,e),o=t.width/2||1,s=t.height/2||1;switch(t.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)>=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(c-n.x,d-n.y)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s>=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(d-n.x,h-n.y)}default:{const r=o+n.x,i=o-n.x,l=s+n.y,a=s-n.y,c=Math.min(r,i,l,a);return c>0?c:0}}}function Kl(t,e){const n=cn(e,t),o=e.width/2,s=e.height/2;switch(e.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)<=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(n.x-c,n.y-d)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s<=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(n.x-d,n.y-h)}default:{const r=Math.max(-o-n.x,0,n.x-o),i=Math.max(-s-n.y,0,n.y-s);return Math.hypot(r,i)}}}function ke(t,e,n=Nl,o=new Set,s,r,i=$s,l){let a=null,c=1/0;for(const d of e){if(!ko(d)||o.has(d.id))continue;const h=Kl(t,d);if(h>n)continue;const u=h===0,f=d.x+d.width/2,p=d.y+d.height/2,y=Math.hypot(f-t.x,p-t.y),b=u?-1e6+y:h*1e3+y;if(b<c){c=b;let W;if(r!==void 0)W=r;else if(h===0){const T=Math.min(d.width,d.height)/2,O=Math.min(Ul,T*.6),ot=zl(d,t);l===!0?W=ot<=O+js:l===!1?W=ot<=Math.max(0,O-js):W=ot<=O}else W=!0;let v,G;if(W)v=Rs(d,t),G=ae(d,v,i);else{v=[.5,.5];const $=cn(d,t);Math.abs($.x)+Math.abs($.y)<2?G=s?de(d,s,i):de(d,{x:f+d.width,y:p},i):G=de(d,t,i)}a={elementId:d.id,fixedPoint:v,position:G,isPrecise:W}}}return a}function Se(t,e){const{startBinding:n,endBinding:o}=t;if(!n&&!o)return null;const s=new Map(e.map(v=>[v.id,v])),r=t.points,i=r.length/2;let l={x:t.x+r[0],y:t.y+r[1]},a={x:t.x+r[r.length-2],y:t.y+r[r.length-1]};const c=n?s.get(n.elementId):void 0,d=o?s.get(o.elementId):void 0,h=(v,G)=>v.isPrecise?ae(G,v.fixedPoint,0):{x:G.x+G.width/2,y:G.y+G.height/2},u=t.lineType==="elbow",f=(v,G,$)=>{const T=Bn(v,G),O=v.x+v.width/2,ot=v.y+v.height/2,Y=Math.max(v.width,v.height)*10;let J;switch(T){case"up":J={x:O,y:ot-Y};break;case"down":J={x:O,y:ot+Y};break;case"left":J={x:O-Y,y:ot};break;case"right":J={x:O+Y,y:ot};break}return de(v,J,$)},p=u?(v,G,$)=>f(v,G,$):de;if(n&&c&&o&&d){if(n.isPrecise)l=ae(c,n.fixedPoint,n.gap);else{const v=h(o,d);l=p(c,v,n.gap)}if(o.isPrecise)a=ae(d,o.fixedPoint,o.gap);else{const v=h(n,c);a=p(d,v,o.gap)}n.isPrecise||(l=p(c,a,n.gap)),o.isPrecise||(a=p(d,l,o.gap))}else n&&c&&(n.isPrecise?l=ae(c,n.fixedPoint,n.gap):l=p(c,a,n.gap)),o&&d&&(o.isPrecise?a=ae(d,o.fixedPoint,o.gap):a=p(d,l,o.gap));const y=[0,0];for(let v=1;v<i-1;v++){const G=t.x+r[v*2],$=t.y+r[v*2+1];y.push(G-l.x,$-l.y)}y.push(a.x-l.x,a.y-l.y);const b=a.x-l.x,W=a.y-l.y;return{x:l.x,y:l.y,points:y,width:Math.abs(b),height:Math.abs(W)}}function an(t,e){return e.filter(n=>{var s,r;if(n.type!=="line"&&n.type!=="arrow")return!1;const o=n;return((s=o.startBinding)==null?void 0:s.elementId)===t||((r=o.endBinding)==null?void 0:r.elementId)===t})}function Jl(t,e){return e.map(n=>{let o=!1;if(n.boundElements&&n.boundElements.length>0){const l=n.boundElements.filter(a=>!t.has(a.id));l.length!==n.boundElements.length&&(n={...n,boundElements:l.length>0?l:null},o=!0)}if(n.type!=="line"&&n.type!=="arrow")return n;const s=n;let r=s.startBinding,i=s.endBinding;return r&&t.has(r.elementId)&&(r=null,o=!0),i&&t.has(i.elementId)&&(i=null,o=!0),o?{...n,startBinding:r,endBinding:i}:n})}function Qs(t,e){const n=t.boundElements??[];return n.some(o=>o.id===e.id)?t:{...t,boundElements:[...n,e]}}function qs(t,e){const n=t.boundElements;if(!n||n.length===0)return t;const o=n.filter(s=>s.id!==e);return{...t,boundElements:o.length>0?o:null}}function ve(t,e,n,o,s,r){if(n&&n.elementId!==(o==null?void 0:o.elementId)){const i=s.find(l=>l.id===n.elementId);if(i){const l=qs(i,t);l!==i&&r(i.id,{boundElements:l.boundElements})}}if(o&&o.elementId!==(n==null?void 0:n.elementId)){const i=s.find(l=>l.id===o.elementId);if(i){const l=Qs(i,{id:t,type:e});l!==i&&r(i.id,{boundElements:l.boundElements})}}}const $l="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let Rl=(t=21)=>{let e="",n=crypto.getRandomValues(new Uint8Array(t|=0));for(;t--;)e+=$l[n[t]&63];return e};function Ft(){return Rl(12)}function jl(t){const e={...t};return e.style&&(e.style={...e.style}),e.boundElements&&(e.boundElements=e.boundElements.map(n=>({...n}))),e.startBinding&&(e.startBinding={...e.startBinding}),e.endBinding&&(e.endBinding={...e.endBinding}),e.groupIds&&(e.groupIds=[...e.groupIds]),Array.isArray(e.points)&&(e.points=[...e.points]),Array.isArray(e.pressures)&&(e.pressures=[...e.pressures]),e.crop&&(e.crop={...e.crop}),e}function Mn(t,e,n=20){const o=new Set(t.map(d=>d.id)),s=new Set;for(const d of t)if(d.boundElements)for(const h of d.boundElements)h.type==="text"&&!o.has(h.id)&&s.add(h.id);const r=[...t,...e.filter(d=>s.has(d.id))],i=new Map;for(const d of r)i.set(d.id,Ft());const l=new Map;for(const d of r)if(d.groupIds)for(const h of d.groupIds)l.has(h)||l.set(h,Ft());const a=r.map(d=>{const h=i.get(d.id),u=jl(d);return u.id=h,u.x=d.x+n,u.y=d.y+n,u.containerId&&i.has(u.containerId)?u.containerId=i.get(u.containerId):u.containerId&&(u.containerId=null),u.boundElements&&(u.boundElements=u.boundElements.map(f=>i.has(f.id)?{...f,id:i.get(f.id)}:null).filter(Boolean),u.boundElements.length===0&&(u.boundElements=null)),u.startBinding&&i.has(u.startBinding.elementId)?u.startBinding={...u.startBinding,elementId:i.get(u.startBinding.elementId)}:u.startBinding&&(u.startBinding=null),u.endBinding&&i.has(u.endBinding.elementId)?u.endBinding={...u.endBinding,elementId:i.get(u.endBinding.elementId)}:u.endBinding&&(u.endBinding=null),u.groupIds&&u.groupIds.length>0&&(u.groupIds=u.groupIds.map(f=>l.get(f)??f)),u}),c=a.filter(d=>{var u;const h=(u=[...i.entries()].find(([,f])=>f===d.id))==null?void 0:u[0];return h?o.has(h):!1}).map(d=>d.id);return{clones:a,idMap:i,selectedCloneIds:c}}function tr(t,e){const n=new Set(t),o=new Set;for(const s of e)if(n.has(s.id)&&s.groupIds)for(const r of s.groupIds)o.add(r);if(o.size>0){for(const s of e)if(!n.has(s.id)&&s.groupIds){for(const r of s.groupIds)if(o.has(r)){n.add(s.id);break}}}for(const s of e)if(n.has(s.id)&&s.boundElements)for(const r of s.boundElements)r.type==="text"&&!n.has(r.id)&&n.add(r.id);return e.filter(s=>n.has(s.id))}function er(t,e,n,o=200){const{x:s,y:r,scale:i}=t,l=-s/i-o,a=-r/i-o,c=(-s+e)/i+o,d=(-r+n)/i+o;return{minX:l,minY:a,maxX:c,maxY:d}}function dn(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r}}if(t.type==="freedraw"&&"points"in t){if(t.isComplete===!1){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return n===1/0?{minX:t.x,minY:t.y,maxX:t.x+1,maxY:t.y+1}:{minX:n,minY:s,maxX:o,maxY:r}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}function nr(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function or(t,e,n,o,s,r){if(t.length<=100)return t;const i=er(e,n,o,r);return t.filter(l=>{if(s.has(l.id))return!0;const a=dn(l);return nr(i,a)})}function Ql(t){const e=new Map;for(const n of t)e.set(n.id,n);return e}function ql(t){if(typeof structuredClone=="function"){const e=new Map,n=new Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s.type==="image"&&"src"in s){const r=s;e.has(r.id)||e.set(r.id,r.src);const{src:i,...l}=r,a=structuredClone(l);a.src=e.get(r.id),n[o]=a}else n[o]=structuredClone(s)}return n}return JSON.parse(JSON.stringify(t))}function sr(t){let e=null,n=null;const o=(...s)=>{n=s,e===null&&(e=requestAnimationFrame(()=>{e=null,n&&(t(...n),n=null)}))};return o.cancel=()=>{e!==null&&(cancelAnimationFrame(e),e=null),n=null},o}function tc(t,e){if(e.length===0)return t;const n=new Map;for(const o of e){const s=n.get(o.id);n.set(o.id,s?{...s,...o.changes}:o.changes)}return t.map(o=>{const s=n.get(o.id);return s?{...o,...s}:o})}function rr(t){return new Set(t)}const un=[.1,.25,.5,.75,1,1.5,2,3,4,5],ir=280;function _n({viewport:t,point:e,targetScale:n}){const o=Math.min(Le,Math.max(De,n)),s=(e.x-t.x)/t.scale,r=(e.y-t.y)/t.scale;return{scale:o,x:e.x-s*o,y:e.y-r*o}}function lr(t){for(const e of un)if(e>t+.01)return e;return Le}function cr(t){for(let e=un.length-1;e>=0;e--)if(un[e]<t-.01)return un[e];return De}function So(t){if(t.length===0)return null;let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const r of t){const i=dn(r);i.minX<e&&(e=i.minX),i.minY<n&&(n=i.minY),i.maxX>o&&(o=i.maxX),i.maxY>s&&(s=i.maxY)}return{minX:e,minY:n,maxX:o,maxY:s}}function vo(t,e,n,o={}){const s=o.padding??50,r=o.maxZoom??2,i=t.maxX-t.minX,l=t.maxY-t.minY;if(i===0&&l===0)return{scale:1,x:e/2-t.minX,y:n/2-t.minY};const a=(e-s*2)/(i||1),c=(n-s*2)/(l||1),d=Math.min(Math.min(a,c),r),h=Math.min(Le,Math.max(De,d)),u=(t.minX+t.maxX)/2,f=(t.minY+t.maxY)/2;return{scale:h,x:e/2-u*h,y:n/2-f*h}}function ec(t){return 1-Math.pow(1-t,3)}let Pt=null;function Ee(t,e,n,o=ir){Pt!==null&&(cancelAnimationFrame(Pt),Pt=null);const s=performance.now(),r=i=>{const l=i-s,a=Math.min(l/o,1),c=ec(a),d={x:t.x+(e.x-t.x)*c,y:t.y+(e.y-t.y)*c,scale:t.scale+(e.scale-t.scale)*c};n(d),a<1?Pt=requestAnimationFrame(r):(Pt=null,n(e))};return Pt=requestAnimationFrame(r),()=>{Pt!==null&&(cancelAnimationFrame(Pt),Pt=null)}}function We(){Pt!==null&&(cancelAnimationFrame(Pt),Pt=null)}const nc=100;function ue(t){if(t.type==="image"&&"src"in t){const{src:e,...n}=t,o=structuredClone(n);return o.src=e,o}return structuredClone(t)}const B=Zs.create((t,e)=>({elements:[],selectedIds:[],activeTool:"select",currentStyle:{...En},currentLineType:"sharp",currentStartArrowhead:null,currentEndArrowhead:"arrow",viewport:{x:0,y:0,scale:1},isDrawing:!1,drawStart:null,history:[],historyIndex:-1,_historyBaseline:new Map,_historyPaused:!1,showGrid:!1,addElement:n=>{t(o=>({elements:[...o.elements,n]})),e().pushHistory()},updateElement:(n,o)=>{t(s=>{const r=s.elements,i=r.findIndex(c=>c.id===n);if(i===-1)return s;const l={...r[i],...o};if(l===r[i])return s;const a=r.slice();return a[i]=l,{elements:a}})},batchUpdateElements:n=>{if(n.length!==0){if(n.length===1){e().updateElement(n[0].id,n[0].updates);return}t(o=>{const s=o.elements,r=new Map;for(let l=0;l<s.length;l++)r.set(s[l].id,l);let i=null;for(const{id:l,updates:a}of n){const c=r.get(l);if(c===void 0)continue;const d=i?i[c]:s[c],h={...d,...a};h!==d&&(i||(i=s.slice()),i[c]=h)}return i?{elements:i}:o})}},deleteElements:n=>{const o=new Set(n),{elements:s}=e();for(const r of s)if(o.has(r.id)&&r.boundElements)for(const i of r.boundElements)i.type==="text"&&o.add(i.id);for(const r of s)r.type==="text"&&"containerId"in r&&r.containerId&&o.has(r.containerId)&&o.add(r.id);t(r=>{const i=r.elements.filter(a=>!o.has(a.id));return{elements:Jl(o,i),selectedIds:r.selectedIds.filter(a=>!o.has(a))}}),e().pushHistory()},setElements:n=>{const o=new Map;for(const s of n)o.set(s.id,s);t({elements:n,_historyBaseline:o})},duplicateElements:n=>{const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),{clones:r,selectedCloneIds:i}=Mn(s,o);t(l=>({elements:[...l.elements,...r],selectedIds:i.length>0?i:r.map(a=>a.id)})),e().pushHistory()},convertElementType:(n,o)=>{const s=new Set(["rectangle","ellipse","diamond"]);s.has(o)&&(t(r=>({elements:r.elements.map(i=>{if(!n.includes(i.id)||!s.has(i.type)||i.type===o)return i;const l={...i,type:o};return o==="rectangle"?{...l,cornerRadius:0}:l})})),e().pushHistory())},bringToFront:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id)),r=o.elements.filter(i=>n.includes(i.id));return{elements:[...s,...r]}}),e().pushHistory()},sendToBack:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id));return{elements:[...o.elements.filter(i=>n.includes(i.id)),...s]}}),e().pushHistory()},bringForward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=s.length-2;i>=0;i--)r.has(s[i].id)&&!r.has(s[i+1].id)&&([s[i],s[i+1]]=[s[i+1],s[i]]);return{elements:s}}),e().pushHistory()},sendBackward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=1;i<s.length;i++)r.has(s[i].id)&&!r.has(s[i-1].id)&&([s[i],s[i-1]]=[s[i-1],s[i]]);return{elements:s}}),e().pushHistory()},toggleLockElements:n=>{t(o=>({elements:o.elements.map(s=>n.includes(s.id)?{...s,isLocked:!s.isLocked}:s)})),e().pushHistory()},groupElements:n=>{if(n.length<2)return;const o=Ft(),s=new Set(n),{elements:r}=e();for(const i of r)if(s.has(i.id)&&i.boundElements)for(const l of i.boundElements)l.type==="text"&&s.add(l.id);t(i=>({elements:i.elements.map(l=>s.has(l.id)?{...l,groupIds:[...l.groupIds??[],o]}:l)})),e().pushHistory()},ungroupElements:n=>{var i;const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),r=new Set;for(const l of s)(i=l.groupIds)!=null&&i.length&&r.add(l.groupIds[l.groupIds.length-1]);r.size!==0&&(t(l=>({elements:l.elements.map(a=>{var d;if(!((d=a.groupIds)!=null&&d.length))return a;const c=a.groupIds.filter(h=>!r.has(h));return{...a,groupIds:c.length>0?c:void 0}})})),e().pushHistory())},setSelectedIds:n=>t({selectedIds:n}),clearSelection:()=>t({selectedIds:[]}),setActiveTool:n=>t(o=>({activeTool:n,selectedIds:n==="select"?o.selectedIds:[]})),setCurrentStyle:n=>t(o=>({currentStyle:{...o.currentStyle,...n}})),setCurrentLineType:n=>t({currentLineType:n}),setCurrentStartArrowhead:n=>t({currentStartArrowhead:n}),setCurrentEndArrowhead:n=>t({currentEndArrowhead:n}),setViewport:n=>{We(),t(o=>({viewport:{...o.viewport,...n}}))},zoomIn:(n,o)=>{const{viewport:s}=e(),r=lr(s.scale),l=_n({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},zoomOut:(n,o)=>{const{viewport:s}=e(),r=cr(s.scale),l=_n({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},resetZoom:n=>{const{viewport:o}=e(),s={x:0,y:0,scale:1};n!=null&&n.animate?Ee(o,s,r=>t(i=>({viewport:{...i.viewport,...r}}))):(We(),t({viewport:s}))},zoomToFit:(n,o,s,r)=>{const{elements:i,viewport:l}=e(),a=s?i.filter(h=>s.includes(h.id)):i,c=So(a);if(!c)return;const d=vo(c,n,o,{padding:r==null?void 0:r.padding,maxZoom:r==null?void 0:r.maxZoom});r!=null&&r.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},zoomToSelection:(n,o,s)=>{const{elements:r,selectedIds:i,viewport:l}=e();if(i.length===0)return;const a=r.filter(h=>i.includes(h.id)),c=So(a);if(!c)return;const d=vo(c,n,o,{padding:(s==null?void 0:s.padding)??80,maxZoom:(s==null?void 0:s.maxZoom)??2});s!=null&&s.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},setIsDrawing:n=>t({isDrawing:n}),setDrawStart:n=>t({drawStart:n}),pushHistory:n=>{const{elements:o,_historyBaseline:s,_historyPaused:r}=e();if(r)return;const i=[],l=new Map;for(const a of o)l.set(a.id,a);for(const a of o){const c=s.get(a.id);c?c!==a&&i.push({type:"modify",elementId:a.id,before:ue(c),after:ue(a)}):i.push({type:"add",elementId:a.id,after:ue(a)})}for(const[a,c]of s)l.has(a)||i.push({type:"delete",elementId:a,before:ue(c)});i.length!==0&&t(a=>{const c=a.history.slice(0,a.historyIndex+1);return c.push({diffs:i,mark:n,timestamp:Date.now()}),c.length>nc&&c.shift(),{history:c,historyIndex:c.length-1,_historyBaseline:new Map(l)}})},undo:()=>{const{historyIndex:n,history:o}=e();if(n<0)return;const s=o[n];t(r=>{let i=[...r.elements];for(let a=s.diffs.length-1;a>=0;a--){const c=s.diffs[a];switch(c.type){case"add":i=i.filter(d=>d.id!==c.elementId);break;case"modify":i=i.map(d=>d.id===c.elementId?ue(c.before):d);break;case"delete":i.push(ue(c.before));break}}const l=new Map;for(const a of i)l.set(a.id,a);return{historyIndex:n-1,elements:i,selectedIds:[],_historyBaseline:l}})},redo:()=>{const{historyIndex:n,history:o}=e();if(n>=o.length-1)return;const s=n+1,r=o[s];t(i=>{let l=[...i.elements];for(const c of r.diffs)switch(c.type){case"add":l.push(ue(c.after));break;case"modify":l=l.map(d=>d.id===c.elementId?ue(c.after):d);break;case"delete":l=l.filter(d=>d.id!==c.elementId);break}const a=new Map;for(const c of l)a.set(c.id,c);return{historyIndex:s,elements:l,selectedIds:[],_historyBaseline:a}})},squashHistory:(n=2)=>{t(o=>{if(o.history.length<n)return o;const s=Math.max(0,o.history.length-n),r=o.history.slice(s),i=new Map;for(const c of r)for(const d of c.diffs){const h=i.get(d.elementId);h?d.type==="delete"?h.type==="add"?i.delete(d.elementId):i.set(d.elementId,{type:"delete",elementId:d.elementId,before:h.before}):d.type==="modify"&&i.set(d.elementId,{type:h.type==="add"?"add":"modify",elementId:d.elementId,before:h.before,after:d.after}):i.set(d.elementId,{...d})}const l={diffs:Array.from(i.values()),mark:r[r.length-1].mark,timestamp:Date.now()},a=[...o.history.slice(0,s),l];return{history:a,historyIndex:a.length-1}})},pauseHistory:()=>t({_historyPaused:!0}),resumeHistory:()=>t({_historyPaused:!1}),canUndo:()=>e().historyIndex>=0,canRedo:()=>{const{historyIndex:n,history:o}=e();return n<o.length-1},toggleGrid:()=>t(n=>({showGrid:!n.showGrid}))})),Eo={elementId:null,isEditing:!1,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1},hn=Zs.create(t=>({...Eo,enterEditMode:e=>t({elementId:e,isEditing:!0,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1}),exitEditMode:()=>t({...Eo}),setSelectedPoints:e=>t({selectedPointIndices:e}),togglePointSelection:e=>t(n=>({selectedPointIndices:n.selectedPointIndices.includes(e)?n.selectedPointIndices.filter(s=>s!==e):[...n.selectedPointIndices,e]})),setHoveredPoint:e=>t({hoveredPointIndex:e}),setHoveredMidpoint:e=>t({hoveredMidpointIndex:e}),setIsDraggingPoint:e=>t({isDraggingPoint:e}),reset:()=>t({...Eo})}));function At(t,e){return Math.round(t/e)*e}function oc(t,e){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Wo(t,e){return{x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)}}function ar(t,e,n){const o=Math.cos(n),s=Math.sin(n),r=t.x-e.x,i=t.y-e.y;return{x:e.x+r*o-i*s,y:e.y+r*s+i*o}}function sc(t,e){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function gn(t,e){return[t/2,0,t,e/2,t/2,e,0,e/2]}function rc(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.max(Math.abs(n),Math.abs(o)),r=n>=0?1:-1,i=o>=0?1:-1,l=r>=0?t.x:t.x-s,a=i>=0?t.y:t.y-s;return{x:l,y:a,width:s,height:s}}const dr=[0,45,90,135,180,225,270,315,360],ic=Math.PI/180;function lc(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.sqrt(n*n+o*o);if(s===0)return{...e};let r=Math.atan2(o,n)*180/Math.PI;r<0&&(r+=360);let i=dr[0],l=999;for(const c of dr){const d=Math.abs(r-c);d<l&&(l=d,i=c)}i===360&&(i=0);const a=i*ic;return{x:t.x+s*Math.cos(a),y:t.y+s*Math.sin(a)}}function Xn(t){let e=0,n=0,o=0,s=0;for(let r=0;r<t.length;r+=2)e=Math.min(e,t[r]),n=Math.max(n,t[r]),o=Math.min(o,t[r+1]),s=Math.max(s,t[r+1]);return{width:n-e,height:s-o}}function Mt(t,e){switch(t){case"dashed":return[e*4,e*4];case"dotted":return[e,e*2];case"solid":default:return[]}}const Kt=.2;function Jt(t,e,n=Kt){const o=(t.x+e.x)/2,s=(t.y+e.y)/2,r=e.x-t.x,i=e.y-t.y,l=Math.sqrt(r*r+i*i);if(l===0)return{x:o,y:s};const a=-i/l,c=r/l,d=l*n;return{x:o+a*d,y:s+c*d}}function Pe(t,e,n,o){const s=1-o;return{x:s*s*t.x+2*s*o*e.x+o*o*n.x,y:s*s*t.y+2*s*o*e.y+o*o*n.y}}function To(t,e,n,o){const s=1-o;return{x:2*s*(e.x-t.x)+2*o*(n.x-e.x),y:2*s*(e.y-t.y)+2*o*(n.y-e.y)}}function Bo(t,e,n,o){if(o){const s=To(t,e,n,1),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:n.x-s.x/r*20,y:n.y-s.y/r*20}}else{const s=To(t,e,n,0),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:t.x+s.x/r*20,y:t.y+s.y/r*20}}}function ur(t,e,n){const o=e.x-t.x,s=e.y-t.y,r=Math.sqrt(o*o+s*s);if(r===0)return Kt;const i=-s/r,l=o/r,a=(t.x+e.x)/2,c=(t.y+e.y)/2,d=n.x-a,h=n.y-c;return 2*(d*i+h*l)/r}const cc={name:"select",onMouseDown(t,e,n){t.target===t.target.getStage()&&(n.linearEdit.isEditing&&n.linearEdit.exitEditMode(),n.clearSelection(),n.setIsDrawing(!0),n.setDrawStart(e),n.setSelectionBox({x:e.x,y:e.y,width:0,height:0}))},onMouseMove(t,e,n){!n.isDrawing||!n.drawStart||n.setSelectionBox(Wo(n.drawStart,e))},onMouseUp(t){if(!t.isDrawing)return;const e=t.selectionBox;if(e&&(e.width>2||e.height>2)){const n=t.elements.filter(r=>{let i=r.x,l=r.y,a=r.width,c=r.height;if((r.type==="arrow"||r.type==="line")&&"points"in r){const p=r.points,y=[],b=[];for(let W=0;W<p.length;W+=2)y.push(r.x+p[W]),b.push(r.y+p[W+1]);i=Math.min(...y),l=Math.min(...b),a=Math.max(...y)-i,c=Math.max(...b)-l}const d=i+a,h=l+c,u=e.x+e.width,f=e.y+e.height;return i<u&&d>e.x&&l<f&&h>e.y}).map(r=>r.id),o=new Set(n),s=new Set;for(const r of n){const i=t.elements.find(l=>l.id===r);if(i!=null&&i.groupIds)for(const l of i.groupIds)s.add(l)}if(s.size>0){for(const r of t.elements)if(!o.has(r.id)&&r.groupIds){for(const i of r.groupIds)if(s.has(i)){o.add(r.id);break}}}t.setSelectedIds([...o])}t.setSelectionBox(null),t.setIsDrawing(!1),t.setDrawStart(null)}};let Zo=!1;const ac={name:"eraser",onMouseDown(t,e,n){var s;Zo=!0;const o=t.target.id();o&&(n.deleteElements([o]),(s=n.onElementDelete)==null||s.call(n,[o]))},onMouseMove(t,e,n){var r,i;if(!Zo)return;const o=t.target,s=(r=o.id)==null?void 0:r.call(o);s&&o!==o.getStage()&&(n.deleteElements([s]),(i=n.onElementDelete)==null||i.call(n,[s]))},onMouseUp(t){Zo=!1},getCursor(){return"not-allowed"}},Mo={name:"rectangle",onMouseDown(t,e,n){var l;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Ft();n.currentElementIdRef.current=s;const r={id:s,type:n.activeTool,x:o.x,y:o.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null},i=n.activeTool==="rectangle"?{...r,type:"rectangle",cornerRadius:0}:r;B.getState().pauseHistory(),n.addElement(i),(l=n.onElementCreate)==null||l.call(n,i)},onMouseMove(t,e,n){if(!n.isDrawing||!n.drawStart||!n.currentElementIdRef.current)return;const o=n.snapPos(e),s=n.shiftKeyRef.current?rc(n.drawStart,o):Wo(n.drawStart,o);n.updateElement(n.currentElementIdRef.current,s)},onMouseUp(t){B.getState().resumeHistory(),t.currentElementIdRef.current&&(t.setSelectedIds([t.currentElementIdRef.current]),t.pushHistory()),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},{PI:dc}=Math,uc=.275,fn=dc+1e-4,hr=13,hc=29,gc=13,fc=3,pc=.15,yc=.85,Ic=.01,Cc=.25,gr=.5,fr=[1,1];function mc(t){return[-t[0],-t[1]]}function $t(t,e){return[t[0]+e[0],t[1]+e[1]]}function pr(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function he(t,e){return[t[0]-e[0],t[1]-e[1]]}function _o(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function ge(t,e){return[t[0]*e,t[1]*e]}function Xo(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function bc(t,e){return[t[0]/e,t[1]/e]}function yr(t){return[t[1],-t[0]]}function Go(t,e){const n=e[0];return t[0]=e[1],t[1]=-n,t}function Ir(t,e){return t[0]*e[0]+t[1]*e[1]}function Ac(t,e){return t[0]===e[0]&&t[1]===e[1]}function wc(t){return Math.hypot(t[0],t[1])}function Cr(t,e){const n=t[0]-e[0],o=t[1]-e[1];return n*n+o*o}function mr(t){return bc(t,wc(t))}function xc(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function Do(t,e,n){const o=Math.sin(n),s=Math.cos(n),r=t[0]-e[0],i=t[1]-e[1];return[r*s-i*o+e[0],r*o+i*s+e[1]]}function br(t,e,n,o){const s=Math.sin(o),r=Math.cos(o),i=e[0]-n[0],l=e[1]-n[1];return t[0]=i*r-l*s+n[0],t[1]=i*s+l*r+n[1],t}function Ar(t,e,n){return $t(t,ge(he(e,t),n))}function kc(t,e,n,o){return t[0]=e[0]+(n[0]-e[0])*o,t[1]=e[1]+(n[1]-e[1])*o,t}function wr(t,e,n){return $t(t,ge(e,n))}function xr(t,e,n){const o=Math.min(1,e/n),s=Math.min(1,1-o);return Math.min(1,t+(s-t)*(o*uc))}function kr(t,e,n,o=s=>s){return t*o(.5-e*(.5-n))}const Sr=[0,0];function vr(t){return t!=null&&t>=0}function Sc(t,e={}){var u;const{streamline:n=.5,size:o=16,last:s=!1}=e;if(t.length===0)return[];const r=pc+(1-n)*yc;let i=t.map(({x:f,y:p,pressure:y=gr})=>[f,p,y]);if(i.length===2){const f=i[1];i=i.slice(0,-1);for(let p=1;p<5;p++)i.push([...Ar(i[0],f,p/4)])}i.length===1&&(i=[...i,[...$t(i[0],fr),...i[0].slice(2)]]);const l=[{point:[i[0][0],i[0][1]],pressure:vr(i[0][2])?i[0][2]:Cc,vector:[...fr],distance:0,runningLength:0}];let a=!1,c=0,d=l[0];const h=i.length-1;for(let f=1;f<i.length;f++){const p=s&&f===h?[i[f][0],i[f][1]]:Ar(d.point,i[f],r);if(Ac(d.point,p))continue;const y=xc(p,d.point);if(c+=y,f<h&&!a){if(c<o)continue;a=!0}_o(Sr,d.point,p),d={point:p,pressure:vr(i[f][2])?i[f][2]:gr,vector:mr(Sr),distance:y,runningLength:c},l.push(d)}return l[0].vector=((u=l[1])==null?void 0:u.vector)||[0,0],l}const Zt=[0,0],fe=[0,0],pe=[0,0];function vc(t,e){const n=$t(t,[1,1]),o=wr(t,mr(yr(he(t,n))),-e),s=[],r=1/hr;for(let i=r;i<=1;i+=r)s.push(Do(o,t,fn*2*i));return s}function Ec(t,e,n){const o=[],s=1/n;for(let r=s;r<=1;r+=s)o.push(Do(e,t,fn*r));return o}function Wc(t,e,n){const o=he(e,n),s=ge(o,.5),r=ge(o,.51);return[he(t,s),he(t,r),$t(t,r),$t(t,s)]}function Tc(t,e,n,o){const s=[],r=wr(t,e,n),i=1/o;for(let l=i;l<1;l+=i)s.push(Do(r,t,fn*3*l));return s}function Bc(t,e,n){return[$t(t,ge(e,n)),$t(t,ge(e,n*.99)),he(t,ge(e,n*.99)),he(t,ge(e,n))]}function Er(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function Zc(t,e,n){return t.slice(0,10).reduce((o,s)=>{let r=s.pressure;return e&&(r=xr(o,s.distance,n)),(o+r)/2},t[0].pressure)}function Mc(t,e={}){const{size:n=16,smoothing:o=.5,thinning:s=.5,simulatePressure:r=!0,easing:i=Z=>Z,start:l={},end:a={},last:c=!1}=e,{cap:d=!0,easing:h=Z=>Z*(2-Z)}=l,{cap:u=!0,easing:f=Z=>--Z*Z*Z+1}=a;if(t.length===0||n<=0)return[];const p=t[t.length-1].runningLength,y=Er(l.taper,n,p),b=Er(a.taper,n,p),W=Math.pow(n*o,2),v=[],G=[];let $=Zc(t,r,n),T=kr(n,s,t[t.length-1].pressure,i),O,ot=t[0].vector,Y=t[0].point,J=Y,P=Y,Q=J,_=!1;for(let Z=0;Z<t.length;Z++){let{pressure:X}=t[Z];const{point:U,vector:D,distance:L,runningLength:at}=t[Z],tt=Z===t.length-1;if(!tt&&p-at<fc)continue;s?(r&&(X=xr($,L,n)),T=kr(n,s,X,i)):T=n/2,O===void 0&&(O=T);const E=at<y?h(at/y):1,V=p-at<b?f((p-at)/b):1;T=Math.max(Ic,T*Math.min(E,V));const dt=(tt?t[Z]:t[Z+1]).vector,R=tt?1:Ir(D,dt),et=Ir(D,ot)<0&&!_,It=R!==null&&R<0;if(et||It){Go(Zt,ot),Xo(Zt,Zt,T);const Ct=1/gc;for(let rt=0;rt<=1;rt+=Ct)_o(fe,U,Zt),br(fe,fe,U,fn*rt),P=[fe[0],fe[1]],v.push(P),pr(pe,U,Zt),br(pe,pe,U,fn*-rt),Q=[pe[0],pe[1]],G.push(Q);Y=P,J=Q,It&&(_=!0);continue}if(_=!1,tt){Go(Zt,D),Xo(Zt,Zt,T),v.push(he(U,Zt)),G.push($t(U,Zt));continue}kc(Zt,dt,D,R),Go(Zt,Zt),Xo(Zt,Zt,T),_o(fe,U,Zt),P=[fe[0],fe[1]],(Z<=1||Cr(Y,P)>W)&&(v.push(P),Y=P),pr(pe,U,Zt),Q=[pe[0],pe[1]],(Z<=1||Cr(J,Q)>W)&&(G.push(Q),J=Q),$=X,ot=D}const x=[t[0].point[0],t[0].point[1]],C=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:$t(t[0].point,[1,1]),w=[],S=[];if(t.length===1){if(!(y||b)||c)return vc(x,O||T)}else{y||b&&t.length===1||(d?w.push(...Ec(x,G[0],hr)):w.push(...Wc(x,v[0],G[0])));const Z=yr(mc(t[t.length-1].vector));b||y&&t.length===1?S.push(C):u?S.push(...Tc(C,Z,T,hc)):S.push(...Bc(C,Z,T))}return v.concat(S,G.reverse(),w)}function _c(t,e={}){return Mc(Sc(t,e),e)}const Gn=(t,e)=>(t+e)/2;function Xc(t,e=!0){const n=t.length;if(n<4)return"";let o=t[0],s=t[1];const r=t[2];let i=`M${o[0].toFixed(2)},${o[1].toFixed(2)} Q${s[0].toFixed(2)},${s[1].toFixed(2)} ${Gn(s[0],r[0]).toFixed(2)},${Gn(s[1],r[1]).toFixed(2)} T`;for(let l=2,a=n-1;l<a;l++)o=t[l],s=t[l+1],i+=`${Gn(o[0],s[0]).toFixed(2)},${Gn(o[1],s[1]).toFixed(2)} `;return e&&(i+="Z"),i}function Lo(t){let e=1/0,n=1/0,o=-1/0,s=-1/0;for(let r=0;r<t.length;r+=2){const i=t[r],l=t[r+1];i<e&&(e=i),i>o&&(o=i),l<n&&(n=l),l>s&&(s=l)}return isFinite(e)||(e=0,o=0,n=0,s=0),{minX:e,minY:n,maxX:o,maxY:s,width:Math.max(1,o-e),height:Math.max(1,s-n)}}function Wr(t,e,n={}){if(t.length<4)return"";const o=[];for(let r=0;r<t.length;r+=2)o.push({x:t[r],y:t[r+1],pressure:e&&e[r/2]!==void 0?e[r/2]:.5});const s=_c(o,n);return Xc(s)}const Gc=9,Dc={name:"freedraw",onMouseDown(t,e,n){var i;n.setIsDrawing(!0),n.setDrawStart(e),n.clearSelection();let o=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(o=t.evt.pressure===0?.5:t.evt.pressure);const s=Ft();n.currentElementIdRef.current=s;const r={id:s,type:"freedraw",x:e.x,y:e.y,width:1,height:1,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[e.x,e.y],pressures:[o],isComplete:!1};B.getState().pauseHistory(),n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r)},onMouseMove(t,e,n){if(!n.isDrawing||!n.currentElementIdRef.current)return;const o=n.elements.find(s=>s.id===n.currentElementIdRef.current);if(o){let s=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(s=t.evt.pressure===0?.5:t.evt.pressure);const r=o.points;if(r.length>=2){const h=r[r.length-2],u=r[r.length-1],f=e.x-h,p=e.y-u;if(f*f+p*p<Gc)return}const i=[...o.points,e.x,e.y],{minX:l,minY:a,width:c,height:d}=Lo(i);n.updateElement(o.id,{points:i,pressures:o.pressures?[...o.pressures,s]:[s],isComplete:!1,x:l,y:a,width:c,height:d})}},onMouseUp(t){if(t.currentElementIdRef.current){const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const{minX:n,minY:o,width:s,height:r}=Lo(e.points);t.updateElement(e.id,{x:n,y:o,width:s,height:r,points:e.points.map((i,l)=>l%2===0?i-n:i-o),isComplete:!0})}B.getState().resumeHistory(),t.pushHistory()}t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null},getCursor(){return"crosshair"}},Lc={name:"text",onMouseDown(t,e,n){var i;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Ft(),r={id:s,type:"text",x:o.x,y:o.y,width:10,height:30,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:null,textAlign:"left",verticalAlign:"top"};n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r),n.setSelectedIds([s]),n.setActiveTool("select"),n.setIsDrawing(!1),n.setAutoEditTextId(s)},onMouseMove(){},onMouseUp(){},getCursor(){return"text"}},Yc=800,Vc=600;function Dn(t){return new Promise((e,n)=>{const o=new FileReader;o.onload=()=>e(o.result),o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function pn(t){return new Promise((e,n)=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>e(o),o.onerror=()=>n(new Error("Failed to load image")),o.src=t})}function Tr(t,e,n=Yc,o=Vc){if(t<=n&&e<=o)return{width:t,height:e};const s=t/e,r=n/o;return s>r?{width:n,height:n/s}:{width:o*s,height:o}}function Ln(t,e,n,o,s,r={...En}){const i=Tr(e,n);return{id:Ft(),type:"image",x:o-i.width/2,y:s-i.height/2,width:i.width,height:i.height,rotation:0,style:{...r,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,src:t,naturalWidth:e,naturalHeight:n,scaleMode:"stretch",crop:null,cornerRadius:0,alt:""}}function Yo(t){const e=[];if(t.files)for(let n=0;n<t.files.length;n++){const o=t.files[n];o.type.startsWith("image/")&&e.push(o)}return e}function Vo(t){const e=t.clipboardData;if(!e)return{file:null,imgUrl:null};const n=Yo(e);if(n.length>0)return{file:n[0],imgUrl:null};const o=e.getData("text/html");if(o){const s=o.match(/<img[^>]+src=["']([^"']+)["']/i);if(s!=null&&s[1])return{file:null,imgUrl:s[1]}}return{file:null,imgUrl:null}}function Fc(t){const{file:e,imgUrl:n}=Vo(t);return e!==null||n!==null}async function Br(t){if(t.file)return Dn(t.file);if(t.imgUrl)try{const e=await pn(t.imgUrl),n=document.createElement("canvas");n.width=e.naturalWidth,n.height=e.naturalHeight;const o=n.getContext("2d");if(o)return o.drawImage(e,0,0),n.toDataURL("image/png")}catch{return t.imgUrl}return null}function Zr(){return new Promise(t=>{const e=document.createElement("input");e.type="file",e.accept="image/*",e.multiple=!0,e.style.display="none",e.onchange=()=>{const n=[];if(e.files)for(let o=0;o<e.files.length;o++)n.push(e.files[o]);t(n),document.body.removeChild(e)},e.oncancel=()=>{t([]),document.body.removeChild(e)},document.body.appendChild(e),e.click()})}const Pc={name:"image",onMouseDown(t,e,n){n.setIsDrawing(!1);const o=n.snapPos(e);n.clearSelection(),Zr().then(async s=>{var r;for(const i of s)try{const l=await Dn(i),a=await pn(l),c=Ln(l,a.naturalWidth,a.naturalHeight,o.x,o.y,{...n.currentStyle});n.addElement(c),(r=n.onElementCreate)==null||r.call(n,c),n.setSelectedIds([c.id]),n.pushHistory()}catch{}n.setActiveTool("select")})},onMouseMove(){},onMouseUp(){},getCursor(){return"copy"}};let Yn=null,He;const Mr={name:"line",onMouseDown(t,e,n){var p;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Ft();n.currentElementIdRef.current=s;const r=ce(n.currentStyle.strokeWidth??2),i=ke(e,n.elements,24,void 0,void 0,void 0,r);let l=e,a=null;He=void 0,i?(l=i.position,a={elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}):l=o,n.startBindingRef.current=a,B.getState().pauseHistory();const c={id:s,x:l.x,y:l.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[0,0,0,0],startBinding:a,endBinding:null},{currentLineType:d,currentStartArrowhead:h,currentEndArrowhead:u}=B.getState(),f=n.activeTool==="arrow"?{...c,type:"arrow",startArrowhead:h,endArrowhead:u,lineType:d}:{...c,type:"line",lineType:d};n.addElement(f),(p=n.onElementCreate)==null||p.call(n,f)},onMouseMove(t,e,n){if(!n.isDrawing){const h=ce(n.currentStyle.strokeWidth??2),u=ke(e,n.elements,24,void 0,void 0,void 0,h);n.setSnapTarget(u);return}if(!n.currentElementIdRef.current)return;const o=n.elements.find(h=>h.id===n.currentElementIdRef.current);if(!o)return;Yn=e;const s=new Set([o.id]);o.startBinding&&s.add(o.startBinding.elementId);const r=ce(o.style.strokeWidth??2),i=ke(e,n.elements,24,s,{x:o.x,y:o.y},void 0,r,He);n.setSnapTarget(i),He=i==null?void 0:i.isPrecise;let l=i?i.position:n.snapPos(e);!i&&n.shiftKeyRef.current&&(l=lc({x:o.x,y:o.y},l));const a=i?{elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}:null,c=l.x-o.x,d=l.y-o.y;if(o.startBinding){const h=n.elements.find(u=>u.id===o.startBinding.elementId);if(h){let u;o.startBinding.isPrecise?u=ae(h,o.startBinding.fixedPoint,o.startBinding.gap):u=de(h,l,o.startBinding.gap);const f=l.x-u.x,p=l.y-u.y;n.updateElement(o.id,{x:u.x,y:u.y,points:[0,0,f,p],width:Math.abs(f),height:Math.abs(p),endBinding:a});return}}n.updateElement(o.id,{points:[0,0,c,d],width:Math.abs(c),height:Math.abs(d),endBinding:a})},onMouseUp(t){if(!t.currentElementIdRef.current)return;const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const n=e.points;if(Math.sqrt((n[n.length-2]-n[0])**2+(n[n.length-1]-n[1])**2)<2)B.getState().resumeHistory(),t.deleteElements([t.currentElementIdRef.current]),t.currentElementIdRef.current=null,t.startBindingRef.current=null,t.setSnapTarget(null),Yn=null,He=void 0;else{const s=Yn??{x:e.x+n[n.length-2],y:e.y+n[n.length-1]},r=new Set([e.id]);e.startBinding&&r.add(e.startBinding.elementId);const i=ce(e.style.strokeWidth??2),l=ke(s,t.elements,24,r,void 0,void 0,i,He),a=ce(e.style.strokeWidth??2),c=l?{elementId:l.elementId,fixedPoint:l.fixedPoint,gap:a,isPrecise:l.isPrecise}:null,d=e.startBinding??t.startBindingRef.current,h=c&&d&&c.elementId===d.elementId?null:c,u=[...n];l&&(u[u.length-2]=l.position.x-e.x,u[u.length-1]=l.position.y-e.y);const f={points:u,width:Math.abs(u[u.length-2]-u[0]),height:Math.abs(u[u.length-1]-u[1]),startBinding:d,endBinding:h},p={...e,...f},y=Se(p,t.elements);y&&Object.assign(f,y),t.updateElement(e.id,f);const b=e.type,W=B.getState().elements;ve(e.id,b,null,d,W,t.updateElement);const v=B.getState().elements;ve(e.id,b,null,h,v,t.updateElement),t.startBindingRef.current=null,t.setSnapTarget(null),t.setSelectedIds([t.currentElementIdRef.current]),B.getState().resumeHistory(),t.pushHistory()}}Yn=null,He=void 0,B.getState().resumeHistory(),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},Hc={select:cc,rectangle:Mo,ellipse:Mo,diamond:Mo,line:Mr,arrow:Mr,freedraw:Dc,text:Lc,image:Pc,eraser:ac};function yn(t){return Hc[t]}function ye(t){const e=typeof t=="number"?String(t):t;let n=0,o=0,s=0,r=0;function i(){const l=n^n<<11;return n=o,o=s,s=r,r^=(r>>>19^l^l>>>8)>>>0,r/4294967296*2}for(let l=0;l<e.length+64;l++)n^=e.charCodeAt(l)|0,i();return i}function In(t,e){if(t===0)return 0;const n=t===1?.8:1.5,o=e*(t===1?.4:.8);return Math.max(n,o)}function _r(t,e){return t===0?0:Math.max(e*(t===1?1.2:2),t===1?1.5:3)}function Oc(t,e,n,o){const s=n-t,r=o-e;return Math.sqrt(s*s+r*r)}function Nc(t,e,n,o){const s=t*n+e*o,r=Math.sqrt(t*t+e*e),i=Math.sqrt(n*n+o*o);return r<1e-6||i<1e-6?0:Math.acos(Math.max(-1,Math.min(1,s/(r*i))))}function Uc(t,e,n,o,s,r,i,l=!0){const a=o-e,c=s-n,d=Math.sqrt(a*a+c*c);if(d<.5){l&&t.moveTo(e,n),t.lineTo(o,s);return}const h=-c/d,u=a/d,f=Math.min(r,d*.25),p=f*.15,y=e+i()*p,b=n+i()*p,W=o+i()*p,v=s+i()*p,G=y+a*.33+h*i()*f,$=b+c*.33+u*i()*f,T=y+a*.67+h*i()*f,O=b+c*.67+u*i()*f;l&&t.moveTo(y,b),t.bezierCurveTo(G,$,T,O,W,v)}function Xr(t,e,n,o,s){const r=e.length;if(r<3)return;const i=[];for(let l=0;l<r;l++){const[a,c]=e[l],[d,h]=e[(l+1)%r];i.push(Oc(a,c,d,h))}for(let l=0;l<r;l++){const a=e[(l-1+r)%r],c=e[l],d=e[(l+1)%r],h=i[(l-1+r)%r],u=i[l],f=c[0]-a[0],p=c[1]-a[1],y=d[0]-c[0],b=d[1]-c[1],v=1-Nc(-f,-p,y,b)/Math.PI;let G=o*v;const $=Math.min(h,u);G=Math.min(G,$*.4),G=Math.max(G,0);const T=h>1e-6?G/h:0,O=u>1e-6?G/u:0,ot=c[0]-f*T,Y=c[1]-p*T,J=c[0]+y*O,P=c[1]+b*O,Q=ot+s()*n,_=Y+s()*n,x=J+s()*n,C=P+s()*n,w=c[0]+s()*n,S=c[1]+s()*n;l===0?t.moveTo(Q,_):t.lineTo(Q,_),G>.5?t.quadraticCurveTo(w,S,x,C):t.lineTo(x,C)}t.closePath()}function Oe(t){return t>=2?2:1}function zc(t,e,n,o,s,r,i,l=1,a=2){const c=In(r,a),d=_r(r,a),h=[[e,n],[e+o,n],[e+o,n+s],[e,n+s]];for(let u=0;u<l;u++)t.beginPath(),Xr(t,h,c,d,i)}function Kc(t,e,n,o,s,r,i,l=1,a=2){const c=In(r,a),d=Math.PI*2*Math.sqrt((o*o+s*s)/2),h=Math.max(16,Math.min(64,Math.floor(d*.08))),u=Math.PI*2/h,f=4/3*Math.tan(u/4);for(let p=0;p<l;p++){const y=[];for(let b=0;b<=h;b++){const W=b*u,v=i()*c*1.8;y.push({x:e+(o+v)*Math.cos(W),y:n+(s+v)*Math.sin(W),angle:W})}t.moveTo(y[0].x,y[0].y);for(let b=0;b<h;b++){const W=y[b],v=y[b+1],G=Math.cos(W.angle),$=Math.sin(W.angle),T=Math.cos(v.angle),O=Math.sin(v.angle),ot=-$,Y=G,J=-O,P=T;o+i()*c,s+i()*c;const Q=W.x+ot*o*f+i()*c*.8,_=W.y+Y*s*f+i()*c*.8,x=v.x-J*o*f+i()*c*.8,C=v.y-P*s*f+i()*c*.8;t.bezierCurveTo(Q,_,x,C,v.x,v.y)}}}function Jc(t,e,n,o,s,r=1,i=2){const l=In(o,i),a=_r(o,i),c=[[e/2,0],[e,n/2],[e/2,n],[0,n/2]];for(let d=0;d<r;d++)t.beginPath(),Xr(t,c,l,a,s)}function Fo(t,e,n,o,s=1,r=2){if(e.length<4)return;const i=In(n,r);for(let l=0;l<s;l++)for(let a=0;a<e.length-2;a+=2)Uc(t,e[a],e[a+1],e[a+2],e[a+3],i,o,!0)}function Gr(t,e,n,o,s,r,i=1,l=2){const a=In(s,l),c=a*2;for(let d=0;d<i;d++){const h=e.x+r()*a*.6,u=e.y+r()*a*.6,f=o.x+r()*a*.6,p=o.y+r()*a*.6,y=n.x+r()*c,b=n.y+r()*c;t.moveTo(h,u),t.quadraticCurveTo(y,b,f,p)}}function $c(t,e,n,o,s,r){const i=Math.min(r,o/2,s/2);t.beginPath(),t.moveTo(e+i,n),t.lineTo(e+o-i,n),t.arcTo(e+o,n,e+o,n+i,i),t.lineTo(e+o,n+s-i),t.arcTo(e+o,n+s,e+o-i,n+s,i),t.lineTo(e+i,n+s),t.arcTo(e,n+s,e,n+s-i,i),t.lineTo(e,n+i),t.arcTo(e,n,e+i,n,i),t.closePath()}const Rc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,cornerRadius:y,style:b,isLocked:W}=t,v=!W&&!n,G=b.roughness,$=I.useCallback(()=>o(c),[o,c]),T=I.useCallback(()=>i==null?void 0:i(c),[i,c]),O=I.useCallback(x=>{let C=x.target.x(),w=x.target.y();if(l&&(C=At(C,l),w=At(w,l),x.target.x(C),x.target.y(w)),!l&&a){const S=a(c,{x:C,y:w,width:u,height:f});S&&(C=S.x,w=S.y,x.target.x(C),x.target.y(w))}r==null||r(c,{x:C,y:w})},[c,l,u,f,r,a]),ot=I.useCallback(x=>{let C=x.target.x(),w=x.target.y();l&&(C=At(C,l),w=At(w,l)),s(c,{x:C,y:w})},[c,l,s]),Y=I.useCallback(x=>{const C=x.target,w=C.scaleX(),S=C.scaleY(),Z=Math.max(5,C.width()*w),X=Math.max(5,C.height()*S);C.setAttrs({scaleX:1,scaleY:1,width:Z,height:X}),r==null||r(c,{x:C.x(),y:C.y(),width:Z,height:X})},[c,r]),J=I.useCallback(x=>{const C=x.target,w=Math.max(5,C.width()*C.scaleX()),S=Math.max(5,C.height()*C.scaleY());C.setAttrs({scaleX:1,scaleY:1,width:w,height:S}),s(c,{x:C.x(),y:C.y(),width:w,height:S,rotation:C.rotation()})},[c,s]),P=e?Tt.color:void 0,Q=e?Tt.blur:0,_=e?Tt.opacity:0;if(G>0){const x=Oe(G),C=Mt(b.strokeStyle,b.strokeWidth);return g.jsx(ht.Shape,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{y>0?$c(w,0,0,u,f,y):(w.beginPath(),w.rect(0,0,u,f)),w.fillShape(S);for(let Z=0;Z<x;Z++){const X=ye(c+":"+Z);w.beginPath(),zc(w,0,0,u,f,G,X,1,b.strokeWidth),w.strokeShape(S)}},fill:b.fillColor,stroke:b.strokeColor,strokeWidth:b.strokeWidth,opacity:b.opacity,dash:C,lineCap:"round",lineJoin:"round",draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:P,shadowBlur:Q,shadowOpacity:_,onDragMove:O,onDragEnd:ot,onTransform:Y,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(ht.Rect,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",cornerRadius:y,fill:b.fillColor,stroke:b.strokeColor,strokeWidth:b.strokeWidth,opacity:b.opacity,dash:Mt(b.strokeStyle,b.strokeWidth),draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:P,shadowBlur:Q,shadowOpacity:_,onDragMove:O,onDragEnd:ot,onTransform:Y,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},jc=I.memo(Rc),Qc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:b}=t,W=!b&&!n,v=y.roughness,G=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(_=>{let x=_.target.x(),C=_.target.y();if(l){const w=At(x-u/2,l),S=At(C-f/2,l);x=w+u/2,C=S+f/2,_.target.x(x),_.target.y(C)}if(!l&&a){const w=a(c,{x:x-u/2,y:C-f/2,width:u,height:f});w&&(x=w.x+u/2,C=w.y+f/2,_.target.x(x),_.target.y(C))}r==null||r(c,{x:x-u/2,y:C-f/2})},[c,l,u,f,r,a]),O=I.useCallback(_=>{let x=_.target.x(),C=_.target.y();if(l){const w=At(x-u/2,l),S=At(C-f/2,l);x=w+u/2,C=S+f/2}s(c,{x:x-u/2,y:C-f/2})},[c,l,u,f,s]),ot=I.useCallback(_=>{const x=_.target,C=x.scaleX(),w=x.scaleY(),S=Math.max(5,u*C/2),Z=Math.max(5,f*w/2);x.setAttrs({scaleX:1,scaleY:1,radiusX:S,radiusY:Z});const X=S*2,U=Z*2;r==null||r(c,{x:x.x()-S,y:x.y()-Z,width:X,height:U})},[c,u,f,r]),Y=I.useCallback(_=>{const x=_.target,C=x.getAttr("radiusX"),w=x.getAttr("radiusY");x.setAttrs({scaleX:1,scaleY:1});const S=Math.max(5,C*2),Z=Math.max(5,w*2);s(c,{x:x.x()-C,y:x.y()-w,width:S,height:Z,rotation:x.rotation()})},[c,s]),J=e?Tt.color:void 0,P=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const _=Oe(v),x=u/2,C=f/2;return g.jsx(ht.Shape,{id:c,x:d+x,y:h+C,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{w.beginPath(),w.ellipse(0,0,x,C,0,0,Math.PI*2),w.fillShape(S);for(let Z=0;Z<_;Z++){const X=ye(c+":"+Z);w.beginPath(),Kc(w,0,0,x,C,v,X,1,y.strokeWidth),w.strokeShape(S)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",draggable:W,onClick:G,onTap:G,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:P,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:Y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(ht.Ellipse,{id:c,x:d+u/2,y:h+f/2,radiusX:u/2,radiusY:f/2,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),draggable:W,onClick:G,onTap:G,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:P,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:Y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},qc=I.memo(Qc),ta=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:b}=t,W=!b&&!n,v=y.roughness,G=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(_=>{let x=_.target.x(),C=_.target.y();if(l&&(x=At(x,l),C=At(C,l),_.target.x(x),_.target.y(C)),!l&&a){const w=a(c,{x,y:C,width:u,height:f});w&&(x=w.x,C=w.y,_.target.x(x),_.target.y(C))}r==null||r(c,{x,y:C})},[c,l,u,f,r,a]),O=I.useCallback(_=>{let x=_.target.x(),C=_.target.y();l&&(x=At(x,l),C=At(C,l)),s(c,{x,y:C})},[c,l,s]),ot=I.useCallback(_=>{const x=_.target,C=x.scaleX(),w=x.scaleY(),S=Math.max(5,u*C),Z=Math.max(5,f*w);x.setAttrs({scaleX:1,scaleY:1,points:gn(S,Z)}),r==null||r(c,{x:x.x(),y:x.y(),width:S,height:Z})},[c,u,f,r]),Y=I.useCallback(_=>{const x=_.target;x.setAttrs({scaleX:1,scaleY:1});const C=x.getAttr("points"),w=C?C[2]:u,S=C?C[5]:f;s(c,{x:x.x(),y:x.y(),width:Math.max(5,w),height:Math.max(5,S),rotation:x.rotation()})},[c,u,f,s]),J=e?Tt.color:void 0,P=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const _=Oe(v),x=Mt(y.strokeStyle,y.strokeWidth);return g.jsx(ht.Shape,{id:c,x:d,y:h,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(C,w)=>{const S=gn(u,f);C.beginPath(),C.moveTo(S[0],S[1]);for(let Z=2;Z<S.length;Z+=2)C.lineTo(S[Z],S[Z+1]);C.closePath(),C.fillShape(w);for(let Z=0;Z<_;Z++){const X=ye(c+":"+Z);C.beginPath(),Jc(C,u,f,v,X,1,y.strokeWidth),C.strokeShape(w)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:x,lineCap:"round",lineJoin:"round",draggable:W,onClick:G,onTap:G,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:P,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:Y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(ht.Line,{id:c,x:d,y:h,points:gn(u,f),closed:!0,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),draggable:W,onClick:G,onTap:G,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:P,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:Y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},ea=I.memo(ta),na=new Set(["rectangle","ellipse","diamond","text","image"]);function Dr(t){const e=I.useRef(t??[]);return e.current=t??[],{fingerprint:I.useMemo(()=>{if(!t||t.length===0)return"";const o=r=>Math.round(r*2)/2,s=[];for(const r of t)na.has(r.type)&&r.isVisible&&s.push(`${r.id}:${o(r.x)},${o(r.y)},${o(r.width)},${o(r.height)},${o(r.rotation||0)}`);return s.join(";")},[t]),elementsRef:e}}function oa(t){const e=t.indexOf(",");if(e===-1)throw new Error("Invalid data URL");const o=t.slice(5,e).endsWith(";base64"),s=t.slice(e+1);let r;if(o){const l=atob(s);r=new Uint8Array(l.length);for(let a=0;a<l.length;a++)r[a]=l.charCodeAt(a)}else{const l=decodeURIComponent(s);r=new TextEncoder().encode(l)}const i=new Blob([r],{type:"application/javascript"});return URL.createObjectURL(i)}function Vn(t,e){if(typeof Worker>"u"||e!=null&&e.disabled)return null;if(e!=null&&e.url)try{return new Worker(e.url,{type:"module"})}catch(n){return console.warn("[workerFactory] Failed to create worker from custom URL:",e.url,n),null}try{const n=typeof t=="function"?t():t,o=n instanceof URL?n.href:String(n);if(o.startsWith("data:")){const s=oa(o);return new Worker(s)}return new Worker(n instanceof URL?n:new URL(o),{type:"module"})}catch(n){return console.warn("[workerFactory] Worker creation failed, using sync fallback:",n),null}}function sa(){return typeof Worker<"u"&&typeof URL<"u"}function ra(t){const e=new Array(t.length);for(let n=0;n<t.length;n++){const o=t[n];e[n]={id:o.id,type:o.type,x:o.x,y:o.y,width:o.width,height:o.height,rotation:o.rotation,isVisible:o.isVisible}}return e}const Lr=50;class ia{constructor(e){ct(this,"worker",null);ct(this,"requestIdCounter",0);ct(this,"pending",new Map);ct(this,"cachedElements",[]);ct(this,"workerSupported",!0);ct(this,"workerConfig");ct(this,"handleMessage",e=>{const{type:n,requestId:o,points:s}=e.data;if(n==="routeResult"){const r=this.pending.get(o);r&&(this.pending.delete(o),r.timerId!==void 0&&clearTimeout(r.timerId),r.resolve(s))}});this.workerConfig=e}_getWorker(){if(!this.workerSupported)return null;if(this.worker)return this.worker;try{return this.worker=Vn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGVsYm93V29ya2VyLnRzIOKAlCBXZWIgV29ya2VyIGZvciBvZmYtbWFpbi10aHJlYWQgZWxib3cgY29ubmVjdG9yIHJvdXRpbmcuCiAqCiAqIFJ1bnMgdGhlIGV4cGVuc2l2ZSBBKiBncmlkLXNlYXJjaCBhbGdvcml0aG0gaW4gYSBiYWNrZ3JvdW5kIHRocmVhZCBzbwogKiB0aGUgbWFpbiB0aHJlYWQgc3RheXMgYXQgNjBmcHMgZHVyaW5nIGludGVuc2l2ZSBkcmFnIG9wZXJhdGlvbnMgdGhhdAogKiB0cmlnZ2VyIG1hbnkgc2ltdWx0YW5lb3VzIHJvdXRlIHJlY29tcHV0YXRpb25zLgogKgogKiBDb21tdW5pY2F0aW9uIHByb3RvY29sOgogKiAgIE1haW4g4oaSIFdvcmtlcjoKICogICAgIHsgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJywgZWxlbWVudHM6IFNlcmlhbGl6ZWRFbGVtZW50W10gfQogKiAgICAgeyB0eXBlOiAnY29tcHV0ZVJvdXRlJywgcmVxdWVzdElkLCBwYXJhbXM6IFJvdXRlUGFyYW1zIH0KICogICBXb3JrZXIg4oaSIE1haW46CiAqICAgICB7IHR5cGU6ICdyb3V0ZVJlc3VsdCcsIHJlcXVlc3RJZCwgcG9pbnRzOiBudW1iZXJbXSB9CiAqCiAqIFVzZXMgVml0ZSdzIG5hdGl2ZSBXb3JrZXIgbW9kdWxlIHN1cHBvcnQg4oCUIGltcG9ydGVkIHdpdGg6CiAqICAgbmV3IFdvcmtlcihuZXcgVVJMKCcuL2VsYm93V29ya2VyLnRzJywgaW1wb3J0Lm1ldGEudXJsKSwgeyB0eXBlOiAnbW9kdWxlJyB9KQogKi8KCi8vIE5PVEU6IFdlIGltcG9ydCB0aGUgZnVsbCBlbGJvdyBtb2R1bGUgaGVyZS4gIFZpdGUgYnVuZGxlcyBpdCBpbnRvIHRoZQovLyBXb3JrZXIgY2h1bmsgYXV0b21hdGljYWxseS4gIFRoZSBgQC9gIHBhdGggYWxpYXMgaXMgcmVzb2x2ZWQgYnkgVml0ZS4KaW1wb3J0IHsgY29tcHV0ZUVsYm93UG9pbnRzLCBzaW1wbGlmeUVsYm93UGF0aCB9IGZyb20gJ0AvdXRpbHMvZWxib3cnOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQsIEJpbmRpbmcsIFBvaW50IH0gZnJvbSAnQC90eXBlcyc7CgovLyDilIDilIDilIAgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgU2VyaWFsaXplZEVsZW1lbnQgewogICAgaWQ6IHN0cmluZzsKICAgIHR5cGU6IHN0cmluZzsKICAgIHg6IG51bWJlcjsKICAgIHk6IG51bWJlcjsKICAgIHdpZHRoOiBudW1iZXI7CiAgICBoZWlnaHQ6IG51bWJlcjsKICAgIHJvdGF0aW9uOiBudW1iZXI7CiAgICBpc1Zpc2libGU6IGJvb2xlYW47CiAgICAvLyBNaW5pbWFsIGZpZWxkcyBuZWVkZWQgZm9yIG9ic3RhY2xlIGRldGVjdGlvbiDigJQgc3R5bGUsIHRleHQsIGV0Yy4gYXJlIG9taXR0ZWQuCiAgICAvLyBXZSByZWNvbnN0cnVjdCBhICJwc2V1ZG8tQ2FudmFzRWxlbWVudCIgZnJvbSB0aGVzZSBmaWVsZHMuCn0KCmludGVyZmFjZSBSb3V0ZVBhcmFtcyB7CiAgICBzdGFydFdvcmxkOiBQb2ludDsKICAgIGVuZFdvcmxkOiBQb2ludDsKICAgIHN0YXJ0QmluZGluZzogQmluZGluZyB8IG51bGw7CiAgICBlbmRCaW5kaW5nOiBCaW5kaW5nIHwgbnVsbDsKICAgIG1pblN0dWJMZW5ndGg/OiBudW1iZXI7Cn0KCmludGVyZmFjZSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgewogICAgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJzsKICAgIGVsZW1lbnRzOiBTZXJpYWxpemVkRWxlbWVudFtdOwp9CgppbnRlcmZhY2UgQ29tcHV0ZVJvdXRlTWVzc2FnZSB7CiAgICB0eXBlOiAnY29tcHV0ZVJvdXRlJzsKICAgIHJlcXVlc3RJZDogbnVtYmVyOwogICAgcGFyYW1zOiBSb3V0ZVBhcmFtczsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgfCBDb21wdXRlUm91dGVNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBzdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCi8qKiBMaWdodHdlaWdodCBlbGVtZW50IHByb3hpZXMgdXNlZCBmb3Igb2JzdGFjbGUgZGV0ZWN0aW9uIGluIHJvdXRpbmcgKi8KbGV0IGNhY2hlZEVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gPSBbXTsKCi8qKgogKiBSZWNvbnN0cnVjdCBtaW5pbWFsIENhbnZhc0VsZW1lbnQtc2hhcGVkIG9iamVjdHMgZnJvbSBzZXJpYWxpemVkIGRhdGEuCiAqIE9ubHkgdGhlIGZpZWxkcyB1c2VkIGJ5IGNvbXB1dGVFbGJvd1BvaW50cyBhcmUgbmVlZGVkOgogKiAgIGlkLCB0eXBlLCB4LCB5LCB3aWR0aCwgaGVpZ2h0LCByb3RhdGlvbiwgaXNWaXNpYmxlCiAqLwpmdW5jdGlvbiBkZXNlcmlhbGl6ZUVsZW1lbnRzKHNlcmlhbGl6ZWQ6IFNlcmlhbGl6ZWRFbGVtZW50W10pOiBDYW52YXNFbGVtZW50W10gewogICAgLy8gQ2FzdCBpcyBzYWZlIGJlY2F1c2UgY29tcHV0ZUVsYm93UG9pbnRzIG9ubHkgcmVhZHMgc3BhdGlhbCBmaWVsZHMKICAgIC8vIGFuZCBjaGVja3MgYHR5cGVgIG1lbWJlcnNoaXAgaW4gT0JTVEFDTEVfVFlQRVMgc2V0LgogICAgcmV0dXJuIHNlcmlhbGl6ZWQgYXMgdW5rbm93biBhcyBDYW52YXNFbGVtZW50W107Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIGhhbmRsZXIg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpzZWxmLm9ubWVzc2FnZSA9IChlOiBNZXNzYWdlRXZlbnQ8SW5jb21pbmdNZXNzYWdlPikgPT4gewogICAgY29uc3QgbXNnID0gZS5kYXRhOwoKICAgIGlmIChtc2cudHlwZSA9PT0gJ3VwZGF0ZUVsZW1lbnRzJykgewogICAgICAgIGNhY2hlZEVsZW1lbnRzID0gZGVzZXJpYWxpemVFbGVtZW50cyhtc2cuZWxlbWVudHMpOwogICAgICAgIHJldHVybjsKICAgIH0KCiAgICBpZiAobXNnLnR5cGUgPT09ICdjb21wdXRlUm91dGUnKSB7CiAgICAgICAgY29uc3QgeyByZXF1ZXN0SWQsIHBhcmFtcyB9ID0gbXNnOwogICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHJhdyA9IGNvbXB1dGVFbGJvd1BvaW50cygKICAgICAgICAgICAgICAgIHBhcmFtcy5zdGFydFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLmVuZFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLnN0YXJ0QmluZGluZywKICAgICAgICAgICAgICAgIHBhcmFtcy5lbmRCaW5kaW5nLAogICAgICAgICAgICAgICAgY2FjaGVkRWxlbWVudHMsCiAgICAgICAgICAgICAgICBwYXJhbXMubWluU3R1Ykxlbmd0aCwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc2ltcGxpZmllZCA9IHNpbXBsaWZ5RWxib3dQYXRoKHJhdyk7CiAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UoeyB0eXBlOiAncm91dGVSZXN1bHQnLCByZXF1ZXN0SWQsIHBvaW50czogc2ltcGxpZmllZCB9KTsKICAgICAgICB9IGNhdGNoIHsKICAgICAgICAgICAgLy8gT24gZXJyb3IsIHJldHVybiBhIHN0cmFpZ2h0IGxpbmUgZmFsbGJhY2sKICAgICAgICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICB0eXBlOiAncm91dGVSZXN1bHQnLAogICAgICAgICAgICAgICAgcmVxdWVzdElkLAogICAgICAgICAgICAgICAgcG9pbnRzOiBbMCwgMCwgcGFyYW1zLmVuZFdvcmxkLnggLSBwYXJhbXMuc3RhcnRXb3JsZC54LCBwYXJhbXMuZW5kV29ybGQueSAtIHBhcmFtcy5zdGFydFdvcmxkLnldLAogICAgICAgICAgICB9KTsKICAgICAgICB9CiAgICB9Cn07Cg==",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this.workerConfig),this.worker?(this.worker.onmessage=this.handleMessage,this.worker.onerror=()=>{this.workerSupported=!1,this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker failed"));this.pending.clear()},this.worker):(this.workerSupported=!1,null)}catch{return this.workerSupported=!1,null}}updateElements(e){this.cachedElements=e;const n=this._getWorker();n&&e.length>=Lr&&n.postMessage({type:"updateElements",elements:ra(e)})}async computeRoute(e){const n=this._getWorker();if(!n||this.cachedElements.length<Lr)return this.computeSync(e);const o=++this.requestIdCounter;return new Promise((s,r)=>{const i=setTimeout(()=>{this.pending.has(o)&&(this.pending.delete(o),s(this.computeSync(e)))},100);this.pending.set(o,{resolve:s,reject:r,timerId:i}),n.postMessage({type:"computeRoute",requestId:o,params:e})})}computeSync(e){const n=rn(e.startWorld,e.endWorld,e.startBinding,e.endBinding,this.cachedElements,e.minStubLength);return ln(n)}dispose(){this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker disposed"));this.pending.clear()}get isWorkerActive(){return this.workerSupported}}let ne=null,Po;function Ho(t){return ne&&t&&JSON.stringify(t)!==JSON.stringify(Po)&&(ne.dispose(),ne=null),ne||(Po=t,ne=new ia(t)),ne}function Yr(){ne&&(ne.dispose(),ne=null,Po=void 0)}const Oo=I.createContext(void 0);function Vr(){return I.useContext(Oo)}function Fr(t,e,n,o){const[s,r]=I.useState(null),i=I.useRef(n),l=Vr(),a=l==null?void 0:l.elbowWorkerConfig;return i.current=n,I.useEffect(()=>{Ho(a).updateElements(n)},[o,a]),I.useEffect(()=>()=>{},[]),I.useEffect(()=>{if(!t){r(null);return}const c=Ho(a);let d=!1;const h={startWorld:e.startWorld,endWorld:e.endWorld,startBinding:e.startBinding,endBinding:e.endBinding,minStubLength:e.minStubLength};if(c.isWorkerActive)c.computeRoute(h).then(u=>{d||r(u)});else{const u=rn(e.startWorld,e.endWorld,e.startBinding,e.endBinding,i.current,e.minStubLength),f=ln(u);r(f)}return()=>{d=!0}},[t,e.startWorld.x,e.startWorld.y,e.endWorld.x,e.endWorld.y,e.startBinding,e.endBinding,e.minStubLength,o]),s}const la=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:b,endBinding:W,lineType:v,isLocked:G}=t,$=!G&&!o,T=I.useRef(null),O=y.roughness,ot=v==="curved",Y=v==="elbow",{fingerprint:J,elementsRef:P}=Dr(c),Q=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),_=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),x=Fr(Y,{startWorld:Q,endWorld:_,startBinding:b,endBinding:W},c??[],J),C=I.useMemo(()=>{if(!Y)return f;const R=rn(Q,_,b,W,P.current);return ln(R)},[Y,h,u,f,b,W,J]),w=Y?x??C:f,S=I.useMemo(()=>{if(!Y)return f;const R=[...w],z=f[0],et=f[1];if(z!==0||et!==0)for(let It=0;It<R.length;It+=2)R[It]+=z,R[It+1]+=et;return R},[Y,w,f]),Z=I.useMemo(()=>{if(!ot)return null;const R={x:f[0],y:f[1]},z={x:f[f.length-2],y:f[f.length-1]},et=Jt(R,z,t.curvature??Kt);return{start:R,end:z,cp:et}},[ot,f,t.curvature]),X=I.useCallback(()=>s(d),[s,d]),U=I.useCallback(()=>l==null?void 0:l(d),[l,d]),D=I.useCallback(R=>{let z=R.target.x(),et=R.target.y();a&&(z=At(z,a),et=At(et,a),R.target.x(z),R.target.y(et)),i==null||i(d,{x:z,y:et})},[d,a,i]),L=I.useCallback(R=>{let z=R.target.x(),et=R.target.y();a&&(z=At(z,a),et=At(et,a)),r(d,{x:z,y:et})},[d,a,r]),at=I.useCallback(R=>{const z=R.target,et=z.scaleX(),It=z.scaleY();z.setAttrs({scaleX:1,scaleY:1});const Ct=f.map((st,pt)=>pt%2===0?st*et:st*It),rt=Xn(Ct);r(d,{x:z.x(),y:z.y(),points:Ct,rotation:z.rotation(),width:rt.width,height:rt.height})},[d,f,r]),tt=Oe(O),E=e?Tt.color:void 0,V=e?Tt.blur:0,dt=e?Tt.opacity:0;return g.jsx(ht.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:X,onTap:X,onDblClick:U,onDblTap:U,onDragMove:D,onDragEnd:L,onTransformEnd:at,children:Y?g.jsxs(g.Fragment,{children:[g.jsx(ht.Line,{points:S,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(ht.Line,{points:S,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]}):ot?g.jsx(ht.Shape,{sceneFunc:(R,z)=>{if(Z){if(R.beginPath(),O>0){const et=ye(d);Gr(R,Z.start,Z.cp,Z.end,O,et,tt,y.strokeWidth)}else R.moveTo(Z.start.x,Z.start.y),R.quadraticCurveTo(Z.cp.x,Z.cp.y,Z.end.x,Z.end.y);R.fillStrokeShape(z)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):O>0?g.jsx(ht.Shape,{sceneFunc:(R,z)=>{const et=ye(d);R.beginPath(),Fo(R,f,O,et,tt,y.strokeWidth),R.fillStrokeShape(z)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsxs(g.Fragment,{children:[g.jsx(ht.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(ht.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]})})},ca=I.memo(la);function aa(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function da(t){return{x:-t.y,y:t.x}}function No(t){return Math.max(10,t*4)}function oe(t,e,n,o,s,r,i){const l=aa(n,o),a=da(l),c=s*.45,d=t._context;switch(d.save(),d.strokeStyle=r,d.fillStyle=r,d.lineWidth=i,d.lineJoin="round",d.lineCap="round",e){case"arrow":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(h.x,h.y),d.lineTo(n.x,n.y),d.lineTo(u.x,u.y),d.stroke();break}case"triangle":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"triangle_outline":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"circle":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"circle_outline":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.fillStyle="#ffffff",d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"diamond":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"diamond_outline":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"bar":{const h=c*1.2;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one":{const h=c*1,u=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.stroke();break}case"crowfoot_many":{const h=c*1,u=s*.6;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(f.x,f.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one_or_many":{const h=c*1,u=s*.6,f=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const p={x:n.x-l.x*f,y:n.y-l.y*f};d.beginPath(),d.moveTo(p.x+a.x*h,p.y+a.y*h),d.lineTo(p.x-a.x*h,p.y-a.y*h),d.stroke();const y={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(y.x,y.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}}d.restore()}function Fn(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function ua(t){let e=t.startArrowhead??null,n=t.endArrowhead??null;return e===null&&t.startArrow&&(e="arrow"),n===null&&t.endArrow&&(n="arrow"),{start:e,end:n}}const ha=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:b,endBinding:W,lineType:v,isLocked:G}=t,$=!G&&!o,T=I.useRef(null),O=y.roughness,{start:ot,end:Y}=ua(t),J=ot!=null||Y!=null,P=v==="curved",Q=v==="elbow",_=No(y.strokeWidth),x=Oe(O),{fingerprint:C,elementsRef:w}=Dr(c),S=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),Z=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),X=J?Math.ceil(_*1.5):void 0,U=Fr(Q,{startWorld:S,endWorld:Z,startBinding:b,endBinding:W,minStubLength:X},c??[],C),D=I.useMemo(()=>{if(!Q)return f;const rt=rn(S,Z,b,W,w.current,X);return ln(rt)},[Q,h,u,f,b,W,C]),L=Q?U??D:f,at=I.useMemo(()=>{if(!Q)return f;const rt=[...L],st=f[0],pt=f[1];if(st!==0||pt!==0)for(let A=0;A<rt.length;A+=2)rt[A]+=st,rt[A+1]+=pt;return rt},[Q,L,f]),tt=I.useMemo(()=>{if(!P)return null;const rt={x:f[0],y:f[1]},st={x:f[f.length-2],y:f[f.length-1]},pt=Jt(rt,st,t.curvature??Kt);return{start:rt,end:st,cp:pt}},[P,f,t.curvature]),E=I.useCallback(()=>s(d),[s,d]),V=I.useCallback(()=>l==null?void 0:l(d),[l,d]),dt=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a),rt.target.x(st),rt.target.y(pt)),i==null||i(d,{x:st,y:pt})},[d,a,i]),R=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a)),r(d,{x:st,y:pt})},[d,a,r]),z=I.useCallback(rt=>{const st=rt.target,pt=st.scaleX(),A=st.scaleY();st.setAttrs({scaleX:1,scaleY:1});const lt=f.map((j,Gt)=>Gt%2===0?j*pt:j*A),bt=Xn(lt);r(d,{x:st.x(),y:st.y(),points:lt,rotation:st.rotation(),width:bt.width,height:bt.height})},[d,f,r]),et=e?Tt.color:void 0,It=e?Tt.blur:0,Ct=e?Tt.opacity:0;return g.jsx(ht.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:E,onTap:E,onDblClick:V,onDblTap:V,onDragMove:dt,onDragEnd:R,onTransformEnd:z,children:Q?g.jsxs(g.Fragment,{children:[g.jsx(ht.Line,{points:at,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(ht.Line,{points:at,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:et,shadowBlur:It,shadowOpacity:Ct,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(ht.Shape,{sceneFunc:(rt,st)=>{const pt=Fn(at);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],_,y.strokeColor,y.strokeWidth),Y){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,Y,A,lt,_,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):P?g.jsxs(g.Fragment,{children:[g.jsx(ht.Shape,{sceneFunc:(rt,st)=>{if(tt){if(rt.beginPath(),O>0){const pt=ye(d);Gr(rt,tt.start,tt.cp,tt.end,O,pt,x,y.strokeWidth)}else rt.moveTo(tt.start.x,tt.start.y),rt.quadraticCurveTo(tt.cp.x,tt.cp.y,tt.end.x,tt.end.y);rt.fillStrokeShape(st)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:It,shadowOpacity:Ct,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&tt&&g.jsx(ht.Shape,{sceneFunc:rt=>{if(ot){const st=Bo(tt.start,tt.cp,tt.end,!1);oe(rt,ot,tt.start,st,_,y.strokeColor,y.strokeWidth)}if(Y){const st=Bo(tt.start,tt.cp,tt.end,!0);oe(rt,Y,tt.end,st,_,y.strokeColor,y.strokeWidth)}},listening:!1,opacity:y.opacity})]}):O>0?g.jsxs(g.Fragment,{children:[g.jsx(ht.Shape,{sceneFunc:(rt,st)=>{const pt=ye(d);rt.beginPath(),Fo(rt,f,O,pt,x,y.strokeWidth),rt.fillStrokeShape(st)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:It,shadowOpacity:Ct,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(ht.Shape,{sceneFunc:(rt,st)=>{const pt=Fn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],_,y.strokeColor,y.strokeWidth),Y){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,Y,A,lt,_,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):g.jsxs(g.Fragment,{children:[g.jsx(ht.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(ht.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:Mt(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:et,shadowBlur:It,shadowOpacity:Ct,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(ht.Shape,{sceneFunc:(rt,st)=>{const pt=Fn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],_,y.strokeColor,y.strokeWidth),Y){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,Y,A,lt,_,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]})})},ga=I.memo(ha),fa=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,points:u,rotation:f,style:p,isLocked:y}=t,b=!y&&!n,W=I.useCallback(()=>o(c),[o,c]),v=I.useCallback(()=>i==null?void 0:i(c),[i,c]),G=I.useCallback(X=>{let U=X.target.x(),D=X.target.y();if(l&&(U=At(U,l),D=At(D,l),X.target.x(U),X.target.y(D)),!l&&a){const{minX:L,minY:at,width:tt,height:E}=Lo(u),V=a(c,{x:U+L,y:D+at,width:tt,height:E});V&&(U=V.x-L,D=V.y-at,X.target.x(U),X.target.y(D))}r==null||r(c,{x:U,y:D})},[c,l,u,r,a]),$=I.useCallback(X=>{let U=X.target.x(),D=X.target.y();l&&(U=At(U,l),D=At(D,l)),s(c,{x:U,y:D})},[c,l,s]),T=I.useCallback(X=>{const U=X.target,D=U.scaleX(),L=U.scaleY();U.setAttrs({scaleX:1,scaleY:1});const at=u.map((tt,E)=>E%2===0?tt*D:tt*L);s(c,{x:U.x(),y:U.y(),points:at,rotation:U.rotation()})},[c,u,s]),O=e?Tt.color:void 0,ot=e?Tt.blur:0,Y=e?Tt.opacity:0,J=p.freehandStyle||"standard",P=t.isComplete===!1,Q=P?0:d,_=P?0:h,x=J==="pen"||J==="brush",C=J==="pencil",w=I.useMemo(()=>{if(!x)return"";const X=!P;if(J==="brush"){const U=p.strokeWidth*4;return Wr(u,t.pressures,{size:U,thinning:.7,smoothing:.5,streamline:.5,simulatePressure:!0,last:X,start:{cap:!0},end:{cap:!0}})}return Wr(u,t.pressures,{size:p.strokeWidth*1.8,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:!0,last:X,start:{cap:!0,taper:0},end:{cap:!0,taper:0}})},[u,t.pressures,x,J,p.strokeWidth,P]),S=I.useMemo(()=>{if(!C||u.length===0)return[];const X=[u[0],u[1]];let U=u[0],D=u[1];for(let L=2;L<u.length;L+=2){const at=u[L],tt=u[L+1],E=at-U,V=tt-D;(E*E+V*V>2.25||L===u.length-2)&&(X.push(at,tt),U=at,D=tt)}return X},[C,u]),Z=I.useCallback((X,U)=>{const D=p.roughness,L=ye(c);X.beginPath(),Fo(X,S,D,L,Oe(D),p.strokeWidth),X.fillStrokeShape(U)},[c,S,p.roughness,p.strokeWidth]);return x&&w?g.jsx(ht.Path,{id:c,x:Q,y:_,data:w,rotation:f,transformsEnabled:f?"all":"position",fill:p.strokeColor,opacity:p.opacity,draggable:b,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:Y,hitStrokeWidth:20,onDragMove:G,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):C?g.jsx(ht.Shape,{id:c,x:Q,y:_,width:P?void 0:t.width,height:P?void 0:t.height,rotation:f,transformsEnabled:f?"all":"position",sceneFunc:Z,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",draggable:b,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:Y,hitStrokeWidth:Math.max(20,p.strokeWidth+16),onDragMove:G,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsx(ht.Line,{id:c,x:Q,y:_,points:u,rotation:f,transformsEnabled:f?"all":"position",stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",tension:.5,globalCompositeOperation:"source-over",draggable:b,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:Y,hitStrokeWidth:20,onDragMove:G,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},pa=I.memo(fa),Pn=1.18,ya=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,autoEdit:i,onEditStart:l,onEditEnd:a,allElements:c,gridSnap:d})=>{const{id:h,x:u,y:f,width:p,height:y,rotation:b,style:W,text:v,containerId:G,textAlign:$,verticalAlign:T,isLocked:O}=t,ot=I.useRef(null),Y=I.useRef(!1),J=I.useRef(!1),P=!!G,Q=!P&&!O&&!n,_=I.useMemo(()=>!G||!c?null:c.find(D=>D.id===G)??null,[G,c]),x=I.useMemo(()=>{var dt,R;if(!_)return{x:u,y:f};if(_.type==="arrow"||_.type==="line"){const z=_,et=z.points,It={x:et[0],y:et[1]},Ct={x:et[et.length-2],y:et[et.length-1]};let rt,st;if(z.lineType==="curved"){const lt=Jt(It,Ct,z.curvature??Kt),bt=Pe(It,lt,Ct,.5);rt=z.x+bt.x,st=z.y+bt.y}else rt=z.x+(It.x+Ct.x)/2,st=z.y+(It.y+Ct.y)/2;const pt=Math.max(80,p||80),A=((dt=ot.current)==null?void 0:dt.height())??y;return{x:rt-pt/2,y:st-A/2,width:pt}}const D=4,L=_.width-D*2,at=Math.max(20,L),tt=_.x+D,E=((R=ot.current)==null?void 0:R.height())??y;let V;return T==="top"?V=_.y+D:T==="bottom"?V=_.y+_.height-E-D:V=_.y+(_.height-E)/2,{x:tt,y:V,width:at}},[_,u,f,y,T]),C=I.useCallback(()=>{const D=ot.current;if(!D||Y.current)return;const L=D.height(),at={};let tt=!1;if(Math.abs(L-y)>1&&(at.height=L,tt=!0),!P){const E=Math.ceil(D.getTextWidth());Math.abs(E-p)>1&&(at.width=E,tt=!0)}tt&&s(h,at)},[h,y,p,P,s]);I.useEffect(()=>{requestAnimationFrame(C)},[v,W.fontSize,W.fontFamily,C]);const w=I.useCallback(()=>{const D=ot.current;if(!D||Y.current)return;const L=D.getStage();if(!L)return;Y.current=!0,l==null||l(h);const at=L.container(),E=D.getAbsoluteTransform().copy().point({x:0,y:0}),V=L.scaleX(),dt=W.fontSize*V,R=dt*(Pn-1.07)/2;let z=0,et=0,It=0,Ct=0;const st=4*V;if(P&&_){const Yt=L.getAbsoluteTransform().copy().point({x:_.x,y:_.y});z=Yt.x,et=Yt.y,It=_.width*V,Ct=_.height*V}const pt=D.width(),A=P?It-st*2:Math.max(pt,100)*V,lt=P?z+st:E.x,bt=v,j=document.createElement("textarea");if(at.appendChild(j),j.value=v,j.style.position="absolute",P&&_){const vt=T||"middle",Yt=D.height()*V;let Ut;vt==="top"?Ut=et+st-R:vt==="bottom"?Ut=et+Ct-Yt-st-R:Ut=et+(Ct-Yt)/2-R,j.style.top=`${Ut}px`}else j.style.top=`${E.y-R}px`;j.style.left=`${lt}px`,j.style.width=`${A}px`,j.style.fontSize=`${dt}px`,j.style.fontFamily=W.fontFamily,j.style.color=W.strokeColor,j.style.lineHeight=`${Pn}`,j.style.border="none",j.style.borderRadius="0",j.style.padding="0",j.style.margin="0",j.style.outline="none",j.style.resize="none",j.style.overflow="hidden",j.style.background="transparent",j.style.zIndex="1000",j.rows=1,j.style.minHeight=`${Math.max(20,dt*Pn)}px`,j.style.boxSizing="border-box",j.style.transformOrigin="left top",j.style.letterSpacing="normal",j.style.caretColor=W.strokeColor;const Gt=P?$||"center":"left";j.style.textAlign=Gt,P?(j.style.whiteSpace="pre-wrap",j.style.wordBreak="break-word"):(j.style.whiteSpace="pre",j.style.wordBreak="normal");const Xt=P?(_==null?void 0:_.rotation)??b:b;Xt&&(j.style.transform=`rotateZ(${Xt}deg)`);const Ot=()=>{j.style.height="auto";const vt=j.scrollHeight;if(j.style.height=`${vt}px`,P&&_){const Yt=T||"middle";let Ut;Yt==="top"?Ut=et+st-R:Yt==="bottom"?Ut=et+Ct-vt-st-R:Ut=et+(Ct-vt)/2-R,j.style.top=`${Ut}px`}P||(j.style.width="auto",j.style.width=`${Math.max(j.scrollWidth,100*V)}px`)};j.addEventListener("input",Ot),requestAnimationFrame(Ot),D.hide(),L.batchDraw(),j.focus(),j.select();let Xe=!1;const jt=()=>{if(!Y.current)return;Y.current=!1;const vt=Xe?bt:j.value,Yt=vt.trim()==="";j.removeEventListener("input",Ot),j.removeEventListener("blur",Sn),j.removeEventListener("keydown",Nt),j.parentNode&&j.parentNode.removeChild(j),D.show(),L.batchDraw(),Xe||s(h,{text:vt}),a==null||a(h,Yt)},Sn=()=>{jt()},Nt=vt=>{vt.stopPropagation(),vt.key==="Escape"&&(Xe=!0,j.blur()),vt.key==="Enter"&&!vt.shiftKey&&(vt.preventDefault(),j.blur()),vt.key==="Tab"&&(vt.preventDefault(),j.blur())};j.addEventListener("blur",Sn),j.addEventListener("keydown",Nt)},[h,v,b,W,P,_,$,T,s,l,a]);I.useEffect(()=>{i||(J.current=!1)},[i]),I.useEffect(()=>{i&&!J.current&&ot.current&&(J.current=!0,w())},[i,w]);const S=P?x.x:u,Z=P?x.y:f,X=P&&x.width?x.width:void 0,U=P?$||"center":void 0;return g.jsx(ht.Text,{ref:ot,id:h,x:S,y:Z,text:v||(P?"":"Double-click to edit"),fontSize:W.fontSize,fontFamily:W.fontFamily,fill:W.strokeColor,lineHeight:Pn,width:X,align:U,wrap:P?"word":"none",rotation:P?(_==null?void 0:_.rotation)??b:b,transformsEnabled:(P?(_==null?void 0:_.rotation)??b:b)?"all":"position",visible:!(i&&!Y.current&&!v),opacity:v?W.opacity:P?0:.4,draggable:Q,listening:!P,onClick:P?void 0:()=>o(h),onTap:P?void 0:()=>o(h),onDblClick:w,onDblTap:w,shadowColor:!P&&e?"#4f8df7":void 0,shadowBlur:!P&&e?6:0,shadowOpacity:!P&&e?.5:0,hitStrokeWidth:P?0:10,perfectDrawEnabled:!1,onDragMove:P?void 0:D=>{let L=D.target.x(),at=D.target.y();d&&(L=At(L,d),at=At(at,d),D.target.x(L),D.target.y(at)),r==null||r(h,{x:L,y:at})},onDragEnd:P?void 0:D=>{let L=D.target.x(),at=D.target.y();d&&(L=At(L,d),at=At(at,d)),s(h,{x:L,y:at})},onTransformEnd:P?void 0:D=>{const L=D.target,at=L.scaleX(),tt=L.scaleY(),E=Math.max(Math.abs(at),Math.abs(tt)),V=Math.max(8,Math.round(W.fontSize*E));L.scaleX(1),L.scaleY(1),s(h,{x:L.x(),y:L.y(),rotation:L.rotation(),style:{...W,fontSize:V}})}})},Ia=I.memo(ya),Ca=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,src:y,style:b,crop:W,cornerRadius:v,scaleMode:G,isLocked:$}=t,[T,O]=I.useState(null),[ot,Y]=I.useState(!1),[J,P]=I.useState({w:u,h:f});I.useEffect(()=>{P({w:u,h:f})},[u,f]);const Q=J.w,_=J.h;I.useEffect(()=>{if(!y){O(null),Y(!0);return}const E=new window.Image;return E.crossOrigin="anonymous",E.onload=()=>{O(E),Y(!1)},E.onerror=()=>{O(null),Y(!0)},E.src=y,()=>{E.onload=null,E.onerror=null}},[y]);const x=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();if(l&&(V=At(V,l),dt=At(dt,l),E.target.x(V),E.target.y(dt)),!l&&a){const R=a(c,{x:V,y:dt,width:u,height:f});R&&(V=R.x,dt=R.y,E.target.x(V),E.target.y(dt))}r==null||r(c,{x:V,y:dt})},[c,u,f,l,a,r]),C=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();l&&(V=At(V,l),dt=At(dt,l)),s(c,{x:V,y:dt})},[c,l,s]),w=I.useCallback(E=>{const V=E.target,dt=V.scaleX(),R=V.scaleY(),z=Math.max(10,V.width()*dt),et=Math.max(10,V.height()*R);V.setAttrs({scaleX:1,scaleY:1,width:z,height:et}),P({w:z,h:et}),r==null||r(c,{x:V.x(),y:V.y(),width:z,height:et})},[c,r]),S=I.useCallback(E=>{const V=E.target;s(c,{x:V.x(),y:V.y(),width:Math.max(10,V.width()),height:Math.max(10,V.height()),rotation:V.rotation()})},[c,s]);let Z=0,X=0,U=Q,D=_,L;if(W&&(L={x:W.x,y:W.y,width:W.width,height:W.height}),T){const E=W?W.width:T.naturalWidth,V=W?W.height:T.naturalHeight;if(G==="fit"){const dt=E/V,R=Q/_;dt>R?(U=Q,D=Q/dt,X=(_-D)/2):(D=_,U=_*dt,Z=(Q-U)/2)}else if(G==="fill"&&!W){const dt=T.naturalWidth,R=T.naturalHeight,z=dt/R,et=Q/_;if(z>et){const It=R*et;L={x:(dt-It)/2,y:0,width:It,height:R}}else{const It=dt/et;L={x:0,y:(R-It)/2,width:dt,height:It}}U=Q,D=_}}const at=v>0?E=>{const V=Math.min(v,Q/2,_/2);E.beginPath(),E.moveTo(V,0),E.lineTo(Q-V,0),E.arcTo(Q,0,Q,V,V),E.lineTo(Q,_-V),E.arcTo(Q,_,Q-V,_,V),E.lineTo(V,_),E.arcTo(0,_,0,_-V,V),E.lineTo(0,V),E.arcTo(0,0,V,0,V),E.closePath()}:void 0,tt={id:c,x:d,y:h,width:Q,height:_,rotation:p,transformsEnabled:p?"all":"position",draggable:!$&&!n,clipFunc:at,onClick:()=>o(c),onTap:()=>o(c),onDblClick:()=>i==null?void 0:i(c),onDblTap:()=>i==null?void 0:i(c),onDragMove:x,onDragEnd:C,onTransform:w,onTransformEnd:S};return!T||ot?g.jsx(ht.Group,{...tt,children:g.jsx(ht.Rect,{width:Q,height:_,fill:"#f0f0f0",stroke:b.strokeColor,strokeWidth:b.strokeWidth,cornerRadius:v,opacity:b.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}):g.jsxs(ht.Group,{...tt,shadowColor:e?"#4f8df7":void 0,shadowBlur:e?6:0,shadowOpacity:e?.5:0,children:[G==="fit"&&g.jsx(ht.Rect,{width:Q,height:_,fill:b.fillColor==="transparent"?void 0:b.fillColor,cornerRadius:v}),g.jsx(ht.Image,{image:T,x:Z,y:X,width:U,height:D,crop:L,opacity:b.opacity,listening:!1,perfectDrawEnabled:!1}),b.strokeWidth>0&&b.strokeColor!=="transparent"&&g.jsx(ht.Rect,{width:Q,height:_,stroke:b.strokeColor,strokeWidth:b.strokeWidth,cornerRadius:v,listening:!1})]})},ma=I.memo(Ca),ba=.5,Aa=1,wa=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,autoEditText:a,onTextEditStart:c,onTextEditEnd:d,allElements:h,gridSnap:u,onDragSnap:f,viewportScale:p})=>{var b,W,v;const y=I.useCallback(()=>s(t.id),[s,t.id]);if(!t.isVisible)return null;if(p!==void 0&&!e&&!n){const G=Math.max(t.width,t.height)*p;if(G<ba)return null;if(G<Aa)return g.jsx(ht.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:((b=t.style)==null?void 0:b.fillColor)||"#e0e0e0",stroke:((W=t.style)==null?void 0:W.strokeColor)||"#999",strokeWidth:1/p,opacity:((v=t.style)==null?void 0:v.opacity)??1,onClick:y,onTap:y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,transformsEnabled:"position"})}switch(t.type){case"rectangle":return g.jsx(jc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"ellipse":return g.jsx(qc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"diamond":return g.jsx(ea,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"line":return g.jsx(ca,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"arrow":return g.jsx(ga,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"freedraw":return g.jsx(pa,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"text":return g.jsx(Ia,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,autoEdit:a,onEditStart:c,onEditEnd:d,allElements:h,gridSnap:u});case"image":return g.jsx(ma,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});default:return null}};function xa(t,e){return!(t.element!==e.element||t.isSelected!==e.isSelected||t.isEditing!==e.isEditing||t.isGrouped!==e.isGrouped||t.autoEditText!==e.autoEditText||t.viewportScale!==e.viewportScale||t.gridSnap!==e.gridSnap)}const Hn=I.memo(wa,xa);function ka(t,e){if(t.length===0)return"";const n=new Set(t),o=new Map;for(const r of e)if(n.has(r.id)&&(o.set(r.id,r),o.size===n.size))break;const s=[];for(const r of t){const i=o.get(r);i&&s.push(`${r}:${i.isLocked?1:0}:${i.type}`)}return s.join(",")}const Sa=({selectedIds:t,selectionColor:e="#4f8df7"})=>{const n=I.useRef(null),o=B(c=>ka(t,c.elements)),{hasLocked:s,allLocked:r,allText:i}=I.useMemo(()=>{if(!o||t.length===0)return{hasLocked:!1,allLocked:!1,allText:!1};const c=o.split(",");let d=0,h=0;for(const u of c){const f=u.split(":");f[1]==="1"&&d++,f[2]==="text"&&h++}return{hasLocked:d>0,allLocked:d===c.length,allText:h===c.length}},[o,t.length]),l=i?["top-left","top-right","bottom-left","bottom-right"]:["top-left","top-right","bottom-left","bottom-right","middle-left","middle-right","top-center","bottom-center"];if(I.useEffect(()=>{var u;const c=n.current;if(!c)return;const d=c.getStage();if(!d)return;const h=t.map(f=>d.findOne(`#${f}`)).filter(Boolean);c.nodes(h),(u=c.getLayer())==null||u.batchDraw()},[t]),t.length===0)return null;const a=s?"#ff9500":e;return g.jsx(ht.Transformer,{ref:n,flipEnabled:!1,keepRatio:i,resizeEnabled:!r,rotateEnabled:!r,boundBoxFunc:(c,d)=>r||Math.abs(d.width)<5||Math.abs(d.height)<5?c:d,anchorFill:r?"#ff9500":"#ffffff",anchorStroke:a,anchorSize:r?0:8,anchorCornerRadius:2,borderStroke:a,borderStrokeWidth:1,borderDash:r?[6,3]:[4,4],rotateAnchorOffset:25,enabledAnchors:r?[]:l})},va=I.memo(Sa),Ea=({width:t,height:e,viewport:n,gridColor:o="#e5e5e5"})=>{const{x:s,y:r,scale:i}=n,l=xe,a=I.useMemo(()=>{const c=Math.floor((-s/i-l)/l)*l,d=Math.ceil((-s/i+t/i+l)/l)*l,h=Math.floor((-r/i-l)/l)*l,u=Math.ceil((-r/i+e/i+l)/l)*l;return{startX:c,endX:d,startY:h,endY:u}},[s,r,i,t,e,l]);return g.jsx(ht.Shape,{sceneFunc:c=>{const{startX:d,endX:h,startY:u,endY:f}=a,p=1/i,y=c._context;y.beginPath(),y.strokeStyle=o,y.lineWidth=p;for(let b=d;b<=h;b+=l)y.moveTo(b,u),y.lineTo(b,f);for(let b=u;b<=f;b+=l)y.moveTo(d,b),y.lineTo(h,b);y.stroke()},listening:!1,perfectDrawEnabled:!1})},Wa=I.memo(Ea),Ta=({box:t,selectionColor:e="#4f8df7",viewportScale:n=1})=>t?g.jsx(ht.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:`${e}14`,stroke:e,strokeWidth:1/n,dash:[4/n,4/n],listening:!1}):null,Ba=I.memo(Ta),Ie=6,Za=({el:t,color:e,viewportScale:n})=>{const o=t.x+t.width/2,s=t.y+t.height/2,r=t.rotation||0;switch(t.type){case"ellipse":return g.jsx(ht.Ellipse,{x:o,y:s,radiusX:t.width/2+Ie,radiusY:t.height/2+Ie,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1});case"diamond":{const i=t.width+Ie*2,l=t.height+Ie*2,a=[i/2,0,i,l/2,i/2,l,0,l/2];return g.jsx(ht.Line,{x:o-i/2,y:s-l/2,points:a,closed:!0,rotation:r,offsetX:0,offsetY:0,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}default:return g.jsx(ht.Rect,{x:o,y:s,offsetX:t.width/2+Ie,offsetY:t.height/2+Ie,width:t.width+Ie*2,height:t.height+Ie*2,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],cornerRadius:6,fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}},Ma=({elements:t,snapTarget:e,visible:n,color:o="#4f8df7",viewportScale:s=1})=>{if(!n||!e)return null;const r=t.find(i=>i.id===e.elementId&&ko(i));return r?g.jsxs(g.Fragment,{children:[g.jsx(Za,{el:r,color:o,viewportScale:s}),g.jsx(ht.Circle,{x:e.position.x,y:e.position.y,radius:6/s,fill:o,stroke:"white",strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1}),!e.isPrecise&&(()=>{const i=r.rotation||0,l={x:r.x+r.width/2,y:r.y+r.height/2},a=i!==0?ar(l,{x:r.x,y:r.y},i*Math.PI/180):l;return g.jsx(ht.Circle,{x:a.x,y:a.y,radius:4/s,fill:"white",stroke:o,strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1})})()]}):null},_a=I.memo(Ma),Pr=4,Xa=3,Ga="#ffffff",Da="#4f8df7",La="#2563eb",Ya="#4f8df7",Va=5,Fa="#ff6b35",Pa="#ffffff";function Ha(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Hr(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const Oa=({element:t,allElements:e,onPointsChange:n,onPointDragMove:o,onSnapTargetChange:s,color:r="#4f8df7"})=>{const{selectedPointIndices:i,hoveredPointIndex:l,hoveredMidpointIndex:a,setSelectedPoints:c,togglePointSelection:d,setHoveredPoint:h,setHoveredMidpoint:u,setIsDraggingPoint:f}=hn(),{id:p,x:y,y:b,points:W}=t,v=Ha(W),G=I.useRef(null),$=I.useRef(null),T=I.useRef(void 0),O="lineType"in t&&t.lineType==="curved",ot="lineType"in t&&t.lineType==="elbow",Y=O||ot,J=I.useCallback(w=>w===0||w===v.length-1,[v.length]),P=I.useCallback(w=>{f(!0),G.current={points:[...W],x:y,y:b},T.current=void 0,i.includes(w)||c([w])},[W,y,b,i,c,f]),Q=I.useCallback((w,S)=>{const Z=S.target,X=Z.x(),U=Z.y(),D=[...W];D[w*2]=X-y,D[w*2+1]=U-b;const L={};if(J(w)){const at=Z.getStage(),tt=at==null?void 0:at.getRelativePointerPosition(),E=(tt==null?void 0:tt.x)??X,V=(tt==null?void 0:tt.y)??U;$.current={x:E,y:V};const dt={x:E,y:V},R=new Set([p]),z=w===0?t.endBinding:t.startBinding;z&&R.add(z.elementId);const et=ce(t.style.strokeWidth??2),It=ke(dt,e,24,R,void 0,void 0,et,T.current);if(s==null||s(It),T.current=It==null?void 0:It.isPrecise,It){const Ct=It.position;D[w*2]=Ct.x-y,D[w*2+1]=Ct.y-b,Z.x(Ct.x),Z.y(Ct.y);const rt={elementId:It.elementId,fixedPoint:It.fixedPoint,gap:et,isPrecise:It.isPrecise};w===0?L.startBinding=rt:L.endBinding=rt}else w===0?L.startBinding=null:L.endBinding=null}o==null||o(p,{points:D,x:y,y:b,...L})},[W,y,b,p,t,e,J,o,s]),_=I.useCallback((w,S)=>{f(!1);const Z=S.target;let X,U;J(w)&&$.current?(X=$.current.x,U=$.current.y):(X=Z.x(),U=Z.y()),$.current=null;const D=[...W];D[w*2]=X-y,D[w*2+1]=U-b;const L={points:D};if(J(w)){const R={x:X,y:U},z=new Set([p]),et=w===0?t.endBinding:t.startBinding;et&&z.add(et.elementId);const It=ce(t.style.strokeWidth??2),Ct=ke(R,e,24,z,void 0,void 0,It,T.current);if(s==null||s(null),T.current=void 0,Ct){const rt=ce(t.style.strokeWidth??2),st={elementId:Ct.elementId,fixedPoint:Ct.fixedPoint,gap:rt,isPrecise:Ct.isPrecise};w===0?L.startBinding=st:L.endBinding=st,D[w*2]=Ct.position.x-y,D[w*2+1]=Ct.position.y-b,L.points=D}else w===0?L.startBinding=null:L.endBinding=null}const at=L.points??D,tt=at[0],E=at[1];if(tt!==0||E!==0){const R=[];for(let z=0;z<at.length;z+=2)R.push(at[z]-tt,at[z+1]-E);L.x=y+tt,L.y=b+E,L.points=R}const V=L.points??at,dt=Xn(V);L.width=dt.width,L.height=dt.height,n(p,L),G.current=null},[W,y,b,p,v,t,e,J,f,n,s]),x=I.useCallback((w,S)=>{S.cancelBubble=!0,S.evt.shiftKey?d(w):c([w])},[c,d]),C=I.useCallback((w,S)=>{S.cancelBubble=!0;const Z=v[w],X=v[w+1],U=Hr(Z,X),D=w+1,L=[];for(let tt=0;tt<v.length;tt++)L.push(v[tt].x,v[tt].y),tt===w&&L.push(U.x,U.y);const at=Xn(L);c([D]),u(null),n(p,{points:L,width:at.width,height:at.height})},[p,v,c,u,n]);return g.jsxs(ht.Group,{children:[!Y&&v.length>=2&&v.slice(0,-1).map((w,S)=>{const Z=v[S+1],X=Hr(w,Z),U=a===S;return g.jsx(ht.Circle,{x:y+X.x,y:b+X.y,radius:Xa,fill:U?La:Da,opacity:U?.9:.5,stroke:"white",strokeWidth:1.5,onMouseEnter:()=>u(S),onMouseLeave:()=>u(null),onClick:D=>C(S,D),onTap:D=>C(S,D),hitStrokeWidth:10,perfectDrawEnabled:!1},`mid-${S}`)}),v.map((w,S)=>{const Z=J(S);if(Y&&!Z)return null;const X=i.includes(S),U=l===S,D=Z?Pr+1:Pr;return g.jsx(ht.Circle,{x:y+w.x,y:b+w.y,radius:D,fill:X?Ya:Ga,stroke:U||X?"#2563eb":r,strokeWidth:X?2.5:2,draggable:!0,onMouseEnter:()=>h(S),onMouseLeave:()=>h(-1),onClick:L=>x(S,L),onTap:L=>x(S,L),onDragStart:()=>P(S),onDragMove:L=>Q(S,L),onDragEnd:L=>_(S,L),hitStrokeWidth:10,perfectDrawEnabled:!1},`pt-${S}`)}),O&&v.length>=2&&(()=>{const w=v[0],S=v[v.length-1],Z=t.curvature??Kt,X=Jt(w,S,Z),U=Pe(w,X,S,.5);return g.jsx(ht.Circle,{x:y+U.x,y:b+U.y,radius:Va,fill:Fa,stroke:Pa,strokeWidth:2,draggable:!0,onDragStart:()=>f(!0),onDragMove:D=>{const L=D.target,at={x:y+w.x,y:b+w.y},tt={x:y+S.x,y:b+S.y},E={x:L.x(),y:L.y()},V=ur(at,tt,E),dt=Jt(w,S,V),R=Pe(w,dt,S,.5);L.x(y+R.x),L.y(b+R.y),o==null||o(p,{curvature:V})},onDragEnd:D=>{f(!1);const L=D.target,at={x:y+w.x,y:b+w.y},tt={x:y+S.x,y:b+S.y},E={x:L.x(),y:L.y()},V=ur(at,tt,E),dt=Jt(w,S,V),R=Pe(w,dt,S,.5);L.x(y+R.x),L.y(b+R.y),n(p,{curvature:V})},hitStrokeWidth:12,perfectDrawEnabled:!1},"curve-handle")})()]})},Na=I.memo(Oa);/**
2
+ * @license lucide-react v0.468.0 - ISC
3
+ *
4
+ * This source code is licensed under the ISC license.
5
+ * See the LICENSE file in the root directory of this source tree.
6
+ */const Ua=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Or=(...t)=>t.filter((e,n,o)=>!!e&&e.trim()!==""&&o.indexOf(e)===n).join(" ").trim();/**
7
+ * @license lucide-react v0.468.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */var za={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
12
+ * @license lucide-react v0.468.0 - ISC
13
+ *
14
+ * This source code is licensed under the ISC license.
15
+ * See the LICENSE file in the root directory of this source tree.
16
+ */const Ka=I.forwardRef(({color:t="currentColor",size:e=24,strokeWidth:n=2,absoluteStrokeWidth:o,className:s="",children:r,iconNode:i,...l},a)=>I.createElement("svg",{ref:a,...za,width:e,height:e,stroke:t,strokeWidth:o?Number(n)*24/Number(e):n,className:Or("lucide",s),...l},[...i.map(([c,d])=>I.createElement(c,d)),...Array.isArray(r)?r:[r]]));/**
17
+ * @license lucide-react v0.468.0 - ISC
18
+ *
19
+ * This source code is licensed under the ISC license.
20
+ * See the LICENSE file in the root directory of this source tree.
21
+ */const mt=(t,e)=>{const n=I.forwardRef(({className:o,...s},r)=>I.createElement(Ka,{ref:r,iconNode:e,className:Or(`lucide-${Ua(t)}`,o),...s}));return n.displayName=`${t}`,n};/**
22
+ * @license lucide-react v0.468.0 - ISC
23
+ *
24
+ * This source code is licensed under the ISC license.
25
+ * See the LICENSE file in the root directory of this source tree.
26
+ */const Ja=mt("AlignCenterVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]]);/**
27
+ * @license lucide-react v0.468.0 - ISC
28
+ *
29
+ * This source code is licensed under the ISC license.
30
+ * See the LICENSE file in the root directory of this source tree.
31
+ */const $a=mt("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
32
+ * @license lucide-react v0.468.0 - ISC
33
+ *
34
+ * This source code is licensed under the ISC license.
35
+ * See the LICENSE file in the root directory of this source tree.
36
+ */const Ra=mt("AlignEndVertical",[["rect",{width:"16",height:"6",x:"2",y:"4",rx:"2",key:"10wcwx"}],["rect",{width:"9",height:"6",x:"9",y:"14",rx:"2",key:"4p5bwg"}],["path",{d:"M22 22V2",key:"12ipfv"}]]);/**
37
+ * @license lucide-react v0.468.0 - ISC
38
+ *
39
+ * This source code is licensed under the ISC license.
40
+ * See the LICENSE file in the root directory of this source tree.
41
+ */const ja=mt("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
42
+ * @license lucide-react v0.468.0 - ISC
43
+ *
44
+ * This source code is licensed under the ISC license.
45
+ * See the LICENSE file in the root directory of this source tree.
46
+ */const Qa=mt("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/**
47
+ * @license lucide-react v0.468.0 - ISC
48
+ *
49
+ * This source code is licensed under the ISC license.
50
+ * See the LICENSE file in the root directory of this source tree.
51
+ */const qa=mt("AlignStartVertical",[["rect",{width:"9",height:"6",x:"6",y:"14",rx:"2",key:"lpm2y7"}],["rect",{width:"16",height:"6",x:"6",y:"4",rx:"2",key:"rdj6ps"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/**
52
+ * @license lucide-react v0.468.0 - ISC
53
+ *
54
+ * This source code is licensed under the ISC license.
55
+ * See the LICENSE file in the root directory of this source tree.
56
+ */const td=mt("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/**
57
+ * @license lucide-react v0.468.0 - ISC
58
+ *
59
+ * This source code is licensed under the ISC license.
60
+ * See the LICENSE file in the root directory of this source tree.
61
+ */const Nr=mt("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/**
62
+ * @license lucide-react v0.468.0 - ISC
63
+ *
64
+ * This source code is licensed under the ISC license.
65
+ * See the LICENSE file in the root directory of this source tree.
66
+ */const ed=mt("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/**
67
+ * @license lucide-react v0.468.0 - ISC
68
+ *
69
+ * This source code is licensed under the ISC license.
70
+ * See the LICENSE file in the root directory of this source tree.
71
+ */const nd=mt("Brush",[["path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08",key:"1styjt"}],["path",{d:"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z",key:"z0l1mu"}]]);/**
72
+ * @license lucide-react v0.468.0 - ISC
73
+ *
74
+ * This source code is licensed under the ISC license.
75
+ * See the LICENSE file in the root directory of this source tree.
76
+ */const od=mt("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/**
77
+ * @license lucide-react v0.468.0 - ISC
78
+ *
79
+ * This source code is licensed under the ISC license.
80
+ * See the LICENSE file in the root directory of this source tree.
81
+ */const sd=mt("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/**
82
+ * @license lucide-react v0.468.0 - ISC
83
+ *
84
+ * This source code is licensed under the ISC license.
85
+ * See the LICENSE file in the root directory of this source tree.
86
+ */const rd=mt("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/**
87
+ * @license lucide-react v0.468.0 - ISC
88
+ *
89
+ * This source code is licensed under the ISC license.
90
+ * See the LICENSE file in the root directory of this source tree.
91
+ */const id=mt("ChevronsUp",[["path",{d:"m17 11-5-5-5 5",key:"e8nh98"}],["path",{d:"m17 18-5-5-5 5",key:"2avn1x"}]]);/**
92
+ * @license lucide-react v0.468.0 - ISC
93
+ *
94
+ * This source code is licensed under the ISC license.
95
+ * See the LICENSE file in the root directory of this source tree.
96
+ */const Ur=mt("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/**
97
+ * @license lucide-react v0.468.0 - ISC
98
+ *
99
+ * This source code is licensed under the ISC license.
100
+ * See the LICENSE file in the root directory of this source tree.
101
+ */const ld=mt("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/**
102
+ * @license lucide-react v0.468.0 - ISC
103
+ *
104
+ * This source code is licensed under the ISC license.
105
+ * See the LICENSE file in the root directory of this source tree.
106
+ */const zr=mt("Diamond",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z",key:"1f1r0c"}]]);/**
107
+ * @license lucide-react v0.468.0 - ISC
108
+ *
109
+ * This source code is licensed under the ISC license.
110
+ * See the LICENSE file in the root directory of this source tree.
111
+ */const cd=mt("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/**
112
+ * @license lucide-react v0.468.0 - ISC
113
+ *
114
+ * This source code is licensed under the ISC license.
115
+ * See the LICENSE file in the root directory of this source tree.
116
+ */const ad=mt("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/**
117
+ * @license lucide-react v0.468.0 - ISC
118
+ *
119
+ * This source code is licensed under the ISC license.
120
+ * See the LICENSE file in the root directory of this source tree.
121
+ */const dd=mt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/**
122
+ * @license lucide-react v0.468.0 - ISC
123
+ *
124
+ * This source code is licensed under the ISC license.
125
+ * See the LICENSE file in the root directory of this source tree.
126
+ */const ud=mt("FlipHorizontal",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3",key:"1i73f7"}],["path",{d:"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3",key:"saxlbk"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/**
127
+ * @license lucide-react v0.468.0 - ISC
128
+ *
129
+ * This source code is licensed under the ISC license.
130
+ * See the LICENSE file in the root directory of this source tree.
131
+ */const hd=mt("FlipVertical",[["path",{d:"M21 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3",key:"14bfxa"}],["path",{d:"M21 16v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3",key:"14rx03"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/**
132
+ * @license lucide-react v0.468.0 - ISC
133
+ *
134
+ * This source code is licensed under the ISC license.
135
+ * See the LICENSE file in the root directory of this source tree.
136
+ */const gd=mt("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/**
137
+ * @license lucide-react v0.468.0 - ISC
138
+ *
139
+ * This source code is licensed under the ISC license.
140
+ * See the LICENSE file in the root directory of this source tree.
141
+ */const fd=mt("Group",[["path",{d:"M3 7V5c0-1.1.9-2 2-2h2",key:"adw53z"}],["path",{d:"M17 3h2c1.1 0 2 .9 2 2v2",key:"an4l38"}],["path",{d:"M21 17v2c0 1.1-.9 2-2 2h-2",key:"144t0e"}],["path",{d:"M7 21H5c-1.1 0-2-.9-2-2v-2",key:"rtnfgi"}],["rect",{width:"7",height:"5",x:"7",y:"7",rx:"1",key:"1eyiv7"}],["rect",{width:"7",height:"5",x:"10",y:"12",rx:"1",key:"1qlmkx"}]]);/**
142
+ * @license lucide-react v0.468.0 - ISC
143
+ *
144
+ * This source code is licensed under the ISC license.
145
+ * See the LICENSE file in the root directory of this source tree.
146
+ */const pd=mt("Hand",[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]]);/**
147
+ * @license lucide-react v0.468.0 - ISC
148
+ *
149
+ * This source code is licensed under the ISC license.
150
+ * See the LICENSE file in the root directory of this source tree.
151
+ */const yd=mt("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/**
152
+ * @license lucide-react v0.468.0 - ISC
153
+ *
154
+ * This source code is licensed under the ISC license.
155
+ * See the LICENSE file in the root directory of this source tree.
156
+ */const Id=mt("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/**
157
+ * @license lucide-react v0.468.0 - ISC
158
+ *
159
+ * This source code is licensed under the ISC license.
160
+ * See the LICENSE file in the root directory of this source tree.
161
+ */const Cd=mt("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/**
162
+ * @license lucide-react v0.468.0 - ISC
163
+ *
164
+ * This source code is licensed under the ISC license.
165
+ * See the LICENSE file in the root directory of this source tree.
166
+ */const Kr=mt("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/**
167
+ * @license lucide-react v0.468.0 - ISC
168
+ *
169
+ * This source code is licensed under the ISC license.
170
+ * See the LICENSE file in the root directory of this source tree.
171
+ */const Jr=mt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/**
172
+ * @license lucide-react v0.468.0 - ISC
173
+ *
174
+ * This source code is licensed under the ISC license.
175
+ * See the LICENSE file in the root directory of this source tree.
176
+ */const md=mt("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/**
177
+ * @license lucide-react v0.468.0 - ISC
178
+ *
179
+ * This source code is licensed under the ISC license.
180
+ * See the LICENSE file in the root directory of this source tree.
181
+ */const bd=mt("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/**
182
+ * @license lucide-react v0.468.0 - ISC
183
+ *
184
+ * This source code is licensed under the ISC license.
185
+ * See the LICENSE file in the root directory of this source tree.
186
+ */const Ad=mt("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/**
187
+ * @license lucide-react v0.468.0 - ISC
188
+ *
189
+ * This source code is licensed under the ISC license.
190
+ * See the LICENSE file in the root directory of this source tree.
191
+ */const $r=mt("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/**
192
+ * @license lucide-react v0.468.0 - ISC
193
+ *
194
+ * This source code is licensed under the ISC license.
195
+ * See the LICENSE file in the root directory of this source tree.
196
+ */const wd=mt("Redo2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/**
197
+ * @license lucide-react v0.468.0 - ISC
198
+ *
199
+ * This source code is licensed under the ISC license.
200
+ * See the LICENSE file in the root directory of this source tree.
201
+ */const xd=mt("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/**
202
+ * @license lucide-react v0.468.0 - ISC
203
+ *
204
+ * This source code is licensed under the ISC license.
205
+ * See the LICENSE file in the root directory of this source tree.
206
+ */const kd=mt("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/**
207
+ * @license lucide-react v0.468.0 - ISC
208
+ *
209
+ * This source code is licensed under the ISC license.
210
+ * See the LICENSE file in the root directory of this source tree.
211
+ */const Rr=mt("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/**
212
+ * @license lucide-react v0.468.0 - ISC
213
+ *
214
+ * This source code is licensed under the ISC license.
215
+ * See the LICENSE file in the root directory of this source tree.
216
+ */const Sd=mt("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/**
217
+ * @license lucide-react v0.468.0 - ISC
218
+ *
219
+ * This source code is licensed under the ISC license.
220
+ * See the LICENSE file in the root directory of this source tree.
221
+ */const vd=mt("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/**
222
+ * @license lucide-react v0.468.0 - ISC
223
+ *
224
+ * This source code is licensed under the ISC license.
225
+ * See the LICENSE file in the root directory of this source tree.
226
+ */const Ed=mt("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/**
227
+ * @license lucide-react v0.468.0 - ISC
228
+ *
229
+ * This source code is licensed under the ISC license.
230
+ * See the LICENSE file in the root directory of this source tree.
231
+ */const Wd=mt("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/**
232
+ * @license lucide-react v0.468.0 - ISC
233
+ *
234
+ * This source code is licensed under the ISC license.
235
+ * See the LICENSE file in the root directory of this source tree.
236
+ */const Td=mt("Ungroup",[["rect",{width:"8",height:"6",x:"5",y:"4",rx:"1",key:"nzclkv"}],["rect",{width:"8",height:"6",x:"11",y:"14",rx:"1",key:"4tytwb"}]]);/**
237
+ * @license lucide-react v0.468.0 - ISC
238
+ *
239
+ * This source code is licensed under the ISC license.
240
+ * See the LICENSE file in the root directory of this source tree.
241
+ */const Bd=mt("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/**
242
+ * @license lucide-react v0.468.0 - ISC
243
+ *
244
+ * This source code is licensed under the ISC license.
245
+ * See the LICENSE file in the root directory of this source tree.
246
+ */const Zd=mt("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),Md={Hand:g.jsx(pd,{size:18}),MousePointer2:g.jsx(md,{size:18}),Square:g.jsx(Rr,{size:18}),Circle:g.jsx(Ur,{size:18}),Diamond:g.jsx(zr,{size:18}),Minus:g.jsx(Jr,{size:18}),ArrowUpRight:g.jsx(Nr,{size:18}),Pencil:g.jsx($r,{size:18}),Type:g.jsx(Ed,{size:18}),ImageIcon:g.jsx(yd,{size:18}),Eraser:g.jsx(dd,{size:18}),StickyNote:g.jsx(Sd,{size:18})},Ce=(t,e,n)=>({display:"flex",alignItems:"center",justifyContent:"center",width:34,height:34,borderRadius:8,border:"none",cursor:n?"not-allowed":"pointer",transition:"background 150ms, color 150ms",background:t?`${e.activeToolColor}20`:"transparent",color:t?e.activeToolColor:n?`${e.mutedTextColor}55`:e.mutedTextColor,outline:t?`1.5px solid ${e.activeToolColor}50`:"none",flexShrink:0,opacity:n?.45:1}),On=t=>({width:1,height:22,background:t.toolbarBorder,margin:"0 3px",flexShrink:0}),jr=t=>({display:"flex",alignItems:"center",gap:1,background:t.toolbarBg,backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",boxShadow:"0 2px 10px rgba(0,0,0,0.08)",borderRadius:12,padding:"5px 8px",border:`1px solid ${t.toolbarBorder}`});function _d(t,e,n){const[o,s]=I.useState(null),r=I.useRef(e);r.current=e;const i=I.useCallback(()=>{t.current&&s(r.current(t.current.getBoundingClientRect()))},[t]);return I.useEffect(()=>{if(!n){s(null);return}return i(),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0)}},[n,i]),o}const Uo=({anchorRef:t,onClose:e,theme:n,placement:o,computePos:s,transform:r,dataAttribute:i,style:l,children:a,isOpen:c})=>{const d=_d(t,h=>s(h,o),c);return I.useEffect(()=>{if(!c)return;const h=f=>{t.current&&t.current.contains(f.target)||f.target.closest(`[${i}]`)||e()},u=()=>e();return document.addEventListener("mousedown",h),window.addEventListener("resize",u),()=>{document.removeEventListener("mousedown",h),window.removeEventListener("resize",u)}},[c,e,i,t]),!c||!d?null:Ms.createPortal(g.jsx("div",{[i]:"true",style:{position:"fixed",top:d.top,left:d.left,transform:r,background:n.toolbarBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:`1px solid ${n.toolbarBorder}`,borderRadius:12,boxShadow:"0 8px 28px rgba(0,0,0,0.12)",zIndex:9999,...l},children:a}),document.body)},Qr=({icon:t,label:e,disabled:n,isActive:o,onClick:s,theme:r,size:i=36})=>g.jsx("button",{title:e,disabled:n,onClick:n?void 0:s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:i,height:i,borderRadius:8,border:`1px solid ${o?`${r.activeToolColor}50`:"transparent"}`,background:o?`${r.activeToolColor}18`:"transparent",cursor:n?"default":"pointer",color:o?r.activeToolColor:n?`${r.mutedTextColor}55`:r.mutedTextColor,opacity:n?.4:1,transition:"background 120ms, color 120ms, border-color 120ms"},onMouseEnter:l=>{!n&&!o&&(l.currentTarget.style.background=`${r.activeToolColor}14`,l.currentTarget.style.color=r.activeToolColor,l.currentTarget.style.borderColor=`${r.activeToolColor}30`)},onMouseLeave:l=>{o||(l.currentTarget.style.background="transparent",l.currentTarget.style.color=n?`${r.mutedTextColor}55`:r.mutedTextColor,l.currentTarget.style.borderColor="transparent")},children:t}),Xd=({actions:t,anchorRef:e,onClose:n,theme:o,placement:s="bottom"})=>g.jsx(Uo,{isOpen:!0,anchorRef:e,onClose:n,theme:o,placement:s,computePos:(r,i)=>i==="top"?{top:r.bottom+8,left:r.left+r.width/2}:{top:r.top-12,left:r.left+r.width/2},transform:s==="top"?"translate(-50%, 0)":"translate(-50%, -100%)",dataAttribute:"data-subtools-popup",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(4, 36px)",gap:4},children:t.map((r,i)=>g.jsx(Qr,{icon:r.icon,label:r.label,disabled:r.disabled,onClick:()=>{r.onClick(),n()},theme:o},i))}),Gd=({shapes:t,activeTool:e,anchorRef:n,onSelect:o,onClose:s,theme:r,placement:i="bottom"})=>g.jsx(Uo,{isOpen:!0,anchorRef:n,onClose:s,theme:r,placement:i,computePos:(l,a)=>a==="top"?{top:l.bottom+8,left:l.right}:{top:l.top-12,left:l.right},transform:i==="top"?"translate(-100%, 0)":"translate(-100%, -100%)",dataAttribute:"data-shape-picker",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(5, 40px)",gap:4},children:t.filter(l=>l.tool!==null).map((l,a)=>g.jsx(Qr,{icon:l.icon,label:l.label,disabled:l.tool===null,isActive:l.tool!==null&&e===l.tool,onClick:()=>{l.tool&&(o(l.tool),s())},theme:r,size:40},a))}),Dd=({scale:t,theme:e,onZoomIn:n,onZoomOut:o,onReset:s,placement:r="bottom"})=>{const[i,l]=I.useState(!1),a=I.useRef(null);return g.jsxs("div",{ref:a,style:{position:"relative"},children:[g.jsxs("button",{style:{...Ce(i,e),width:"auto",padding:"0 6px",gap:2,fontSize:11,minWidth:52},onClick:()=>l(!i),title:"Zoom",children:[g.jsxs("span",{style:{minWidth:32,textAlign:"center",userSelect:"none"},children:[Math.round(t*100),"%"]}),g.jsx(od,{size:12})]}),g.jsx(Uo,{isOpen:i,anchorRef:a,onClose:()=>l(!1),theme:e,placement:r,computePos:(c,d)=>d==="top"?{top:c.bottom+6,left:c.left}:{top:c.top-6,left:c.left},transform:r==="top"?"translateY(0)":"translateY(-100%)",dataAttribute:"data-zoom-dropdown",style:{padding:4,minWidth:130},children:[{icon:g.jsx(Bd,{size:14}),label:"Zoom In",fn:()=>{n(),l(!1)}},{icon:g.jsx(Zd,{size:14}),label:"Zoom Out",fn:()=>{o(),l(!1)}},{icon:g.jsx(Kr,{size:14}),label:"Reset Zoom",fn:()=>{s(),l(!1)}}].map(({icon:c,label:d,fn:h})=>g.jsxs("button",{onClick:h,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:"transparent",color:e.textColor,cursor:"pointer",borderRadius:4,fontSize:12},onMouseEnter:u=>{u.currentTarget.style.background=`${e.activeToolColor}14`},onMouseLeave:u=>{u.currentTarget.style.background="transparent"},children:[c,g.jsx("span",{children:d})]},d))})]})},Ld=({visibleTools:t,theme:e,position:n="bottom"})=>{const o=B(E=>E.activeTool),s=B(E=>E.setActiveTool),r=B(E=>E.undo),i=B(E=>E.redo),l=B(E=>E.selectedIds),a=B(E=>E.elements),c=B(E=>E.deleteElements),d=B(E=>E.duplicateElements),h=B(E=>E.bringToFront),u=B(E=>E.bringForward),f=B(E=>E.sendBackward),p=B(E=>E.sendToBack),y=B(E=>E.toggleLockElements),b=B(E=>E.ungroupElements),W=B(E=>E.pushHistory),v=B(E=>E.showGrid),G=B(E=>E.toggleGrid),$=B(E=>E.zoomIn),T=B(E=>E.zoomOut),O=B(E=>E.resetZoom),ot=B(E=>E.viewport.scale),[Y,J]=I.useState(!1),P=I.useRef(null),[Q,_]=I.useState(!1),x=I.useRef(null),C=l.length>0,w=l.length>1,S=C&&a.filter(E=>l.includes(E.id)).every(E=>E.isLocked),Z=()=>{const E=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),V=URL.createObjectURL(E),dt=Object.assign(document.createElement("a"),{href:V,download:"canvas.json"});document.body.appendChild(dt),dt.click(),document.body.removeChild(dt),URL.revokeObjectURL(V)},X=[{icon:g.jsx(ja,{size:16}),label:"Align Left",disabled:!w,onClick:()=>{}},{icon:g.jsx($a,{size:16}),label:"Align Center H",disabled:!w,onClick:()=>{}},{icon:g.jsx(Qa,{size:16}),label:"Align Right",disabled:!w,onClick:()=>{}},{icon:g.jsx(Ja,{size:16}),label:"Align Center V",disabled:!w,onClick:()=>{}},{icon:g.jsx(qa,{size:16}),label:"Align Top",disabled:!w,onClick:()=>{}},{icon:g.jsx(Ra,{size:16}),label:"Align Bottom",disabled:!w,onClick:()=>{}},{icon:g.jsx(ud,{size:16}),label:"Flip H",disabled:!C,onClick:()=>{}},{icon:g.jsx(hd,{size:16}),label:"Flip V",disabled:!C,onClick:()=>{}},{icon:g.jsx(id,{size:16}),label:"Bring to Front",disabled:!C,onClick:()=>{h(l),W()}},{icon:g.jsx(ed,{size:16}),label:"Bring Forward",disabled:!C,onClick:()=>{u(l),W()}},{icon:g.jsx(td,{size:16}),label:"Send Backward",disabled:!C,onClick:()=>{f(l),W()}},{icon:g.jsx(rd,{size:16}),label:"Send to Back",disabled:!C,onClick:()=>{p(l),W()}},{icon:g.jsx(xd,{size:16}),label:"Rotate Left 90°",disabled:!C,onClick:()=>{}},{icon:g.jsx(kd,{size:16}),label:"Rotate Right 90°",disabled:!C,onClick:()=>{}},{icon:S?g.jsx(Id,{size:16}):g.jsx(Cd,{size:16}),label:S?"Unlock":"Lock",disabled:!C,onClick:()=>{y(l),W()}},{icon:g.jsx(Td,{size:16}),label:"Ungroup",disabled:!C,onClick:()=>{b(l),W()}},{icon:g.jsx(gd,{size:16}),label:v?"Hide Grid":"Show Grid",disabled:!1,onClick:G},{icon:g.jsx(cd,{size:16}),label:"Export JSON",disabled:!1,onClick:Z},{icon:g.jsx(Kr,{size:16}),label:"Reset Zoom",disabled:!1,onClick:O},{icon:g.jsx(fd,{size:16}),label:"Select All",disabled:!1,onClick:()=>{}}],D=[{icon:g.jsx(Rr,{size:16}),label:"Rectangle",tool:"rectangle"},{icon:g.jsx(Ur,{size:16}),label:"Ellipse",tool:"ellipse"},{icon:g.jsx(zr,{size:16}),label:"Diamond",tool:"diamond"},{icon:g.jsx(Jr,{size:16}),label:"Line",tool:"line"},{icon:g.jsx(Nr,{size:16}),label:"Arrow",tool:"arrow"}].filter(E=>E.tool===null?!0:!t.some(V=>V.type===E.tool)),L=E=>s(E),at=X.filter(E=>!["Undo","Redo","Delete","Duplicate"].includes(E.label)),tt=n==="top";return g.jsx("div",{style:{position:"absolute",...tt?{top:16}:{bottom:16},left:0,right:0,zIndex:50,display:"flex",justifyContent:"center",alignItems:tt?"flex-start":"flex-end",pointerEvents:"none"},children:g.jsxs("div",{style:{display:"flex",flexDirection:tt?"column-reverse":"column",alignItems:"center",maxWidth:"calc(100% - 32px)",gap:0,pointerEvents:"none"},children:[g.jsxs("div",{style:{...jr(e),pointerEvents:"auto",...tt?{borderRadius:"0 0 12px 12px",borderTop:"none"}:{borderRadius:"12px 12px 0 0",borderBottom:"none"}},children:[g.jsx("button",{style:Ce(!1,e),onClick:r,title:"Undo (⌘Z)",children:g.jsx(Wd,{size:16})}),g.jsx("button",{style:Ce(!1,e),onClick:i,title:"Redo (⌘⇧Z)",children:g.jsx(wd,{size:16})}),g.jsx("div",{style:On(e)}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&c(l)},title:"Delete (⌫)",children:g.jsx(vd,{size:16})}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&d(l)},title:"Duplicate (⌘D)",children:g.jsx(ld,{size:16})}),at.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:On(e)}),g.jsx("button",{ref:P,style:Ce(Y,e),onClick:()=>{J(!Y),_(!1)},title:"More actions",children:g.jsx(ad,{size:16})})]})]}),g.jsxs("div",{style:{...jr(e),pointerEvents:"auto",...tt?{borderRadius:"12px 12px 0 0",borderBottom:"none"}:{}},children:[t.map(E=>g.jsx("button",{style:Ce(o===E.type,e),onClick:()=>s(E.type),title:`${E.label} (${E.shortcut})`,children:Md[E.icon]},E.type)),g.jsx("div",{style:On(e)}),g.jsx(Dd,{scale:ot,theme:e,onZoomIn:$,onZoomOut:T,onReset:O,placement:n}),D.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:On(e)}),g.jsx("button",{ref:x,style:Ce(Q,e),onClick:()=>{_(!Q),J(!1)},title:"More shapes",children:g.jsx(sd,{size:16})})]})]}),Y&&at.length>0&&g.jsx(Xd,{actions:at,anchorRef:P,onClose:()=>J(!1),theme:e,placement:n}),Q&&D.length>0&&g.jsx(Gd,{shapes:D,activeTool:o,anchorRef:x,onSelect:L,onClose:()=>_(!1),theme:e,placement:n})]})})},me=({theme:t,variant:e="toggle",isActive:n=!1,dangerHover:o=!1,onClick:s,title:r,disabled:i=!1,width:l=28,height:a=28,style:c,children:d})=>{const[h,u]=I.useState(!1),f=n||h,p=()=>e==="toggle"&&n?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",y=()=>e==="toggle"&&n?`${t.activeToolColor}10`:h?"#f3f4f6":"transparent";return g.jsx("button",{title:r,onClick:i?void 0:s,disabled:i,onMouseEnter:()=>!i&&u(!0),onMouseLeave:()=>u(!1),style:{width:l,height:a,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:5,border:p(),background:y(),cursor:i?"not-allowed":"pointer",color:n?t.activeToolColor:t.textColor,transition:"background 0.1s, border-color 0.1s",outline:"none",padding:0,opacity:i?.35:1,flexShrink:0,...c},children:typeof d=="function"?d(f):d})},zo=({theme:t,isActive:e=!1,onClick:n,title:o,disabled:s,flex:r=1,width:i,children:l,style:a})=>g.jsx("button",{title:o,onClick:n,disabled:s,style:{flex:r,width:i,padding:"3px 0",borderRadius:4,border:e?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",background:e?`${t.activeToolColor}10`:"transparent",cursor:"pointer",fontSize:10,fontWeight:500,color:e?t.activeToolColor:t.textColor,textAlign:"center",outline:"none",...a},children:l}),_t=({theme:t,label:e,headerAction:n,children:o,style:s})=>g.jsxs("div",{style:{marginBottom:10,...s},children:[e&&g.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:n?"space-between":"flex-start",marginBottom:n?0:5},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:e}),n]}),o]}),Te=({children:t,gap:e=5,wrap:n=!1,columns:o=4,style:s})=>g.jsx("div",{style:{display:o?"grid":"flex",gridTemplateColumns:o?`repeat(${o}, 1fr)`:void 0,gap:e,justifyContent:o?void 0:"flex-start",flexWrap:!o&&n?"wrap":"nowrap",...s},children:t}),Nn=({options:t,value:e,onChange:n,theme:o,label:s,isOpen:r,onToggle:i,pickerRef:l,columns:a,style:c})=>{const d=t.find(p=>p.value===e)??t[0],h=I.useRef(null),[u,f]=I.useState(null);return I.useEffect(()=>{if(r&&h.current){const p=h.current.getBoundingClientRect();f({top:p.bottom+3,left:p.left})}else f(null)},[r]),g.jsxs("div",{ref:l,style:{position:"relative",display:"inline-flex",...c},children:[g.jsx("button",{ref:h,title:`${s}: ${d.label}`,onClick:i,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",height:28,padding:"0 8px",borderRadius:6,border:r?`1.5px solid ${o.activeToolColor}`:"1px solid #e0e3e7",background:r?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:r?o.activeToolColor:o.textColor,outline:"none",transition:"background 0.15s, border-color 0.15s",boxShadow:r?`0 0 0 2px ${o.activeToolColor}20`:"none"},children:typeof d.icon=="function"?d.icon(r?o.activeToolColor:o.textColor):d.icon}),r&&u&&Ms.createPortal(g.jsx("div",{"data-compact-dropdown":"true",style:{position:"fixed",top:u.top,left:u.left,background:o.panelBg,border:`1px solid ${o.toolbarBorder}`,borderRadius:6,padding:3,boxShadow:"0 3px 12px rgba(0,0,0,0.1)",zIndex:9999,display:"grid",gridTemplateColumns:a?`repeat(${a}, 26px)`:`repeat(${t.length}, 26px)`,gap:1},children:t.map(p=>{const y=p.value===e,b=y?o.activeToolColor:o.textColor;return g.jsx("button",{title:p.label,onClick:()=>{n(p.value),i()},style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,borderRadius:4,border:y?`1.5px solid ${o.activeToolColor}`:"1px solid transparent",background:y?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:b,outline:"none"},children:typeof p.icon=="function"?p.icon(b):p.icon},String(p.value))})}),document.body)]})},Ko=20,Yd=4,Vd=6,Fd=[{value:1,label:"Thin",thickness:1},{value:2,label:"Normal",thickness:2},{value:4,label:"Bold",thickness:3.5},{value:6,label:"Extra Bold",thickness:5.5}],Pd=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],Hd=({thickness:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"2",y1:"7",x2:"12",y2:"7",stroke:e,strokeWidth:t,strokeLinecap:"round"})}),Od=({style:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"1",y1:"7",x2:"13",y2:"7",stroke:e,strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:t==="dashed"?"3.5 2.5":t==="dotted"?"1 2.5":void 0})}),Nd=({level:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t===0?g.jsx("path",{d:"M2,9 Q5,5 7,7 Q9,9 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):t===1?g.jsx("path",{d:"M2,9 Q3.5,3 6,8 Q8,13 10,6 Q11,3 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):g.jsx("path",{d:"M1,8 Q3,3 4.5,9 Q6,13 7,6 Q8.5,1 10,9 Q11.5,13 13,6",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"})}),Ud=({type:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t==="sharp"?g.jsx("polyline",{points:"2,11 7,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}):t==="elbow"?g.jsx("polyline",{points:"2,11 2,3 12,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"square",strokeLinejoin:"miter"}):g.jsx("path",{d:"M2,11 Q7,0 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round"})}),qr={standard:({size:t,color:e,strokeWidth:n})=>g.jsx(bd,{size:t,color:e,strokeWidth:n}),pen:({size:t,color:e,strokeWidth:n})=>g.jsx(Ad,{size:t,color:e,strokeWidth:n}),pencil:({size:t,color:e,strokeWidth:n})=>g.jsx($r,{size:t,color:e,strokeWidth:n}),brush:({size:t,color:e,strokeWidth:n})=>g.jsx(nd,{size:t,color:e,strokeWidth:n})},zd=({style:t,color:e})=>{const n=qr[t]??qr.standard;return g.jsx(n,{size:16,color:e,strokeWidth:1.5})},ti=({arrowhead:t,end:e,color:n})=>{let l=18,a=null;switch(t){case null:break;case"arrow":l=16,a=g.jsx("path",{d:`M12,${6-3.5} L18,6 L12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"});break;case"triangle":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:n});break;case"triangle_outline":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinejoin:"round"});break;case"circle":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:n});break;case"circle_outline":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"diamond":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:n});break;case"diamond_outline":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"bar":a=g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"});break;case"crowfoot_one":l=14,a=g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:14,y1:6-3.5,x2:14,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_one_or_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18-3.5,y1:6-3.5,x2:18-3.5,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break}const c=e==="start"?"scale(-1,1) translate(-20,0)":void 0;return g.jsx("svg",{width:14,height:12,viewBox:"0 0 20 12",fill:"none",children:g.jsxs("g",{transform:c,children:[g.jsx("line",{x1:2,y1:6,x2:l,y2:6,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"}),a]})})},be=({children:t,color:e,size:n=12})=>g.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t}),Un={sendToBack:t=>g.jsxs(be,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 12 12 18"}),g.jsx("polyline",{points:"9 15 12 18 15 15"})]}),sendBackward:t=>g.jsxs(be,{color:t,children:[g.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),g.jsx("polyline",{points:"19 12 12 19 5 12"})]}),bringForward:t=>g.jsxs(be,{color:t,children:[g.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),g.jsx("polyline",{points:"5 12 12 5 19 12"})]}),bringToFront:t=>g.jsxs(be,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 18 12 12"}),g.jsx("polyline",{points:"9 15 12 12 15 15"})]})},zn={duplicate:t=>g.jsxs(be,{color:t,children:[g.jsx("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"}),g.jsx("path",{d:"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"})]}),delete:t=>g.jsxs(be,{color:t,children:[g.jsx("polyline",{points:"3 6 5 6 21 6"}),g.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),g.jsx("path",{d:"M10 11v6"}),g.jsx("path",{d:"M14 11v6"}),g.jsx("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),link:t=>g.jsxs(be,{color:t,children:[g.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),g.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),ungroup:t=>g.jsxs(be,{color:t,children:[g.jsx("rect",{x:"2",y:"2",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("rect",{x:"14",y:"14",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("path",{d:"M14 2h4a2 2 0 0 1 2 2v4"}),g.jsx("path",{d:"M2 14v4a2 2 0 0 0 2 2h4"})]})},Kd=({theme:t})=>{const e=B(A=>A.currentStyle),n=B(A=>A.setCurrentStyle),o=B(A=>A.selectedIds),s=B(A=>A.elements),r=B(A=>A.updateElement),i=B(A=>A.pushHistory),l=B(A=>A.toggleLockElements),a=B(A=>A.deleteElements),c=B(A=>A.duplicateElements),d=B(A=>A.bringToFront),h=B(A=>A.sendToBack),u=B(A=>A.bringForward),f=B(A=>A.sendBackward),p=B(A=>A.activeTool),y=B(A=>A.currentLineType),b=B(A=>A.setCurrentLineType),W=B(A=>A.currentStartArrowhead),v=B(A=>A.setCurrentStartArrowhead),G=B(A=>A.currentEndArrowhead),$=B(A=>A.setCurrentEndArrowhead),[T,O]=I.useState(null),ot=I.useRef(null),Y=I.useRef(null),[J,P]=I.useState(null),Q=I.useRef(null),_=I.useRef(null),x=I.useRef(null),C=I.useRef(null);I.useEffect(()=>{if(!T)return;const A=lt=>{const bt=T==="start"?ot:Y,j=bt.current&&bt.current.contains(lt.target),Gt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Gt&&O(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[T]),I.useEffect(()=>{if(!J)return;const A=lt=>{const bt=J==="sloppiness"?Q:_,j=bt.current&&bt.current.contains(lt.target),Gt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Gt&&P(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[J]);const w=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(bt=>bt.id===A))==null?void 0:lt.type)==="text"}),[o,s]),S=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return A&&(A.type==="arrow"||A.type==="line")?A:null},[o,s]),Z=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return!A||A.type!=="image"?null:A},[o,s]),X=I.useMemo(()=>{if(o.length===0)return null;const A=s.filter(j=>o.includes(j.id)),lt=A.every(j=>j.isLocked),bt=A.some(j=>j.isLocked);return{allLocked:lt,anyLocked:bt}},[o,s]),U=(S==null?void 0:S.type)==="arrow",D=S!=null,L=o.length>0,at=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(bt=>bt.id===A))==null?void 0:lt.type)==="freedraw"}),[o,s]),tt=p==="arrow"||p==="line",E=p==="arrow",V=D||tt,dt=U||E,R=at||p==="freedraw",z=I.useMemo(()=>{if(o.length===0)return e;if(o.length===1){const lt=s.find(bt=>bt.id===o[0]);if(lt)return lt.style}const A=s.find(lt=>o.includes(lt.id));return A?A.style:e},[o,s,e]),et=A=>{n(A),o.length>0&&(o.forEach(lt=>{const bt=s.find(j=>j.id===lt);bt&&r(lt,{style:{...bt.style,...A}})}),i())},It=Math.round(z.opacity*100),Ct={position:"absolute",left:12,top:64,zIndex:50,width:160,background:t.panelBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",boxShadow:"0 1px 4px rgba(0,0,0,0.05), 0 3px 12px rgba(0,0,0,0.07)",borderRadius:10,padding:"10px 10px 8px",border:`1px solid ${t.toolbarBorder}`,maxHeight:"calc(100vh - 90px)",overflowY:"auto",fontFamily:"system-ui, -apple-system, sans-serif"},rt=(A,lt)=>({width:Ko,height:Ko,borderRadius:4,border:lt?`2px solid ${t.activeToolColor}`:"1.5px solid #d5d8dc",cursor:"pointer",background:A==="transparent"?"repeating-conic-gradient(#d1d5db 0% 25%, transparent 0% 50%) 50%/6px 6px":A,boxShadow:lt?`0 0 0 1.5px ${t.activeToolColor}30`:"none",outline:"none",flexShrink:0,transition:"border-color 0.1s, box-shadow 0.1s",padding:0}),st={height:1,background:t.toolbarBorder,margin:"10px 0",border:"none"},pt={display:"grid",gridTemplateColumns:`repeat(${Vd}, ${Ko}px)`,gap:Yd};return g.jsxs("div",{style:Ct,children:[g.jsx(_t,{label:"Stroke",theme:t,children:g.jsxs("div",{style:pt,children:[nn.map(A=>g.jsx("button",{style:rt(A,z.strokeColor===A),onClick:()=>et({strokeColor:A}),title:A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=x.current)==null?void 0:A.click()},style:{...rt(z.strokeColor,!nn.includes(z.strokeColor)),background:nn.includes(z.strokeColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":z.strokeColor,border:nn.includes(z.strokeColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:x,type:"color",value:z.strokeColor.startsWith("#")?z.strokeColor:"#000000",onChange:A=>et({strokeColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),!D&&!tt&&!at&&p!=="freedraw"&&g.jsx(_t,{label:"Background",theme:t,children:g.jsxs("div",{style:pt,children:[on.map(A=>g.jsx("button",{style:rt(A,z.fillColor===A),onClick:()=>et({fillColor:A}),title:A==="transparent"?"None":A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=C.current)==null?void 0:A.click()},style:{...rt(z.fillColor,!on.includes(z.fillColor)),background:on.includes(z.fillColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":z.fillColor,border:on.includes(z.fillColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:C,type:"color",value:z.fillColor.startsWith("#")?z.fillColor:"#ffffff",onChange:A=>et({fillColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),g.jsx(_t,{label:"Stroke width",theme:t,children:g.jsx(Te,{columns:4,children:Fd.map(A=>g.jsx(me,{isActive:z.strokeWidth===A.value,theme:t,onClick:()=>et({strokeWidth:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Hd,{thickness:A.thickness,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(_t,{label:"Stroke style",theme:t,children:g.jsx(Te,{columns:4,children:Pd.map(A=>g.jsx(me,{isActive:z.strokeStyle===A.value,theme:t,onClick:()=>et({strokeStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Od,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(_t,{label:"Sloppiness",theme:t,headerAction:g.jsx(Nn,{label:"Sloppiness",style:{width:32},value:z.roughness,options:Xs.map(A=>({value:A.value,label:A.label,icon:lt=>g.jsx(Nd,{level:A.value,color:lt})})),onChange:A=>{et({roughness:A})},theme:t,isOpen:J==="sloppiness",onToggle:()=>P(J==="sloppiness"?null:"sloppiness"),pickerRef:Q})}),R&&g.jsx(_t,{label:"Pen style",theme:t,children:g.jsx(Te,{columns:4,children:Al.map(A=>g.jsx(me,{isActive:(z.freehandStyle||"standard")===A.value,theme:t,onClick:()=>et({freehandStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(zd,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),V&&g.jsx(_t,{label:U||E?"Arrow type":"Line type",theme:t,headerAction:g.jsx(Nn,{label:U||E?"Arrow type":"Line type",style:{width:32},value:S?S.lineType:y,options:Co.map(A=>({value:A.type,label:A.label,icon:lt=>g.jsx(Ud,{type:A.type,color:lt})})),onChange:A=>{const lt=Co.find(bt=>bt.type===A);if(lt){if(S){const bt={lineType:lt.type};if(lt.type==="curved"||lt.type==="elbow"){const j=S;j.points.length>4&&(bt.points=[j.points[0],j.points[1],j.points[j.points.length-2],j.points[j.points.length-1]])}r(S.id,bt),i()}b(lt.type),P(null)}},theme:t,isOpen:J==="lineType",onToggle:()=>P(J==="lineType"?null:"lineType"),pickerRef:_})}),dt&&g.jsx(_t,{label:"Arrows",theme:t,headerAction:g.jsxs("div",{style:{display:"flex",gap:4},children:[g.jsx(Nn,{label:"Start arrowhead",style:{width:32},value:(S?S.startArrowhead:W)??"__none__",options:Io.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(ti,{arrowhead:A.type,end:"start",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{startArrowhead:lt}),i()),v(lt)},columns:4,theme:t,isOpen:T==="start",onToggle:()=>O(T==="start"?null:"start"),pickerRef:ot}),g.jsx(Nn,{label:"End arrowhead",style:{width:32},value:(S?S.endArrowhead:G)??"__none__",options:Io.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(ti,{arrowhead:A.type,end:"end",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{endArrowhead:lt}),i()),$(lt)},columns:4,theme:t,isOpen:T==="end",onToggle:()=>O(T==="end"?null:"end"),pickerRef:Y})]})}),g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsxs(_t,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Opacity"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[It,"%"]})]}),g.jsx("input",{type:"range",min:"0",max:"100",step:"1",value:It,onChange:A=>et({opacity:parseInt(A.target.value)/100}),style:{width:"100%",accentColor:t.activeToolColor,height:4}})]})]}),w&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(_t,{label:"Font size",theme:t,children:g.jsx(Te,{columns:0,wrap:!0,gap:2,children:ml.map(A=>g.jsx(zo,{isActive:z.fontSize===A,theme:t,onClick:()=>et({fontSize:A}),flex:"none",style:{width:28,padding:"2px 0"},children:A},A))})}),g.jsx(_t,{label:"Font family",theme:t,children:g.jsx("select",{value:z.fontFamily,onChange:A=>et({fontFamily:A.target.value}),style:{width:"100%",padding:"4px 6px",borderRadius:4,border:`1px solid ${t.toolbarBorder}`,background:t.panelBg,color:t.textColor,fontSize:10,cursor:"pointer",outline:"none"},children:bl.map(A=>g.jsx("option",{value:A.value,children:A.label},A.value))})})]}),Z&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(_t,{label:"Scale mode",theme:t,children:g.jsx(Te,{columns:3,children:["stretch","fit","fill"].map(A=>g.jsx(zo,{isActive:Z.scaleMode===A,theme:t,title:A==="stretch"?"Stretch to fill":A==="fit"?"Fit (contain)":"Fill (cover)",onClick:()=>{r(Z.id,{scaleMode:A}),i()},flex:"1",children:A.charAt(0).toUpperCase()+A.slice(1)},A))})}),g.jsxs(_t,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Corner radius"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[Z.cornerRadius,"px"]})]}),g.jsx("input",{type:"range",min:"0",max:"50",step:"1",value:Z.cornerRadius,onChange:A=>{r(Z.id,{cornerRadius:parseInt(A.target.value)}),i()},style:{width:"100%",accentColor:t.activeToolColor,height:4}})]}),g.jsx(_t,{theme:t,children:g.jsx(zo,{theme:t,style:{width:"100%",padding:"5px 0",borderRadius:4},onClick:()=>{const A=document.createElement("input");A.type="file",A.accept="image/*",A.onchange=async()=>{var j;const lt=(j=A.files)==null?void 0:j[0];if(!lt)return;const bt=new FileReader;bt.onload=()=>{const Gt=bt.result,Xt=new window.Image;Xt.onload=()=>{r(Z.id,{src:Gt,naturalWidth:Xt.naturalWidth,naturalHeight:Xt.naturalHeight}),i()},Xt.src=Gt},bt.readAsDataURL(lt)},A.click()},children:"Replace Image…"})})]}),L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(_t,{label:"Layers",theme:t,children:g.jsx(Te,{columns:4,children:[{fn:h,icon:Un.sendToBack,tip:"Send to back"},{fn:f,icon:Un.sendBackward,tip:"Send backward"},{fn:u,icon:Un.bringForward,tip:"Bring forward"},{fn:d,icon:Un.bringToFront,tip:"Bring to front"}].map(({fn:A,icon:lt,tip:bt})=>g.jsx(me,{variant:"action",theme:t,title:bt,width:"100%",height:32,onClick:()=>{A(o),i()},children:j=>lt(j?t.activeToolColor:t.textColor)},bt))})}),g.jsx(_t,{label:"Actions",theme:t,children:g.jsxs(Te,{columns:4,children:[g.jsx(me,{variant:"action",theme:t,title:"Duplicate (⌘D)",width:"100%",height:32,onClick:()=>c(o),children:A=>zn.duplicate(A?t.activeToolColor:t.textColor)}),g.jsx(me,{variant:"action",theme:t,title:"Delete (⌫)",dangerHover:!0,width:"100%",height:32,onClick:()=>{a(o),i()},children:A=>zn.delete(A?"#e03131":t.textColor)}),g.jsx(me,{variant:"action",theme:t,title:"Add link (coming soon)",width:"100%",height:32,disabled:!0,children:zn.link(t.mutedTextColor)}),g.jsx(me,{variant:"action",theme:t,title:"Ungroup",width:"100%",height:32,onClick:()=>{B.getState().ungroupElements(o),i()},children:A=>zn.ungroup(A?t.activeToolColor:t.textColor)})]})})]}),X&&L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx("button",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",padding:"5px 0",borderRadius:6,border:X.allLocked?"1.5px solid #ff9500":`1px solid ${t.toolbarBorder}`,background:X.allLocked?"#ff950010":"transparent",cursor:"pointer",fontSize:10,fontWeight:600,color:X.allLocked?"#ff9500":t.textColor,letterSpacing:.2,transition:"all 0.1s ease",outline:"none",marginBottom:2},title:X.allLocked?"Unlock position (⌘⇧L)":"Lock position (⌘⇧L)",onClick:()=>l(o),children:X.allLocked?g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}),"Unlock"]}):g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),"Lock Position"]})})]})]})},Jd=({x:t,y:e,items:n,onClose:o,theme:s})=>{const r=I.useRef(null),[i,l]=I.useState({x:t,y:e}),[a,c]=I.useState(!1),d=I.useRef(o);d.current=o,I.useEffect(()=>{const u=r.current;if(!u)return;const f=u.getBoundingClientRect(),p=u.parentElement;if(!p)return;const y=p.getBoundingClientRect();let b=t,W=e;t+f.width>y.width&&(b=Math.max(0,t-f.width)),e+f.height>y.height&&(W=Math.max(0,e-f.height)),l({x:b,y:W}),requestAnimationFrame(()=>c(!0))},[t,e]);const h=I.useCallback(()=>{d.current()},[]);return I.useEffect(()=>{const u=b=>{r.current&&!r.current.contains(b.target)&&h()},f=b=>{b.key==="Escape"&&h()},p=()=>h(),y=requestAnimationFrame(()=>{document.addEventListener("pointerdown",u,!0),document.addEventListener("keydown",f,!0),window.addEventListener("scroll",p,!0)});return()=>{cancelAnimationFrame(y),document.removeEventListener("pointerdown",u,!0),document.removeEventListener("keydown",f,!0),window.removeEventListener("scroll",p,!0)}},[h]),g.jsx("div",{ref:r,style:{position:"absolute",left:i.x,top:i.y,zIndex:1e3,background:s.panelBg,border:`1px solid ${s.toolbarBorder}`,borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.12)",padding:"4px 0",minWidth:180,backdropFilter:"blur(8px)",userSelect:"none",opacity:a?1:0,transform:a?"scale(1)":"scale(0.95)",transformOrigin:"top left",transition:"opacity 0.12s ease-out, transform 0.12s ease-out"},onContextMenu:u=>u.preventDefault(),children:n.map((u,f)=>g.jsxs(I.Fragment,{children:[u.divider&&g.jsx("div",{style:{height:1,background:s.toolbarBorder,margin:"4px 0"}}),g.jsxs("button",{onClick:()=>{u.disabled||(u.action(),o())},disabled:u.disabled,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"6px 12px",border:"none",background:"transparent",color:u.disabled?s.mutedTextColor:s.textColor,fontSize:13,cursor:u.disabled?"default":"pointer",textAlign:"left",fontFamily:"inherit",lineHeight:"20px"},onMouseEnter:p=>{u.disabled||(p.currentTarget.style.background=s.activeToolColor+"18")},onMouseLeave:p=>{p.currentTarget.style.background="transparent"},children:[g.jsx("span",{children:u.label}),u.shortcut&&g.jsx("span",{style:{color:s.mutedTextColor,fontSize:11,marginLeft:24,opacity:.8},children:u.shortcut})]})]},f))})},$d=I.memo(Jd);let Jo=[];function Cn(t){Jo=structuredClone(t)}function $o(){return structuredClone(Jo)}function Rd(){return Jo.length>0}function ei(t){return t.toDataURL({pixelRatio:2})}function jd(t,e="canvas.png"){const n=ei(t),o=document.createElement("a");o.download=e,o.href=n,document.body.appendChild(o),o.click(),document.body.removeChild(o)}function ni(t){return JSON.stringify(t,null,2)}function Qd(t,e="canvas.json"){const n=ni(t),o=new Blob([n],{type:"application/json"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const Kn=20;function St(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function mn(t,e){const n=Mt(t,e);return n.length>0?n.join(","):"none"}function Ro(t){const{strokeColor:e,fillColor:n,strokeWidth:o,opacity:s,strokeStyle:r}=t.style,i=mn(r,o),l=[`fill="${St(n==="transparent"?"none":n)}"`,`stroke="${St(e)}"`,`stroke-width="${o}"`,`opacity="${s}"`];return i!=="none"&&l.push(`stroke-dasharray="${i}"`),l.join(" ")}function Jn(t,e,n,o){return e.rotation?`<g transform="rotate(${e.rotation} ${n} ${o})">${t}</g>`:t}function qd(t){const{x:e,y:n,width:o,height:s,cornerRadius:r}=t,i=r?` rx="${r}" ry="${r}"`:"",l=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${i} ${Ro(t)} />`;return Jn(l,t,e+o/2,n+s/2)}function tu(t){const e=t.x+t.width/2,n=t.y+t.height/2,o=`<ellipse cx="${e}" cy="${n}" rx="${t.width/2}" ry="${t.height/2}" ${Ro(t)} />`;return Jn(o,t,e,n)}function eu(t){const e=gn(t.width,t.height),n=[];for(let s=0;s<e.length;s+=2)n.push(`${t.x+e[s]},${t.y+e[s+1]}`);const o=`<polygon points="${n.join(" ")}" ${Ro(t)} />`;return Jn(o,t,t.x+t.width/2,t.y+t.height/2)}function nu(t){const n=t.points.map((s,r)=>`${r%2===0?t.x+s:t.y+s}`),o=[];for(let s=0;s<n.length;s+=2)o.push(`${n[s]},${n[s+1]}`);return`<polyline points="${o.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round"${mn(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${mn(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function ou(t){const e=t.points,n={x:e[0],y:e[1]},o={x:e[e.length-2],y:e[e.length-1]},s=Jt(n,o,t.curvature??Kt),r=t.x+n.x,i=t.y+n.y,l=t.x+s.x,a=t.y+s.y,c=t.x+o.x,d=t.y+o.y;return`<path d="M ${r} ${i} Q ${l} ${a} ${c} ${d}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round"${mn(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${mn(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function su(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function ru(t){return{x:-t.y,y:t.x}}function $n(t,e,n,o,s,r){const i=su(e,n),l=ru(i),a=o*.45;switch(t){case"arrow":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polyline points="${c.x},${c.y} ${e.x},${e.y} ${d.x},${d.y}" fill="none" stroke="${St(s)}" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round" />`}case"triangle":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"triangle_outline":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"circle":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"circle_outline":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"bar":{const c=a*1.2;return`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`}case"diamond":case"diamond_outline":{const c=a*.7,d=o*.55,h={x:e.x-i.x*d,y:e.y-i.y*d},u=t==="diamond"?St(s):"#ffffff";return`<polygon points="${e.x},${e.y} ${h.x+l.x*c},${h.y+l.y*c} ${h.x-i.x*d},${h.y-i.y*d} ${h.x-l.x*c},${h.y-l.y*c}" fill="${u}" stroke="${St(s)}" stroke-width="${r}" />`}case"crowfoot_one":{const c=a*1,d=o*.25,h={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<line x1="${h.x+l.x*c}" y1="${h.y+l.y*c}" x2="${h.x-l.x*c}" y2="${h.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`].join(`
2
247
  `)}case"crowfoot_many":{const c=a*1,d=o*.6,h={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<polyline points="${e.x+l.x*c},${e.y+l.y*c} ${h.x},${h.y} ${e.x-l.x*c},${e.y-l.y*c}" fill="none" stroke="${St(s)}" stroke-width="${r}" />`].join(`
3
248
  `)}case"crowfoot_one_or_many":{const c=a*1,d=o*.6,h=o*.25,u={x:e.x-i.x*h,y:e.y-i.y*h},f={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<line x1="${u.x+l.x*c}" y1="${u.y+l.y*c}" x2="${u.x-l.x*c}" y2="${u.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<polyline points="${e.x+l.x*c},${e.y+l.y*c} ${f.x},${f.y} ${e.x-l.x*c},${e.y-l.y*c}" fill="none" stroke="${St(s)}" stroke-width="${r}" />`].join(`
4
- `)}default:return""}}function td(t){const e=[],n=t.lineType==="curved";if(e.push(n?ja(t):Ra(t)),t.type==="arrow"){const o=t,s=o.startArrowhead??(o.startArrow?"arrow":null),r=o.endArrowhead??(o.endArrow?"arrow":null),i=Lo(t.style.strokeWidth),l=t.points;if(n){const a={x:l[0],y:l[1]},c={x:l[l.length-2],y:l[l.length-1]},d=Jt(a,c,o.curvature??zt),h={x:t.x+a.x,y:t.y+a.y},u={x:t.x+c.x,y:t.y+c.y},f={x:t.x+d.x*.1+a.x*.9,y:t.y+d.y*.1+a.y*.9},p={x:t.x+d.x*.1+c.x*.9,y:t.y+d.y*.1+c.y*.9};s&&e.push(Nn(s,h,f,i,t.style.strokeColor,t.style.strokeWidth)),r&&e.push(Nn(r,u,p,i,t.style.strokeColor,t.style.strokeWidth))}else{if(s&&l.length>=4){const a={x:t.x+l[0],y:t.y+l[1]},c={x:t.x+l[2],y:t.y+l[3]};e.push(Nn(s,a,c,i,t.style.strokeColor,t.style.strokeWidth))}if(r&&l.length>=4){const a={x:t.x+l[l.length-2],y:t.y+l[l.length-1]},c={x:t.x+l[l.length-4],y:t.y+l[l.length-3]};e.push(Nn(r,a,c,i,t.style.strokeColor,t.style.strokeWidth))}}}return e.join(`
5
- `)}function ed(t){if(t.points.length<4)return"";const e=[];for(let n=0;n<t.points.length;n+=2)e.push(`${t.x+t.points[n]},${t.y+t.points[n+1]}`);return`<polyline points="${e.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round" />`}function nd(t){if(!t.text)return"";const{style:e,x:n,y:o,text:s,textAlign:r}=t,i=s.split(`
6
- `),l=e.fontSize*1.18;let a="start",c=0;r==="center"?(a="middle",c=t.width/2):r==="right"&&(a="end",c=t.width);const d=i.map((u,f)=>`<tspan x="${n+c}" dy="${f===0?0:l}">${St(u)}</tspan>`).join(""),h=[`font-family="${St(e.fontFamily)}"`,`font-size="${e.fontSize}"`,`fill="${St(e.strokeColor)}"`,`opacity="${e.opacity}"`,`text-anchor="${a}"`];return`<text x="${n+c}" y="${o+e.fontSize}" ${h.join(" ")}>${d}</text>`}function od(t){const{x:e,y:n,width:o,height:s,src:r,cornerRadius:i,style:l}=t,a=[],c=i>0?`clip-${t.id}`:"";c&&a.push(`<defs><clipPath id="${c}"><rect x="${e}" y="${n}" width="${o}" height="${s}" rx="${i}" ry="${i}" /></clipPath></defs>`);const d=`<image href="${St(r)}" x="${e}" y="${n}" width="${o}" height="${s}" opacity="${l.opacity}" preserveAspectRatio="none"${c?` clip-path="url(#${c})"`:""} />`;let h="";if(l.strokeWidth>0&&l.strokeColor!=="transparent"){const f=i?` rx="${i}" ry="${i}"`:"";h=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${f} fill="none" stroke="${St(l.strokeColor)}" stroke-width="${l.strokeWidth}" opacity="${l.opacity}" />`}const u=a.join("")+d+h;return On(u,t,e+o/2,n+s/2)}function sd(t){switch(t.type){case"rectangle":return za(t);case"ellipse":return Ja(t);case"diamond":return $a(t);case"line":case"arrow":return td(t);case"freedraw":return ed(t);case"text":return nd(t);case"image":return od(t);default:return""}}function Ne(t){if(t.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>';let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const d of t)if(d.isVisible)if(d.type==="line"||d.type==="arrow"||d.type==="freedraw"){const h=d.points;for(let u=0;u<h.length;u+=2){const f=d.x+h[u],p=d.y+h[u+1];e=Math.min(e,f),n=Math.min(n,p),o=Math.max(o,f),s=Math.max(s,p)}}else e=Math.min(e,d.x),n=Math.min(n,d.y),o=Math.max(o,d.x+d.width),s=Math.max(s,d.y+d.height);const r=o-e+Hn*2,i=s-n+Hn*2,l=-e+Hn,a=-n+Hn,c=t.filter(d=>d.isVisible).map(d=>sd(d)).filter(Boolean).join(`
249
+ `)}default:return""}}function iu(t){const e=[],n=t.lineType==="curved";if(e.push(n?ou(t):nu(t)),t.type==="arrow"){const o=t,s=o.startArrowhead??(o.startArrow?"arrow":null),r=o.endArrowhead??(o.endArrow?"arrow":null),i=No(t.style.strokeWidth),l=t.points;if(n){const a={x:l[0],y:l[1]},c={x:l[l.length-2],y:l[l.length-1]},d=Jt(a,c,o.curvature??Kt),h={x:t.x+a.x,y:t.y+a.y},u={x:t.x+c.x,y:t.y+c.y},f={x:t.x+d.x*.1+a.x*.9,y:t.y+d.y*.1+a.y*.9},p={x:t.x+d.x*.1+c.x*.9,y:t.y+d.y*.1+c.y*.9};s&&e.push($n(s,h,f,i,t.style.strokeColor,t.style.strokeWidth)),r&&e.push($n(r,u,p,i,t.style.strokeColor,t.style.strokeWidth))}else{if(s&&l.length>=4){const a={x:t.x+l[0],y:t.y+l[1]},c={x:t.x+l[2],y:t.y+l[3]};e.push($n(s,a,c,i,t.style.strokeColor,t.style.strokeWidth))}if(r&&l.length>=4){const a={x:t.x+l[l.length-2],y:t.y+l[l.length-1]},c={x:t.x+l[l.length-4],y:t.y+l[l.length-3]};e.push($n(r,a,c,i,t.style.strokeColor,t.style.strokeWidth))}}}return e.join(`
250
+ `)}function lu(t){if(t.points.length<4)return"";const e=[];for(let n=0;n<t.points.length;n+=2)e.push(`${t.x+t.points[n]},${t.y+t.points[n+1]}`);return`<polyline points="${e.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round" />`}function cu(t){if(!t.text)return"";const{style:e,x:n,y:o,text:s,textAlign:r}=t,i=s.split(`
251
+ `),l=e.fontSize*1.18;let a="start",c=0;r==="center"?(a="middle",c=t.width/2):r==="right"&&(a="end",c=t.width);const d=i.map((u,f)=>`<tspan x="${n+c}" dy="${f===0?0:l}">${St(u)}</tspan>`).join(""),h=[`font-family="${St(e.fontFamily)}"`,`font-size="${e.fontSize}"`,`fill="${St(e.strokeColor)}"`,`opacity="${e.opacity}"`,`text-anchor="${a}"`];return`<text x="${n+c}" y="${o+e.fontSize}" ${h.join(" ")}>${d}</text>`}function au(t){const{x:e,y:n,width:o,height:s,src:r,cornerRadius:i,style:l}=t,a=[],c=i>0?`clip-${t.id}`:"";c&&a.push(`<defs><clipPath id="${c}"><rect x="${e}" y="${n}" width="${o}" height="${s}" rx="${i}" ry="${i}" /></clipPath></defs>`);const d=`<image href="${St(r)}" x="${e}" y="${n}" width="${o}" height="${s}" opacity="${l.opacity}" preserveAspectRatio="none"${c?` clip-path="url(#${c})"`:""} />`;let h="";if(l.strokeWidth>0&&l.strokeColor!=="transparent"){const f=i?` rx="${i}" ry="${i}"`:"";h=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${f} fill="none" stroke="${St(l.strokeColor)}" stroke-width="${l.strokeWidth}" opacity="${l.opacity}" />`}const u=a.join("")+d+h;return Jn(u,t,e+o/2,n+s/2)}function du(t){switch(t.type){case"rectangle":return qd(t);case"ellipse":return tu(t);case"diamond":return eu(t);case"line":case"arrow":return iu(t);case"freedraw":return lu(t);case"text":return cu(t);case"image":return au(t);default:return""}}function Ne(t){if(t.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>';let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const d of t)if(d.isVisible)if(d.type==="line"||d.type==="arrow"||d.type==="freedraw"){const h=d.points;for(let u=0;u<h.length;u+=2){const f=d.x+h[u],p=d.y+h[u+1];e=Math.min(e,f),n=Math.min(n,p),o=Math.max(o,f),s=Math.max(s,p)}}else e=Math.min(e,d.x),n=Math.min(n,d.y),o=Math.max(o,d.x+d.width),s=Math.max(s,d.y+d.height);const r=o-e+Kn*2,i=s-n+Kn*2,l=-e+Kn,a=-n+Kn,c=t.filter(d=>d.isVisible).map(d=>du(d)).filter(Boolean).join(`
7
252
  `);return[`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${i}" viewBox="0 0 ${r} ${i}">`,` <g transform="translate(${l} ${a})">`,` ${c}`," </g>","</svg>"].join(`
8
- `)}function rd(t,e="canvas.svg"){const n=Ne(t),o=new Blob([n],{type:"image/svg+xml"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const id=5;function ld(t){if((t.type==="line"||t.type==="arrow"||t.type==="freedraw")&&"points"in t){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=t.x+e[i],a=t.y+e[i+1];n=Math.min(n,l),o=Math.max(o,l),s=Math.min(s,a),r=Math.max(r,a)}return{left:n,right:o,top:s,bottom:r,cx:(n+o)/2,cy:(s+r)/2}}return{left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2}}function cd(t,e,n,o=id){const s={left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2},r=[],i=[];for(const a of e){if(n.has(a.id)||!a.isVisible||a.type==="text"&&a.containerId)continue;const c=ld(a),d=[[s.left,"left",c.left],[s.left,"left",c.right],[s.right,"right",c.left],[s.right,"right",c.right],[s.cx,"cx",c.cx],[s.left,"left",c.cx],[s.right,"right",c.cx],[s.cx,"cx",c.left],[s.cx,"cx",c.right]];for(const[u,f,p]of d)Math.abs(u-p)<o&&r.push({value:p,edge:f,other:c});const h=[[s.top,"top",c.top],[s.top,"top",c.bottom],[s.bottom,"bottom",c.top],[s.bottom,"bottom",c.bottom],[s.cy,"cy",c.cy],[s.top,"top",c.cy],[s.bottom,"bottom",c.cy],[s.cy,"cy",c.top],[s.cy,"cy",c.bottom]];for(const[u,f,p]of h)Math.abs(u-p)<o&&i.push({value:p,edge:f,other:c})}const l={guides:[]};if(r.length>0){r.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=r[0],c=a.value-s[a.edge];l.x=t.x+c;const d=a.value,h=r.filter(p=>Math.abs(p.value-d)<1);let u=s.top+(l.y!==void 0?l.y-t.y:0),f=s.bottom+(l.y!==void 0?l.y-t.y:0);for(const p of h)u=Math.min(u,p.other.top),f=Math.max(f,p.other.bottom);l.guides.push({orientation:"v",position:d,start:u-10,end:f+10})}if(i.length>0){i.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=i[0],c=a.value-s[a.edge];l.y=t.y+c;const d=a.value,h=i.filter(p=>Math.abs(p.value-d)<1);let u=s.left+(l.x!==void 0?l.x-t.x:0),f=s.right+(l.x!==void 0?l.x-t.x:0);for(const p of h)u=Math.min(u,p.other.left),f=Math.max(f,p.other.right);l.guides.push({orientation:"h",position:d,start:u-10,end:f+10})}return l}function ad(t=!0,e){const n=B(k=>k.setActiveTool),o=B(k=>k.undo),s=B(k=>k.redo),r=B(k=>k.selectedIds),i=B(k=>k.elements),l=B(k=>k.deleteElements),a=B(k=>k.duplicateElements),c=B(k=>k.bringToFront),d=B(k=>k.sendToBack),h=B(k=>k.bringForward),u=B(k=>k.sendBackward),f=B(k=>k.toggleGrid),p=B(k=>k.showGrid),y=B(k=>k.zoomIn),m=B(k=>k.zoomOut),W=B(k=>k.resetZoom),v=B(k=>k.zoomToFit),D=B(k=>k.zoomToSelection),$=B(k=>k.clearSelection),T=B(k=>k.updateElement),O=B(k=>k.addElement),ot=B(k=>k.setSelectedIds),F=B(k=>k.pushHistory),J=dn(),Y=I.useCallback(()=>{r.length!==0&&yn(Us(r,i))},[r,i]),Q=I.useCallback(()=>{const k=Ho();if(k.length===0)return;const C=20,{clones:w,selectedCloneIds:S}=En(k,k,C);w.forEach(Z=>O(Z)),ot(S.length>0?S:w.map(Z=>Z.id)),F(),yn(k.map(Z=>({...Z,x:Z.x+C,y:Z.y+C})))},[O,ot,F]),M=I.useCallback((k,C)=>{r.length!==0&&(r.forEach(w=>{const S=i.find(Z=>Z.id===w);S&&!S.isLocked&&T(w,{x:S.x+k,y:S.y+C})}),F())},[r,i,T,F]);I.useEffect(()=>{if(!t)return;const k=C=>{const w=C.target.tagName;if(w==="INPUT"||w==="TEXTAREA"||w==="SELECT")return;const S=C.metaKey||C.ctrlKey;if(!S&&!C.shiftKey){const G={v:"select",h:"hand",r:"rectangle",o:"ellipse",d:"diamond",l:"line",a:"arrow",p:"freedraw",t:"text",i:"image",e:"eraser"}[C.key.toLowerCase()];if(G){C.preventDefault(),n(G);return}}if(S&&C.key==="z"&&!C.shiftKey){C.preventDefault(),o();return}if(S&&C.key==="z"&&C.shiftKey){C.preventDefault(),s();return}if(S&&C.key==="y"){C.preventDefault(),s();return}if((C.key==="Delete"||C.key==="Backspace")&&!S){if(J.isEditing&&J.selectedPointIndices.length>0){C.preventDefault();const{elements:Z,updateElement:G,pushHistory:U}=B.getState(),X=Z.find(L=>L.id===J.elementId);if(X){const L=X.points.length/2,at=new Set(J.selectedPointIndices);if(L-at.size>=2){const E=[];for(let st=0;st<L;st++)at.has(st)||E.push(X.points[st*2],X.points[st*2+1]);const V=E[0],dt=E[1],R=[];for(let st=0;st<E.length;st+=2)R.push(E[st]-V,E[st+1]-dt);let K=0,et=0,Ct=0,bt=0;for(let st=0;st<R.length;st+=2)K=Math.min(K,R[st]),et=Math.max(et,R[st]),Ct=Math.min(Ct,R[st+1]),bt=Math.max(bt,R[st+1]);const rt={x:X.x+V,y:X.y+dt,points:R,width:et-K,height:bt-Ct};at.has(0)&&(rt.startBinding=null),at.has(L-1)&&(rt.endBinding=null),G(X.id,rt),U(),J.setSelectedPoints([])}}return}if(r.length>0){C.preventDefault();const Z=r.filter(G=>{const U=i.find(X=>X.id===G);return U&&!U.isLocked});Z.length>0&&l(Z)}return}if(S&&C.key==="d"){C.preventDefault(),r.length>0&&a(r);return}if(C.key==="]"&&S&&C.shiftKey){C.preventDefault(),c(r);return}if(C.key==="["&&S&&C.shiftKey){C.preventDefault(),d(r);return}if(C.key==="]"&&S&&!C.shiftKey){C.preventDefault(),h(r);return}if(C.key==="["&&S&&!C.shiftKey){C.preventDefault(),u(r);return}if(C.key==="g"&&!S){C.preventDefault(),f();return}if(S&&(C.key==="="||C.key==="+")){C.preventDefault(),y();return}if(S&&C.key==="-"){C.preventDefault(),m();return}if(S&&C.key==="0"){C.preventDefault(),W();return}if(S&&C.shiftKey&&C.key==="1"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();v(Z.width,Z.height,void 0,{animate:!0})}return}if(S&&C.shiftKey&&C.key==="2"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();D(Z.width,Z.height,{animate:!0})}return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(C.key)&&!S&&r.length>0&&!J.isEditing){C.preventDefault();const Z=p?xe:1,G=C.shiftKey?Z*10:Z,U=C.key==="ArrowLeft"?-G:C.key==="ArrowRight"?G:0,X=C.key==="ArrowUp"?-G:C.key==="ArrowDown"?G:0;M(U,X);return}if(S&&C.key==="c"){r.length>0&&(C.preventDefault(),Y());return}if(!(S&&C.key==="v")){if(S&&C.key==="x"){r.length>0&&(C.preventDefault(),Y(),l(r));return}if(S&&C.key==="g"&&!C.shiftKey){if(C.preventDefault(),r.length>=2){const{groupElements:Z}=B.getState();Z(r)}return}if(S&&C.key==="g"&&C.shiftKey){if(C.preventDefault(),r.length>0){const{ungroupElements:Z}=B.getState();Z(r)}return}if(S&&C.shiftKey&&C.key==="l"){if(C.preventDefault(),r.length>0){const{toggleLockElements:Z}=B.getState();Z(r)}return}if(C.key==="Escape"){if(C.preventDefault(),J.isEditing){J.exitEditMode();return}$(),n("select");return}if(S&&C.key==="a"){C.preventDefault();const{elements:Z,setSelectedIds:G}=B.getState();G(Z.map(U=>U.id));return}}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,n,o,s,r,i,l,a,c,d,h,u,f,p,y,m,W,v,D,e,$,J,M,Y,Q])}function No(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r,id:t.id}}return t.type==="freedraw"?{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}:{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}}class Uo{constructor(e=9){ct(this,"tree");ct(this,"_elementMap",new Map);ct(this,"_fattenedMap",new Map);ct(this,"_margin",50);this.tree=new Qi(e)}get margin(){return this._margin}set margin(e){this._margin=Math.max(0,e)}rebuild(e){this._elementMap.clear(),this._fattenedMap.clear();const n=this._margin,o=new Array(e.length);for(let s=0;s<e.length;s++){const r=e[s];this._elementMap.set(r.id,r);const i=No(r),l={minX:i.minX-n,minY:i.minY-n,maxX:i.maxX+n,maxY:i.maxY+n,id:r.id};this._fattenedMap.set(r.id,{trueMinX:i.minX,trueMinY:i.minY,trueMaxX:i.maxX,trueMaxY:i.maxY,item:l}),o[s]=l}this.tree.clear(),this.tree.load(o)}update(e){this._elementMap.set(e.id,e);const n=No(e),o=this._fattenedMap.get(e.id);if(o){const{item:i}=o;if(n.minX>=i.minX&&n.minY>=i.minY&&n.maxX<=i.maxX&&n.maxY<=i.maxY)return o.trueMinX=n.minX,o.trueMinY=n.minY,o.trueMaxX=n.maxX,o.trueMaxY=n.maxY,!1;this.tree.remove(i,(l,a)=>l.id===a.id)}const s=this._margin,r={minX:n.minX-s,minY:n.minY-s,maxX:n.maxX+s,maxY:n.maxY+s,id:e.id};return this._fattenedMap.set(e.id,{trueMinX:n.minX,trueMinY:n.minY,trueMaxX:n.maxX,trueMaxY:n.maxY,item:r}),this.tree.insert(r),!0}remove(e){const n=this._fattenedMap.get(e);n&&this.tree.remove(n.item,(o,s)=>o.id===s.id),this._elementMap.delete(e),this._fattenedMap.delete(e)}queryViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,u=this.tree.search({minX:a,minY:c,maxX:d,maxY:h}),f=new Array(u.length);for(let p=0;p<u.length;p++)f[p]=u[p].id;return f}queryRect(e,n,o,s){return this.tree.search({minX:e,minY:n,maxX:o,maxY:s})}queryPoint(e,n){return this.tree.search({minX:e,minY:n,maxX:e,maxY:n}).map(o=>o.id)}getElementById(e){return this._elementMap.get(e)}get elementMap(){return this._elementMap}get size(){return this._elementMap.size}getTrueAABB(e){const n=this._fattenedMap.get(e);if(n)return{minX:n.trueMinX,minY:n.trueMinY,maxX:n.trueMaxX,maxY:n.trueMaxY}}clear(){this.tree.clear(),this._elementMap.clear(),this._fattenedMap.clear()}}let Ko=null;function dd(){return Ko||(Ko=new Uo),Ko}const Pr=200;function ud(t,e,n,o,s,r){const i=I.useRef(new Uo),l=I.useMemo(()=>Rs(s),[s]),a=I.useRef([]),c=I.useRef([]),d=I.useRef(0);if(t!==c.current){const h=c.current;if(c.current=t,t.length>Pr)if(t.length!==d.current)i.current.rebuild(t);else{const f=i.current;for(let p=0;p<t.length;p++)t[p]!==h[p]&&f.update(t[p])}d.current=t.length}return I.useMemo(()=>{if(t.length<=Pr)return Js(t,e,n,o,l,r);const u=i.current.queryViewport(e,n,o,r),f=new Set(u);for(const m of s)f.add(m);const p=[];for(const m of t)f.has(m.id)&&p.push(m);const y=a.current;if(p.length===y.length){let m=!0;for(let W=0;W<p.length;W++)if(p[W]!==y[W]){m=!1;break}if(m)return y}return a.current=p,p},[t,e.x,e.y,e.scale,n,o,l,s,r])}const gd=[.0625,.125,.25,.5,1,2,4,8];function Yr(t){const e=gd;if(t<=e[0])return e[0];if(t>=e[e.length-1])return e[e.length-1];for(let n=0;n<e.length-1;n++){const o=(e[n]+e[n+1])/2;if(t<=o)return e[n]}return e[e.length-1]}function Hr(t){return I.useMemo(()=>Yr(t),[t])}const hd=500,fd=500;function Or(t,e={}){const{batchSize:n=fd,threshold:o=hd,enabled:s=!0}=e,r=I.useRef(0),[i,l]=I.useState(0),a=I.useRef([]),c=I.useRef(!1),d=I.useRef(0);t!==a.current&&(a.current=t);const u=s&&t.length>o;I.useEffect(()=>{if(!u){l(t.length),c.current=!0,d.current=t.length;return}const m=d.current;if(c.current&&Math.abs(t.length-m)<n){l(t.length),d.current=t.length;return}const W=++r.current;c.current=!1,d.current=t.length,l(Math.min(n,t.length));let v=n;function D(){r.current===W&&(v=Math.min(v+n,t.length),l(v),v<t.length?requestAnimationFrame(D):c.current=!0)}return n<t.length?requestAnimationFrame(D):c.current=!0,()=>{r.current++}},[t,u,n]);const f=I.useMemo(()=>!u||i>=t.length?t:t.slice(0,i),[t,i,u]),p=u&&i<t.length,y=t.length>0?Math.min(i/t.length,1):1;return{visibleElements:f,isLoading:p,progress:y}}function Nr(t,e){const n=(e==null?void 0:e.timeout)??1e3;"requestIdleCallback"in window?window.requestIdleCallback(o=>{o.timeRemaining()>5?t():Nr(t,e)},{timeout:n}):setTimeout(t,100)}function pd(){return new Promise(t=>setTimeout(t,0))}const yd=200,Id=1e4;class Ur{constructor(e){ct(this,"_worker",null);ct(this,"_pending",new Map);ct(this,"_workerSupported",!0);ct(this,"_workerConfig");ct(this,"_onMessage",e=>{const n=e.data;if(!n||!n.requestId)return;const o=this._pending.get(n.requestId);o&&(this._pending.delete(n.requestId),n.type==="svgResult"?o.resolve(n.svg):n.type==="error"&&o.reject(new Error(n.message)))});this._workerConfig=e}_getWorker(){if(!this._workerSupported)return null;if(this._worker)return this._worker;try{return this._worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGV4cG9ydFdvcmtlci50cyDigJQgV2ViIFdvcmtlciBmb3Igb2ZmLW1haW4tdGhyZWFkIFNWRyBleHBvcnQuCiAqCiAqIEdlbmVyYXRlcyBTVkcgc3RyaW5ncyBmcm9tIHNlcmlhbGl6ZWQgZWxlbWVudCBkYXRhIGluIGEgYmFja2dyb3VuZAogKiB0aHJlYWQsIGtlZXBpbmcgdGhlIG1haW4gdGhyZWFkIHJlc3BvbnNpdmUgZHVyaW5nIGV4cG9ydCBvZiBsYXJnZQogKiBjYW52YXNlcyAoMTBLKyBlbGVtZW50cykuCiAqCiAqIENvbW11bmljYXRpb24gcHJvdG9jb2w6CiAqICAgTWFpbiDihpIgV29ya2VyOgogKiAgICAgeyB0eXBlOiAnZXhwb3J0U1ZHJywgcmVxdWVzdElkOiBzdHJpbmcsIGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gfQogKiAgIFdvcmtlciDihpIgTWFpbjoKICogICAgIHsgdHlwZTogJ3N2Z1Jlc3VsdCcsIHJlcXVlc3RJZDogc3RyaW5nLCBzdmc6IHN0cmluZyB9CiAqICAgICB7IHR5cGU6ICdlcnJvcicsIHJlcXVlc3RJZDogc3RyaW5nLCBtZXNzYWdlOiBzdHJpbmcgfQogKgogKiBVc2VzIFZpdGUncyBuYXRpdmUgV29ya2VyIG1vZHVsZSBzdXBwb3J0IOKAlCBpbXBvcnRlZCB3aXRoOgogKiAgIG5ldyBXb3JrZXIobmV3IFVSTCgnLi9leHBvcnRXb3JrZXIudHMnLCBpbXBvcnQubWV0YS51cmwpLCB7IHR5cGU6ICdtb2R1bGUnIH0pCiAqLwoKaW1wb3J0IHsgZXhwb3J0VG9TVkcgfSBmcm9tICdAL3V0aWxzL2V4cG9ydCc7CmltcG9ydCB0eXBlIHsgQ2FudmFzRWxlbWVudCB9IGZyb20gJ0AvdHlwZXMnOwoKLy8g4pSA4pSA4pSAIE1lc3NhZ2UgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgRXhwb3J0U1ZHTWVzc2FnZSB7CiAgICB0eXBlOiAnZXhwb3J0U1ZHJzsKICAgIHJlcXVlc3RJZDogc3RyaW5nOwogICAgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXTsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBFeHBvcnRTVkdNZXNzYWdlOwoKaW50ZXJmYWNlIFNWR1Jlc3VsdE1lc3NhZ2UgewogICAgdHlwZTogJ3N2Z1Jlc3VsdCc7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIHN2Zzogc3RyaW5nOwp9CgppbnRlcmZhY2UgRXJyb3JNZXNzYWdlIHsKICAgIHR5cGU6ICdlcnJvcic7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIG1lc3NhZ2U6IHN0cmluZzsKfQoKdHlwZSBPdXRnb2luZ01lc3NhZ2UgPSBTVkdSZXN1bHRNZXNzYWdlIHwgRXJyb3JNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBtYWluIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKc2VsZi5vbm1lc3NhZ2UgPSAoZXY6IE1lc3NhZ2VFdmVudDxJbmNvbWluZ01lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBldi5kYXRhOwoKICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICBjYXNlICdleHBvcnRTVkcnOiB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBjb25zdCBzdmcgPSBleHBvcnRUb1NWRyhtc2cuZWxlbWVudHMpOwogICAgICAgICAgICAgICAgY29uc3QgcmVzcG9uc2U6IE91dGdvaW5nTWVzc2FnZSA9IHsKICAgICAgICAgICAgICAgICAgICB0eXBlOiAnc3ZnUmVzdWx0JywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgc3ZnLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9IGNhdGNoIChlcnIpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHJlc3BvbnNlOiBPdXRnb2luZ01lc3NhZ2UgPSB7CiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2Vycm9yJywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgbWVzc2FnZTogZXJyIGluc3RhbmNlb2YgRXJyb3IgPyBlcnIubWVzc2FnZSA6IFN0cmluZyhlcnIpLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBicmVhazsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this._workerConfig),this._worker?(this._worker.onmessage=this._onMessage,this._worker.onerror=e=>{console.warn("[ExportWorkerManager] Worker error, falling back to sync:",e.message),this._workerSupported=!1,this._rejectAll(new Error("Export Worker failed")),this._worker&&(this._worker.terminate(),this._worker=null)},this._worker):(this._workerSupported=!1,null)}catch{return this._workerSupported=!1,null}}_rejectAll(e){for(const[,n]of this._pending)n.reject(e);this._pending.clear()}async exportSVG(e){if(e.length<=yd)return Ne(e);const n=this._getWorker();if(!n)return Ne(e);const o=Pt();return new Promise((s,r)=>{this._pending.set(o,{resolve:s,reject:r});const i=setTimeout(()=>{if(this._pending.has(o)){this._pending.delete(o),console.warn("[ExportWorkerManager] Timeout, falling back to sync export");try{s(Ne(e))}catch(d){r(d)}}},Id),l=s,a=r,c=this._pending.get(o);c&&(c.resolve=d=>{clearTimeout(i),l(d)},c.reject=d=>{clearTimeout(i),a(d)}),n.postMessage({type:"exportSVG",requestId:o,elements:e})})}async downloadSVG(e,n="canvas.svg"){const o=await this.exportSVG(e),s=new Blob([o],{type:"image/svg+xml"}),r=URL.createObjectURL(s),i=document.createElement("a");i.download=n,i.href=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}dispose(){var e;this._rejectAll(new Error("ExportWorkerManager disposed")),(e=this._worker)==null||e.terminate(),this._worker=null}}let se=null,zo;function Cd(t){return se&&t&&JSON.stringify(t)!==JSON.stringify(zo)&&(se.dispose(),se=null),se||(zo=t,se=new Ur(t)),se}function Kr(){se&&(se.dispose(),se=null,zo=void 0)}const zr={canvasBackground:"#f8f9fa",gridColor:"#e5e5e5",selectionColor:"#4f8df7",toolbarBg:"rgba(255, 255, 255, 0.95)",toolbarBorder:"#e5e7eb",panelBg:"rgba(255, 255, 255, 0.95)",activeToolColor:"#4f46e5",textColor:"#374151",mutedTextColor:"#9ca3af"};let Rt=null,Wt=null,Jo=new Set;function Jr(t){return Wt&&Un(),Rt=new Kt.Doc,Wt=new ks.WebsocketProvider(t.serverUrl,t.roomName,Rt,{connect:!0,params:t.authToken?{token:t.authToken}:void 0}),Wt.awareness.setLocalState({user:t.user,cursor:null,selectedIds:[]}),Wt.on("status",e=>{const n=e.status;for(const o of Jo)o(n)}),{doc:Rt,provider:Wt}}function Un(){Wt&&(Wt.awareness.setLocalState(null),Wt.disconnect(),Wt.destroy(),Wt=null),Rt&&(Rt.destroy(),Rt=null)}function $r(){return Rt}function $o(){return Wt}function Rr(){return Rt==null?void 0:Rt.getMap("elements")}function bd(){return Wt!==null&&Wt.wsconnected}function jr(t){return Jo.add(t),()=>{Jo.delete(t)}}function Kn(t){if(!Wt)return;const e=Wt.awareness.getLocalState();Wt.awareness.setLocalState({...e,...t})}function Qr(){if(!Wt)return new Map;const t=Wt.awareness.getStates(),e=Wt.awareness.clientID,n=new Map;for(const[o,s]of t)o!==e&&s&&s.user&&n.set(o,s);return n}const Ro=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],zn=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"];function Cn(t,e){const n=t;for(const o of Ro){const s=n[o];s!==void 0&&e.set(o,s)}if(t.style)for(const o of zn)e.set(`style.${o}`,t.style[o]);switch(t.boundElements?e.set("boundElements",JSON.stringify(t.boundElements)):e.set("boundElements",null),t.groupIds&&e.set("groupIds",JSON.stringify(t.groupIds)),t.type){case"rectangle":e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":e.set("points",JSON.stringify(t.points)),e.set("lineType",t.lineType),t.curvature!==void 0&&e.set("curvature",t.curvature),e.set("startBinding",t.startBinding?JSON.stringify(t.startBinding):null),e.set("endBinding",t.endBinding?JSON.stringify(t.endBinding):null),t.type==="arrow"&&(e.set("startArrowhead",t.startArrowhead),e.set("endArrowhead",t.endArrowhead));break;case"freedraw":e.set("points",JSON.stringify(t.points));break;case"text":e.set("text",t.text),e.set("containerId",t.containerId),e.set("textAlign",t.textAlign),e.set("verticalAlign",t.verticalAlign);break;case"image":e.set("src",t.src),e.set("naturalWidth",t.naturalWidth),e.set("naturalHeight",t.naturalHeight),e.set("scaleMode",t.scaleMode),e.set("crop",t.crop?JSON.stringify(t.crop):null),e.set("cornerRadius",t.cornerRadius),e.set("alt",t.alt);break}}function Be(t){const e=t.get("type"),n=t.get("id");if(!e||!n)return null;const o={};for(const r of zn){const i=t.get(`style.${r}`);i!==void 0&&(o[r]=i)}const s={id:n,type:e,x:t.get("x")??0,y:t.get("y")??0,width:t.get("width")??100,height:t.get("height")??100,rotation:t.get("rotation")??0,isLocked:t.get("isLocked")??!1,isVisible:t.get("isVisible")??!0,style:o,boundElements:Ze(t.get("boundElements"))??null,groupIds:Ze(t.get("groupIds"))??void 0,sortOrder:t.get("sortOrder")??void 0};switch(e){case"rectangle":s.cornerRadius=t.get("cornerRadius")??0;break;case"line":case"arrow":s.points=Ze(t.get("points"))??[0,0,100,0],s.lineType=t.get("lineType")??"sharp",s.curvature=t.get("curvature")??void 0,s.startBinding=Ze(t.get("startBinding")),s.endBinding=Ze(t.get("endBinding")),e==="arrow"&&(s.startArrowhead=t.get("startArrowhead")??null,s.endArrowhead=t.get("endArrowhead")??"arrow");break;case"freedraw":s.points=Ze(t.get("points"))??[];break;case"text":s.text=t.get("text")??"",s.containerId=t.get("containerId")??null,s.textAlign=t.get("textAlign")??"center",s.verticalAlign=t.get("verticalAlign")??"middle";break;case"image":s.src=t.get("src")??"",s.naturalWidth=t.get("naturalWidth")??0,s.naturalHeight=t.get("naturalHeight")??0,s.scaleMode=t.get("scaleMode")??"fit",s.crop=Ze(t.get("crop"))??null,s.cornerRadius=t.get("cornerRadius")??0,s.alt=t.get("alt")??"";break}return s}function Ze(t){if(t==null)return null;try{return JSON.parse(t)}catch{return null}}let _e=!1,Me=!1,Jn=null,$n=null,Ue=null,re=[];function qr(t=50){const e=$r(),n=Rr();if(!e||!n){console.warn("[SyncBridge] Cannot start sync — no Yjs doc");return}if(Rn(),n.size>0){_e=!0;const l=wd(n);B.getState().setElements(l),re=l,_e=!1}else{const l=B.getState().elements;l.length>0&&(Me=!0,e.transact(()=>{for(const a of l){const c=new Kt.Map;Cn(a,c),n.set(a.id,c)}},"local-init"),Me=!1),re=l}const o=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||Me)return;_e=!0;const c=B.getState();let d=[...re],h=!1;for(const[u,f]of l.keys)if(f.action==="add"||f.action==="update"){const p=n.get(u);if(p){const y=Be(p);if(y){const m=d.findIndex(W=>W.id===u);m>=0?d[m]=y:d.push(y),h=!0}}}else f.action==="delete"&&(d=d.filter(p=>p.id!==u),h=!0);h&&(d.sort((u,f)=>u.sortOrder&&f.sortOrder?u.sortOrder<f.sortOrder?-1:u.sortOrder>f.sortOrder?1:0:0),c.setElements(d),re=d),_e=!1};let s=null;const r=new Set,i=l=>{if(!Me){for(const a of l){let c=a.target;for(;c&&!(c instanceof Kt.Map&&c.parent===n);)c=c.parent;if(c instanceof Kt.Map){const d=c.get("id");d&&r.add(d)}}s&&clearTimeout(s),s=setTimeout(()=>{if(r.size===0||Me)return;_e=!0;let a=[...re],c=!1;for(const d of r){const h=n.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}r.clear(),c&&(B.getState().setElements(a),re=a),_e=!1},16)}};n.observe(o),n.observeDeep(i),$n=()=>{n.unobserve(o),n.unobserveDeep(i),s&&clearTimeout(s),r.clear()},Jn=B.subscribe(l=>{_e||l.elements!==re&&(Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{md(l.elements,n,e)},t))})}function Rn(){Jn&&(Jn(),Jn=null),$n&&($n(),$n=null),Ue&&(clearTimeout(Ue),Ue=null),re=[]}function md(t,e,n){Me=!0,re=t;const o=new Map;for(const s of t)o.set(s.id,s);n.transact(()=>{for(const[s]of e.entries())o.has(s)||e.delete(s);for(const s of t){let r=e.get(s.id);r?Ad(s,r):(r=new Kt.Map,Cn(s,r),e.set(s.id,r))}},"local-sync"),Me=!1}function Ad(t,e){const n=t;for(const s of Ro){const r=n[s];r!==e.get(s)&&e.set(s,r)}if(t.style)for(const s of zn){const r=t.style[s];r!==e.get(`style.${s}`)&&e.set(`style.${s}`,r)}const o=t.boundElements?JSON.stringify(t.boundElements):null;switch(o!==e.get("boundElements")&&e.set("boundElements",o),t.type){case"rectangle":t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r),t.lineType!==e.get("lineType")&&e.set("lineType",t.lineType),t.curvature!==e.get("curvature")&&e.set("curvature",t.curvature);const i=t.startBinding?JSON.stringify(t.startBinding):null;i!==e.get("startBinding")&&e.set("startBinding",i);const l=t.endBinding?JSON.stringify(t.endBinding):null;l!==e.get("endBinding")&&e.set("endBinding",l),t.type==="arrow"&&(t.startArrowhead!==e.get("startArrowhead")&&e.set("startArrowhead",t.startArrowhead),t.endArrowhead!==e.get("endArrowhead")&&e.set("endArrowhead",t.endArrowhead));break}case"freedraw":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r);break}case"text":t.text!==e.get("text")&&e.set("text",t.text),t.containerId!==e.get("containerId")&&e.set("containerId",t.containerId),t.textAlign!==e.get("textAlign")&&e.set("textAlign",t.textAlign),t.verticalAlign!==e.get("verticalAlign")&&e.set("verticalAlign",t.verticalAlign);break;case"image":t.src!==e.get("src")&&e.set("src",t.src),t.naturalWidth!==e.get("naturalWidth")&&e.set("naturalWidth",t.naturalWidth),t.naturalHeight!==e.get("naturalHeight")&&e.set("naturalHeight",t.naturalHeight),t.scaleMode!==e.get("scaleMode")&&e.set("scaleMode",t.scaleMode);const s=t.crop?JSON.stringify(t.crop):null;s!==e.get("crop")&&e.set("crop",s),t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius),t.alt!==e.get("alt")&&e.set("alt",t.alt);break}}function wd(t){const e=[];for(const[,n]of t.entries()){const o=Be(n);o&&e.push(o)}return e.sort((n,o)=>n.sortOrder&&o.sortOrder?n.sortOrder<o.sortOrder?-1:n.sortOrder>o.sortOrder?1:0:0),e}function ti(t){const[e,n]=I.useState("disconnected"),[o,s]=I.useState([]),r=I.useRef(t);r.current=t;const i=I.useRef((t==null?void 0:t.awarenessThrottleMs)??100),l=I.useRef(0);I.useEffect(()=>{if(!t){Un(),Rn(),n("disconnected"),s([]);return}const{provider:h}=Jr(t);qr(t.syncDebounceMs??50);const u=jr(n),f=()=>{const y=Qr();s(Array.from(y.values()))};h.awareness.on("change",f);const p=B.subscribe((y,m)=>{y.selectedIds!==m.selectedIds&&Kn({selectedIds:y.selectedIds}),y.activeTool!==m.activeTool&&Kn({activeTool:y.activeTool})});return()=>{u(),p(),h.awareness.off("change",f),Rn(),Un(),n("disconnected"),s([])}},[t==null?void 0:t.serverUrl,t==null?void 0:t.roomName,t==null?void 0:t.user.id,t==null?void 0:t.syncDebounceMs]);const a=I.useCallback(h=>{const u=Date.now();u-l.current<i.current||(l.current=u,Kn({cursor:h}))},[]),c=I.useCallback(()=>{const h=$o();h&&h.disconnect()},[]),d=I.useCallback(()=>{const h=$o();h&&h.connect()},[]);return{isConnected:e==="connected",connectionStatus:e,peers:o,disconnect:c,reconnect:d,updateCursor:a}}const xd=[0,0,0,18,4.5,14.5,9,20,12,18,7.5,12.5,14,12.5,0,0],jo=12,ei="system-ui, -apple-system, sans-serif",ni=6,oi=4,si=14,ri=18,ie={ctx:null,cache:new Map};function kd(t){const e=ie.cache.get(t);if(e!==void 0)return e;if(!ie.ctx)try{const o=document.createElement("canvas");ie.ctx=o.getContext("2d")}catch{}let n;return ie.ctx?(ie.ctx.font=`${jo}px ${ei}`,n=ie.ctx.measureText(t).width):n=t.length*7,ie.cache.size>200&&ie.cache.clear(),ie.cache.set(t,n),n}function ii(t,e,n,o,s,r){const i=(t-n.x)*n.scale,l=(e-n.y)*n.scale;return i>=-r&&i<=o+r&&l>=-r&&l<=s+r}function Sd(t,e,n,o,s){const r=t.x+t.width/2,i=t.y+t.height/2,l=Math.sqrt(t.width*t.width+t.height*t.height)/2;return ii(r,i,e,n,o,s+l*e.scale)}const vd=({peers:t,viewport:e,stageWidth:n,stageHeight:o,elements:s})=>{const r=I.useMemo(()=>{const a=new Map;for(const c of s)a.set(c.id,c);return a},[s]),i=1/e.scale,l=150;return g.jsx(g.Fragment,{children:t.map(a=>{if(!a.cursor&&a.selectedIds.length===0)return null;const{user:c}=a;return g.jsxs(gt.Group,{children:[a.selectedIds.map(d=>{const h=r.get(d);if(!h||!Sd(h,e,n,o,l))return null;const u=3*i;return g.jsx(gt.Rect,{x:h.x+h.width/2,y:h.y+h.height/2,offsetX:h.width/2+u,offsetY:h.height/2+u,width:h.width+u*2,height:h.height+u*2,rotation:h.rotation??0,stroke:c.color,strokeWidth:2*i,dash:[6*i,4*i],cornerRadius:3*i,listening:!1,perfectDrawEnabled:!1},d)}),a.cursor&&ii(a.cursor.x,a.cursor.y,e,n,o,l)&&g.jsxs(gt.Group,{x:a.cursor.x,y:a.cursor.y,scaleX:i,scaleY:i,listening:!1,children:[g.jsx(gt.Line,{points:xd,fill:c.color,stroke:"#ffffff",strokeWidth:1,closed:!0,perfectDrawEnabled:!1}),g.jsx(gt.Rect,{x:si,y:ri,width:kd(c.name)+ni*2,height:jo+oi*2,fill:c.color,cornerRadius:4,listening:!1,perfectDrawEnabled:!1}),g.jsx(gt.Text,{x:si+ni,y:ri+oi,text:c.name,fontSize:jo,fontFamily:ei,fill:"#ffffff",listening:!1,perfectDrawEnabled:!1})]})]},c.id)})})},li=I.memo(vd);qe.showWarnings=!1;function ci(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}const ai=10,Ed=({elements:t,listening:e,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditTextId:i,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u,onGroupDragEnd:f})=>{const p=I.useRef(null);I.useEffect(()=>{const v=p.current;if(!v||t.length===0)return;const $=(window.devicePixelRatio||1)*Math.max(1,u),T=requestAnimationFrame(()=>{if(!p.current)return;const O=v.getClientRect({skipTransform:!0}),ot=8192,F=O.width*$,J=O.height*$;if(F>ot||J>ot||O.width<=0||O.height<=0){v.clearCache(),v.batchDraw();return}v.cache({pixelRatio:$}),v.batchDraw()});return()=>{cancelAnimationFrame(T),v.clearCache()}},[t,u,i]);const{ungrouped:y,groups:m}=I.useMemo(()=>{var $;const v=[],D=new Map;for(const T of t)if(($=T.groupIds)!=null&&$.length){const O=T.groupIds[T.groupIds.length-1];D.has(O)||D.set(O,[]),D.get(O).push(T)}else v.push(T);return{ungrouped:v,groups:D}},[t]),W=I.useCallback(v=>{var D;(D=p.current)==null||D.clearCache()},[]);return g.jsxs(gt.Layer,{ref:p,listening:e,children:[y.map(v=>g.jsx(Ln,{element:v,isSelected:!1,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===v.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},v.id)),Array.from(m.entries()).map(([v,D])=>{const $=D.some(T=>T.isLocked);return g.jsx(gt.Group,{draggable:!$,onDragStart:W,onDragEnd:T=>{const O=T.target.x(),ot=T.target.y();T.target.x(0),T.target.y(0),f==null||f(v,O,ot)},children:D.map(T=>g.jsx(Ln,{element:T,isSelected:!1,isGrouped:!0,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===T.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},T.id))},v)})]})},Wd=I.memo(Ed,(t,e)=>!(t.elements!==e.elements||t.listening!==e.listening||t.autoEditTextId!==e.autoEditTextId||t.gridSnap!==e.gridSnap||t.viewportScale!==e.viewportScale)),Td=({element:t,scale:e})=>{const n=20/e,o=n/24;return g.jsxs(gt.Group,{x:t.x-n/2,y:t.y-n/2,listening:!1,children:[g.jsx(gt.Rect,{width:n,height:n,fill:"#ff9500",cornerRadius:n/4,opacity:.9}),g.jsx(gt.Path,{x:n*.12,y:n*.08,data:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z",fill:"white",scaleX:o*.78,scaleY:o*.78,listening:!1})]})},di=I.forwardRef((t,e)=>{const{initialElements:n,elements:o,onChange:s,onSelectionChange:r,onElementCreate:i,onElementDelete:l,onElementDoubleClick:a,width:c="100%",height:d="100%",tools:h,defaultStyle:u,showToolbar:f=!0,toolbarPosition:p="bottom",defaultTool:y,showStylePanel:m=!0,showStatusBar:W=!0,showGrid:v=!1,enableShortcuts:D=!0,theme:$,readOnly:T=!1,className:O,contextMenuItems:ot,renderContextMenu:F,collaboration:J,workerConfig:Y}=t,Q={...zr,...$},M=I.useMemo(()=>({elbowWorkerConfig:Y!=null&&Y.disabled?{disabled:!0}:Y!=null&&Y.elbowWorkerUrl?{url:Y.elbowWorkerUrl}:void 0,exportWorkerConfig:Y!=null&&Y.disabled?{disabled:!0}:Y!=null&&Y.exportWorkerUrl?{url:Y.exportWorkerUrl}:void 0}),[Y]),k=B(),{elements:C,selectedIds:w,activeTool:S,currentStyle:Z,viewport:G,showGrid:U,isDrawing:X,setIsDrawing:L,setDrawStart:at,drawStart:tt,addElement:E,updateElement:V,setSelectedIds:dt,clearSelection:R,setActiveTool:K,setViewport:et,deleteElements:Ct,pushHistory:bt,setElements:rt,setCurrentStyle:st,undo:pt,redo:A,toggleGrid:lt}=k,mt=I.useMemo(()=>Rs(w),[w]),{peers:j,updateCursor:Dt}=ti(J??null),Gt=I.useRef(null),Ot=I.useRef(null),Ge=I.useRef(null),jt=dn(),mn=jt.isEditing,[Nt,vt]=I.useState({width:800,height:600}),[Ft,Ut]=I.useState(null),[ou,Gi]=I.useState(null),su=I.useRef(null),[ru,Di]=I.useState(null),[Xi,$e]=I.useState(null),[Re,os]=I.useState(null),[le,je]=I.useState(null),[iu,ss]=I.useState([]),rs=I.useRef(!1),to=I.useRef(!1),[De,is]=I.useState(!1),Ae=I.useRef(!1),{isDraggingPoint:ls,elementId:Li}=jt,Fi=I.useRef([]),Qt=I.useMemo(()=>{let b=null;for(let P=0;P<C.length;P++){const nt=C[P];if(nt.type!=="line"&&nt.type!=="arrow"){b&&(b[P]=nt);continue}const it=nt;if(!it.startBinding&&!it.endBinding){b&&(b[P]=nt);continue}if(ls&&Li===nt.id){b&&(b[P]=nt);continue}const N=Se(it,C);N?(b||(b=C.slice(0,P)),b[P]={...it,...N}):b&&(b[P]=nt)}const _=b??C,z=Fi.current;if(_.length===z.length){let P=!0;for(let nt=0;nt<_.length;nt++)if(_[nt]!==z[nt]){P=!1;break}if(P)return z}return Fi.current=_,_},[C,ls,Li]),cs=I.useMemo(()=>{const b=new Map;for(const _ of Qt)b.set(_.id,_);return b},[Qt]),eo=ud(Qt,G,Nt.width,Nt.height,w),lu=Hr(G.scale),as=I.useRef([]),ds=I.useRef([]),{staticElements:cu,interactiveElements:au}=I.useMemo(()=>{var it,N;let b=Re?new Set([...mt,Re]):mt;if(b.size>0){const H=new Set(b);for(const q of eo)if(H.has(q.id)&&((it=q.groupIds)!=null&&it.length)){const ht=q.groupIds[q.groupIds.length-1];for(const ut of eo)(N=ut.groupIds)!=null&&N.includes(ht)&&H.add(ut.id)}H.size!==b.size&&(b=H)}const _=[],z=[];for(const H of eo)b.has(H.id)?z.push(H):_.push(H);const P=ci(_,as.current)?as.current:_,nt=ci(z,ds.current)?ds.current:z;return as.current=P,ds.current=nt,{staticElements:P,interactiveElements:nt}},[eo,mt,Re]),{visibleElements:du}=Or(cu,{batchSize:500,threshold:500,enabled:!0});ad(D&&!T,Ot),I.useEffect(()=>{u&&st({...wn,...u})},[]),I.useEffect(()=>{n&&n.length>0&&(rt(n),bt())},[]),I.useEffect(()=>{v!==U&&lt()},[]),I.useEffect(()=>{y&&K(y)},[]),I.useEffect(()=>{o&&rt(o)},[o,rt]);const Vi=I.useRef(C);I.useEffect(()=>{s&&C!==Vi.current&&s(C),Vi.current=C},[C,s]),I.useEffect(()=>{r&&r(w)},[w,r]),I.useEffect(()=>{const b=dn.getState();if(!b.isEditing)return;if(S!=="select"){b.exitEditMode();return}if(w.length!==1||w[0]!==b.elementId){b.exitEditMode();return}const _=C.find(z=>z.id===w[0]);_&&(_.type==="line"||_.type==="arrow")&&(!b.isEditing||b.elementId!==_.id)&&b.enterEditMode(_.id)},[w,S,C]),I.useEffect(()=>{const b=z=>{z.key==="Shift"&&(rs.current=!0)},_=z=>{z.key==="Shift"&&(rs.current=!1)};return window.addEventListener("keydown",b),window.addEventListener("keyup",_),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",_)}},[]),I.useEffect(()=>{const b=P=>{const nt=P.target.tagName;nt==="INPUT"||nt==="TEXTAREA"||nt==="SELECT"||P.code==="Space"&&!Ae.current&&(P.preventDefault(),Ae.current=!0,is(!0))},_=P=>{P.code==="Space"&&(Ae.current=!1,is(!1))},z=()=>{Ae.current&&(Ae.current=!1,is(!1))};return window.addEventListener("keydown",b),window.addEventListener("keyup",_),window.addEventListener("blur",z),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",_),window.removeEventListener("blur",z)}},[]),I.useEffect(()=>{const b=Ot.current;if(!b||T)return;const _=P=>{P.preventDefault(),P.stopPropagation(),P.dataTransfer&&(P.dataTransfer.dropEffect="copy")},z=async P=>{if(P.preventDefault(),P.stopPropagation(),!P.dataTransfer)return;const nt=Zo(P.dataTransfer);if(nt.length===0)return;const it=b.getBoundingClientRect();Gt.current;const N=B.getState().viewport,H=(P.clientX-it.left-N.x)/N.scale,q=(P.clientY-it.top-N.y)/N.scale,ht=B.getState().currentStyle;for(const ut of nt)try{const ft=await Zn(ut),yt=await hn(ft),xt=_n(ft,yt.naturalWidth,yt.naturalHeight,H,q,{...ht});E(xt),i==null||i(xt),dt([xt.id]),bt()}catch{}K("select")};return b.addEventListener("dragover",_),b.addEventListener("drop",z),()=>{b.removeEventListener("dragover",_),b.removeEventListener("drop",z)}},[T,E,dt,bt,K,i]),I.useEffect(()=>{if(T)return;const b=_=>{const z=_.target.tagName;if(z==="INPUT"||z==="TEXTAREA"||z==="SELECT")return;const P=_o(_);if(P.file||P.imgUrl)_.preventDefault(),_.stopPropagation(),(async()=>{try{const nt=await Ar(P);if(!nt)return;const it=await hn(nt),N=B.getState().viewport,H=Ot.current,q=H==null?void 0:H.getBoundingClientRect(),ht=q?(q.width/2-N.x)/N.scale:400,ut=q?(q.height/2-N.y)/N.scale:300,ft=B.getState().currentStyle,yt=_n(nt,it.naturalWidth,it.naturalHeight,ht,ut,{...ft});E(yt),i==null||i(yt),dt([yt.id]),bt(),K("select")}catch{}})();else{_.preventDefault(),_.stopPropagation();const nt=Ho();if(nt.length===0)return;const it=20,{clones:N,selectedCloneIds:H}=En(nt,nt,it);N.forEach(q=>E(q)),dt(H.length>0?H:N.map(q=>q.id)),bt(),yn(nt.map(q=>({...q,x:q.x+it,y:q.y+it})))}};return window.addEventListener("paste",b,!0),()=>window.removeEventListener("paste",b,!0)},[T,E,dt,bt,K,i]),I.useEffect(()=>{const b=Ot.current;if(!b)return;const _=new ResizeObserver(z=>{for(const P of z){const{width:nt,height:it}=P.contentRect;vt({width:Math.floor(nt),height:Math.floor(it)})}});return _.observe(b),()=>_.disconnect()},[]);const uu=I.useCallback(()=>{const b=Gt.current;if(!b)return null;const _=b.getPointerPosition();return _?{x:(_.x-G.x)/G.scale,y:(_.y-G.y)/G.scale}:null},[G]),gu=I.useCallback(b=>U?{x:At(b.x,xe),y:At(b.y,xe)}:b,[U]),no=I.useRef(null);no.current={elements:C,selectedIds:w,activeTool:S,currentStyle:Z,isDrawing:X,drawStart:tt,showGrid:U,addElement:E,updateElement:V,deleteElements:Ct,setSelectedIds:dt,clearSelection:R,setActiveTool:K,setIsDrawing:L,setDrawStart:at,pushHistory:bt,getPointerPos:uu,snapPos:gu,currentElementIdRef:Ge,shiftKeyRef:rs,startBindingRef:su,setSnapTarget:Gi,selectionBox:Ft,setSelectionBox:Ut,setAutoEditTextId:$e,linearEdit:{isEditing:jt.isEditing,elementId:jt.elementId,exitEditMode:jt.exitEditMode,enterEditMode:jt.enterEditMode},onElementCreate:i,onElementDelete:l};const Pi=I.useCallback(b=>{if(T||Ae.current)return;if(b.evt.button===2){to.current=!0,le&&je(null);return}to.current=!1;const z=no.current,P=z.getPointerPos();if(!P||(le&&je(null),z.activeTool==="hand"||De))return;const nt=fn(z.activeTool);nt==null||nt.onMouseDown(b,P,z),Ge.current&&os(Ge.current)},[T,le,De]),Yi=I.useCallback(b=>{if(Ae.current||T)return;const _=no.current,z=_.getPointerPos();if(!z)return;Dt(z);const P=fn(_.activeTool);P==null||P.onMouseMove(b,z,_)},[T,Dt]),us=I.useRef(null),Hi=I.useRef(Yi);Hi.current=Yi;const Oi=I.useMemo(()=>{var _,z;(z=(_=us.current)==null?void 0:_.cancel)==null||z.call(_);const b=$s(P=>{Hi.current(P)});return us.current=b,b},[]);I.useEffect(()=>()=>{var b,_;(_=(b=us.current)==null?void 0:b.cancel)==null||_.call(b),Tr(),Kr()},[]);const Ni=I.useCallback(()=>{const b=no.current,_=fn(b.activeTool);_==null||_.onMouseUp(b),requestAnimationFrame(()=>{os(null)})},[os]),hu=I.useCallback(b=>{b.evt.preventDefault();const _=Gt.current;if(!_)return;const z=_.getPointerPosition();if(!z)return;const P=1.05,nt=b.evt.deltaY>0?-1:1,it=Math.min(Le,Math.max(Xe,nt>0?G.scale*P:G.scale/P));et(Wn({viewport:G,point:z,targetScale:it}))},[G,et]),fu=I.useCallback(b=>{S!=="hand"&&!Ae.current&&!De||et({x:b.target.x(),y:b.target.y()})},[S,et,De]),gs=I.useCallback(b=>{var q;const{activeTool:_,elements:z,selectedIds:P,setSelectedIds:nt}=B.getState();if(_!=="select"||T)return;if(to.current){to.current=!1;return}const it=z.find(ht=>ht.id===b),N=it&&(it.type==="line"||it.type==="arrow"),H=dn.getState();if(N?(!H.isEditing||H.elementId!==b)&&H.enterEditMode(b):H.isEditing&&H.exitEditMode(),(q=it==null?void 0:it.groupIds)!=null&&q.length){const ht=it.groupIds[it.groupIds.length-1],ut=z.filter(ft=>{var yt;return(yt=ft.groupIds)==null?void 0:yt.includes(ht)}).map(ft=>ft.id);nt(ut)}else nt([b])},[T]),oo=I.useRef(null),hs=I.useRef(!1),fs=I.useRef(!1),we=I.useRef(null),Ui=I.useCallback(()=>{hs.current=!1;const b=oo.current;if(!b||b.size===0)return;const _=Array.from(b,([z,P])=>({id:z,updates:P}));b.clear(),B.getState().batchUpdateElements(_)},[]),so=I.useRef(new Set),ps=I.useCallback((b,_)=>{if(T)return;we.current===null&&(we.current=qe.pixelRatio,qe.pixelRatio=1);const{elements:z,selectedIds:P}=B.getState();if(P.length>ai){fs.current=!0;return}fs.current=!1;const nt=z.find(it=>it.id===b);if(nt&&(nt.type==="line"||nt.type==="arrow")&&!so.current.has(b)){const it=nt;if(it.startBinding||it.endBinding){so.current.add(b);const N={},H=it.type;if(it.startBinding){const q=B.getState().elements;ve(b,H,it.startBinding,null,q,B.getState().updateElement),N.startBinding=null}if(it.endBinding){const q=B.getState().elements;ve(b,H,it.endBinding,null,q,B.getState().updateElement),N.endBinding=null}B.getState().updateElement(b,{..._,...N});return}}oo.current||(oo.current=new Map),oo.current.set(b,_),hs.current||(hs.current=!0,queueMicrotask(Ui))},[T,Ui]),Ki=I.useCallback((b,_)=>{const{elements:z,selectedIds:P}=B.getState();if(P.length>1)return null;const nt=new Set(P),it=cd(_,z,nt);return ss(it.guides),it.x!==void 0||it.y!==void 0?{x:it.x??_.x,y:it.y??_.y}:null},[]),ro=I.useRef(null),ys=I.useRef(!1),zi=I.useCallback(()=>{ys.current=!1;const b=ro.current;if(!b||b.size===0)return;const _=Array.from(b);b.clear(),fs.current=!1,B.getState().batchUpdateElements(_.map(([H,q])=>({id:H,updates:q}))),ss([]);const P=B.getState().elements,nt=new Map;for(const H of P)nt.set(H.id,H);const it=[],N=new Set;for(const[H]of _){so.current.delete(H);const q=ln(H,P);for(const ut of q){if(N.has(ut.id))continue;N.add(ut.id);const ft=nt.get(ut.id);if(!ft)continue;const yt=Se(ft,P);yt&&it.push({id:ft.id,updates:yt})}const ht=nt.get(H);if(ht!=null&&ht.boundElements&&["rectangle","ellipse","diamond","image"].includes(ht.type))for(const ft of ht.boundElements){if(ft.type!=="text")continue;const yt=nt.get(ft.id);if(!yt)continue;const xt=Math.max(20,ht.width-8);let wt;yt.verticalAlign==="top"?wt=ht.y+4:yt.verticalAlign==="bottom"?wt=ht.y+ht.height-yt.height-4:wt=ht.y+(ht.height-yt.height)/2,it.push({id:ft.id,updates:{x:ht.x+4,y:wt,width:xt}})}}it.length>0&&B.getState().batchUpdateElements(it),B.getState().pushHistory(),we.current!==null&&(qe.pixelRatio=we.current,we.current=null)},[]),Is=I.useCallback((b,_)=>{if(T)return;const{selectedIds:z}=B.getState();if(z.length>ai){ro.current||(ro.current=new Map),ro.current.set(b,_),ys.current||(ys.current=!0,queueMicrotask(zi));return}V(b,_),ss([]),so.current.delete(b);const P=B.getState().elements,nt=new Map;for(const H of P)nt.set(H.id,H);const it=ln(b,P);for(const H of it){const q=nt.get(H.id);if(!q)continue;const ht=Se(q,P);ht&&V(q.id,ht)}const N=nt.get(b);if(N!=null&&N.boundElements&&["rectangle","ellipse","diamond","image"].includes(N.type))for(const q of N.boundElements){if(q.type!=="text")continue;const ht=nt.get(q.id);if(!ht)continue;const ut=Math.max(20,N.width-8);let ft;ht.verticalAlign==="top"?ft=N.y+4:ht.verticalAlign==="bottom"?ft=N.y+N.height-ht.height-4:ft=N.y+(N.height-ht.height)/2,V(q.id,{x:N.x+4,y:ft,width:ut})}if((N==null?void 0:N.type)==="text"){const H=N;if(H.containerId){const q=nt.get(H.containerId);if(q&&["rectangle","ellipse","diamond","image"].includes(q.type)){const ut=H.height+8;if(q.height<ut){V(q.id,{height:ut});const ft=B.getState().elements;for(const yt of ln(q.id,ft)){const xt=ft.find(Et=>Et.id===yt.id);if(!xt)continue;const wt=Se(xt,ft);wt&&V(xt.id,wt)}}}}}bt(),we.current!==null&&(qe.pixelRatio=we.current,we.current=null)},[V,bt,T,zi]),pu=I.useCallback((b,_,z)=>{if(T||_===0&&z===0)return;const P=B.getState(),it=P.elements.filter(yt=>{var xt;return(xt=yt.groupIds)==null?void 0:xt.includes(b)});if(it.length===0)return;const N=it.map(yt=>({id:yt.id,updates:{x:yt.x+_,y:yt.y+z}}));P.batchUpdateElements(N);const H=B.getState().elements,q=new Map;for(const yt of H)q.set(yt.id,yt);const ht=new Set(it.map(yt=>yt.id)),ut=[],ft=new Set;for(const yt of it){const xt=ln(yt.id,H);for(const Et of xt){if(ft.has(Et.id)||(ft.add(Et.id),ht.has(Et.id)))continue;const Bt=q.get(Et.id);if(!Bt)continue;const kt=Se(Bt,H);kt&&ut.push({id:Bt.id,updates:kt})}const wt=q.get(yt.id);if(wt!=null&&wt.boundElements&&["rectangle","ellipse","diamond","image"].includes(wt.type))for(const Bt of wt.boundElements){if(Bt.type!=="text"||ht.has(Bt.id))continue;const kt=q.get(Bt.id);if(!kt)continue;const Vt=Math.max(20,wt.width-8);let Xt;kt.verticalAlign==="top"?Xt=wt.y+4:kt.verticalAlign==="bottom"?Xt=wt.y+wt.height-kt.height-4:Xt=wt.y+(wt.height-kt.height)/2,ut.push({id:Bt.id,updates:{x:wt.x+4,y:Xt,width:Vt}})}}ut.length>0&&B.getState().batchUpdateElements(ut),P.pushHistory()},[T]),Cs=I.useCallback(b=>{var q,ht;if(T)return;const{activeTool:_,elements:z,currentStyle:P,addElement:nt,updateElement:it,setSelectedIds:N}=B.getState();if(_!=="select")return;const H=z.find(ut=>ut.id===b);if(H&&(a==null?void 0:a(b,H))!==!0){if(H.type==="line"||H.type==="arrow"){const ut=(q=H.boundElements)==null?void 0:q.find(Qe=>Qe.type==="text");if(ut){N([ut.id]),$e(ut.id);return}const ft=Pt(),yt=H,xt=yt.points,wt={x:xt[0],y:xt[1]},Et={x:xt[xt.length-2],y:xt[xt.length-1]};let Bt,kt;if(yt.lineType==="curved"){const Qe=Jt(wt,Et,yt.curvature??zt),An=Ye(wt,Qe,Et,.5);Bt=yt.x+An.x,kt=yt.y+An.y}else Bt=yt.x+(wt.x+Et.x)/2,kt=yt.y+(wt.y+Et.y)/2;const Vt={id:ft,type:"text",x:Bt,y:kt,width:100,height:30,rotation:0,style:{...P,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:b,textAlign:"center",verticalAlign:"middle"};nt(Vt),i==null||i(Vt);const Xt=H.boundElements??[];it(b,{boundElements:[...Xt,{id:ft,type:"text"}]}),N([ft]),$e(ft);return}if(H.type==="rectangle"||H.type==="ellipse"||H.type==="diamond"||H.type==="image"){const ut=(ht=H.boundElements)==null?void 0:ht.find(wt=>wt.type==="text");if(ut){N([ut.id]),$e(ut.id);return}const ft=Pt(),yt={id:ft,type:"text",x:H.x,y:H.y,width:H.width,height:30,rotation:0,style:{...P,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:b,textAlign:"center",verticalAlign:"middle"};nt(yt),i==null||i(yt);const xt=H.boundElements??[];it(b,{boundElements:[...xt,{id:ft,type:"text"}]}),N([ft]),$e(ft);return}}},[T,a,i]),yu=I.useCallback((b,_)=>{if(T)return;const{elements:z,updateElement:P,pushHistory:nt}=B.getState(),it=z.find(N=>N.id===b);if(P(b,_),it&&(_.startBinding!==void 0||_.endBinding!==void 0)){const N=it.type;if(_.startBinding!==void 0){const H=B.getState().elements;ve(b,N,it.startBinding,_.startBinding??null,H,B.getState().updateElement)}if(_.endBinding!==void 0){const H=B.getState().elements;ve(b,N,it.endBinding,_.endBinding??null,H,B.getState().updateElement)}}nt()},[T]),Iu=I.useCallback((b,_)=>{T||B.getState().updateElement(b,_)},[T]),Cu=I.useCallback(b=>{Gi(b)},[]),Ji=I.useCallback(b=>{Di(b)},[]),$i=I.useCallback((b,_)=>{if(Di(null),$e(null),_){const{elements:z,updateElement:P,deleteElements:nt,pushHistory:it}=B.getState(),N=z.find(H=>H.id===b);if((N==null?void 0:N.type)==="text"&&N.containerId){const H=N.containerId,q=z.find(ht=>ht.id===H);q!=null&&q.boundElements&&P(H,{boundElements:q.boundElements.filter(ht=>ht.id!==b)})}nt([b]),l==null||l([b])}else B.getState().pushHistory()},[l]),bu=I.useCallback(b=>{var nt,it;if(T)return;b.preventDefault();const _=Ot.current;if(!_)return;const z=_.getBoundingClientRect(),P=Gt.current;if(P){const N=P.getPointerPosition(),H=(N==null?void 0:N.x)??b.clientX-z.left,q=(N==null?void 0:N.y)??b.clientY-z.top,ht=B.getState().viewport,ut=(H-ht.x)/ht.scale,ft=(q-ht.y)/ht.scale,{elements:yt,selectedIds:xt,setSelectedIds:wt}=B.getState();let Et=null;for(let Bt=yt.length-1;Bt>=0;Bt--){const kt=yt[Bt];if(kt.type==="text"&&kt.containerId)continue;let Vt=kt.x,Xt=kt.y,Qe=kt.width,An=kt.height;if((kt.type==="arrow"||kt.type==="line")&&"points"in kt){const bs=kt.points,ms=[],As=[];for(let lo=0;lo<bs.length;lo+=2)ms.push(kt.x+bs[lo]),As.push(kt.y+bs[lo+1]);Vt=Math.min(...ms),Xt=Math.min(...As),Qe=Math.max(...ms)-Vt,An=Math.max(...As)-Xt}const io=Math.max(4,((nt=kt.style)==null?void 0:nt.strokeWidth)??2);if(ut>=Vt-io&&ut<=Vt+Qe+io&&ft>=Xt-io&&ft<=Xt+An+io){Et=kt;break}}if(Et&&!xt.includes(Et.id))if((it=Et.groupIds)!=null&&it.length){const Bt=Et.groupIds[Et.groupIds.length-1],kt=yt.filter(Vt=>{var Xt;return(Xt=Vt.groupIds)==null?void 0:Xt.includes(Bt)}).map(Vt=>Vt.id);wt(kt)}else wt([Et.id])}je({x:b.clientX-z.left,y:b.clientY-z.top})},[T]),mu=I.useMemo(()=>{var it;const b=w.length>0,z=navigator.platform.includes("Mac")?"⌘":"Ctrl+",P=[];P.push({label:"Copy",shortcut:`${z}C`,disabled:!b,action:()=>{b&&yn(Us(w,C))}}),P.push({label:"Paste",shortcut:`${z}V`,disabled:!Na(),action:()=>{const N=Ho();if(N.length===0)return;const H=20,{clones:q,selectedCloneIds:ht}=En(N,N,H);q.forEach(ut=>E(ut)),dt(ht.length>0?ht:q.map(ut=>ut.id)),bt(),yn(N.map(ut=>({...ut,x:ut.x+H,y:ut.y+H})))}}),P.push({label:"Duplicate",shortcut:`${z}D`,disabled:!b,action:()=>{b&&k.duplicateElements(w)}}),P.push({label:"Delete",shortcut:"Del",disabled:!b,divider:!0,action:()=>{b&&(Ct(w),l==null||l(w))}}),P.push({label:"Bring to Front",shortcut:`${z}⇧]`,disabled:!b,divider:!0,action:()=>{b&&k.bringToFront(w)}}),P.push({label:"Send to Back",shortcut:`${z}⇧[`,disabled:!b,action:()=>{b&&k.sendToBack(w)}});let nt=!1;if(w.length>=2){const N=C.filter(ut=>w.includes(ut.id)),H=new Set(N.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length}).map(ut=>ut.groupIds[ut.groupIds.length-1]));N.every(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length})&&H.size===1||(P.push({label:"Group",shortcut:`${z}G`,divider:!0,action:()=>k.groupElements(w)}),nt=!0)}if(b){const N=C.filter(q=>w.includes(q.id));if(N.some(q=>{var ht;return(ht=q.groupIds)==null?void 0:ht.length})){const q=new Set;for(const ut of N)(it=ut.groupIds)!=null&&it.length&&q.add(ut.groupIds[ut.groupIds.length-1]);const ht=C.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.some(yt=>q.has(yt))}).map(ut=>ut.id);P.push({label:"Ungroup",shortcut:`${z}⇧G`,divider:!nt,action:()=>k.ungroupElements(ht)})}}if(P.push({label:"Select All",shortcut:`${z}A`,divider:!0,action:()=>dt(C.map(N=>N.id))}),b){const N=C.filter(ht=>w.includes(ht.id)),H=N.every(ht=>ht.isLocked),q=N.some(ht=>ht.isLocked);P.push({label:H?"Unlock":q?"Unlock All":"Lock",shortcut:`${z}⇧L`,divider:!0,action:()=>k.toggleLockElements(w)})}if(b){const N=new Set(["rectangle","ellipse","diamond"]),H=C.filter(q=>w.includes(q.id)&&N.has(q.type));if(H.length>0){const q=new Set(H.map(ft=>ft.type)),ut=[{label:"Rectangle",type:"rectangle"},{label:"Ellipse",type:"ellipse"},{label:"Diamond",type:"diamond"}].filter(ft=>!q.has(ft.type)||q.size>1);ut.length>0&&ut.forEach((ft,yt)=>{P.push({label:`Convert to ${ft.label}`,divider:yt===0,action:()=>k.convertElementType(H.map(xt=>xt.id),ft.type)})})}}if(ot){const N=typeof ot=="function"?ot({selectedIds:w,elements:C,position:le??{x:0,y:0},close:()=>je(null)}):ot;if(N.length>0){P.push({...N[0],divider:!0});for(let H=1;H<N.length;H++)P.push(N[H])}}return P},[w,C,k,E,Ct,dt,bt,l,ot,le]);I.useImperativeHandle(e,()=>({getElements:()=>B.getState().elements,setElements:b=>{rt(b),bt()},addElement:b=>{E(b)},deleteElements:b=>{Ct(b)},getSelectedIds:()=>B.getState().selectedIds,setSelectedIds:b=>{dt(b)},clearSelection:()=>{R()},setActiveTool:b=>{K(b)},getActiveTool:()=>B.getState().activeTool,undo:()=>{pt()},redo:()=>{A()},zoomTo:b=>{et({scale:Math.min(Le,Math.max(Xe,b))})},resetView:()=>{et({x:0,y:0,scale:1})},scrollToElement:(b,_)=>{const z=B.getState().elements.find(wt=>wt.id===b);if(!z)return;const P=Ot.current;if(!P)return;const nt=P.getBoundingClientRect(),it=nt.width,N=nt.height,H=(_==null?void 0:_.zoom)??Math.max(B.getState().viewport.scale,1),q=Math.min(Le,Math.max(Xe,H)),ht=z.x+(z.width??0)/2,ut=z.y+(z.height??0)/2,ft=it/2-ht*q,yt=N/2-ut*q,xt={x:ft,y:yt,scale:q};_!=null&&_.animate?Ee(B.getState().viewport,xt,et):et(xt)},zoomToFit:(b,_)=>{const z=Ot.current;if(!z)return;const P=z.getBoundingClientRect(),nt=P.width,it=P.height;B.getState().zoomToFit(nt,it,b,{padding:_==null?void 0:_.padding,maxZoom:_==null?void 0:_.maxZoom,animate:_==null?void 0:_.animate})},exportPNG:()=>{var b;return((b=Gt.current)==null?void 0:b.toDataURL({pixelRatio:2}))??null},exportJSON:()=>JSON.stringify(B.getState().elements,null,2),exportSVG:()=>Ne(B.getState().elements),importJSON:b=>{try{const _=JSON.parse(b);Array.isArray(_)&&(rt(_),bt())}catch{}},getStage:()=>Gt.current}));const Au=()=>{var _;if(T)return"default";if(De||S==="hand")return"grab";const b=fn(S);return((_=b==null?void 0:b.getCursor)==null?void 0:_.call(b))??"default"},wu=h?co.filter(b=>h.includes(b.type)):co,xu=m&&!T&&(!["hand","select","eraser"].includes(S)||S==="select"&&w.length>0),Ri=!De&&["select","eraser","image"].includes(S);return g.jsx(Xo.Provider,{value:M,children:g.jsxs("div",{ref:Ot,className:O,onContextMenu:bu,onMouseLeave:()=>Dt(null),style:{position:"relative",width:c,height:d,overflow:"hidden",background:Q.canvasBackground},children:[f&&!T&&p!=="hidden"&&g.jsx(Za,{visibleTools:wu,theme:Q,position:p}),xu&&g.jsx(Ya,{theme:Q}),g.jsx("div",{style:{cursor:Au(),position:"absolute",top:0,left:0,right:0,bottom:0},children:g.jsxs(gt.Stage,{ref:Gt,width:Nt.width,height:Nt.height,x:G.x,y:G.y,scaleX:G.scale,scaleY:G.scale,draggable:(S==="hand"||De)&&!T,onMouseDown:Pi,onMouseMove:Oi,onMouseUp:Ni,onWheel:hu,onDragEnd:fu,onTouchStart:Pi,onTouchMove:Oi,onTouchEnd:Ni,children:[U&&g.jsx(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(aa,{width:Nt.width,height:Nt.height,viewport:G,gridColor:Q.gridColor})}),g.jsx(Wd,{elements:du,listening:Ri,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,autoEditTextId:Xi,onTextEditStart:Ji,onTextEditEnd:$i,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:Ki,viewportScale:G.scale,onGroupDragEnd:pu}),g.jsxs(gt.Layer,{listening:Ri,children:[au.filter(b=>b.id!==Re).map(b=>g.jsx(Ln,{element:b,isSelected:!0,isEditing:mn&&jt.elementId===b.id,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,autoEditText:Xi===b.id,onTextEditStart:Ji,onTextEditEnd:$i,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:Ki,viewportScale:lu},b.id)),S==="select"&&!T&&(()=>{const b=w.filter(_=>{const z=cs.get(_);return!(!z||z.type==="line"||z.type==="arrow"||z.type==="text"&&z.containerId||_===ru)});return b.length===0?null:g.jsx(la,{selectedIds:b,selectionColor:Q.selectionColor})})(),mn&&(()=>{const b=cs.get(jt.elementId??"");return b?g.jsx(Sa,{element:b,allElements:Qt,onPointsChange:yu,onPointDragMove:Iu,onSnapTargetChange:Cu,color:Q.selectionColor}):null})()]}),Re&&(()=>{const b=cs.get(Re);return b?g.jsx(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(Ln,{element:b,isSelected:!1,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,allElements:Qt,gridSnap:U?xe:void 0,viewportScale:G.scale},b.id)}):null})(),g.jsxs(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:[g.jsx(ua,{box:Ft,selectionColor:Q.selectionColor,viewportScale:G.scale}),g.jsx(fa,{elements:Qt,snapTarget:ou,visible:(S==="line"||S==="arrow"||ls)&&!T,color:Q.selectionColor,viewportScale:G.scale}),iu.map((b,_)=>b.orientation==="v"?g.jsx(gt.Line,{points:[b.position,b.start,b.position,b.end],stroke:Q.selectionColor,strokeWidth:1/G.scale,dash:[4/G.scale,4/G.scale],listening:!1,perfectDrawEnabled:!1},`ag-${_}`):g.jsx(gt.Line,{points:[b.start,b.position,b.end,b.position],stroke:Q.selectionColor,strokeWidth:1/G.scale,dash:[4/G.scale,4/G.scale],listening:!1,perfectDrawEnabled:!1},`ag-${_}`)),Qt.filter(b=>b.isLocked&&mt.has(b.id)).map(b=>g.jsx(Td,{element:b,scale:G.scale},`lock-${b.id}`)),j.length>0&&g.jsx(li,{peers:j,viewport:G,stageWidth:Nt.width,stageHeight:Nt.height,elements:Qt})]})]})}),le&&(F?F({selectedIds:w,elements:C,position:le,close:()=>je(null)}):g.jsx(Oa,{x:le.x,y:le.y,items:mu,onClose:()=>je(null),theme:Q})),W&&g.jsx(Bd,{theme:Q})]})})});di.displayName="FlowCanvas";const Bd=I.memo(({theme:t})=>{const e=B(s=>s.elements.length),n=B(s=>s.activeTool),o=B(s=>s.selectedIds.length);return g.jsxs("div",{style:{position:"absolute",bottom:16,left:12,zIndex:50,display:"flex",alignItems:"center",gap:10,background:t.toolbarBg,backdropFilter:"blur(8px)",boxShadow:"0 1px 3px rgba(0,0,0,0.08)",borderRadius:8,padding:"4px 12px",border:`1px solid ${t.toolbarBorder}`,fontSize:11,color:t.mutedTextColor,userSelect:"none"},children:[g.jsxs("span",{children:["Tool: ",g.jsx("strong",{style:{color:t.textColor,textTransform:"capitalize"},children:n})]}),g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Elements: ",g.jsx("strong",{style:{color:t.textColor},children:e})]}),o>0&&g.jsxs(g.Fragment,{children:[g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Selected: ",g.jsx("strong",{style:{color:t.activeToolColor},children:o})]})]})]})}),ui={rectangle:0,ellipse:1,diamond:2,line:3,arrow:4,freedraw:5,text:6,image:7};class gi{constructor(e=1024){ct(this,"_data");ct(this,"_capacity",0);ct(this,"_indexMap",new Map);this._data=this._allocate(e),this._capacity=e}get length(){return this._data.length}get data(){return this._data}_allocate(e){return{ids:new Array(e),x:new Float64Array(e),y:new Float64Array(e),w:new Float64Array(e),h:new Float64Array(e),types:new Uint8Array(e),length:0}}_ensureCapacity(e){if(e<=this._capacity)return;const n=Math.max(e,this._capacity*2),o=this._data,s=this._allocate(n);s.x.set(o.x.subarray(0,o.length)),s.y.set(o.y.subarray(0,o.length)),s.w.set(o.w.subarray(0,o.length)),s.h.set(o.h.subarray(0,o.length)),s.types.set(o.types.subarray(0,o.length));for(let r=0;r<o.length;r++)s.ids[r]=o.ids[r];s.length=o.length,this._data=s,this._capacity=n}rebuild(e){const n=e.length;this._ensureCapacity(n),this._indexMap.clear();const{ids:o,x:s,y:r,w:i,h:l,types:a}=this._data;for(let c=0;c<n;c++){const d=e[c];o[c]=d.id,s[c]=d.x,r[c]=d.y,i[c]=d.width,l[c]=d.height,a[c]=ui[d.type]??0,this._indexMap.set(d.id,c)}this._data.length=n}updateElement(e){const n=this._indexMap.get(e.id);return n===void 0?!1:(this._data.x[n]=e.x,this._data.y[n]=e.y,this._data.w[n]=e.width,this._data.h[n]=e.height,!0)}cullViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,{ids:u,x:f,y:p,w:y,h:m,length:W}=this._data,v=[];for(let D=0;D<W;D++){const $=f[D],T=p[D],O=y[D],ot=m[D];$+O>=a&&$<=d&&T+ot>=c&&T<=h&&v.push(u[D])}return v}queryRect(e,n,o,s){const{ids:r,x:i,y:l,w:a,h:c,length:d}=this._data,h=[];for(let u=0;u<d;u++){const f=i[u],p=l[u],y=a[u],m=c[u];f+y>=e&&f<=o&&p+m>=n&&p<=s&&h.push(r[u])}return h}queryPoint(e,n){const{ids:o,x:s,y:r,w:i,h:l,length:a}=this._data,c=[];for(let d=0;d<a;d++)e>=s[d]&&e<=s[d]+i[d]&&n>=r[d]&&n<=r[d]+l[d]&&c.push(o[d]);return c}clear(){this._data.length=0,this._indexMap.clear()}}let Qo=null;function Zd(){return Qo||(Qo=new gi),Qo}const Lt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qo=Lt.length,Ke=Lt[0],_d=Lt[qo-1];function Md(t,e){const n=Lt.indexOf(t),o=Lt.indexOf(e);if(o-n<=1)return null;const s=Math.floor((n+o)/2);return Lt[s]}function ts(t,e){return t===null&&e===null?"a0":e===null?hi(t):t===null?Gd(e):Dd(t,e)}function es(t,e,n){if(n===0)return[];if(n===1)return[ts(t,e)];const o=Math.floor(n/2),s=ts(t,e),r=es(t,s,o),i=es(s,e,n-o-1);return[...r,s,...i]}function hi(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o<qo-1)return e[n]=Lt[o+1],e.join("");e[n]=Ke}return t+Lt[1]}function Gd(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o>0){e[n]=Lt[o-1];let s=e.join("");for(;s.length>1&&s.endsWith(Ke);)s=s.slice(0,-1);return s}e[n]=_d}return Ke+t}function Dd(t,e){const n=Math.max(t.length,e.length),o=t.padEnd(n,Ke),s=e.padEnd(n,Ke);let r="";for(let i=0;i<n;i++){if(o[i]===s[i]){r+=o[i];continue}const l=Md(o[i],s[i]);return l!==null?r+l:r+o[i]+hi(o.slice(i+1).replace(/0+$/,"")||Ke)}return t+Lt[Math.floor(qo/2)]}function Xd(t){if(!t||t.length===0)return!1;for(const e of t)if(Lt.indexOf(e)===-1)return!1;return!0}function Ld(t,e){return t===e?0:t<e?-1:1}class Fd{constructor(e=1e4){ct(this,"_entries",[]);ct(this,"_maxEntries");this._maxEntries=e}push(e){this._entries.push(e),this._entries.length>this._maxEntries&&(this._entries=this._entries.slice(this._entries.length-this._maxEntries))}get entries(){return this._entries}entriesSince(e){return this._entries.filter(n=>n.timestamp>=e)}entriesByClient(e){return this._entries.filter(n=>n.clientId===e)}clear(){this._entries=[]}get length(){return this._entries.length}}function fi(t){return{type:"add",element:t}}function pi(t){return{type:"delete",elementId:t}}function yi(t,e,n){return{type:"move",elementId:t,dx:e,dy:n}}function Ii(t,e,n,o,s){return{type:"resize",elementId:t,width:e,height:n,x:o,y:s}}function Ci(t,e){return{type:"style",elementId:t,changes:e}}function bi(t,e){return{type:"rotate",elementId:t,rotation:e}}function mi(t,e){return{type:"reorder",elementId:t,sortOrder:e}}function Ai(t,e){return{type:"updatePoints",elementId:t,points:e}}function wi(t,e){return{type:"setText",elementId:t,text:e}}function Vd(...t){return{type:"batch",operations:t}}function xi(t,e){switch(e.type){case"add":return[...t,e.element];case"delete":return t.filter(n=>n.id!==e.elementId);case"move":return t.map(n=>n.id===e.elementId?{...n,x:n.x+e.dx,y:n.y+e.dy}:n);case"resize":return t.map(n=>n.id===e.elementId?{...n,width:e.width,height:e.height,...e.x!==void 0?{x:e.x}:{},...e.y!==void 0?{y:e.y}:{}}:n);case"style":return t.map(n=>n.id===e.elementId?{...n,style:{...n.style,...e.changes}}:n);case"rotate":return t.map(n=>n.id===e.elementId?{...n,rotation:e.rotation}:n);case"reorder":return t.map(n=>n.id===e.elementId?{...n,sortOrder:e.sortOrder}:n);case"updatePoints":return t.map(n=>n.id!==e.elementId?n:"points"in n?{...n,points:e.points}:n);case"setText":return t.map(n=>n.id!==e.elementId?n:n.type==="text"?{...n,text:e.text}:n);case"batch":{let n=t;for(const o of e.operations)n=xi(n,o);return n}default:return t}}function Pd(t,e){const n=[],o=new Map,s=new Map;for(const r of t)o.set(r.id,r);for(const r of e)s.set(r.id,r);for(const r of e)o.has(r.id)||n.push(fi(r));for(const r of t)s.has(r.id)||n.push(pi(r.id));for(const r of e){const i=o.get(r.id);if(!i||i===r)continue;(i.x!==r.x||i.y!==r.y)&&n.push(yi(r.id,r.x-i.x,r.y-i.y)),(i.width!==r.width||i.height!==r.height)&&n.push(Ii(r.id,r.width,r.height)),i.rotation!==r.rotation&&n.push(bi(r.id,r.rotation));const l={};let a=!1;for(const c of Object.keys(r.style))i.style[c]!==r.style[c]&&(l[c]=r.style[c],a=!0);if(a&&n.push(Ci(r.id,l)),r.type==="text"&&i.type==="text"&&r.text!==i.text&&n.push(wi(r.id,r.text)),(r.type==="line"||r.type==="arrow"||r.type==="freedraw")&&(i.type==="line"||i.type==="arrow"||i.type==="freedraw")){const c=r.points,d=i.points;(c.length!==d.length||c.some((h,u)=>h!==d[u]))&&n.push(Ai(r.id,c))}i.sortOrder!==r.sortOrder&&r.sortOrder!==void 0&&n.push(mi(r.id,r.sortOrder))}return n}class Yd{constructor(){ct(this,"_doc",null);ct(this,"_provider",null);ct(this,"_config",null);ct(this,"_isApplyingRemote",!1);ct(this,"_isApplyingLocal",!1);ct(this,"_lastElements",[]);ct(this,"_syncTimer",null);ct(this,"_deepTimer",null);ct(this,"_dirtyIds",new Set);ct(this,"_storeUnsub",null);ct(this,"_yObserverCleanup",null);ct(this,"_statusListeners",new Set)}get doc(){return this._doc}get provider(){return this._provider}get config(){return this._config}get isActive(){return this._provider!==null&&this._provider.wsconnected}connect(e){return this.dispose(),this._config=e,this._doc=new Kt.Doc,this._provider=new ks.WebsocketProvider(e.serverUrl,e.roomName,this._doc,{connect:!0,params:e.authToken?{token:e.authToken}:void 0}),this._provider.awareness.setLocalState({user:e.user,cursor:null,selectedIds:[]}),this._provider.on("status",n=>{const o=n.status;for(const s of this._statusListeners)s(o)}),{doc:this._doc,provider:this._provider}}getYElements(){var e;return(e=this._doc)==null?void 0:e.getMap("elements")}updateAwareness(e){if(!this._provider)return;const n=this._provider.awareness.getLocalState();this._provider.awareness.setLocalState({...n,...e})}getRemoteAwareness(){if(!this._provider)return new Map;const e=this._provider.awareness.getStates(),n=this._provider.awareness.clientID,o=new Map;for(const[s,r]of e)s!==n&&r&&r.user&&o.set(s,r);return o}onStatusChange(e){return this._statusListeners.add(e),()=>{this._statusListeners.delete(e)}}startSync(e,n=50){const o=this._doc,s=this.getYElements();if(!o||!s){console.warn("[CollaborationManager] Cannot start sync — not connected");return}if(this.stopSync(),s.size>0){this._isApplyingRemote=!0;const l=this._yMapCollectionToElements(s);e.setElements(l),this._lastElements=l,this._isApplyingRemote=!1}else{const l=e.getState().elements;l.length>0&&(this._isApplyingLocal=!0,o.transact(()=>{for(const a of l){const c=new Kt.Map;Cn(a,c),s.set(a.id,c)}},"local-init"),this._isApplyingLocal=!1),this._lastElements=l}const r=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||this._isApplyingLocal)return;this._isApplyingRemote=!0;let c=[...this._lastElements],d=!1;for(const[h,u]of l.keys)if(u.action==="add"||u.action==="update"){const f=s.get(h);if(f){const p=Be(f);if(p){const y=c.findIndex(m=>m.id===h);y>=0?c[y]=p:c.push(p),d=!0}}}else u.action==="delete"&&(c=c.filter(f=>f.id!==h),d=!0);d&&(c.sort((h,u)=>h.sortOrder&&u.sortOrder?h.sortOrder<u.sortOrder?-1:h.sortOrder>u.sortOrder?1:0:0),e.setElements(c),this._lastElements=c),this._isApplyingRemote=!1},i=l=>{if(!this._isApplyingLocal){for(const a of l){let c=a.target;for(;c&&!(c instanceof Kt.Map&&c.parent===s);)c=c.parent;if(c instanceof Kt.Map){const d=c.get("id");d&&this._dirtyIds.add(d)}}this._deepTimer&&clearTimeout(this._deepTimer),this._deepTimer=setTimeout(()=>{if(this._dirtyIds.size===0||this._isApplyingLocal)return;this._isApplyingRemote=!0;let a=[...this._lastElements],c=!1;for(const d of this._dirtyIds){const h=s.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}this._dirtyIds.clear(),c&&(e.setElements(a),this._lastElements=a),this._isApplyingRemote=!1},16)}};s.observe(r),s.observeDeep(i),this._yObserverCleanup=()=>{s.unobserve(r),s.unobserveDeep(i),this._deepTimer&&clearTimeout(this._deepTimer),this._dirtyIds.clear()},this._storeUnsub=e.subscribe(l=>{this._isApplyingRemote||l.elements!==this._lastElements&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(()=>{this._syncLocalToYjs(l.elements,s,o)},n))})}stopSync(){var e,n;(e=this._storeUnsub)==null||e.call(this),this._storeUnsub=null,(n=this._yObserverCleanup)==null||n.call(this),this._yObserverCleanup=null,this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=null),this._lastElements=[]}dispose(){this.stopSync(),this._provider&&(this._provider.awareness.setLocalState(null),this._provider.disconnect(),this._provider.destroy(),this._provider=null),this._doc&&(this._doc.destroy(),this._doc=null),this._config=null,this._statusListeners.clear()}_syncLocalToYjs(e,n,o){this._isApplyingLocal=!0,this._lastElements=e;const s=new Map;for(const r of e)s.set(r.id,r);o.transact(()=>{for(const[r]of n.entries())s.has(r)||n.delete(r);for(const r of e){let i=n.get(r.id);i?this._updateYMapFromElement(r,i):(i=new Kt.Map,Cn(r,i),n.set(r.id,i))}},"local-sync"),this._isApplyingLocal=!1}_updateYMapFromElement(e,n){const o=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],s=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"],r=e;for(const l of o){const a=r[l];a!==n.get(l)&&n.set(l,a)}if(e.style)for(const l of s){const a=e.style[l];a!==n.get(`style.${l}`)&&n.set(`style.${l}`,a)}const i=e.boundElements?JSON.stringify(e.boundElements):null;switch(i!==n.get("boundElements")&&n.set("boundElements",i),e.type){case"rectangle":e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius);break;case"line":case"arrow":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a),e.lineType!==n.get("lineType")&&n.set("lineType",e.lineType),e.curvature!==n.get("curvature")&&n.set("curvature",e.curvature);const c=e.startBinding?JSON.stringify(e.startBinding):null;c!==n.get("startBinding")&&n.set("startBinding",c);const d=e.endBinding?JSON.stringify(e.endBinding):null;d!==n.get("endBinding")&&n.set("endBinding",d),e.type==="arrow"&&(e.startArrowhead!==n.get("startArrowhead")&&n.set("startArrowhead",e.startArrowhead),e.endArrowhead!==n.get("endArrowhead")&&n.set("endArrowhead",e.endArrowhead));break}case"freedraw":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a);break}case"text":e.text!==n.get("text")&&n.set("text",e.text),e.containerId!==n.get("containerId")&&n.set("containerId",e.containerId),e.textAlign!==n.get("textAlign")&&n.set("textAlign",e.textAlign),e.verticalAlign!==n.get("verticalAlign")&&n.set("verticalAlign",e.verticalAlign);break;case"image":e.src!==n.get("src")&&n.set("src",e.src),e.naturalWidth!==n.get("naturalWidth")&&n.set("naturalWidth",e.naturalWidth),e.naturalHeight!==n.get("naturalHeight")&&n.set("naturalHeight",e.naturalHeight),e.scaleMode!==n.get("scaleMode")&&n.set("scaleMode",e.scaleMode);const l=e.crop?JSON.stringify(e.crop):null;l!==n.get("crop")&&n.set("crop",l),e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius),e.alt!==n.get("alt")&&n.set("alt",e.alt);break}}_yMapCollectionToElements(e){const n=[];for(const[,o]of e.entries()){const s=Be(o);s&&n.push(s)}return n.sort((o,s)=>o.sortOrder&&s.sortOrder?o.sortOrder<s.sortOrder?-1:o.sortOrder>s.sortOrder?1:0:0),n}}class Hd{constructor(e){ct(this,"_worker",null);ct(this,"_callbacks");this._callbacks=e}connect(e,n){if(this.dispose(),this._worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGNvbGxhYm9yYXRpb24vc3luY1dvcmtlci53b3JrZXIudHMg4oCUIFdlYiBXb3JrZXIgaW1wbGVtZW50YXRpb24uCiAqCiAqIFJ1bnMgWWpzIGRvY3VtZW50ICsgV2ViU29ja2V0IHByb3ZpZGVyICsgc3luYyBsb2dpYyBlbnRpcmVseSBvZmYgdGhlCiAqIG1haW4gdGhyZWFkLiBDb21tdW5pY2F0ZXMgd2l0aCB0aGUgbWFpbiB0aHJlYWQgdmlhIHBvc3RNZXNzYWdlLgogKgogKiBUaGlzIGZpbGUgaXMgZGVzaWduZWQgdG8gYmUgaW1wb3J0ZWQgdmlhIFZpdGUncyBgbmV3IFdvcmtlcihuZXcgVVJMKC4uLikpYC4KICovCgovLyBJbXBvcnQgWWpzICh5anMgYW5kIHktd2Vic29ja2V0IGFyZSBwdXJlIEpTIOKAlCBubyBET00gZGVwZW5kZW5jeSkKaW1wb3J0ICogYXMgWSBmcm9tICd5anMnOwppbXBvcnQgeyBXZWJzb2NrZXRQcm92aWRlciB9IGZyb20gJ3ktd2Vic29ja2V0JzsKaW1wb3J0IHR5cGUgeyBXb3JrZXJJbk1lc3NhZ2UsIFdvcmtlck91dE1lc3NhZ2UgfSBmcm9tICcuL3N5bmNXb3JrZXInOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQgfSBmcm9tICdAL3R5cGVzJzsKaW1wb3J0IHR5cGUgeyBBd2FyZW5lc3NTdGF0ZSwgQ29sbGFib3JhdGlvbkNvbmZpZyB9IGZyb20gJy4vdHlwZXMnOwppbXBvcnQgeyBlbGVtZW50VG9ZTWFwLCB5TWFwVG9FbGVtZW50LCBTWU5DX0ZJRUxEUywgU1RZTEVfRklFTERTIH0gZnJvbSAnLi9zeW5jQnJpZGdlQ29kZWMnOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBTdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmxldCBfZG9jOiBZLkRvYyB8IG51bGwgPSBudWxsOwpsZXQgX3Byb3ZpZGVyOiBXZWJzb2NrZXRQcm92aWRlciB8IG51bGwgPSBudWxsOwpsZXQgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKbGV0IF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKbGV0IF9sYXN0RWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwpsZXQgX3N5bmNUaW1lcjogUmV0dXJuVHlwZTx0eXBlb2Ygc2V0VGltZW91dD4gfCBudWxsID0gbnVsbDsKbGV0IF9kZWVwVGltZXI6IFJldHVyblR5cGU8dHlwZW9mIHNldFRpbWVvdXQ+IHwgbnVsbCA9IG51bGw7CmNvbnN0IF9kaXJ0eUlkcyA9IG5ldyBTZXQ8c3RyaW5nPigpOwpsZXQgX3N5bmNEZWJvdW5jZU1zID0gNTA7CgovLyDilIDilIDilIAgUG9zdCBNZXNzYWdlIEhlbHBlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIHBvc3QobXNnOiBXb3JrZXJPdXRNZXNzYWdlKTogdm9pZCB7CiAgICBzZWxmLnBvc3RNZXNzYWdlKG1zZyk7Cn0KCi8vIOKUgOKUgOKUgCBZLk1hcCBDb2xsZWN0aW9uIEhlbHBlcnMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpmdW5jdGlvbiB5TWFwQ29sbGVjdGlvblRvRWxlbWVudHMoeUVsZW1lbnRzOiBZLk1hcDxZLk1hcDx1bmtub3duPj4pOiBDYW52YXNFbGVtZW50W10gewogICAgY29uc3QgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwogICAgZm9yIChjb25zdCBbLCB5TWFwXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgY29uc3QgZWwgPSB5TWFwVG9FbGVtZW50KHlNYXApOwogICAgICAgIGlmIChlbCkgZWxlbWVudHMucHVzaChlbCk7CiAgICB9CiAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgaWYgKGEuc29ydE9yZGVyICYmIGIuc29ydE9yZGVyKSB7CiAgICAgICAgICAgIHJldHVybiBhLnNvcnRPcmRlciA8IGIuc29ydE9yZGVyID8gLTEgOiBhLnNvcnRPcmRlciA+IGIuc29ydE9yZGVyID8gMSA6IDA7CiAgICAgICAgfQogICAgICAgIHJldHVybiAwOwogICAgfSk7CiAgICByZXR1cm4gZWxlbWVudHM7Cn0KCmZ1bmN0aW9uIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbDogQ2FudmFzRWxlbWVudCwgeU1hcDogWS5NYXA8dW5rbm93bj4pOiB2b2lkIHsKICAgIGNvbnN0IGVsUmVjb3JkID0gZWwgYXMgdW5rbm93biBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPjsKICAgIGZvciAoY29uc3QgZmllbGQgb2YgU1lOQ19GSUVMRFMpIHsKICAgICAgICBjb25zdCB2YWx1ZSA9IGVsUmVjb3JkW2ZpZWxkXTsKICAgICAgICBpZiAodmFsdWUgIT09IHlNYXAuZ2V0KGZpZWxkKSkgeU1hcC5zZXQoZmllbGQsIHZhbHVlKTsKICAgIH0KCiAgICBpZiAoZWwuc3R5bGUpIHsKICAgICAgICBmb3IgKGNvbnN0IHNmIG9mIFNUWUxFX0ZJRUxEUykgewogICAgICAgICAgICBjb25zdCB2YWwgPSBlbC5zdHlsZVtzZl07CiAgICAgICAgICAgIGlmICh2YWwgIT09IHlNYXAuZ2V0KGBzdHlsZS4ke3NmfWApKSB5TWFwLnNldChgc3R5bGUuJHtzZn1gLCB2YWwpOwogICAgICAgIH0KICAgIH0KCiAgICBjb25zdCBiZUpzb24gPSBlbC5ib3VuZEVsZW1lbnRzID8gSlNPTi5zdHJpbmdpZnkoZWwuYm91bmRFbGVtZW50cykgOiBudWxsOwogICAgaWYgKGJlSnNvbiAhPT0geU1hcC5nZXQoJ2JvdW5kRWxlbWVudHMnKSkgeU1hcC5zZXQoJ2JvdW5kRWxlbWVudHMnLCBiZUpzb24pOwoKICAgIHN3aXRjaCAoZWwudHlwZSkgewogICAgICAgIGNhc2UgJ3JlY3RhbmdsZSc6CiAgICAgICAgICAgIGlmIChlbC5jb3JuZXJSYWRpdXMgIT09IHlNYXAuZ2V0KCdjb3JuZXJSYWRpdXMnKSkgeU1hcC5zZXQoJ2Nvcm5lclJhZGl1cycsIGVsLmNvcm5lclJhZGl1cyk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgJ2xpbmUnOgogICAgICAgIGNhc2UgJ2Fycm93JzogewogICAgICAgICAgICBjb25zdCBwdHNKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKHB0c0pzb24gIT09IHlNYXAuZ2V0KCdwb2ludHMnKSkgeU1hcC5zZXQoJ3BvaW50cycsIHB0c0pzb24pOwogICAgICAgICAgICBpZiAoZWwubGluZVR5cGUgIT09IHlNYXAuZ2V0KCdsaW5lVHlwZScpKSB5TWFwLnNldCgnbGluZVR5cGUnLCBlbC5saW5lVHlwZSk7CiAgICAgICAgICAgIGlmIChlbC5jdXJ2YXR1cmUgIT09IHlNYXAuZ2V0KCdjdXJ2YXR1cmUnKSkgeU1hcC5zZXQoJ2N1cnZhdHVyZScsIGVsLmN1cnZhdHVyZSk7CiAgICAgICAgICAgIGNvbnN0IHNiSnNvbiA9IGVsLnN0YXJ0QmluZGluZyA/IEpTT04uc3RyaW5naWZ5KGVsLnN0YXJ0QmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoc2JKc29uICE9PSB5TWFwLmdldCgnc3RhcnRCaW5kaW5nJykpIHlNYXAuc2V0KCdzdGFydEJpbmRpbmcnLCBzYkpzb24pOwogICAgICAgICAgICBjb25zdCBlYkpzb24gPSBlbC5lbmRCaW5kaW5nID8gSlNPTi5zdHJpbmdpZnkoZWwuZW5kQmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoZWJKc29uICE9PSB5TWFwLmdldCgnZW5kQmluZGluZycpKSB5TWFwLnNldCgnZW5kQmluZGluZycsIGViSnNvbik7CiAgICAgICAgICAgIGlmIChlbC50eXBlID09PSAnYXJyb3cnKSB7CiAgICAgICAgICAgICAgICBpZiAoZWwuc3RhcnRBcnJvd2hlYWQgIT09IHlNYXAuZ2V0KCdzdGFydEFycm93aGVhZCcpKSB5TWFwLnNldCgnc3RhcnRBcnJvd2hlYWQnLCBlbC5zdGFydEFycm93aGVhZCk7CiAgICAgICAgICAgICAgICBpZiAoZWwuZW5kQXJyb3doZWFkICE9PSB5TWFwLmdldCgnZW5kQXJyb3doZWFkJykpIHlNYXAuc2V0KCdlbmRBcnJvd2hlYWQnLCBlbC5lbmRBcnJvd2hlYWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBjYXNlICdmcmVlZHJhdyc6IHsKICAgICAgICAgICAgY29uc3QgZnBKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKGZwSnNvbiAhPT0geU1hcC5nZXQoJ3BvaW50cycpKSB5TWFwLnNldCgncG9pbnRzJywgZnBKc29uKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIGNhc2UgJ3RleHQnOgogICAgICAgICAgICBpZiAoZWwudGV4dCAhPT0geU1hcC5nZXQoJ3RleHQnKSkgeU1hcC5zZXQoJ3RleHQnLCBlbC50ZXh0KTsKICAgICAgICAgICAgaWYgKGVsLmNvbnRhaW5lcklkICE9PSB5TWFwLmdldCgnY29udGFpbmVySWQnKSkgeU1hcC5zZXQoJ2NvbnRhaW5lcklkJywgZWwuY29udGFpbmVySWQpOwogICAgICAgICAgICBpZiAoZWwudGV4dEFsaWduICE9PSB5TWFwLmdldCgndGV4dEFsaWduJykpIHlNYXAuc2V0KCd0ZXh0QWxpZ24nLCBlbC50ZXh0QWxpZ24pOwogICAgICAgICAgICBpZiAoZWwudmVydGljYWxBbGlnbiAhPT0geU1hcC5nZXQoJ3ZlcnRpY2FsQWxpZ24nKSkgeU1hcC5zZXQoJ3ZlcnRpY2FsQWxpZ24nLCBlbC52ZXJ0aWNhbEFsaWduKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSAnaW1hZ2UnOgogICAgICAgICAgICBpZiAoZWwuc3JjICE9PSB5TWFwLmdldCgnc3JjJykpIHlNYXAuc2V0KCdzcmMnLCBlbC5zcmMpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbFdpZHRoICE9PSB5TWFwLmdldCgnbmF0dXJhbFdpZHRoJykpIHlNYXAuc2V0KCduYXR1cmFsV2lkdGgnLCBlbC5uYXR1cmFsV2lkdGgpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbEhlaWdodCAhPT0geU1hcC5nZXQoJ25hdHVyYWxIZWlnaHQnKSkgeU1hcC5zZXQoJ25hdHVyYWxIZWlnaHQnLCBlbC5uYXR1cmFsSGVpZ2h0KTsKICAgICAgICAgICAgaWYgKGVsLnNjYWxlTW9kZSAhPT0geU1hcC5nZXQoJ3NjYWxlTW9kZScpKSB5TWFwLnNldCgnc2NhbGVNb2RlJywgZWwuc2NhbGVNb2RlKTsKICAgICAgICAgICAgY29uc3QgY3JvcEpzb24gPSBlbC5jcm9wID8gSlNPTi5zdHJpbmdpZnkoZWwuY3JvcCkgOiBudWxsOwogICAgICAgICAgICBpZiAoY3JvcEpzb24gIT09IHlNYXAuZ2V0KCdjcm9wJykpIHlNYXAuc2V0KCdjcm9wJywgY3JvcEpzb24pOwogICAgICAgICAgICBpZiAoZWwuY29ybmVyUmFkaXVzICE9PSB5TWFwLmdldCgnY29ybmVyUmFkaXVzJykpIHlNYXAuc2V0KCdjb3JuZXJSYWRpdXMnLCBlbC5jb3JuZXJSYWRpdXMpOwogICAgICAgICAgICBpZiAoZWwuYWx0ICE9PSB5TWFwLmdldCgnYWx0JykpIHlNYXAuc2V0KCdhbHQnLCBlbC5hbHQpOwogICAgICAgICAgICBicmVhazsKICAgIH0KfQoKLy8g4pSA4pSA4pSAIENvbm5lY3QgLyBEaXNjb25uZWN0IOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gY29ubmVjdChjb25maWc6IENvbGxhYm9yYXRpb25Db25maWcsIHN5bmNEZWJvdW5jZU1zOiBudW1iZXIpOiB2b2lkIHsKICAgIGRpc2Nvbm5lY3QoKTsKCiAgICBfc3luY0RlYm91bmNlTXMgPSBzeW5jRGVib3VuY2VNczsKICAgIF9kb2MgPSBuZXcgWS5Eb2MoKTsKCiAgICBfcHJvdmlkZXIgPSBuZXcgV2Vic29ja2V0UHJvdmlkZXIoCiAgICAgICAgY29uZmlnLnNlcnZlclVybCwKICAgICAgICBjb25maWcucm9vbU5hbWUsCiAgICAgICAgX2RvYywKICAgICAgICB7CiAgICAgICAgICAgIGNvbm5lY3Q6IHRydWUsCiAgICAgICAgICAgIHBhcmFtczogY29uZmlnLmF1dGhUb2tlbiA/IHsgdG9rZW46IGNvbmZpZy5hdXRoVG9rZW4gfSA6IHVuZGVmaW5lZCwKICAgICAgICB9LAogICAgKTsKCiAgICAvLyBBd2FyZW5lc3MKICAgIF9wcm92aWRlci5hd2FyZW5lc3Muc2V0TG9jYWxTdGF0ZSh7CiAgICAgICAgdXNlcjogY29uZmlnLnVzZXIsCiAgICAgICAgY3Vyc29yOiBudWxsLAogICAgICAgIHNlbGVjdGVkSWRzOiBbXSwKICAgIH0gc2F0aXNmaWVzIEF3YXJlbmVzc1N0YXRlKTsKCiAgICAvLyBTdGF0dXMgZXZlbnRzCiAgICBfcHJvdmlkZXIub24oJ3N0YXR1cycsIChldmVudDogeyBzdGF0dXM6IHN0cmluZyB9KSA9PiB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdzdGF0dXMnLCBzdGF0dXM6IGV2ZW50LnN0YXR1cyBhcyBXb3JrZXJPdXRNZXNzYWdlIGV4dGVuZHMgeyB0eXBlOiAnc3RhdHVzJzsgc3RhdHVzOiBpbmZlciBTIH0gPyBTIDogbmV2ZXIgfSk7CiAgICB9KTsKCiAgICAvLyBBd2FyZW5lc3MgY2hhbmdlcyDihpIgcGVlcnMKICAgIF9wcm92aWRlci5hd2FyZW5lc3Mub24oJ2NoYW5nZScsICgpID0+IHsKICAgICAgICBpZiAoIV9wcm92aWRlcikgcmV0dXJuOwogICAgICAgIGNvbnN0IGFsbCA9IF9wcm92aWRlci5hd2FyZW5lc3MuZ2V0U3RhdGVzKCk7CiAgICAgICAgY29uc3QgbG9jYWxJZCA9IF9wcm92aWRlci5hd2FyZW5lc3MuY2xpZW50SUQ7CiAgICAgICAgY29uc3QgcGVlcnM6IEF3YXJlbmVzc1N0YXRlW10gPSBbXTsKICAgICAgICBmb3IgKGNvbnN0IFtjbGllbnRJZCwgc3RhdGVdIG9mIGFsbCkgewogICAgICAgICAgICBpZiAoY2xpZW50SWQgIT09IGxvY2FsSWQgJiYgc3RhdGUgJiYgKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKS51c2VyKSB7CiAgICAgICAgICAgICAgICBwZWVycy5wdXNoKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBwb3N0KHsgdHlwZTogJ3BlZXJzJywgcGVlcnMgfSk7CiAgICB9KTsKCiAgICAvLyBTdGFydCBzeW5jCiAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgLy8gSW5pdGlhbCBzeW5jOiBpZiBZanMgaGFzIGRhdGEsIHNlbmQgdG8gbWFpbiB0aHJlYWQKICAgIGlmICh5RWxlbWVudHMuc2l6ZSA+IDApIHsKICAgICAgICBjb25zdCBlbGVtZW50cyA9IHlNYXBDb2xsZWN0aW9uVG9FbGVtZW50cyh5RWxlbWVudHMpOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKICAgICAgICBwb3N0KHsgdHlwZTogJ3JlbW90ZS11cGRhdGUnLCBlbGVtZW50cyB9KTsKICAgIH0KCiAgICAvLyBZanMgb2JzZXJ2ZXJzIOKGkiBwb3N0IHJlbW90ZS11cGRhdGUKICAgIHlFbGVtZW50cy5vYnNlcnZlKChldmVudHMsIHRyYW5zYWN0aW9uKSA9PiB7CiAgICAgICAgaWYgKHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLXN5bmMnIHx8IHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLWluaXQnKSByZXR1cm47CiAgICAgICAgaWYgKF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSB0cnVlOwogICAgICAgIGxldCBlbGVtZW50cyA9IFsuLi5fbGFzdEVsZW1lbnRzXTsKICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICBmb3IgKGNvbnN0IFtrZXksIGNoYW5nZV0gb2YgZXZlbnRzLmtleXMpIHsKICAgICAgICAgICAgaWYgKGNoYW5nZS5hY3Rpb24gPT09ICdhZGQnIHx8IGNoYW5nZS5hY3Rpb24gPT09ICd1cGRhdGUnKSB7CiAgICAgICAgICAgICAgICBjb25zdCB5TWFwID0geUVsZW1lbnRzLmdldChrZXkpOwogICAgICAgICAgICAgICAgaWYgKHlNYXApIHsKICAgICAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgaWYgKGVsKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGtleSk7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgZWxlbWVudHNbaWR4XSA9IGVsOwogICAgICAgICAgICAgICAgICAgICAgICBlbHNlIGVsZW1lbnRzLnB1c2goZWwpOwogICAgICAgICAgICAgICAgICAgICAgICBjaGFuZ2VkID0gdHJ1ZTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSBpZiAoY2hhbmdlLmFjdGlvbiA9PT0gJ2RlbGV0ZScpIHsKICAgICAgICAgICAgICAgIGVsZW1lbnRzID0gZWxlbWVudHMuZmlsdGVyKGUgPT4gZS5pZCAhPT0ga2V5KTsKICAgICAgICAgICAgICAgIGNoYW5nZWQgPSB0cnVlOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgICAgICAgICBpZiAoYS5zb3J0T3JkZXIgJiYgYi5zb3J0T3JkZXIpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gYS5zb3J0T3JkZXIgPCBiLnNvcnRPcmRlciA/IC0xIDogYS5zb3J0T3JkZXIgPiBiLnNvcnRPcmRlciA/IDEgOiAwOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgcmV0dXJuIDA7CiAgICAgICAgICAgIH0pOwogICAgICAgICAgICBfbGFzdEVsZW1lbnRzID0gZWxlbWVudHM7CiAgICAgICAgICAgIHBvc3QoeyB0eXBlOiAncmVtb3RlLXVwZGF0ZScsIGVsZW1lbnRzIH0pOwogICAgICAgIH0KICAgICAgICBfaXNBcHBseWluZ1JlbW90ZSA9IGZhbHNlOwogICAgfSk7CgogICAgeUVsZW1lbnRzLm9ic2VydmVEZWVwKChldmVudHMpID0+IHsKICAgICAgICBpZiAoX2lzQXBwbHlpbmdMb2NhbCkgcmV0dXJuOwoKICAgICAgICBmb3IgKGNvbnN0IGV2ZW50IG9mIGV2ZW50cykgewogICAgICAgICAgICBsZXQgdGFyZ2V0OiBZLkFic3RyYWN0VHlwZTx1bmtub3duPiB8IG51bGwgPSBldmVudC50YXJnZXQ7CiAgICAgICAgICAgIHdoaWxlICh0YXJnZXQgJiYgISh0YXJnZXQgaW5zdGFuY2VvZiBZLk1hcCAmJiB0YXJnZXQucGFyZW50ID09PSB5RWxlbWVudHMpKSB7CiAgICAgICAgICAgICAgICB0YXJnZXQgPSB0YXJnZXQucGFyZW50IGFzIFkuQWJzdHJhY3RUeXBlPHVua25vd24+IHwgbnVsbDsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAodGFyZ2V0IGluc3RhbmNlb2YgWS5NYXApIHsKICAgICAgICAgICAgICAgIGNvbnN0IGlkID0gdGFyZ2V0LmdldCgnaWQnKSBhcyBzdHJpbmc7CiAgICAgICAgICAgICAgICBpZiAoaWQpIF9kaXJ0eUlkcy5hZGQoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoX2RlZXBUaW1lcikgY2xlYXJUaW1lb3V0KF9kZWVwVGltZXIpOwogICAgICAgIF9kZWVwVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICAgICAgaWYgKF9kaXJ0eUlkcy5zaXplID09PSAwIHx8IF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgICAgIF9pc0FwcGx5aW5nUmVtb3RlID0gdHJ1ZTsKICAgICAgICAgICAgbGV0IGVsZW1lbnRzID0gWy4uLl9sYXN0RWxlbWVudHNdOwogICAgICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICAgICAgZm9yIChjb25zdCBpZCBvZiBfZGlydHlJZHMpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHlNYXAgPSB5RWxlbWVudHMuZ2V0KGlkKTsKICAgICAgICAgICAgICAgIGlmICgheU1hcCkgY29udGludWU7CiAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICBpZiAoIWVsKSBjb250aW51ZTsKICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGlkKTsKICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgeyBlbGVtZW50c1tpZHhdID0gZWw7IGNoYW5nZWQgPSB0cnVlOyB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2RpcnR5SWRzLmNsZWFyKCk7CgogICAgICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICAgICAgX2xhc3RFbGVtZW50cyA9IGVsZW1lbnRzOwogICAgICAgICAgICAgICAgcG9zdCh7IHR5cGU6ICdyZW1vdGUtdXBkYXRlJywgZWxlbWVudHMgfSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgICAgICB9LCAxNik7CiAgICB9KTsKfQoKZnVuY3Rpb24gZGlzY29ubmVjdCgpOiB2b2lkIHsKICAgIGlmIChfc3luY1RpbWVyKSB7IGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsgX3N5bmNUaW1lciA9IG51bGw7IH0KICAgIGlmIChfZGVlcFRpbWVyKSB7IGNsZWFyVGltZW91dChfZGVlcFRpbWVyKTsgX2RlZXBUaW1lciA9IG51bGw7IH0KICAgIF9kaXJ0eUlkcy5jbGVhcigpOwoKICAgIGlmIChfcHJvdmlkZXIpIHsKICAgICAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUobnVsbCk7CiAgICAgICAgX3Byb3ZpZGVyLmRpc2Nvbm5lY3QoKTsKICAgICAgICBfcHJvdmlkZXIuZGVzdHJveSgpOwogICAgICAgIF9wcm92aWRlciA9IG51bGw7CiAgICB9CiAgICBpZiAoX2RvYykgewogICAgICAgIF9kb2MuZGVzdHJveSgpOwogICAgICAgIF9kb2MgPSBudWxsOwogICAgfQogICAgX2xhc3RFbGVtZW50cyA9IFtdOwogICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgIF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKCiAgICBwb3N0KHsgdHlwZTogJ3N0YXR1cycsIHN0YXR1czogJ2Rpc2Nvbm5lY3RlZCcgfSk7Cn0KCi8vIOKUgOKUgOKUgCBMb2NhbCBVcGRhdGUgSGFuZGxlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIGhhbmRsZUxvY2FsVXBkYXRlKGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10pOiB2b2lkIHsKICAgIGlmICghX2RvYyB8fCBfaXNBcHBseWluZ1JlbW90ZSkgcmV0dXJuOwogICAgaWYgKGVsZW1lbnRzID09PSBfbGFzdEVsZW1lbnRzKSByZXR1cm47CgogICAgaWYgKF9zeW5jVGltZXIpIGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsKICAgIF9zeW5jVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICBpZiAoIV9kb2MpIHJldHVybjsKICAgICAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgICAgIF9pc0FwcGx5aW5nTG9jYWwgPSB0cnVlOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKCiAgICAgICAgY29uc3QgbG9jYWxNYXAgPSBuZXcgTWFwPHN0cmluZywgQ2FudmFzRWxlbWVudD4oKTsKICAgICAgICBmb3IgKGNvbnN0IGVsIG9mIGVsZW1lbnRzKSBsb2NhbE1hcC5zZXQoZWwuaWQsIGVsKTsKCiAgICAgICAgX2RvYy50cmFuc2FjdCgoKSA9PiB7CiAgICAgICAgICAgIGZvciAoY29uc3QgW2lkXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgICAgICAgICBpZiAoIWxvY2FsTWFwLmhhcyhpZCkpIHlFbGVtZW50cy5kZWxldGUoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZvciAoY29uc3QgZWwgb2YgZWxlbWVudHMpIHsKICAgICAgICAgICAgICAgIGxldCB5TWFwID0geUVsZW1lbnRzLmdldChlbC5pZCk7CiAgICAgICAgICAgICAgICBpZiAoIXlNYXApIHsKICAgICAgICAgICAgICAgICAgICB5TWFwID0gbmV3IFkuTWFwPHVua25vd24+KCk7CiAgICAgICAgICAgICAgICAgICAgZWxlbWVudFRvWU1hcChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgeUVsZW1lbnRzLnNldChlbC5pZCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LCAnbG9jYWwtc3luYycpOwoKICAgICAgICBfaXNBcHBseWluZ0xvY2FsID0gZmFsc2U7CiAgICB9LCBfc3luY0RlYm91bmNlTXMpOwp9CgovLyDilIDilIDilIAgQXdhcmVuZXNzIFVwZGF0ZSBIYW5kbGVyIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gaGFuZGxlQXdhcmVuZXNzKG1zZzogRXh0cmFjdDxXb3JrZXJJbk1lc3NhZ2UsIHsgdHlwZTogJ2F3YXJlbmVzcycgfT4pOiB2b2lkIHsKICAgIGlmICghX3Byb3ZpZGVyKSByZXR1cm47CiAgICBjb25zdCBjdXJyZW50ID0gX3Byb3ZpZGVyLmF3YXJlbmVzcy5nZXRMb2NhbFN0YXRlKCkgYXMgQXdhcmVuZXNzU3RhdGUgfCBudWxsOwogICAgY29uc3QgdXBkYXRlOiBQYXJ0aWFsPEF3YXJlbmVzc1N0YXRlPiA9IHsgY3Vyc29yOiBtc2cuY3Vyc29yIH07CiAgICBpZiAobXNnLnNlbGVjdGVkSWRzKSB1cGRhdGUuc2VsZWN0ZWRJZHMgPSBtc2cuc2VsZWN0ZWRJZHM7CiAgICBpZiAobXNnLmFjdGl2ZVRvb2wpIHVwZGF0ZS5hY3RpdmVUb29sID0gbXNnLmFjdGl2ZVRvb2w7CiAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUoeyAuLi5jdXJyZW50LCAuLi51cGRhdGUgfSk7Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIFJvdXRlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCnNlbGYub25tZXNzYWdlID0gKGU6IE1lc3NhZ2VFdmVudDxXb3JrZXJJbk1lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBlLmRhdGE7CiAgICB0cnkgewogICAgICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICAgICAgY2FzZSAnY29ubmVjdCc6CiAgICAgICAgICAgICAgICBjb25uZWN0KG1zZy5jb25maWcsIG1zZy5zeW5jRGVib3VuY2VNcyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnZGlzY29ubmVjdCc6CiAgICAgICAgICAgICAgICBkaXNjb25uZWN0KCk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnbG9jYWwtdXBkYXRlJzoKICAgICAgICAgICAgICAgIGhhbmRsZUxvY2FsVXBkYXRlKG1zZy5lbGVtZW50cyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXdhcmVuZXNzJzoKICAgICAgICAgICAgICAgIGhhbmRsZUF3YXJlbmVzcyhtc2cpOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdlcnJvcicsIG1lc3NhZ2U6IGVyciBpbnN0YW5jZW9mIEVycm9yID8gZXJyLm1lc3NhZ2UgOiBTdHJpbmcoZXJyKSB9KTsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href)),!this._worker){console.warn("[SyncWorkerBridge] Worker creation failed, collaboration disabled"),this._callbacks.onStatus("disconnected");return}this._worker.onmessage=o=>{const s=o.data;switch(s.type){case"status":this._callbacks.onStatus(s.status);break;case"remote-update":this._callbacks.onRemoteUpdate(s.elements);break;case"peers":this._callbacks.onPeers(s.peers);break;case"error":this._callbacks.onError(s.message);break}},this._worker.onerror=o=>{this._callbacks.onError(`Worker error: ${o.message}`)},this._post({type:"connect",config:e,syncDebounceMs:n})}disconnect(){this._post({type:"disconnect"})}sendLocalUpdate(e){this._post({type:"local-update",elements:e})}sendAwareness(e){this._post({type:"awareness",cursor:e.cursor??null,selectedIds:e.selectedIds,activeTool:e.activeTool})}dispose(){this._worker&&(this._worker.terminate(),this._worker=null)}_post(e){var n;(n=this._worker)==null||n.postMessage(e)}}function ze(t){return`${t.zoom}:${t.col}:${t.row}`}class ki{constructor(e=200){ct(this,"_cache",new Map);ct(this,"_accessCounter",0);ct(this,"_maxTiles");this._maxTiles=e}get(e){const n=this._cache.get(ze(e));return n?(n.accessOrder=++this._accessCounter,n.bitmap):null}set(e,n,o=0){const s=ze(e),r=this._cache.get(s);r&&r.bitmap.close(),this._cache.set(s,{key:s,bitmap:n,accessOrder:++this._accessCounter,generation:o}),this._evict()}isFresh(e,n){const o=this._cache.get(ze(e));return o!=null&&o.generation>=n}invalidate(e){const n=ze(e),o=this._cache.get(n);o&&(o.bitmap.close(),this._cache.delete(n))}clear(){for(const e of this._cache.values())e.bitmap.close();this._cache.clear()}get size(){return this._cache.size}dispose(){this.clear()}_evict(){if(this._cache.size<=this._maxTiles)return;const e=Array.from(this._cache.values()).sort((o,s)=>o.accessOrder-s.accessOrder),n=e.length-this._maxTiles;for(let o=0;o<n;o++)e[o].bitmap.close(),this._cache.delete(e[o].key)}}const bn=256,jn=[.1,.15,.2,.25,.33,.5,.67,.75,1,1.25,1.5,2,2.5,3,4,5];function Si(t){let e=jn[0],n=Math.abs(t-e);for(let o=1;o<jn.length;o++){const s=Math.abs(t-jn[o]);s<n&&(e=jn[o],n=s)}return e}function Je(t){return bn/t}function vi(t,e,n,o=1){const s=Si(t.scale),r=Je(s),i=-t.x/t.scale,l=-t.y/t.scale,a=i+e/t.scale,c=l+n/t.scale,d=Math.floor(i/r)-o,h=Math.ceil(a/r)+o,u=Math.floor(l/r)-o,f=Math.ceil(c/r)+o,p=[];for(let y=d;y<=h;y++)for(let m=u;m<=f;m++)p.push({col:y,row:m,zoom:s});return{tiles:p,zoom:s}}function Ei(t){const e=Je(t.zoom);return{minX:t.col*e,minY:t.row*e,maxX:(t.col+1)*e,maxY:(t.row+1)*e}}function Od(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Nd(t,e){const n=cn(t),o=Je(e),s=[],r=Math.floor(n.minX/o),i=Math.floor(n.maxX/o),l=Math.floor(n.minY/o),a=Math.floor(n.maxY/o);for(let c=r;c<=i;c++)for(let d=l;d<=a;d++)s.push({col:c,row:d,zoom:e});return s}class Wi{constructor(e={}){ct(this,"_cache");ct(this,"_drawFn");ct(this,"_elementTiles",new Map);ct(this,"_generation",0);this._cache=new ki(e.maxCachedTiles??200),this._drawFn=e.drawFn??Ud}getTiles(e,n,o,s){const{tiles:r,zoom:i}=vi(e,n,o),l=[];for(const a of r){let c=this._cache.get(a);c||(c=this._rasterise(a,s),this._cache.set(a,c,this._generation));const d=Je(i);l.push({coord:a,bitmap:c,worldX:a.col*d,worldY:a.row*d,worldSize:d})}return l}invalidateElements(e){const n=new Set;for(const o of e){const s=this._elementTiles.get(o);if(s){for(const r of s)n.add(r);this._elementTiles.delete(o)}}for(const o of n){const[s,r,i]=o.split(":").map(Number);this._cache.invalidate({zoom:s,col:r,row:i})}}invalidateAll(){this._generation++,this._cache.clear(),this._elementTiles.clear()}dispose(){this._cache.dispose(),this._elementTiles.clear()}get cacheSize(){return this._cache.size}_rasterise(e,n){const o=Ei(e),s=Je(e.zoom),r=[];for(const c of n){const d=cn(c);if(Od(d,o)){r.push(c);const h=ze(e),u=this._elementTiles.get(c.id);u?u.includes(h)||u.push(h):this._elementTiles.set(c.id,[h])}}const i=new OffscreenCanvas(bn,bn),l=i.getContext("2d"),a=bn/s;return l.scale(a,a),l.translate(-o.minX,-o.minY),this._drawFn(l,r,o),i.transferToImageBitmap()}}function Ud(t,e,n){var o,s,r,i,l,a,c;for(const d of e){if(t.save(),d.rotation){const p=d.x+d.width/2,y=d.y+d.height/2;t.translate(p,y),t.rotate(d.rotation*Math.PI/180),t.translate(-p,-y)}t.globalAlpha=((o=d.style)==null?void 0:o.opacity)??1;const h=((s=d.style)==null?void 0:s.strokeColor)??"#000000",u=((r=d.style)==null?void 0:r.fillColor)??"transparent",f=((i=d.style)==null?void 0:i.strokeWidth)??2;switch(t.strokeStyle=h,t.fillStyle=u,t.lineWidth=f,d.type){case"rectangle":t.beginPath(),t.rect(d.x,d.y,d.width,d.height),u!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(d.x+d.width/2,d.y+d.height/2,d.width/2,d.height/2,0,0,Math.PI*2),u!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{const p=d.x+d.width/2,y=d.y+d.height/2;t.beginPath(),t.moveTo(p,d.y),t.lineTo(d.x+d.width,y),t.lineTo(p,d.y+d.height),t.lineTo(d.x,y),t.closePath(),u!=="transparent"&&t.fill(),t.stroke();break}case"line":case"arrow":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"freedraw":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"text":{const p=d;t.font=`${((l=p.style)==null?void 0:l.fontSize)??16}px ${((a=p.style)==null?void 0:a.fontFamily)??"sans-serif"}`,t.fillStyle=h,t.fillText(p.text,d.x,d.y+(((c=p.style)==null?void 0:c.fontSize)??16));break}case"image":t.strokeStyle="#ccc",t.setLineDash([4,4]),t.strokeRect(d.x,d.y,d.width,d.height);break}t.restore()}}function Kd(t,e,n,o,s={}){var p;const{enabled:r=!1,maxCachedTiles:i=200,drawFn:l,elementThreshold:a=500}=s,c=I.useRef(null);I.useEffect(()=>(c.current=new Wi({maxCachedTiles:i,drawFn:l}),()=>{var y;(y=c.current)==null||y.dispose(),c.current=null}),[i,l]);const d=r&&t.length>=a,h=I.useMemo(()=>!d||!c.current||n===0||o===0?[]:c.current.getTiles(e,n,o,t).map(m=>({key:`${m.coord.zoom}:${m.coord.col}:${m.coord.row}`,bitmap:m.bitmap,worldX:m.worldX,worldY:m.worldY,worldSize:m.worldSize})),[d,e.x,e.y,e.scale,n,o,t]),u=I.useCallback(y=>{var m;(m=c.current)==null||m.invalidateElements(y)},[]),f=I.useCallback(()=>{var y;(y=c.current)==null||y.invalidateAll()},[]);return{isActive:d,tiles:h,invalidateElements:u,invalidateAll:f,cacheSize:((p=c.current)==null?void 0:p.cacheSize)??0}}const Ht=4096,Qn=1024,qn=16,Ti=2;class zd{constructor(e=Ht,n=Ht){ct(this,"_shelves",[]);ct(this,"_atlasWidth");ct(this,"_atlasHeight");this._atlasWidth=e,this._atlasHeight=n}pack(e,n){const o=e+Ti,s=n+Ti;for(const l of this._shelves)if(l.height>=s&&l.x+o<=this._atlasWidth){const a={x:l.x,y:l.y};return l.x+=o,a}const r=this._shelves.length>0?this._shelves[this._shelves.length-1].y+this._shelves[this._shelves.length-1].height:0;if(r+s>this._atlasHeight)return null;const i={y:r,height:s,x:o};return this._shelves.push(i),{x:0,y:r}}reset(){this._shelves=[]}}class Bi{constructor(e){ct(this,"_entries",new Map);ct(this,"_packer");ct(this,"_canvas");ct(this,"_ctx");ct(this,"_drawFn");ct(this,"_dirty",!1);ct(this,"_generation",0);this._packer=new zd(Ht,Ht),this._canvas=new OffscreenCanvas(Ht,Ht),this._ctx=this._canvas.getContext("2d"),this._drawFn=e??$d}addOrUpdate(e,n){const o=this._entries.get(e.id);if(o&&o.generation>=n)return o.region;const{pw:s,ph:r}=Jd(e),i=this._packer.pack(s,r);if(!i)return null;this._ctx.save(),this._ctx.clearRect(i.x,i.y,s,r),this._ctx.translate(i.x,i.y);const l=s/Math.max(e.width,1),a=r/Math.max(e.height,1);this._ctx.scale(l,a),this._drawFn(this._ctx,e,e.width,e.height),this._ctx.restore();const c={atlasIndex:0,u:i.x/Ht,v:i.y/Ht,uWidth:s/Ht,vHeight:r/Ht,pixelWidth:s,pixelHeight:r};return this._entries.set(e.id,{elementId:e.id,region:c,generation:n}),this._dirty=!0,c}getRegion(e){var n;return((n=this._entries.get(e))==null?void 0:n.region)??null}remove(e){this._entries.delete(e)}rebuild(e){this._generation++,this._packer.reset(),this._entries.clear(),this._ctx.clearRect(0,0,Ht,Ht);for(const n of e)this.addOrUpdate(n,this._generation);this._dirty=!0}get isDirty(){return this._dirty}getCanvas(){return this._dirty=!1,this._canvas}get generation(){return this._generation}get size(){return this._entries.size}dispose(){this._entries.clear()}}function Jd(t){const e=Math.max(t.width,1)/Math.max(t.height,1);let n,o;return t.width>=t.height?(n=Math.min(Math.max(Math.ceil(t.width),qn),Qn),o=Math.min(Math.max(Math.ceil(n/e),qn),Qn)):(o=Math.min(Math.max(Math.ceil(t.height),qn),Qn),n=Math.min(Math.max(Math.ceil(o*e),qn),Qn)),{pw:n,ph:o}}function $d(t,e,n,o){var l,a,c,d,h,u,f;const s=((l=e.style)==null?void 0:l.strokeColor)??"#000000",r=((a=e.style)==null?void 0:a.fillColor)??"transparent",i=((c=e.style)==null?void 0:c.strokeWidth)??2;switch(t.strokeStyle=s,t.fillStyle=r,t.lineWidth=i,t.globalAlpha=((d=e.style)==null?void 0:d.opacity)??1,e.type){case"rectangle":t.beginPath(),t.rect(0,0,n,o),r!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(n/2,o/2,n/2,o/2,0,0,Math.PI*2),r!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{t.beginPath(),t.moveTo(n/2,0),t.lineTo(n,o/2),t.lineTo(n/2,o),t.lineTo(0,o/2),t.closePath(),r!=="transparent"&&t.fill(),t.stroke();break}case"text":{const p=e;t.font=`${((h=p.style)==null?void 0:h.fontSize)??16}px ${((u=p.style)==null?void 0:u.fontFamily)??"sans-serif"}`,t.fillStyle=s,t.fillText(p.text,0,((f=p.style)==null?void 0:f.fontSize)??16);break}default:t.strokeStyle="#aaa",t.strokeRect(0,0,n,o);break}}const Rd=`#version 300 es
253
+ `)}function uu(t,e="canvas.svg"){const n=Ne(t),o=new Blob([n],{type:"image/svg+xml"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const hu=5;function gu(t){if((t.type==="line"||t.type==="arrow"||t.type==="freedraw")&&"points"in t){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=t.x+e[i],a=t.y+e[i+1];n=Math.min(n,l),o=Math.max(o,l),s=Math.min(s,a),r=Math.max(r,a)}return{left:n,right:o,top:s,bottom:r,cx:(n+o)/2,cy:(s+r)/2}}return{left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2}}function fu(t,e,n,o=hu){const s={left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2},r=[],i=[];for(const a of e){if(n.has(a.id)||!a.isVisible||a.type==="text"&&a.containerId)continue;const c=gu(a),d=[[s.left,"left",c.left],[s.left,"left",c.right],[s.right,"right",c.left],[s.right,"right",c.right],[s.cx,"cx",c.cx],[s.left,"left",c.cx],[s.right,"right",c.cx],[s.cx,"cx",c.left],[s.cx,"cx",c.right]];for(const[u,f,p]of d)Math.abs(u-p)<o&&r.push({value:p,edge:f,other:c});const h=[[s.top,"top",c.top],[s.top,"top",c.bottom],[s.bottom,"bottom",c.top],[s.bottom,"bottom",c.bottom],[s.cy,"cy",c.cy],[s.top,"top",c.cy],[s.bottom,"bottom",c.cy],[s.cy,"cy",c.top],[s.cy,"cy",c.bottom]];for(const[u,f,p]of h)Math.abs(u-p)<o&&i.push({value:p,edge:f,other:c})}const l={guides:[]};if(r.length>0){r.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=r[0],c=a.value-s[a.edge];l.x=t.x+c;const d=a.value,h=r.filter(p=>Math.abs(p.value-d)<1);let u=s.top+(l.y!==void 0?l.y-t.y:0),f=s.bottom+(l.y!==void 0?l.y-t.y:0);for(const p of h)u=Math.min(u,p.other.top),f=Math.max(f,p.other.bottom);l.guides.push({orientation:"v",position:d,start:u-10,end:f+10})}if(i.length>0){i.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=i[0],c=a.value-s[a.edge];l.y=t.y+c;const d=a.value,h=i.filter(p=>Math.abs(p.value-d)<1);let u=s.left+(l.x!==void 0?l.x-t.x:0),f=s.right+(l.x!==void 0?l.x-t.x:0);for(const p of h)u=Math.min(u,p.other.left),f=Math.max(f,p.other.right);l.guides.push({orientation:"h",position:d,start:u-10,end:f+10})}return l}function pu(t=!0,e){const n=B(x=>x.setActiveTool),o=B(x=>x.undo),s=B(x=>x.redo),r=B(x=>x.selectedIds),i=B(x=>x.elements),l=B(x=>x.deleteElements),a=B(x=>x.duplicateElements),c=B(x=>x.bringToFront),d=B(x=>x.sendToBack),h=B(x=>x.bringForward),u=B(x=>x.sendBackward),f=B(x=>x.toggleGrid),p=B(x=>x.showGrid),y=B(x=>x.zoomIn),b=B(x=>x.zoomOut),W=B(x=>x.resetZoom),v=B(x=>x.zoomToFit),G=B(x=>x.zoomToSelection),$=B(x=>x.clearSelection),T=B(x=>x.updateElement),O=B(x=>x.addElement),ot=B(x=>x.setSelectedIds),Y=B(x=>x.pushHistory),J=hn(),P=I.useCallback(()=>{r.length!==0&&Cn(tr(r,i))},[r,i]),Q=I.useCallback(()=>{const x=$o();if(x.length===0)return;const C=20,{clones:w,selectedCloneIds:S}=Mn(x,x,C);w.forEach(Z=>O(Z)),ot(S.length>0?S:w.map(Z=>Z.id)),Y(),Cn(x.map(Z=>({...Z,x:Z.x+C,y:Z.y+C})))},[O,ot,Y]),_=I.useCallback((x,C)=>{r.length!==0&&(r.forEach(w=>{const S=i.find(Z=>Z.id===w);S&&!S.isLocked&&T(w,{x:S.x+x,y:S.y+C})}),Y())},[r,i,T,Y]);I.useEffect(()=>{if(!t)return;const x=C=>{const w=C.target.tagName;if(w==="INPUT"||w==="TEXTAREA"||w==="SELECT")return;const S=C.metaKey||C.ctrlKey;if(!S&&!C.shiftKey){const X={v:"select",h:"hand",r:"rectangle",o:"ellipse",d:"diamond",l:"line",a:"arrow",p:"freedraw",t:"text",i:"image",e:"eraser"}[C.key.toLowerCase()];if(X){C.preventDefault(),n(X);return}}if(S&&C.key==="z"&&!C.shiftKey){C.preventDefault(),o();return}if(S&&C.key==="z"&&C.shiftKey){C.preventDefault(),s();return}if(S&&C.key==="y"){C.preventDefault(),s();return}if((C.key==="Delete"||C.key==="Backspace")&&!S){if(J.isEditing&&J.selectedPointIndices.length>0){C.preventDefault();const{elements:Z,updateElement:X,pushHistory:U}=B.getState(),D=Z.find(L=>L.id===J.elementId);if(D){const L=D.points.length/2,at=new Set(J.selectedPointIndices);if(L-at.size>=2){const E=[];for(let st=0;st<L;st++)at.has(st)||E.push(D.points[st*2],D.points[st*2+1]);const V=E[0],dt=E[1],R=[];for(let st=0;st<E.length;st+=2)R.push(E[st]-V,E[st+1]-dt);let z=0,et=0,It=0,Ct=0;for(let st=0;st<R.length;st+=2)z=Math.min(z,R[st]),et=Math.max(et,R[st]),It=Math.min(It,R[st+1]),Ct=Math.max(Ct,R[st+1]);const rt={x:D.x+V,y:D.y+dt,points:R,width:et-z,height:Ct-It};at.has(0)&&(rt.startBinding=null),at.has(L-1)&&(rt.endBinding=null),X(D.id,rt),U(),J.setSelectedPoints([])}}return}if(r.length>0){C.preventDefault();const Z=r.filter(X=>{const U=i.find(D=>D.id===X);return U&&!U.isLocked});Z.length>0&&l(Z)}return}if(S&&C.key==="d"){C.preventDefault(),r.length>0&&a(r);return}if(C.key==="]"&&S&&C.shiftKey){C.preventDefault(),c(r);return}if(C.key==="["&&S&&C.shiftKey){C.preventDefault(),d(r);return}if(C.key==="]"&&S&&!C.shiftKey){C.preventDefault(),h(r);return}if(C.key==="["&&S&&!C.shiftKey){C.preventDefault(),u(r);return}if(C.key==="g"&&!S){C.preventDefault(),f();return}if(S&&(C.key==="="||C.key==="+")){C.preventDefault(),y();return}if(S&&C.key==="-"){C.preventDefault(),b();return}if(S&&C.key==="0"){C.preventDefault(),W();return}if(S&&C.shiftKey&&C.key==="1"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();v(Z.width,Z.height,void 0,{animate:!0})}return}if(S&&C.shiftKey&&C.key==="2"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();G(Z.width,Z.height,{animate:!0})}return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(C.key)&&!S&&r.length>0&&!J.isEditing){C.preventDefault();const Z=p?xe:1,X=C.shiftKey?Z*10:Z,U=C.key==="ArrowLeft"?-X:C.key==="ArrowRight"?X:0,D=C.key==="ArrowUp"?-X:C.key==="ArrowDown"?X:0;_(U,D);return}if(S&&C.key==="c"){r.length>0&&(C.preventDefault(),P());return}if(!(S&&C.key==="v")){if(S&&C.key==="x"){r.length>0&&(C.preventDefault(),P(),l(r));return}if(S&&C.key==="g"&&!C.shiftKey){if(C.preventDefault(),r.length>=2){const{groupElements:Z}=B.getState();Z(r)}return}if(S&&C.key==="g"&&C.shiftKey){if(C.preventDefault(),r.length>0){const{ungroupElements:Z}=B.getState();Z(r)}return}if(S&&C.shiftKey&&C.key==="l"){if(C.preventDefault(),r.length>0){const{toggleLockElements:Z}=B.getState();Z(r)}return}if(C.key==="Escape"){if(C.preventDefault(),J.isEditing){J.exitEditMode();return}$(),n("select");return}if(S&&C.key==="a"){C.preventDefault();const{elements:Z,setSelectedIds:X}=B.getState();X(Z.map(U=>U.id));return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[t,n,o,s,r,i,l,a,c,d,h,u,f,p,y,b,W,v,G,e,$,J,_,P,Q])}function oi(t,e,n=0,o=t.length-1,s=yu){for(;o>n;){if(o-n>600){const a=o-n+1,c=e-n+1,d=Math.log(a),h=.5*Math.exp(2*d/3),u=.5*Math.sqrt(d*h*(a-h)/a)*(c-a/2<0?-1:1),f=Math.max(n,Math.floor(e-c*h/a+u)),p=Math.min(o,Math.floor(e+(a-c)*h/a+u));oi(t,e,f,p,s)}const r=t[e];let i=n,l=o;for(bn(t,n,e),s(t[o],r)>0&&bn(t,n,o);i<l;){for(bn(t,i,l),i++,l--;s(t[i],r)<0;)i++;for(;s(t[l],r)>0;)l--}s(t[n],r)===0?bn(t,n,l):(l++,bn(t,l,o)),l<=e&&(n=l+1),e<=l&&(o=l-1)}}function bn(t,e,n){const o=t[e];t[e]=t[n],t[n]=o}function yu(t,e){return t<e?-1:t>e?1:0}class Iu{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(this._maxEntries*.4)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const o=[];if(!jn(e,n))return o;const s=this.toBBox,r=[];for(;n;){for(let i=0;i<n.children.length;i++){const l=n.children[i],a=n.leaf?s(l):l;jn(e,a)&&(n.leaf?o.push(l):Qo(e,a)?this._all(l,o):r.push(l))}n=r.pop()}return o}collides(e){let n=this.data;if(!jn(e,n))return!1;const o=[];for(;n;){for(let s=0;s<n.children.length;s++){const r=n.children[s],i=n.leaf?this.toBBox(r):r;if(jn(e,i)){if(n.leaf||Qo(e,i))return!0;o.push(r)}}n=o.pop()}return!1}load(e){if(!(e&&e.length))return this;if(e.length<this._minEntries){for(let o=0;o<e.length;o++)this.insert(e[o]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(!this.data.children.length)this.data=n;else if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const o=this.data;this.data=n,n=o}this._insert(n,this.data.height-n.height-1,!0)}return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=ze([]),this}remove(e,n){if(!e)return this;let o=this.data;const s=this.toBBox(e),r=[],i=[];let l,a,c;for(;o||r.length;){if(o||(o=r.pop(),a=r[r.length-1],l=i.pop(),c=!0),o.leaf){const d=Cu(e,o.children,n);if(d!==-1)return o.children.splice(d,1),r.push(o),this._condense(r),this}!c&&!o.leaf&&Qo(o,s)?(r.push(o),i.push(l),l=0,a=o,o=o.children[0]):a?(l++,o=a.children[l],c=!1):o=null}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const o=[];for(;e;)e.leaf?n.push(...e.children):o.push(...e.children),e=o.pop();return n}_build(e,n,o,s){const r=o-n+1;let i=this._maxEntries,l;if(r<=i)return l=ze(e.slice(n,o+1)),Ue(l,this.toBBox),l;s||(s=Math.ceil(Math.log(r)/Math.log(i)),i=Math.ceil(r/Math.pow(i,s-1))),l=ze([]),l.leaf=!1,l.height=s;const a=Math.ceil(r/i),c=a*Math.ceil(Math.sqrt(i));si(e,n,o,c,this.compareMinX);for(let d=n;d<=o;d+=c){const h=Math.min(d+c-1,o);si(e,d,h,a,this.compareMinY);for(let u=d;u<=h;u+=a){const f=Math.min(u+a-1,h);l.children.push(this._build(e,u,f,s-1))}}return Ue(l,this.toBBox),l}_chooseSubtree(e,n,o,s){for(;s.push(n),!(n.leaf||s.length-1===o);){let r=1/0,i=1/0,l;for(let a=0;a<n.children.length;a++){const c=n.children[a],d=jo(c),h=Au(e,c)-d;h<i?(i=h,r=d<r?d:r,l=c):h===i&&d<r&&(r=d,l=c)}n=l||n.children[0]}return n}_insert(e,n,o){const s=o?e:this.toBBox(e),r=[],i=this._chooseSubtree(s,this.data,n,r);for(i.children.push(e),wn(i,s);n>=0&&r[n].children.length>this._maxEntries;)this._split(r,n),n--;this._adjustParentBBoxes(s,r,n)}_split(e,n){const o=e[n],s=o.children.length,r=this._minEntries;this._chooseSplitAxis(o,r,s);const i=this._chooseSplitIndex(o,r,s),l=ze(o.children.splice(i,o.children.length-i));l.height=o.height,l.leaf=o.leaf,Ue(o,this.toBBox),Ue(l,this.toBBox),n?e[n-1].children.push(l):this._splitRoot(o,l)}_splitRoot(e,n){this.data=ze([e,n]),this.data.height=e.height+1,this.data.leaf=!1,Ue(this.data,this.toBBox)}_chooseSplitIndex(e,n,o){let s,r=1/0,i=1/0;for(let l=n;l<=o-n;l++){const a=An(e,0,l,this.toBBox),c=An(e,l,o,this.toBBox),d=wu(a,c),h=jo(a)+jo(c);d<r?(r=d,s=l,i=h<i?h:i):d===r&&h<i&&(i=h,s=l)}return s||o-n}_chooseSplitAxis(e,n,o){const s=e.leaf?this.compareMinX:mu,r=e.leaf?this.compareMinY:bu,i=this._allDistMargin(e,n,o,s),l=this._allDistMargin(e,n,o,r);i<l&&e.children.sort(s)}_allDistMargin(e,n,o,s){e.children.sort(s);const r=this.toBBox,i=An(e,0,n,r),l=An(e,o-n,o,r);let a=Rn(i)+Rn(l);for(let c=n;c<o-n;c++){const d=e.children[c];wn(i,e.leaf?r(d):d),a+=Rn(i)}for(let c=o-n-1;c>=n;c--){const d=e.children[c];wn(l,e.leaf?r(d):d),a+=Rn(l)}return a}_adjustParentBBoxes(e,n,o){for(let s=o;s>=0;s--)wn(n[s],e)}_condense(e){for(let n=e.length-1,o;n>=0;n--)e[n].children.length===0?n>0?(o=e[n-1].children,o.splice(o.indexOf(e[n]),1)):this.clear():Ue(e[n],this.toBBox)}}function Cu(t,e,n){if(!n)return e.indexOf(t);for(let o=0;o<e.length;o++)if(n(t,e[o]))return o;return-1}function Ue(t,e){An(t,0,t.children.length,e,t)}function An(t,e,n,o,s){s||(s=ze(null)),s.minX=1/0,s.minY=1/0,s.maxX=-1/0,s.maxY=-1/0;for(let r=e;r<n;r++){const i=t.children[r];wn(s,t.leaf?o(i):i)}return s}function wn(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function mu(t,e){return t.minX-e.minX}function bu(t,e){return t.minY-e.minY}function jo(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Rn(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Au(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function wu(t,e){const n=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),s=Math.min(t.maxX,e.maxX),r=Math.min(t.maxY,e.maxY);return Math.max(0,s-n)*Math.max(0,r-o)}function Qo(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function jn(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function ze(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function si(t,e,n,o,s){const r=[e,n];for(;r.length;){if(n=r.pop(),e=r.pop(),n-e<=o)continue;const i=e+Math.ceil((n-e)/o/2)*o;oi(t,i,e,n,s),r.push(e,i,i,n)}}function qo(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r,id:t.id}}return t.type==="freedraw"?{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}:{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}}class ts{constructor(e=9){ct(this,"tree");ct(this,"_elementMap",new Map);ct(this,"_fattenedMap",new Map);ct(this,"_margin",50);this.tree=new Iu(e)}get margin(){return this._margin}set margin(e){this._margin=Math.max(0,e)}rebuild(e){this._elementMap.clear(),this._fattenedMap.clear();const n=this._margin,o=new Array(e.length);for(let s=0;s<e.length;s++){const r=e[s];this._elementMap.set(r.id,r);const i=qo(r),l={minX:i.minX-n,minY:i.minY-n,maxX:i.maxX+n,maxY:i.maxY+n,id:r.id};this._fattenedMap.set(r.id,{trueMinX:i.minX,trueMinY:i.minY,trueMaxX:i.maxX,trueMaxY:i.maxY,item:l}),o[s]=l}this.tree.clear(),this.tree.load(o)}update(e){this._elementMap.set(e.id,e);const n=qo(e),o=this._fattenedMap.get(e.id);if(o){const{item:i}=o;if(n.minX>=i.minX&&n.minY>=i.minY&&n.maxX<=i.maxX&&n.maxY<=i.maxY)return o.trueMinX=n.minX,o.trueMinY=n.minY,o.trueMaxX=n.maxX,o.trueMaxY=n.maxY,!1;this.tree.remove(i,(l,a)=>l.id===a.id)}const s=this._margin,r={minX:n.minX-s,minY:n.minY-s,maxX:n.maxX+s,maxY:n.maxY+s,id:e.id};return this._fattenedMap.set(e.id,{trueMinX:n.minX,trueMinY:n.minY,trueMaxX:n.maxX,trueMaxY:n.maxY,item:r}),this.tree.insert(r),!0}remove(e){const n=this._fattenedMap.get(e);n&&this.tree.remove(n.item,(o,s)=>o.id===s.id),this._elementMap.delete(e),this._fattenedMap.delete(e)}queryViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,u=this.tree.search({minX:a,minY:c,maxX:d,maxY:h}),f=new Array(u.length);for(let p=0;p<u.length;p++)f[p]=u[p].id;return f}queryRect(e,n,o,s){return this.tree.search({minX:e,minY:n,maxX:o,maxY:s})}queryPoint(e,n){return this.tree.search({minX:e,minY:n,maxX:e,maxY:n}).map(o=>o.id)}getElementById(e){return this._elementMap.get(e)}get elementMap(){return this._elementMap}get size(){return this._elementMap.size}getTrueAABB(e){const n=this._fattenedMap.get(e);if(n)return{minX:n.trueMinX,minY:n.trueMinY,maxX:n.trueMaxX,maxY:n.trueMaxY}}clear(){this.tree.clear(),this._elementMap.clear(),this._fattenedMap.clear()}}let es=null;function xu(){return es||(es=new ts),es}const ri=200;function ku(t,e,n,o,s,r){const i=I.useRef(new ts),l=I.useMemo(()=>rr(s),[s]),a=I.useRef([]),c=I.useRef([]),d=I.useRef(0);if(t!==c.current){const h=c.current;if(c.current=t,t.length>ri)if(t.length!==d.current)i.current.rebuild(t);else{const f=i.current;for(let p=0;p<t.length;p++)t[p]!==h[p]&&f.update(t[p])}d.current=t.length}return I.useMemo(()=>{if(t.length<=ri)return or(t,e,n,o,l,r);const u=i.current.queryViewport(e,n,o,r),f=new Set(u);for(const b of s)f.add(b);const p=[];for(const b of t)f.has(b.id)&&p.push(b);const y=a.current;if(p.length===y.length){let b=!0;for(let W=0;W<p.length;W++)if(p[W]!==y[W]){b=!1;break}if(b)return y}return a.current=p,p},[t,e.x,e.y,e.scale,n,o,l,s,r])}const Su=[.0625,.125,.25,.5,1,2,4,8];function ii(t){const e=Su;if(t<=e[0])return e[0];if(t>=e[e.length-1])return e[e.length-1];for(let n=0;n<e.length-1;n++){const o=(e[n]+e[n+1])/2;if(t<=o)return e[n]}return e[e.length-1]}function li(t){return I.useMemo(()=>ii(t),[t])}const vu=500,Eu=500;function ci(t,e={}){const{batchSize:n=Eu,threshold:o=vu,enabled:s=!0}=e,r=I.useRef(0),[i,l]=I.useState(0),a=I.useRef([]),c=I.useRef(!1),d=I.useRef(0);t!==a.current&&(a.current=t);const u=s&&t.length>o;I.useEffect(()=>{if(!u){l(t.length),c.current=!0,d.current=t.length;return}const b=d.current;if(c.current&&Math.abs(t.length-b)<n){l(t.length),d.current=t.length;return}const W=++r.current;c.current=!1,d.current=t.length,l(Math.min(n,t.length));let v=n;function G(){r.current===W&&(v=Math.min(v+n,t.length),l(v),v<t.length?requestAnimationFrame(G):c.current=!0)}return n<t.length?requestAnimationFrame(G):c.current=!0,()=>{r.current++}},[t,u,n]);const f=I.useMemo(()=>!u||i>=t.length?t:t.slice(0,i),[t,i,u]),p=u&&i<t.length,y=t.length>0?Math.min(i/t.length,1):1;return{visibleElements:f,isLoading:p,progress:y}}function ai(t,e){const n=(e==null?void 0:e.timeout)??1e3;"requestIdleCallback"in window?window.requestIdleCallback(o=>{o.timeRemaining()>5?t():ai(t,e)},{timeout:n}):setTimeout(t,100)}function Wu(){return new Promise(t=>setTimeout(t,0))}const Tu=200,Bu=1e4;class di{constructor(e){ct(this,"_worker",null);ct(this,"_pending",new Map);ct(this,"_workerSupported",!0);ct(this,"_workerConfig");ct(this,"_onMessage",e=>{const n=e.data;if(!n||!n.requestId)return;const o=this._pending.get(n.requestId);o&&(this._pending.delete(n.requestId),n.type==="svgResult"?o.resolve(n.svg):n.type==="error"&&o.reject(new Error(n.message)))});this._workerConfig=e}_getWorker(){if(!this._workerSupported)return null;if(this._worker)return this._worker;try{return this._worker=Vn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGV4cG9ydFdvcmtlci50cyDigJQgV2ViIFdvcmtlciBmb3Igb2ZmLW1haW4tdGhyZWFkIFNWRyBleHBvcnQuCiAqCiAqIEdlbmVyYXRlcyBTVkcgc3RyaW5ncyBmcm9tIHNlcmlhbGl6ZWQgZWxlbWVudCBkYXRhIGluIGEgYmFja2dyb3VuZAogKiB0aHJlYWQsIGtlZXBpbmcgdGhlIG1haW4gdGhyZWFkIHJlc3BvbnNpdmUgZHVyaW5nIGV4cG9ydCBvZiBsYXJnZQogKiBjYW52YXNlcyAoMTBLKyBlbGVtZW50cykuCiAqCiAqIENvbW11bmljYXRpb24gcHJvdG9jb2w6CiAqICAgTWFpbiDihpIgV29ya2VyOgogKiAgICAgeyB0eXBlOiAnZXhwb3J0U1ZHJywgcmVxdWVzdElkOiBzdHJpbmcsIGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gfQogKiAgIFdvcmtlciDihpIgTWFpbjoKICogICAgIHsgdHlwZTogJ3N2Z1Jlc3VsdCcsIHJlcXVlc3RJZDogc3RyaW5nLCBzdmc6IHN0cmluZyB9CiAqICAgICB7IHR5cGU6ICdlcnJvcicsIHJlcXVlc3RJZDogc3RyaW5nLCBtZXNzYWdlOiBzdHJpbmcgfQogKgogKiBVc2VzIFZpdGUncyBuYXRpdmUgV29ya2VyIG1vZHVsZSBzdXBwb3J0IOKAlCBpbXBvcnRlZCB3aXRoOgogKiAgIG5ldyBXb3JrZXIobmV3IFVSTCgnLi9leHBvcnRXb3JrZXIudHMnLCBpbXBvcnQubWV0YS51cmwpLCB7IHR5cGU6ICdtb2R1bGUnIH0pCiAqLwoKaW1wb3J0IHsgZXhwb3J0VG9TVkcgfSBmcm9tICdAL3V0aWxzL2V4cG9ydCc7CmltcG9ydCB0eXBlIHsgQ2FudmFzRWxlbWVudCB9IGZyb20gJ0AvdHlwZXMnOwoKLy8g4pSA4pSA4pSAIE1lc3NhZ2UgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgRXhwb3J0U1ZHTWVzc2FnZSB7CiAgICB0eXBlOiAnZXhwb3J0U1ZHJzsKICAgIHJlcXVlc3RJZDogc3RyaW5nOwogICAgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXTsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBFeHBvcnRTVkdNZXNzYWdlOwoKaW50ZXJmYWNlIFNWR1Jlc3VsdE1lc3NhZ2UgewogICAgdHlwZTogJ3N2Z1Jlc3VsdCc7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIHN2Zzogc3RyaW5nOwp9CgppbnRlcmZhY2UgRXJyb3JNZXNzYWdlIHsKICAgIHR5cGU6ICdlcnJvcic7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIG1lc3NhZ2U6IHN0cmluZzsKfQoKdHlwZSBPdXRnb2luZ01lc3NhZ2UgPSBTVkdSZXN1bHRNZXNzYWdlIHwgRXJyb3JNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBtYWluIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKc2VsZi5vbm1lc3NhZ2UgPSAoZXY6IE1lc3NhZ2VFdmVudDxJbmNvbWluZ01lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBldi5kYXRhOwoKICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICBjYXNlICdleHBvcnRTVkcnOiB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBjb25zdCBzdmcgPSBleHBvcnRUb1NWRyhtc2cuZWxlbWVudHMpOwogICAgICAgICAgICAgICAgY29uc3QgcmVzcG9uc2U6IE91dGdvaW5nTWVzc2FnZSA9IHsKICAgICAgICAgICAgICAgICAgICB0eXBlOiAnc3ZnUmVzdWx0JywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgc3ZnLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9IGNhdGNoIChlcnIpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHJlc3BvbnNlOiBPdXRnb2luZ01lc3NhZ2UgPSB7CiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2Vycm9yJywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgbWVzc2FnZTogZXJyIGluc3RhbmNlb2YgRXJyb3IgPyBlcnIubWVzc2FnZSA6IFN0cmluZyhlcnIpLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBicmVhazsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this._workerConfig),this._worker?(this._worker.onmessage=this._onMessage,this._worker.onerror=e=>{console.warn("[ExportWorkerManager] Worker error, falling back to sync:",e.message),this._workerSupported=!1,this._rejectAll(new Error("Export Worker failed")),this._worker&&(this._worker.terminate(),this._worker=null)},this._worker):(this._workerSupported=!1,null)}catch{return this._workerSupported=!1,null}}_rejectAll(e){for(const[,n]of this._pending)n.reject(e);this._pending.clear()}async exportSVG(e){if(e.length<=Tu)return Ne(e);const n=this._getWorker();if(!n)return Ne(e);const o=Ft();return new Promise((s,r)=>{this._pending.set(o,{resolve:s,reject:r});const i=setTimeout(()=>{if(this._pending.has(o)){this._pending.delete(o),console.warn("[ExportWorkerManager] Timeout, falling back to sync export");try{s(Ne(e))}catch(d){r(d)}}},Bu),l=s,a=r,c=this._pending.get(o);c&&(c.resolve=d=>{clearTimeout(i),l(d)},c.reject=d=>{clearTimeout(i),a(d)}),n.postMessage({type:"exportSVG",requestId:o,elements:e})})}async downloadSVG(e,n="canvas.svg"){const o=await this.exportSVG(e),s=new Blob([o],{type:"image/svg+xml"}),r=URL.createObjectURL(s),i=document.createElement("a");i.download=n,i.href=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}dispose(){var e;this._rejectAll(new Error("ExportWorkerManager disposed")),(e=this._worker)==null||e.terminate(),this._worker=null}}let se=null,ns;function Zu(t){return se&&t&&JSON.stringify(t)!==JSON.stringify(ns)&&(se.dispose(),se=null),se||(ns=t,se=new di(t)),se}function ui(){se&&(se.dispose(),se=null,ns=void 0)}const hi={canvasBackground:"#f8f9fa",gridColor:"#e5e5e5",selectionColor:"#4f8df7",toolbarBg:"rgba(255, 255, 255, 0.95)",toolbarBorder:"#e5e7eb",panelBg:"rgba(255, 255, 255, 0.95)",activeToolColor:"#4f46e5",textColor:"#374151",mutedTextColor:"#9ca3af"};let Rt=null,Wt=null,os=new Set;function gi(t){return Wt&&Qn(),Rt=new zt.Doc,Wt=new _s.WebsocketProvider(t.serverUrl,t.roomName,Rt,{connect:!0,params:t.authToken?{token:t.authToken}:void 0}),Wt.awareness.setLocalState({user:t.user,cursor:null,selectedIds:[]}),Wt.on("status",e=>{const n=e.status;for(const o of os)o(n)}),{doc:Rt,provider:Wt}}function Qn(){Wt&&(Wt.awareness.setLocalState(null),Wt.disconnect(),Wt.destroy(),Wt=null),Rt&&(Rt.destroy(),Rt=null)}function fi(){return Rt}function ss(){return Wt}function pi(){return Rt==null?void 0:Rt.getMap("elements")}function Mu(){return Wt!==null&&Wt.wsconnected}function yi(t){return os.add(t),()=>{os.delete(t)}}function qn(t){if(!Wt)return;const e=Wt.awareness.getLocalState();Wt.awareness.setLocalState({...e,...t})}function Ii(){if(!Wt)return new Map;const t=Wt.awareness.getStates(),e=Wt.awareness.clientID,n=new Map;for(const[o,s]of t)o!==e&&s&&s.user&&n.set(o,s);return n}const rs=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],to=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"];function xn(t,e){const n=t;for(const o of rs){const s=n[o];s!==void 0&&e.set(o,s)}if(t.style)for(const o of to)e.set(`style.${o}`,t.style[o]);switch(t.boundElements?e.set("boundElements",JSON.stringify(t.boundElements)):e.set("boundElements",null),t.groupIds&&e.set("groupIds",JSON.stringify(t.groupIds)),t.type){case"rectangle":e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":e.set("points",JSON.stringify(t.points)),e.set("lineType",t.lineType),t.curvature!==void 0&&e.set("curvature",t.curvature),e.set("startBinding",t.startBinding?JSON.stringify(t.startBinding):null),e.set("endBinding",t.endBinding?JSON.stringify(t.endBinding):null),t.type==="arrow"&&(e.set("startArrowhead",t.startArrowhead),e.set("endArrowhead",t.endArrowhead));break;case"freedraw":e.set("points",JSON.stringify(t.points));break;case"text":e.set("text",t.text),e.set("containerId",t.containerId),e.set("textAlign",t.textAlign),e.set("verticalAlign",t.verticalAlign);break;case"image":e.set("src",t.src),e.set("naturalWidth",t.naturalWidth),e.set("naturalHeight",t.naturalHeight),e.set("scaleMode",t.scaleMode),e.set("crop",t.crop?JSON.stringify(t.crop):null),e.set("cornerRadius",t.cornerRadius),e.set("alt",t.alt);break}}function Be(t){const e=t.get("type"),n=t.get("id");if(!e||!n)return null;const o={};for(const r of to){const i=t.get(`style.${r}`);i!==void 0&&(o[r]=i)}const s={id:n,type:e,x:t.get("x")??0,y:t.get("y")??0,width:t.get("width")??100,height:t.get("height")??100,rotation:t.get("rotation")??0,isLocked:t.get("isLocked")??!1,isVisible:t.get("isVisible")??!0,style:o,boundElements:Ze(t.get("boundElements"))??null,groupIds:Ze(t.get("groupIds"))??void 0,sortOrder:t.get("sortOrder")??void 0};switch(e){case"rectangle":s.cornerRadius=t.get("cornerRadius")??0;break;case"line":case"arrow":s.points=Ze(t.get("points"))??[0,0,100,0],s.lineType=t.get("lineType")??"sharp",s.curvature=t.get("curvature")??void 0,s.startBinding=Ze(t.get("startBinding")),s.endBinding=Ze(t.get("endBinding")),e==="arrow"&&(s.startArrowhead=t.get("startArrowhead")??null,s.endArrowhead=t.get("endArrowhead")??"arrow");break;case"freedraw":s.points=Ze(t.get("points"))??[];break;case"text":s.text=t.get("text")??"",s.containerId=t.get("containerId")??null,s.textAlign=t.get("textAlign")??"center",s.verticalAlign=t.get("verticalAlign")??"middle";break;case"image":s.src=t.get("src")??"",s.naturalWidth=t.get("naturalWidth")??0,s.naturalHeight=t.get("naturalHeight")??0,s.scaleMode=t.get("scaleMode")??"fit",s.crop=Ze(t.get("crop"))??null,s.cornerRadius=t.get("cornerRadius")??0,s.alt=t.get("alt")??"";break}return s}function Ze(t){if(t==null)return null;try{return JSON.parse(t)}catch{return null}}let Me=!1,_e=!1,eo=null,no=null,Ke=null,re=[];function Ci(t=50){const e=fi(),n=pi();if(!e||!n){console.warn("[SyncBridge] Cannot start sync — no Yjs doc");return}if(oo(),n.size>0){Me=!0;const l=Gu(n);B.getState().setElements(l),re=l,Me=!1}else{const l=B.getState().elements;l.length>0&&(_e=!0,e.transact(()=>{for(const a of l){const c=new zt.Map;xn(a,c),n.set(a.id,c)}},"local-init"),_e=!1),re=l}const o=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||_e)return;Me=!0;const c=B.getState();let d=[...re],h=!1;for(const[u,f]of l.keys)if(f.action==="add"||f.action==="update"){const p=n.get(u);if(p){const y=Be(p);if(y){const b=d.findIndex(W=>W.id===u);b>=0?d[b]=y:d.push(y),h=!0}}}else f.action==="delete"&&(d=d.filter(p=>p.id!==u),h=!0);h&&(d.sort((u,f)=>u.sortOrder&&f.sortOrder?u.sortOrder<f.sortOrder?-1:u.sortOrder>f.sortOrder?1:0:0),c.setElements(d),re=d),Me=!1};let s=null;const r=new Set,i=l=>{if(!_e){for(const a of l){let c=a.target;for(;c&&!(c instanceof zt.Map&&c.parent===n);)c=c.parent;if(c instanceof zt.Map){const d=c.get("id");d&&r.add(d)}}s&&clearTimeout(s),s=setTimeout(()=>{if(r.size===0||_e)return;Me=!0;let a=[...re],c=!1;for(const d of r){const h=n.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}r.clear(),c&&(B.getState().setElements(a),re=a),Me=!1},16)}};n.observe(o),n.observeDeep(i),no=()=>{n.unobserve(o),n.unobserveDeep(i),s&&clearTimeout(s),r.clear()},eo=B.subscribe(l=>{Me||l.elements!==re&&(Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{_u(l.elements,n,e)},t))})}function oo(){eo&&(eo(),eo=null),no&&(no(),no=null),Ke&&(clearTimeout(Ke),Ke=null),re=[]}function _u(t,e,n){_e=!0,re=t;const o=new Map;for(const s of t)o.set(s.id,s);n.transact(()=>{for(const[s]of e.entries())o.has(s)||e.delete(s);for(const s of t){let r=e.get(s.id);r?Xu(s,r):(r=new zt.Map,xn(s,r),e.set(s.id,r))}},"local-sync"),_e=!1}function Xu(t,e){const n=t;for(const s of rs){const r=n[s];r!==e.get(s)&&e.set(s,r)}if(t.style)for(const s of to){const r=t.style[s];r!==e.get(`style.${s}`)&&e.set(`style.${s}`,r)}const o=t.boundElements?JSON.stringify(t.boundElements):null;switch(o!==e.get("boundElements")&&e.set("boundElements",o),t.type){case"rectangle":t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r),t.lineType!==e.get("lineType")&&e.set("lineType",t.lineType),t.curvature!==e.get("curvature")&&e.set("curvature",t.curvature);const i=t.startBinding?JSON.stringify(t.startBinding):null;i!==e.get("startBinding")&&e.set("startBinding",i);const l=t.endBinding?JSON.stringify(t.endBinding):null;l!==e.get("endBinding")&&e.set("endBinding",l),t.type==="arrow"&&(t.startArrowhead!==e.get("startArrowhead")&&e.set("startArrowhead",t.startArrowhead),t.endArrowhead!==e.get("endArrowhead")&&e.set("endArrowhead",t.endArrowhead));break}case"freedraw":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r);break}case"text":t.text!==e.get("text")&&e.set("text",t.text),t.containerId!==e.get("containerId")&&e.set("containerId",t.containerId),t.textAlign!==e.get("textAlign")&&e.set("textAlign",t.textAlign),t.verticalAlign!==e.get("verticalAlign")&&e.set("verticalAlign",t.verticalAlign);break;case"image":t.src!==e.get("src")&&e.set("src",t.src),t.naturalWidth!==e.get("naturalWidth")&&e.set("naturalWidth",t.naturalWidth),t.naturalHeight!==e.get("naturalHeight")&&e.set("naturalHeight",t.naturalHeight),t.scaleMode!==e.get("scaleMode")&&e.set("scaleMode",t.scaleMode);const s=t.crop?JSON.stringify(t.crop):null;s!==e.get("crop")&&e.set("crop",s),t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius),t.alt!==e.get("alt")&&e.set("alt",t.alt);break}}function Gu(t){const e=[];for(const[,n]of t.entries()){const o=Be(n);o&&e.push(o)}return e.sort((n,o)=>n.sortOrder&&o.sortOrder?n.sortOrder<o.sortOrder?-1:n.sortOrder>o.sortOrder?1:0:0),e}function mi(t){const[e,n]=I.useState("disconnected"),[o,s]=I.useState([]),r=I.useRef(t);r.current=t;const i=I.useRef((t==null?void 0:t.awarenessThrottleMs)??100),l=I.useRef(0);I.useEffect(()=>{if(!t){Qn(),oo(),n("disconnected"),s([]);return}const{provider:h}=gi(t);Ci(t.syncDebounceMs??50);const u=yi(n),f=()=>{const y=Ii();s(Array.from(y.values()))};h.awareness.on("change",f);const p=B.subscribe((y,b)=>{y.selectedIds!==b.selectedIds&&qn({selectedIds:y.selectedIds}),y.activeTool!==b.activeTool&&qn({activeTool:y.activeTool})});return()=>{u(),p(),h.awareness.off("change",f),oo(),Qn(),n("disconnected"),s([])}},[t==null?void 0:t.serverUrl,t==null?void 0:t.roomName,t==null?void 0:t.user.id,t==null?void 0:t.syncDebounceMs]);const a=I.useCallback(h=>{const u=Date.now();u-l.current<i.current||(l.current=u,qn({cursor:h}))},[]),c=I.useCallback(()=>{const h=ss();h&&h.disconnect()},[]),d=I.useCallback(()=>{const h=ss();h&&h.connect()},[]);return{isConnected:e==="connected",connectionStatus:e,peers:o,disconnect:c,reconnect:d,updateCursor:a}}const Du=[0,0,0,18,4.5,14.5,9,20,12,18,7.5,12.5,14,12.5,0,0],is=12,bi="system-ui, -apple-system, sans-serif",Ai=6,wi=4,xi=14,ki=18,ie={ctx:null,cache:new Map};function Lu(t){const e=ie.cache.get(t);if(e!==void 0)return e;if(!ie.ctx)try{const o=document.createElement("canvas");ie.ctx=o.getContext("2d")}catch{}let n;return ie.ctx?(ie.ctx.font=`${is}px ${bi}`,n=ie.ctx.measureText(t).width):n=t.length*7,ie.cache.size>200&&ie.cache.clear(),ie.cache.set(t,n),n}function Si(t,e,n,o,s,r){const i=(t-n.x)*n.scale,l=(e-n.y)*n.scale;return i>=-r&&i<=o+r&&l>=-r&&l<=s+r}function Yu(t,e,n,o,s){const r=t.x+t.width/2,i=t.y+t.height/2,l=Math.sqrt(t.width*t.width+t.height*t.height)/2;return Si(r,i,e,n,o,s+l*e.scale)}const Vu=({peers:t,viewport:e,stageWidth:n,stageHeight:o,elements:s})=>{const r=I.useMemo(()=>{const a=new Map;for(const c of s)a.set(c.id,c);return a},[s]),i=1/e.scale,l=150;return g.jsx(g.Fragment,{children:t.map(a=>{if(!a.cursor&&a.selectedIds.length===0)return null;const{user:c}=a;return g.jsxs(ht.Group,{children:[a.selectedIds.map(d=>{const h=r.get(d);if(!h||!Yu(h,e,n,o,l))return null;const u=3*i;return g.jsx(ht.Rect,{x:h.x+h.width/2,y:h.y+h.height/2,offsetX:h.width/2+u,offsetY:h.height/2+u,width:h.width+u*2,height:h.height+u*2,rotation:h.rotation??0,stroke:c.color,strokeWidth:2*i,dash:[6*i,4*i],cornerRadius:3*i,listening:!1,perfectDrawEnabled:!1},d)}),a.cursor&&Si(a.cursor.x,a.cursor.y,e,n,o,l)&&g.jsxs(ht.Group,{x:a.cursor.x,y:a.cursor.y,scaleX:i,scaleY:i,listening:!1,children:[g.jsx(ht.Line,{points:Du,fill:c.color,stroke:"#ffffff",strokeWidth:1,closed:!0,perfectDrawEnabled:!1}),g.jsx(ht.Rect,{x:xi,y:ki,width:Lu(c.name)+Ai*2,height:is+wi*2,fill:c.color,cornerRadius:4,listening:!1,perfectDrawEnabled:!1}),g.jsx(ht.Text,{x:xi+Ai,y:ki+wi,text:c.name,fontSize:is,fontFamily:bi,fill:"#ffffff",listening:!1,perfectDrawEnabled:!1})]})]},c.id)})})},vi=I.memo(Vu);en.showWarnings=!1;function Ei(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}const Wi=10,Fu=({elements:t,listening:e,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditTextId:i,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u,onGroupDragEnd:f})=>{const p=I.useRef(null);I.useEffect(()=>{const v=p.current;if(!v||t.length===0)return;const $=(window.devicePixelRatio||1)*Math.max(1,u),T=requestAnimationFrame(()=>{if(!p.current)return;const O=v.getClientRect({skipTransform:!0}),ot=8192,Y=O.width*$,J=O.height*$;if(Y>ot||J>ot||O.width<=0||O.height<=0){v.clearCache(),v.batchDraw();return}v.cache({pixelRatio:$}),v.batchDraw()});return()=>{cancelAnimationFrame(T),v.clearCache()}},[t,u,i]);const{ungrouped:y,groups:b}=I.useMemo(()=>{var $;const v=[],G=new Map;for(const T of t)if(($=T.groupIds)!=null&&$.length){const O=T.groupIds[T.groupIds.length-1];G.has(O)||G.set(O,[]),G.get(O).push(T)}else v.push(T);return{ungrouped:v,groups:G}},[t]),W=I.useCallback(v=>{var G;(G=p.current)==null||G.clearCache()},[]);return g.jsxs(ht.Layer,{ref:p,listening:e,children:[y.map(v=>g.jsx(Hn,{element:v,isSelected:!1,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===v.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},v.id)),Array.from(b.entries()).map(([v,G])=>{const $=G.some(T=>T.isLocked);return g.jsx(ht.Group,{draggable:!$,onDragStart:W,onDragEnd:T=>{const O=T.target.x(),ot=T.target.y();T.target.x(0),T.target.y(0),f==null||f(v,O,ot)},children:G.map(T=>g.jsx(Hn,{element:T,isSelected:!1,isGrouped:!0,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===T.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},T.id))},v)})]})},Pu=I.memo(Fu,(t,e)=>!(t.elements!==e.elements||t.listening!==e.listening||t.autoEditTextId!==e.autoEditTextId||t.gridSnap!==e.gridSnap||t.viewportScale!==e.viewportScale)),Hu=({element:t,scale:e})=>{const n=20/e,o=n/24;return g.jsxs(ht.Group,{x:t.x-n/2,y:t.y-n/2,listening:!1,children:[g.jsx(ht.Rect,{width:n,height:n,fill:"#ff9500",cornerRadius:n/4,opacity:.9}),g.jsx(ht.Path,{x:n*.12,y:n*.08,data:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z",fill:"white",scaleX:o*.78,scaleY:o*.78,listening:!1})]})},Ti=I.forwardRef((t,e)=>{const{initialElements:n,elements:o,onChange:s,onSelectionChange:r,onElementCreate:i,onElementDelete:l,onElementDoubleClick:a,width:c="100%",height:d="100%",tools:h,defaultStyle:u,showToolbar:f=!0,toolbarPosition:p="bottom",defaultTool:y,showStylePanel:b=!0,showStatusBar:W=!0,showGrid:v=!1,enableShortcuts:G=!0,theme:$,readOnly:T=!1,className:O,contextMenuItems:ot,renderContextMenu:Y,collaboration:J,workerConfig:P}=t,Q={...hi,...$},_=I.useMemo(()=>({elbowWorkerConfig:P!=null&&P.disabled?{disabled:!0}:P!=null&&P.elbowWorkerUrl?{url:P.elbowWorkerUrl}:void 0,exportWorkerConfig:P!=null&&P.disabled?{disabled:!0}:P!=null&&P.exportWorkerUrl?{url:P.exportWorkerUrl}:void 0}),[P]),x=B(),{elements:C,selectedIds:w,activeTool:S,currentStyle:Z,viewport:X,showGrid:U,isDrawing:D,setIsDrawing:L,setDrawStart:at,drawStart:tt,addElement:E,updateElement:V,setSelectedIds:dt,clearSelection:R,setActiveTool:z,setViewport:et,deleteElements:It,pushHistory:Ct,setElements:rt,setCurrentStyle:st,undo:pt,redo:A,toggleGrid:lt}=x,bt=I.useMemo(()=>rr(w),[w]),{peers:j,updateCursor:Gt}=mi(J??null),Xt=I.useRef(null),Ot=I.useRef(null),Xe=I.useRef(null),jt=hn(),Sn=jt.isEditing,[Nt,vt]=I.useState({width:800,height:600}),[Yt,Ut]=I.useState(null),[yh,qi]=I.useState(null),Ih=I.useRef(null),[Ch,tl]=I.useState(null),[el,je]=I.useState(null),[Qe,hs]=I.useState(null),[le,qe]=I.useState(null),[mh,gs]=I.useState([]),fs=I.useRef(!1),lo=I.useRef(!1),[Ge,ps]=I.useState(!1),Ae=I.useRef(!1),{isDraggingPoint:ys,elementId:nl}=jt,ol=I.useRef([]),Qt=I.useMemo(()=>{let m=null;for(let F=0;F<C.length;F++){const nt=C[F];if(nt.type!=="line"&&nt.type!=="arrow"){m&&(m[F]=nt);continue}const it=nt;if(!it.startBinding&&!it.endBinding){m&&(m[F]=nt);continue}if(ys&&nl===nt.id){m&&(m[F]=nt);continue}const N=Se(it,C);N?(m||(m=C.slice(0,F)),m[F]={...it,...N}):m&&(m[F]=nt)}const M=m??C,K=ol.current;if(M.length===K.length){let F=!0;for(let nt=0;nt<M.length;nt++)if(M[nt]!==K[nt]){F=!1;break}if(F)return K}return ol.current=M,M},[C,ys,nl]),Is=I.useMemo(()=>{const m=new Map;for(const M of Qt)m.set(M.id,M);return m},[Qt]),co=ku(Qt,X,Nt.width,Nt.height,w),bh=li(X.scale),Cs=I.useRef([]),ms=I.useRef([]),{staticElements:Ah,interactiveElements:wh}=I.useMemo(()=>{var it,N;let m=Qe?new Set([...bt,Qe]):bt;if(m.size>0){const H=new Set(m);for(const q of co)if(H.has(q.id)&&((it=q.groupIds)!=null&&it.length)){const gt=q.groupIds[q.groupIds.length-1];for(const ut of co)(N=ut.groupIds)!=null&&N.includes(gt)&&H.add(ut.id)}H.size!==m.size&&(m=H)}const M=[],K=[];for(const H of co)m.has(H.id)?K.push(H):M.push(H);const F=Ei(M,Cs.current)?Cs.current:M,nt=Ei(K,ms.current)?ms.current:K;return Cs.current=F,ms.current=nt,{staticElements:F,interactiveElements:nt}},[co,bt,Qe]),{visibleElements:xh}=ci(Ah,{batchSize:500,threshold:500,enabled:!0});pu(G&&!T,Ot),I.useEffect(()=>{u&&st({...En,...u})},[]),I.useEffect(()=>{n&&n.length>0&&(rt(n),Ct())},[]),I.useEffect(()=>{v!==U&&lt()},[]),I.useEffect(()=>{y&&z(y)},[]),I.useEffect(()=>{o&&rt(o)},[o,rt]);const sl=I.useRef(C);I.useEffect(()=>{s&&C!==sl.current&&s(C),sl.current=C},[C,s]),I.useEffect(()=>{r&&r(w)},[w,r]),I.useEffect(()=>{const m=hn.getState();if(!m.isEditing)return;if(S!=="select"){m.exitEditMode();return}if(w.length!==1||w[0]!==m.elementId){m.exitEditMode();return}const M=C.find(K=>K.id===w[0]);M&&(M.type==="line"||M.type==="arrow")&&(!m.isEditing||m.elementId!==M.id)&&m.enterEditMode(M.id)},[w,S,C]),I.useEffect(()=>{const m=K=>{K.key==="Shift"&&(fs.current=!0)},M=K=>{K.key==="Shift"&&(fs.current=!1)};return window.addEventListener("keydown",m),window.addEventListener("keyup",M),()=>{window.removeEventListener("keydown",m),window.removeEventListener("keyup",M)}},[]),I.useEffect(()=>{const m=F=>{const nt=F.target.tagName;nt==="INPUT"||nt==="TEXTAREA"||nt==="SELECT"||F.code==="Space"&&!Ae.current&&(F.preventDefault(),Ae.current=!0,ps(!0))},M=F=>{F.code==="Space"&&(Ae.current=!1,ps(!1))},K=()=>{Ae.current&&(Ae.current=!1,ps(!1))};return window.addEventListener("keydown",m),window.addEventListener("keyup",M),window.addEventListener("blur",K),()=>{window.removeEventListener("keydown",m),window.removeEventListener("keyup",M),window.removeEventListener("blur",K)}},[]),I.useEffect(()=>{const m=Ot.current;if(!m||T)return;const M=F=>{F.preventDefault(),F.stopPropagation(),F.dataTransfer&&(F.dataTransfer.dropEffect="copy")},K=async F=>{if(F.preventDefault(),F.stopPropagation(),!F.dataTransfer)return;const nt=Yo(F.dataTransfer);if(nt.length===0)return;const it=m.getBoundingClientRect();Xt.current;const N=B.getState().viewport,H=(F.clientX-it.left-N.x)/N.scale,q=(F.clientY-it.top-N.y)/N.scale,gt=B.getState().currentStyle;for(const ut of nt)try{const ft=await Dn(ut),yt=await pn(ft),xt=Ln(ft,yt.naturalWidth,yt.naturalHeight,H,q,{...gt});E(xt),i==null||i(xt),dt([xt.id]),Ct()}catch{}z("select")};return m.addEventListener("dragover",M),m.addEventListener("drop",K),()=>{m.removeEventListener("dragover",M),m.removeEventListener("drop",K)}},[T,E,dt,Ct,z,i]),I.useEffect(()=>{if(T)return;const m=M=>{const K=M.target.tagName;if(K==="INPUT"||K==="TEXTAREA"||K==="SELECT")return;const F=Vo(M);if(F.file||F.imgUrl)M.preventDefault(),M.stopPropagation(),(async()=>{try{const nt=await Br(F);if(!nt)return;const it=await pn(nt),N=B.getState().viewport,H=Ot.current,q=H==null?void 0:H.getBoundingClientRect(),gt=q?(q.width/2-N.x)/N.scale:400,ut=q?(q.height/2-N.y)/N.scale:300,ft=B.getState().currentStyle,yt=Ln(nt,it.naturalWidth,it.naturalHeight,gt,ut,{...ft});E(yt),i==null||i(yt),dt([yt.id]),Ct(),z("select")}catch{}})();else{M.preventDefault(),M.stopPropagation();const nt=$o();if(nt.length===0)return;const it=20,{clones:N,selectedCloneIds:H}=Mn(nt,nt,it);N.forEach(q=>E(q)),dt(H.length>0?H:N.map(q=>q.id)),Ct(),Cn(nt.map(q=>({...q,x:q.x+it,y:q.y+it})))}};return window.addEventListener("paste",m,!0),()=>window.removeEventListener("paste",m,!0)},[T,E,dt,Ct,z,i]),I.useEffect(()=>{const m=Ot.current;if(!m)return;const M=new ResizeObserver(K=>{for(const F of K){const{width:nt,height:it}=F.contentRect;vt({width:Math.floor(nt),height:Math.floor(it)})}});return M.observe(m),()=>M.disconnect()},[]);const kh=I.useCallback(()=>{const m=Xt.current;if(!m)return null;const M=m.getPointerPosition();return M?{x:(M.x-X.x)/X.scale,y:(M.y-X.y)/X.scale}:null},[X]),Sh=I.useCallback(m=>U?{x:At(m.x,xe),y:At(m.y,xe)}:m,[U]),ao=I.useRef(null);ao.current={elements:C,selectedIds:w,activeTool:S,currentStyle:Z,isDrawing:D,drawStart:tt,showGrid:U,addElement:E,updateElement:V,deleteElements:It,setSelectedIds:dt,clearSelection:R,setActiveTool:z,setIsDrawing:L,setDrawStart:at,pushHistory:Ct,getPointerPos:kh,snapPos:Sh,currentElementIdRef:Xe,shiftKeyRef:fs,startBindingRef:Ih,setSnapTarget:qi,selectionBox:Yt,setSelectionBox:Ut,setAutoEditTextId:je,linearEdit:{isEditing:jt.isEditing,elementId:jt.elementId,exitEditMode:jt.exitEditMode,enterEditMode:jt.enterEditMode},onElementCreate:i,onElementDelete:l};const rl=I.useCallback(m=>{if(T||Ae.current)return;if(m.evt.button===2){lo.current=!0,le&&qe(null);return}lo.current=!1;const K=ao.current,F=K.getPointerPos();if(!F||(le&&qe(null),K.activeTool==="hand"||Ge))return;const nt=yn(K.activeTool);nt==null||nt.onMouseDown(m,F,K),Xe.current&&hs(Xe.current)},[T,le,Ge]),il=I.useCallback(m=>{if(Ae.current||T)return;const M=ao.current,K=M.getPointerPos();if(!K)return;Gt(K);const F=yn(M.activeTool);F==null||F.onMouseMove(m,K,M)},[T,Gt]),bs=I.useRef(null),ll=I.useRef(il);ll.current=il;const cl=I.useMemo(()=>{var M,K;(K=(M=bs.current)==null?void 0:M.cancel)==null||K.call(M);const m=sr(F=>{ll.current(F)});return bs.current=m,m},[]);I.useEffect(()=>()=>{var m,M;(M=(m=bs.current)==null?void 0:m.cancel)==null||M.call(m),Yr(),ui()},[]);const al=I.useCallback(()=>{const m=ao.current,M=yn(m.activeTool);M==null||M.onMouseUp(m),requestAnimationFrame(()=>{hs(null)})},[hs]),vh=I.useCallback(m=>{m.evt.preventDefault();const M=Xt.current;if(!M)return;const K=M.getPointerPosition();if(!K)return;const F=1.05,nt=m.evt.deltaY>0?-1:1,it=Math.min(Le,Math.max(De,nt>0?X.scale*F:X.scale/F));et(_n({viewport:X,point:K,targetScale:it}))},[X,et]),Eh=I.useCallback(m=>{S!=="hand"&&!Ae.current&&!Ge||et({x:m.target.x(),y:m.target.y()})},[S,et,Ge]),As=I.useCallback(m=>{var q;const{activeTool:M,elements:K,selectedIds:F,setSelectedIds:nt}=B.getState();if(M!=="select"||T)return;if(lo.current){lo.current=!1;return}const it=K.find(gt=>gt.id===m),N=it&&(it.type==="line"||it.type==="arrow"),H=hn.getState();if(N?(!H.isEditing||H.elementId!==m)&&H.enterEditMode(m):H.isEditing&&H.exitEditMode(),(q=it==null?void 0:it.groupIds)!=null&&q.length){const gt=it.groupIds[it.groupIds.length-1],ut=K.filter(ft=>{var yt;return(yt=ft.groupIds)==null?void 0:yt.includes(gt)}).map(ft=>ft.id);nt(ut)}else nt([m])},[T]),uo=I.useRef(null),ws=I.useRef(!1),xs=I.useRef(!1),we=I.useRef(null),dl=I.useCallback(()=>{ws.current=!1;const m=uo.current;if(!m||m.size===0)return;const M=Array.from(m,([K,F])=>({id:K,updates:F}));m.clear(),B.getState().batchUpdateElements(M)},[]),ho=I.useRef(new Set),ks=I.useCallback((m,M)=>{if(T)return;we.current===null&&(we.current=en.pixelRatio,en.pixelRatio=1);const{elements:K,selectedIds:F}=B.getState();if(F.length>Wi){xs.current=!0;return}xs.current=!1;const nt=K.find(it=>it.id===m);if(nt&&(nt.type==="line"||nt.type==="arrow")&&!ho.current.has(m)){const it=nt;if(it.startBinding||it.endBinding){ho.current.add(m);const N={},H=it.type;if(it.startBinding){const q=B.getState().elements;ve(m,H,it.startBinding,null,q,B.getState().updateElement),N.startBinding=null}if(it.endBinding){const q=B.getState().elements;ve(m,H,it.endBinding,null,q,B.getState().updateElement),N.endBinding=null}B.getState().updateElement(m,{...M,...N});return}}uo.current||(uo.current=new Map),uo.current.set(m,M),ws.current||(ws.current=!0,queueMicrotask(dl))},[T,dl]),ul=I.useCallback((m,M)=>{const{elements:K,selectedIds:F}=B.getState();if(F.length>1)return null;const nt=new Set(F),it=fu(M,K,nt);return gs(it.guides),it.x!==void 0||it.y!==void 0?{x:it.x??M.x,y:it.y??M.y}:null},[]),go=I.useRef(null),Ss=I.useRef(!1),hl=I.useCallback(()=>{Ss.current=!1;const m=go.current;if(!m||m.size===0)return;const M=Array.from(m);m.clear(),xs.current=!1,B.getState().batchUpdateElements(M.map(([H,q])=>({id:H,updates:q}))),gs([]);const F=B.getState().elements,nt=new Map;for(const H of F)nt.set(H.id,H);const it=[],N=new Set;for(const[H]of M){ho.current.delete(H);const q=an(H,F);for(const ut of q){if(N.has(ut.id))continue;N.add(ut.id);const ft=nt.get(ut.id);if(!ft)continue;const yt=Se(ft,F);yt&&it.push({id:ft.id,updates:yt})}const gt=nt.get(H);if(gt!=null&&gt.boundElements&&["rectangle","ellipse","diamond","image"].includes(gt.type))for(const ft of gt.boundElements){if(ft.type!=="text")continue;const yt=nt.get(ft.id);if(!yt)continue;const xt=Math.max(20,gt.width-8);let wt;yt.verticalAlign==="top"?wt=gt.y+4:yt.verticalAlign==="bottom"?wt=gt.y+gt.height-yt.height-4:wt=gt.y+(gt.height-yt.height)/2,it.push({id:ft.id,updates:{x:gt.x+4,y:wt,width:xt}})}}it.length>0&&B.getState().batchUpdateElements(it),B.getState().pushHistory(),we.current!==null&&(en.pixelRatio=we.current,we.current=null)},[]),vs=I.useCallback((m,M)=>{if(T)return;const{selectedIds:K}=B.getState();if(K.length>Wi){go.current||(go.current=new Map),go.current.set(m,M),Ss.current||(Ss.current=!0,queueMicrotask(hl));return}V(m,M),gs([]),ho.current.delete(m);const F=B.getState().elements,nt=new Map;for(const H of F)nt.set(H.id,H);const it=an(m,F);for(const H of it){const q=nt.get(H.id);if(!q)continue;const gt=Se(q,F);gt&&V(q.id,gt)}const N=nt.get(m);if(N!=null&&N.boundElements&&["rectangle","ellipse","diamond","image"].includes(N.type))for(const q of N.boundElements){if(q.type!=="text")continue;const gt=nt.get(q.id);if(!gt)continue;const ut=Math.max(20,N.width-8);let ft;gt.verticalAlign==="top"?ft=N.y+4:gt.verticalAlign==="bottom"?ft=N.y+N.height-gt.height-4:ft=N.y+(N.height-gt.height)/2,V(q.id,{x:N.x+4,y:ft,width:ut})}if((N==null?void 0:N.type)==="text"){const H=N;if(H.containerId){const q=nt.get(H.containerId);if(q&&["rectangle","ellipse","diamond","image"].includes(q.type)){const ut=H.height+8;if(q.height<ut){V(q.id,{height:ut});const ft=B.getState().elements;for(const yt of an(q.id,ft)){const xt=ft.find(Et=>Et.id===yt.id);if(!xt)continue;const wt=Se(xt,ft);wt&&V(xt.id,wt)}}}}}Ct(),we.current!==null&&(en.pixelRatio=we.current,we.current=null)},[V,Ct,T,hl]),Wh=I.useCallback((m,M,K)=>{if(T||M===0&&K===0)return;const F=B.getState(),it=F.elements.filter(yt=>{var xt;return(xt=yt.groupIds)==null?void 0:xt.includes(m)});if(it.length===0)return;const N=it.map(yt=>({id:yt.id,updates:{x:yt.x+M,y:yt.y+K}}));F.batchUpdateElements(N);const H=B.getState().elements,q=new Map;for(const yt of H)q.set(yt.id,yt);const gt=new Set(it.map(yt=>yt.id)),ut=[],ft=new Set;for(const yt of it){const xt=an(yt.id,H);for(const Et of xt){if(ft.has(Et.id)||(ft.add(Et.id),gt.has(Et.id)))continue;const Bt=q.get(Et.id);if(!Bt)continue;const kt=Se(Bt,H);kt&&ut.push({id:Bt.id,updates:kt})}const wt=q.get(yt.id);if(wt!=null&&wt.boundElements&&["rectangle","ellipse","diamond","image"].includes(wt.type))for(const Bt of wt.boundElements){if(Bt.type!=="text"||gt.has(Bt.id))continue;const kt=q.get(Bt.id);if(!kt)continue;const Vt=Math.max(20,wt.width-8);let Dt;kt.verticalAlign==="top"?Dt=wt.y+4:kt.verticalAlign==="bottom"?Dt=wt.y+wt.height-kt.height-4:Dt=wt.y+(wt.height-kt.height)/2,ut.push({id:Bt.id,updates:{x:wt.x+4,y:Dt,width:Vt}})}}ut.length>0&&B.getState().batchUpdateElements(ut),F.pushHistory()},[T]),Es=I.useCallback(m=>{var q,gt;if(T)return;const{activeTool:M,elements:K,currentStyle:F,addElement:nt,updateElement:it,setSelectedIds:N}=B.getState();if(M!=="select")return;const H=K.find(ut=>ut.id===m);if(H&&(a==null?void 0:a(m,H))!==!0){if(H.type==="line"||H.type==="arrow"){const ut=(q=H.boundElements)==null?void 0:q.find(tn=>tn.type==="text");if(ut){N([ut.id]),je(ut.id);return}const ft=Ft(),yt=H,xt=yt.points,wt={x:xt[0],y:xt[1]},Et={x:xt[xt.length-2],y:xt[xt.length-1]};let Bt,kt;if(yt.lineType==="curved"){const tn=Jt(wt,Et,yt.curvature??Kt),vn=Pe(wt,tn,Et,.5);Bt=yt.x+vn.x,kt=yt.y+vn.y}else Bt=yt.x+(wt.x+Et.x)/2,kt=yt.y+(wt.y+Et.y)/2;const Vt={id:ft,type:"text",x:Bt,y:kt,width:100,height:30,rotation:0,style:{...F,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:m,textAlign:"center",verticalAlign:"middle"};nt(Vt),i==null||i(Vt);const Dt=H.boundElements??[];it(m,{boundElements:[...Dt,{id:ft,type:"text"}]}),N([ft]),je(ft);return}if(H.type==="rectangle"||H.type==="ellipse"||H.type==="diamond"||H.type==="image"){const ut=(gt=H.boundElements)==null?void 0:gt.find(wt=>wt.type==="text");if(ut){N([ut.id]),je(ut.id);return}const ft=Ft(),yt={id:ft,type:"text",x:H.x,y:H.y,width:H.width,height:30,rotation:0,style:{...F,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:m,textAlign:"center",verticalAlign:"middle"};nt(yt),i==null||i(yt);const xt=H.boundElements??[];it(m,{boundElements:[...xt,{id:ft,type:"text"}]}),N([ft]),je(ft);return}}},[T,a,i]),Th=I.useCallback((m,M)=>{if(T)return;const{elements:K,updateElement:F,pushHistory:nt}=B.getState(),it=K.find(N=>N.id===m);if(F(m,M),it&&(M.startBinding!==void 0||M.endBinding!==void 0)){const N=it.type;if(M.startBinding!==void 0){const H=B.getState().elements;ve(m,N,it.startBinding,M.startBinding??null,H,B.getState().updateElement)}if(M.endBinding!==void 0){const H=B.getState().elements;ve(m,N,it.endBinding,M.endBinding??null,H,B.getState().updateElement)}}nt()},[T]),Bh=I.useCallback((m,M)=>{T||B.getState().updateElement(m,M)},[T]),Zh=I.useCallback(m=>{qi(m)},[]),gl=I.useCallback(m=>{tl(m)},[]),fl=I.useCallback((m,M)=>{if(tl(null),je(null),M){const{elements:K,updateElement:F,deleteElements:nt,pushHistory:it}=B.getState(),N=K.find(H=>H.id===m);if((N==null?void 0:N.type)==="text"&&N.containerId){const H=N.containerId,q=K.find(gt=>gt.id===H);q!=null&&q.boundElements&&F(H,{boundElements:q.boundElements.filter(gt=>gt.id!==m)})}nt([m]),l==null||l([m])}else B.getState().pushHistory()},[l]),Mh=I.useCallback(m=>{var nt,it;if(T)return;m.preventDefault();const M=Ot.current;if(!M)return;const K=M.getBoundingClientRect(),F=Xt.current;if(F){const N=F.getPointerPosition(),H=(N==null?void 0:N.x)??m.clientX-K.left,q=(N==null?void 0:N.y)??m.clientY-K.top,gt=B.getState().viewport,ut=(H-gt.x)/gt.scale,ft=(q-gt.y)/gt.scale,{elements:yt,selectedIds:xt,setSelectedIds:wt}=B.getState();let Et=null;for(let Bt=yt.length-1;Bt>=0;Bt--){const kt=yt[Bt];if(kt.type==="text"&&kt.containerId)continue;let Vt=kt.x,Dt=kt.y,tn=kt.width,vn=kt.height;if((kt.type==="arrow"||kt.type==="line")&&"points"in kt){const Ws=kt.points,Ts=[],Bs=[];for(let po=0;po<Ws.length;po+=2)Ts.push(kt.x+Ws[po]),Bs.push(kt.y+Ws[po+1]);Vt=Math.min(...Ts),Dt=Math.min(...Bs),tn=Math.max(...Ts)-Vt,vn=Math.max(...Bs)-Dt}const fo=Math.max(4,((nt=kt.style)==null?void 0:nt.strokeWidth)??2);if(ut>=Vt-fo&&ut<=Vt+tn+fo&&ft>=Dt-fo&&ft<=Dt+vn+fo){Et=kt;break}}if(Et&&!xt.includes(Et.id))if((it=Et.groupIds)!=null&&it.length){const Bt=Et.groupIds[Et.groupIds.length-1],kt=yt.filter(Vt=>{var Dt;return(Dt=Vt.groupIds)==null?void 0:Dt.includes(Bt)}).map(Vt=>Vt.id);wt(kt)}else wt([Et.id])}qe({x:m.clientX-K.left,y:m.clientY-K.top})},[T]),_h=I.useMemo(()=>{var it;const m=w.length>0,K=navigator.platform.includes("Mac")?"⌘":"Ctrl+",F=[];F.push({label:"Copy",shortcut:`${K}C`,disabled:!m,action:()=>{m&&Cn(tr(w,C))}}),F.push({label:"Paste",shortcut:`${K}V`,disabled:!Rd(),action:()=>{const N=$o();if(N.length===0)return;const H=20,{clones:q,selectedCloneIds:gt}=Mn(N,N,H);q.forEach(ut=>E(ut)),dt(gt.length>0?gt:q.map(ut=>ut.id)),Ct(),Cn(N.map(ut=>({...ut,x:ut.x+H,y:ut.y+H})))}}),F.push({label:"Duplicate",shortcut:`${K}D`,disabled:!m,action:()=>{m&&x.duplicateElements(w)}}),F.push({label:"Delete",shortcut:"Del",disabled:!m,divider:!0,action:()=>{m&&(It(w),l==null||l(w))}}),F.push({label:"Bring to Front",shortcut:`${K}⇧]`,disabled:!m,divider:!0,action:()=>{m&&x.bringToFront(w)}}),F.push({label:"Send to Back",shortcut:`${K}⇧[`,disabled:!m,action:()=>{m&&x.sendToBack(w)}});let nt=!1;if(w.length>=2){const N=C.filter(ut=>w.includes(ut.id)),H=new Set(N.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length}).map(ut=>ut.groupIds[ut.groupIds.length-1]));N.every(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length})&&H.size===1||(F.push({label:"Group",shortcut:`${K}G`,divider:!0,action:()=>x.groupElements(w)}),nt=!0)}if(m){const N=C.filter(q=>w.includes(q.id));if(N.some(q=>{var gt;return(gt=q.groupIds)==null?void 0:gt.length})){const q=new Set;for(const ut of N)(it=ut.groupIds)!=null&&it.length&&q.add(ut.groupIds[ut.groupIds.length-1]);const gt=C.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.some(yt=>q.has(yt))}).map(ut=>ut.id);F.push({label:"Ungroup",shortcut:`${K}⇧G`,divider:!nt,action:()=>x.ungroupElements(gt)})}}if(F.push({label:"Select All",shortcut:`${K}A`,divider:!0,action:()=>dt(C.map(N=>N.id))}),m){const N=C.filter(gt=>w.includes(gt.id)),H=N.every(gt=>gt.isLocked),q=N.some(gt=>gt.isLocked);F.push({label:H?"Unlock":q?"Unlock All":"Lock",shortcut:`${K}⇧L`,divider:!0,action:()=>x.toggleLockElements(w)})}if(m){const N=new Set(["rectangle","ellipse","diamond"]),H=C.filter(q=>w.includes(q.id)&&N.has(q.type));if(H.length>0){const q=new Set(H.map(ft=>ft.type)),ut=[{label:"Rectangle",type:"rectangle"},{label:"Ellipse",type:"ellipse"},{label:"Diamond",type:"diamond"}].filter(ft=>!q.has(ft.type)||q.size>1);ut.length>0&&ut.forEach((ft,yt)=>{F.push({label:`Convert to ${ft.label}`,divider:yt===0,action:()=>x.convertElementType(H.map(xt=>xt.id),ft.type)})})}}if(ot){const N=typeof ot=="function"?ot({selectedIds:w,elements:C,position:le??{x:0,y:0},close:()=>qe(null)}):ot;if(N.length>0){F.push({...N[0],divider:!0});for(let H=1;H<N.length;H++)F.push(N[H])}}return F},[w,C,x,E,It,dt,Ct,l,ot,le]);I.useImperativeHandle(e,()=>({getElements:()=>B.getState().elements,setElements:m=>{rt(m),Ct()},addElement:m=>{E(m)},deleteElements:m=>{It(m)},getSelectedIds:()=>B.getState().selectedIds,setSelectedIds:m=>{dt(m)},clearSelection:()=>{R()},setActiveTool:m=>{z(m)},getActiveTool:()=>B.getState().activeTool,undo:()=>{pt()},redo:()=>{A()},zoomTo:m=>{et({scale:Math.min(Le,Math.max(De,m))})},resetView:()=>{et({x:0,y:0,scale:1})},scrollToElement:(m,M)=>{const K=B.getState().elements.find(wt=>wt.id===m);if(!K)return;const F=Ot.current;if(!F)return;const nt=F.getBoundingClientRect(),it=nt.width,N=nt.height,H=(M==null?void 0:M.zoom)??Math.max(B.getState().viewport.scale,1),q=Math.min(Le,Math.max(De,H)),gt=K.x+(K.width??0)/2,ut=K.y+(K.height??0)/2,ft=it/2-gt*q,yt=N/2-ut*q,xt={x:ft,y:yt,scale:q};M!=null&&M.animate?Ee(B.getState().viewport,xt,et):et(xt)},zoomToFit:(m,M)=>{const K=Ot.current;if(!K)return;const F=K.getBoundingClientRect(),nt=F.width,it=F.height;B.getState().zoomToFit(nt,it,m,{padding:M==null?void 0:M.padding,maxZoom:M==null?void 0:M.maxZoom,animate:M==null?void 0:M.animate})},exportPNG:()=>{var m;return((m=Xt.current)==null?void 0:m.toDataURL({pixelRatio:2}))??null},exportJSON:()=>JSON.stringify(B.getState().elements,null,2),exportSVG:()=>Ne(B.getState().elements),importJSON:m=>{try{const M=JSON.parse(m);Array.isArray(M)&&(rt(M),Ct())}catch{}},getStage:()=>Xt.current}));const Xh=()=>{var M;if(T)return"default";if(Ge||S==="hand")return"grab";const m=yn(S);return((M=m==null?void 0:m.getCursor)==null?void 0:M.call(m))??"default"},Gh=h?yo.filter(m=>h.includes(m.type)):yo,Dh=b&&!T&&(!["hand","select","eraser"].includes(S)||S==="select"&&w.length>0),pl=!Ge&&["select","eraser","image"].includes(S);return g.jsx(Oo.Provider,{value:_,children:g.jsxs("div",{ref:Ot,className:O,onContextMenu:Mh,onMouseLeave:()=>Gt(null),style:{position:"relative",width:c,height:d,overflow:"hidden",background:Q.canvasBackground},children:[f&&!T&&p!=="hidden"&&g.jsx(Ld,{visibleTools:Gh,theme:Q,position:p}),Dh&&g.jsx(Kd,{theme:Q}),g.jsx("div",{style:{cursor:Xh(),position:"absolute",top:0,left:0,right:0,bottom:0},children:g.jsxs(ht.Stage,{ref:Xt,width:Nt.width,height:Nt.height,x:X.x,y:X.y,scaleX:X.scale,scaleY:X.scale,draggable:(S==="hand"||Ge)&&!T,onMouseDown:rl,onMouseMove:cl,onMouseUp:al,onWheel:vh,onDragEnd:Eh,onTouchStart:rl,onTouchMove:cl,onTouchEnd:al,children:[U&&g.jsx(ht.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(Wa,{width:Nt.width,height:Nt.height,viewport:X,gridColor:Q.gridColor})}),g.jsx(Pu,{elements:xh,listening:pl,onSelect:As,onChange:vs,onDragMove:ks,onDoubleClick:Es,autoEditTextId:el,onTextEditStart:gl,onTextEditEnd:fl,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:ul,viewportScale:X.scale,onGroupDragEnd:Wh}),g.jsxs(ht.Layer,{listening:pl,children:[wh.filter(m=>m.id!==Qe).map(m=>g.jsx(Hn,{element:m,isSelected:!0,isEditing:Sn&&jt.elementId===m.id,onSelect:As,onChange:vs,onDragMove:ks,onDoubleClick:Es,autoEditText:el===m.id,onTextEditStart:gl,onTextEditEnd:fl,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:ul,viewportScale:bh},m.id)),S==="select"&&!T&&(()=>{const m=w.filter(M=>{const K=Is.get(M);return!(!K||K.type==="line"||K.type==="arrow"||K.type==="text"&&K.containerId||M===Ch)});return m.length===0?null:g.jsx(va,{selectedIds:m,selectionColor:Q.selectionColor})})(),Sn&&(()=>{const m=Is.get(jt.elementId??"");return m?g.jsx(Na,{element:m,allElements:Qt,onPointsChange:Th,onPointDragMove:Bh,onSnapTargetChange:Zh,color:Q.selectionColor}):null})()]}),Qe&&(()=>{const m=Is.get(Qe);return m?g.jsx(ht.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(Hn,{element:m,isSelected:!1,onSelect:As,onChange:vs,onDragMove:ks,onDoubleClick:Es,allElements:Qt,gridSnap:U?xe:void 0,viewportScale:X.scale},m.id)}):null})(),g.jsxs(ht.Layer,{listening:!1,hitGraphEnabled:!1,children:[g.jsx(Ba,{box:Yt,selectionColor:Q.selectionColor,viewportScale:X.scale}),g.jsx(_a,{elements:Qt,snapTarget:yh,visible:(S==="line"||S==="arrow"||ys)&&!T,color:Q.selectionColor,viewportScale:X.scale}),mh.map((m,M)=>m.orientation==="v"?g.jsx(ht.Line,{points:[m.position,m.start,m.position,m.end],stroke:Q.selectionColor,strokeWidth:1/X.scale,dash:[4/X.scale,4/X.scale],listening:!1,perfectDrawEnabled:!1},`ag-${M}`):g.jsx(ht.Line,{points:[m.start,m.position,m.end,m.position],stroke:Q.selectionColor,strokeWidth:1/X.scale,dash:[4/X.scale,4/X.scale],listening:!1,perfectDrawEnabled:!1},`ag-${M}`)),Qt.filter(m=>m.isLocked&&bt.has(m.id)).map(m=>g.jsx(Hu,{element:m,scale:X.scale},`lock-${m.id}`)),j.length>0&&g.jsx(vi,{peers:j,viewport:X,stageWidth:Nt.width,stageHeight:Nt.height,elements:Qt})]})]})}),le&&(Y?Y({selectedIds:w,elements:C,position:le,close:()=>qe(null)}):g.jsx($d,{x:le.x,y:le.y,items:_h,onClose:()=>qe(null),theme:Q})),W&&g.jsx(Ou,{theme:Q})]})})});Ti.displayName="FlowCanvas";const Ou=I.memo(({theme:t})=>{const e=B(s=>s.elements.length),n=B(s=>s.activeTool),o=B(s=>s.selectedIds.length);return g.jsxs("div",{style:{position:"absolute",bottom:16,left:12,zIndex:50,display:"flex",alignItems:"center",gap:10,background:t.toolbarBg,backdropFilter:"blur(8px)",boxShadow:"0 1px 3px rgba(0,0,0,0.08)",borderRadius:8,padding:"4px 12px",border:`1px solid ${t.toolbarBorder}`,fontSize:11,color:t.mutedTextColor,userSelect:"none"},children:[g.jsxs("span",{children:["Tool: ",g.jsx("strong",{style:{color:t.textColor,textTransform:"capitalize"},children:n})]}),g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Elements: ",g.jsx("strong",{style:{color:t.textColor},children:e})]}),o>0&&g.jsxs(g.Fragment,{children:[g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Selected: ",g.jsx("strong",{style:{color:t.activeToolColor},children:o})]})]})]})}),Bi={rectangle:0,ellipse:1,diamond:2,line:3,arrow:4,freedraw:5,text:6,image:7};class Zi{constructor(e=1024){ct(this,"_data");ct(this,"_capacity",0);ct(this,"_indexMap",new Map);this._data=this._allocate(e),this._capacity=e}get length(){return this._data.length}get data(){return this._data}_allocate(e){return{ids:new Array(e),x:new Float64Array(e),y:new Float64Array(e),w:new Float64Array(e),h:new Float64Array(e),types:new Uint8Array(e),length:0}}_ensureCapacity(e){if(e<=this._capacity)return;const n=Math.max(e,this._capacity*2),o=this._data,s=this._allocate(n);s.x.set(o.x.subarray(0,o.length)),s.y.set(o.y.subarray(0,o.length)),s.w.set(o.w.subarray(0,o.length)),s.h.set(o.h.subarray(0,o.length)),s.types.set(o.types.subarray(0,o.length));for(let r=0;r<o.length;r++)s.ids[r]=o.ids[r];s.length=o.length,this._data=s,this._capacity=n}rebuild(e){const n=e.length;this._ensureCapacity(n),this._indexMap.clear();const{ids:o,x:s,y:r,w:i,h:l,types:a}=this._data;for(let c=0;c<n;c++){const d=e[c];o[c]=d.id,s[c]=d.x,r[c]=d.y,i[c]=d.width,l[c]=d.height,a[c]=Bi[d.type]??0,this._indexMap.set(d.id,c)}this._data.length=n}updateElement(e){const n=this._indexMap.get(e.id);return n===void 0?!1:(this._data.x[n]=e.x,this._data.y[n]=e.y,this._data.w[n]=e.width,this._data.h[n]=e.height,!0)}cullViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,{ids:u,x:f,y:p,w:y,h:b,length:W}=this._data,v=[];for(let G=0;G<W;G++){const $=f[G],T=p[G],O=y[G],ot=b[G];$+O>=a&&$<=d&&T+ot>=c&&T<=h&&v.push(u[G])}return v}queryRect(e,n,o,s){const{ids:r,x:i,y:l,w:a,h:c,length:d}=this._data,h=[];for(let u=0;u<d;u++){const f=i[u],p=l[u],y=a[u],b=c[u];f+y>=e&&f<=o&&p+b>=n&&p<=s&&h.push(r[u])}return h}queryPoint(e,n){const{ids:o,x:s,y:r,w:i,h:l,length:a}=this._data,c=[];for(let d=0;d<a;d++)e>=s[d]&&e<=s[d]+i[d]&&n>=r[d]&&n<=r[d]+l[d]&&c.push(o[d]);return c}clear(){this._data.length=0,this._indexMap.clear()}}let ls=null;function Nu(){return ls||(ls=new Zi),ls}const Lt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cs=Lt.length,Je=Lt[0],Uu=Lt[cs-1];function zu(t,e){const n=Lt.indexOf(t),o=Lt.indexOf(e);if(o-n<=1)return null;const s=Math.floor((n+o)/2);return Lt[s]}function as(t,e){return t===null&&e===null?"a0":e===null?Mi(t):t===null?Ku(e):Ju(t,e)}function ds(t,e,n){if(n===0)return[];if(n===1)return[as(t,e)];const o=Math.floor(n/2),s=as(t,e),r=ds(t,s,o),i=ds(s,e,n-o-1);return[...r,s,...i]}function Mi(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o<cs-1)return e[n]=Lt[o+1],e.join("");e[n]=Je}return t+Lt[1]}function Ku(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o>0){e[n]=Lt[o-1];let s=e.join("");for(;s.length>1&&s.endsWith(Je);)s=s.slice(0,-1);return s}e[n]=Uu}return Je+t}function Ju(t,e){const n=Math.max(t.length,e.length),o=t.padEnd(n,Je),s=e.padEnd(n,Je);let r="";for(let i=0;i<n;i++){if(o[i]===s[i]){r+=o[i];continue}const l=zu(o[i],s[i]);return l!==null?r+l:r+o[i]+Mi(o.slice(i+1).replace(/0+$/,"")||Je)}return t+Lt[Math.floor(cs/2)]}function $u(t){if(!t||t.length===0)return!1;for(const e of t)if(Lt.indexOf(e)===-1)return!1;return!0}function Ru(t,e){return t===e?0:t<e?-1:1}class ju{constructor(e=1e4){ct(this,"_entries",[]);ct(this,"_maxEntries");this._maxEntries=e}push(e){this._entries.push(e),this._entries.length>this._maxEntries&&(this._entries=this._entries.slice(this._entries.length-this._maxEntries))}get entries(){return this._entries}entriesSince(e){return this._entries.filter(n=>n.timestamp>=e)}entriesByClient(e){return this._entries.filter(n=>n.clientId===e)}clear(){this._entries=[]}get length(){return this._entries.length}}function _i(t){return{type:"add",element:t}}function Xi(t){return{type:"delete",elementId:t}}function Gi(t,e,n){return{type:"move",elementId:t,dx:e,dy:n}}function Di(t,e,n,o,s){return{type:"resize",elementId:t,width:e,height:n,x:o,y:s}}function Li(t,e){return{type:"style",elementId:t,changes:e}}function Yi(t,e){return{type:"rotate",elementId:t,rotation:e}}function Vi(t,e){return{type:"reorder",elementId:t,sortOrder:e}}function Fi(t,e){return{type:"updatePoints",elementId:t,points:e}}function Pi(t,e){return{type:"setText",elementId:t,text:e}}function Qu(...t){return{type:"batch",operations:t}}function Hi(t,e){switch(e.type){case"add":return[...t,e.element];case"delete":return t.filter(n=>n.id!==e.elementId);case"move":return t.map(n=>n.id===e.elementId?{...n,x:n.x+e.dx,y:n.y+e.dy}:n);case"resize":return t.map(n=>n.id===e.elementId?{...n,width:e.width,height:e.height,...e.x!==void 0?{x:e.x}:{},...e.y!==void 0?{y:e.y}:{}}:n);case"style":return t.map(n=>n.id===e.elementId?{...n,style:{...n.style,...e.changes}}:n);case"rotate":return t.map(n=>n.id===e.elementId?{...n,rotation:e.rotation}:n);case"reorder":return t.map(n=>n.id===e.elementId?{...n,sortOrder:e.sortOrder}:n);case"updatePoints":return t.map(n=>n.id!==e.elementId?n:"points"in n?{...n,points:e.points}:n);case"setText":return t.map(n=>n.id!==e.elementId?n:n.type==="text"?{...n,text:e.text}:n);case"batch":{let n=t;for(const o of e.operations)n=Hi(n,o);return n}default:return t}}function qu(t,e){const n=[],o=new Map,s=new Map;for(const r of t)o.set(r.id,r);for(const r of e)s.set(r.id,r);for(const r of e)o.has(r.id)||n.push(_i(r));for(const r of t)s.has(r.id)||n.push(Xi(r.id));for(const r of e){const i=o.get(r.id);if(!i||i===r)continue;(i.x!==r.x||i.y!==r.y)&&n.push(Gi(r.id,r.x-i.x,r.y-i.y)),(i.width!==r.width||i.height!==r.height)&&n.push(Di(r.id,r.width,r.height)),i.rotation!==r.rotation&&n.push(Yi(r.id,r.rotation));const l={};let a=!1;for(const c of Object.keys(r.style))i.style[c]!==r.style[c]&&(l[c]=r.style[c],a=!0);if(a&&n.push(Li(r.id,l)),r.type==="text"&&i.type==="text"&&r.text!==i.text&&n.push(Pi(r.id,r.text)),(r.type==="line"||r.type==="arrow"||r.type==="freedraw")&&(i.type==="line"||i.type==="arrow"||i.type==="freedraw")){const c=r.points,d=i.points;(c.length!==d.length||c.some((h,u)=>h!==d[u]))&&n.push(Fi(r.id,c))}i.sortOrder!==r.sortOrder&&r.sortOrder!==void 0&&n.push(Vi(r.id,r.sortOrder))}return n}class th{constructor(){ct(this,"_doc",null);ct(this,"_provider",null);ct(this,"_config",null);ct(this,"_isApplyingRemote",!1);ct(this,"_isApplyingLocal",!1);ct(this,"_lastElements",[]);ct(this,"_syncTimer",null);ct(this,"_deepTimer",null);ct(this,"_dirtyIds",new Set);ct(this,"_storeUnsub",null);ct(this,"_yObserverCleanup",null);ct(this,"_statusListeners",new Set)}get doc(){return this._doc}get provider(){return this._provider}get config(){return this._config}get isActive(){return this._provider!==null&&this._provider.wsconnected}connect(e){return this.dispose(),this._config=e,this._doc=new zt.Doc,this._provider=new _s.WebsocketProvider(e.serverUrl,e.roomName,this._doc,{connect:!0,params:e.authToken?{token:e.authToken}:void 0}),this._provider.awareness.setLocalState({user:e.user,cursor:null,selectedIds:[]}),this._provider.on("status",n=>{const o=n.status;for(const s of this._statusListeners)s(o)}),{doc:this._doc,provider:this._provider}}getYElements(){var e;return(e=this._doc)==null?void 0:e.getMap("elements")}updateAwareness(e){if(!this._provider)return;const n=this._provider.awareness.getLocalState();this._provider.awareness.setLocalState({...n,...e})}getRemoteAwareness(){if(!this._provider)return new Map;const e=this._provider.awareness.getStates(),n=this._provider.awareness.clientID,o=new Map;for(const[s,r]of e)s!==n&&r&&r.user&&o.set(s,r);return o}onStatusChange(e){return this._statusListeners.add(e),()=>{this._statusListeners.delete(e)}}startSync(e,n=50){const o=this._doc,s=this.getYElements();if(!o||!s){console.warn("[CollaborationManager] Cannot start sync — not connected");return}if(this.stopSync(),s.size>0){this._isApplyingRemote=!0;const l=this._yMapCollectionToElements(s);e.setElements(l),this._lastElements=l,this._isApplyingRemote=!1}else{const l=e.getState().elements;l.length>0&&(this._isApplyingLocal=!0,o.transact(()=>{for(const a of l){const c=new zt.Map;xn(a,c),s.set(a.id,c)}},"local-init"),this._isApplyingLocal=!1),this._lastElements=l}const r=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||this._isApplyingLocal)return;this._isApplyingRemote=!0;let c=[...this._lastElements],d=!1;for(const[h,u]of l.keys)if(u.action==="add"||u.action==="update"){const f=s.get(h);if(f){const p=Be(f);if(p){const y=c.findIndex(b=>b.id===h);y>=0?c[y]=p:c.push(p),d=!0}}}else u.action==="delete"&&(c=c.filter(f=>f.id!==h),d=!0);d&&(c.sort((h,u)=>h.sortOrder&&u.sortOrder?h.sortOrder<u.sortOrder?-1:h.sortOrder>u.sortOrder?1:0:0),e.setElements(c),this._lastElements=c),this._isApplyingRemote=!1},i=l=>{if(!this._isApplyingLocal){for(const a of l){let c=a.target;for(;c&&!(c instanceof zt.Map&&c.parent===s);)c=c.parent;if(c instanceof zt.Map){const d=c.get("id");d&&this._dirtyIds.add(d)}}this._deepTimer&&clearTimeout(this._deepTimer),this._deepTimer=setTimeout(()=>{if(this._dirtyIds.size===0||this._isApplyingLocal)return;this._isApplyingRemote=!0;let a=[...this._lastElements],c=!1;for(const d of this._dirtyIds){const h=s.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}this._dirtyIds.clear(),c&&(e.setElements(a),this._lastElements=a),this._isApplyingRemote=!1},16)}};s.observe(r),s.observeDeep(i),this._yObserverCleanup=()=>{s.unobserve(r),s.unobserveDeep(i),this._deepTimer&&clearTimeout(this._deepTimer),this._dirtyIds.clear()},this._storeUnsub=e.subscribe(l=>{this._isApplyingRemote||l.elements!==this._lastElements&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(()=>{this._syncLocalToYjs(l.elements,s,o)},n))})}stopSync(){var e,n;(e=this._storeUnsub)==null||e.call(this),this._storeUnsub=null,(n=this._yObserverCleanup)==null||n.call(this),this._yObserverCleanup=null,this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=null),this._lastElements=[]}dispose(){this.stopSync(),this._provider&&(this._provider.awareness.setLocalState(null),this._provider.disconnect(),this._provider.destroy(),this._provider=null),this._doc&&(this._doc.destroy(),this._doc=null),this._config=null,this._statusListeners.clear()}_syncLocalToYjs(e,n,o){this._isApplyingLocal=!0,this._lastElements=e;const s=new Map;for(const r of e)s.set(r.id,r);o.transact(()=>{for(const[r]of n.entries())s.has(r)||n.delete(r);for(const r of e){let i=n.get(r.id);i?this._updateYMapFromElement(r,i):(i=new zt.Map,xn(r,i),n.set(r.id,i))}},"local-sync"),this._isApplyingLocal=!1}_updateYMapFromElement(e,n){const o=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],s=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"],r=e;for(const l of o){const a=r[l];a!==n.get(l)&&n.set(l,a)}if(e.style)for(const l of s){const a=e.style[l];a!==n.get(`style.${l}`)&&n.set(`style.${l}`,a)}const i=e.boundElements?JSON.stringify(e.boundElements):null;switch(i!==n.get("boundElements")&&n.set("boundElements",i),e.type){case"rectangle":e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius);break;case"line":case"arrow":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a),e.lineType!==n.get("lineType")&&n.set("lineType",e.lineType),e.curvature!==n.get("curvature")&&n.set("curvature",e.curvature);const c=e.startBinding?JSON.stringify(e.startBinding):null;c!==n.get("startBinding")&&n.set("startBinding",c);const d=e.endBinding?JSON.stringify(e.endBinding):null;d!==n.get("endBinding")&&n.set("endBinding",d),e.type==="arrow"&&(e.startArrowhead!==n.get("startArrowhead")&&n.set("startArrowhead",e.startArrowhead),e.endArrowhead!==n.get("endArrowhead")&&n.set("endArrowhead",e.endArrowhead));break}case"freedraw":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a);break}case"text":e.text!==n.get("text")&&n.set("text",e.text),e.containerId!==n.get("containerId")&&n.set("containerId",e.containerId),e.textAlign!==n.get("textAlign")&&n.set("textAlign",e.textAlign),e.verticalAlign!==n.get("verticalAlign")&&n.set("verticalAlign",e.verticalAlign);break;case"image":e.src!==n.get("src")&&n.set("src",e.src),e.naturalWidth!==n.get("naturalWidth")&&n.set("naturalWidth",e.naturalWidth),e.naturalHeight!==n.get("naturalHeight")&&n.set("naturalHeight",e.naturalHeight),e.scaleMode!==n.get("scaleMode")&&n.set("scaleMode",e.scaleMode);const l=e.crop?JSON.stringify(e.crop):null;l!==n.get("crop")&&n.set("crop",l),e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius),e.alt!==n.get("alt")&&n.set("alt",e.alt);break}}_yMapCollectionToElements(e){const n=[];for(const[,o]of e.entries()){const s=Be(o);s&&n.push(s)}return n.sort((o,s)=>o.sortOrder&&s.sortOrder?o.sortOrder<s.sortOrder?-1:o.sortOrder>s.sortOrder?1:0:0),n}}class eh{constructor(e){ct(this,"_worker",null);ct(this,"_callbacks");this._callbacks=e}connect(e,n){if(this.dispose(),this._worker=Vn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGNvbGxhYm9yYXRpb24vc3luY1dvcmtlci53b3JrZXIudHMg4oCUIFdlYiBXb3JrZXIgaW1wbGVtZW50YXRpb24uCiAqCiAqIFJ1bnMgWWpzIGRvY3VtZW50ICsgV2ViU29ja2V0IHByb3ZpZGVyICsgc3luYyBsb2dpYyBlbnRpcmVseSBvZmYgdGhlCiAqIG1haW4gdGhyZWFkLiBDb21tdW5pY2F0ZXMgd2l0aCB0aGUgbWFpbiB0aHJlYWQgdmlhIHBvc3RNZXNzYWdlLgogKgogKiBUaGlzIGZpbGUgaXMgZGVzaWduZWQgdG8gYmUgaW1wb3J0ZWQgdmlhIFZpdGUncyBgbmV3IFdvcmtlcihuZXcgVVJMKC4uLikpYC4KICovCgovLyBJbXBvcnQgWWpzICh5anMgYW5kIHktd2Vic29ja2V0IGFyZSBwdXJlIEpTIOKAlCBubyBET00gZGVwZW5kZW5jeSkKaW1wb3J0ICogYXMgWSBmcm9tICd5anMnOwppbXBvcnQgeyBXZWJzb2NrZXRQcm92aWRlciB9IGZyb20gJ3ktd2Vic29ja2V0JzsKaW1wb3J0IHR5cGUgeyBXb3JrZXJJbk1lc3NhZ2UsIFdvcmtlck91dE1lc3NhZ2UgfSBmcm9tICcuL3N5bmNXb3JrZXInOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQgfSBmcm9tICdAL3R5cGVzJzsKaW1wb3J0IHR5cGUgeyBBd2FyZW5lc3NTdGF0ZSwgQ29sbGFib3JhdGlvbkNvbmZpZyB9IGZyb20gJy4vdHlwZXMnOwppbXBvcnQgeyBlbGVtZW50VG9ZTWFwLCB5TWFwVG9FbGVtZW50LCBTWU5DX0ZJRUxEUywgU1RZTEVfRklFTERTIH0gZnJvbSAnLi9zeW5jQnJpZGdlQ29kZWMnOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBTdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmxldCBfZG9jOiBZLkRvYyB8IG51bGwgPSBudWxsOwpsZXQgX3Byb3ZpZGVyOiBXZWJzb2NrZXRQcm92aWRlciB8IG51bGwgPSBudWxsOwpsZXQgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKbGV0IF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKbGV0IF9sYXN0RWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwpsZXQgX3N5bmNUaW1lcjogUmV0dXJuVHlwZTx0eXBlb2Ygc2V0VGltZW91dD4gfCBudWxsID0gbnVsbDsKbGV0IF9kZWVwVGltZXI6IFJldHVyblR5cGU8dHlwZW9mIHNldFRpbWVvdXQ+IHwgbnVsbCA9IG51bGw7CmNvbnN0IF9kaXJ0eUlkcyA9IG5ldyBTZXQ8c3RyaW5nPigpOwpsZXQgX3N5bmNEZWJvdW5jZU1zID0gNTA7CgovLyDilIDilIDilIAgUG9zdCBNZXNzYWdlIEhlbHBlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIHBvc3QobXNnOiBXb3JrZXJPdXRNZXNzYWdlKTogdm9pZCB7CiAgICBzZWxmLnBvc3RNZXNzYWdlKG1zZyk7Cn0KCi8vIOKUgOKUgOKUgCBZLk1hcCBDb2xsZWN0aW9uIEhlbHBlcnMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpmdW5jdGlvbiB5TWFwQ29sbGVjdGlvblRvRWxlbWVudHMoeUVsZW1lbnRzOiBZLk1hcDxZLk1hcDx1bmtub3duPj4pOiBDYW52YXNFbGVtZW50W10gewogICAgY29uc3QgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwogICAgZm9yIChjb25zdCBbLCB5TWFwXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgY29uc3QgZWwgPSB5TWFwVG9FbGVtZW50KHlNYXApOwogICAgICAgIGlmIChlbCkgZWxlbWVudHMucHVzaChlbCk7CiAgICB9CiAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgaWYgKGEuc29ydE9yZGVyICYmIGIuc29ydE9yZGVyKSB7CiAgICAgICAgICAgIHJldHVybiBhLnNvcnRPcmRlciA8IGIuc29ydE9yZGVyID8gLTEgOiBhLnNvcnRPcmRlciA+IGIuc29ydE9yZGVyID8gMSA6IDA7CiAgICAgICAgfQogICAgICAgIHJldHVybiAwOwogICAgfSk7CiAgICByZXR1cm4gZWxlbWVudHM7Cn0KCmZ1bmN0aW9uIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbDogQ2FudmFzRWxlbWVudCwgeU1hcDogWS5NYXA8dW5rbm93bj4pOiB2b2lkIHsKICAgIGNvbnN0IGVsUmVjb3JkID0gZWwgYXMgdW5rbm93biBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPjsKICAgIGZvciAoY29uc3QgZmllbGQgb2YgU1lOQ19GSUVMRFMpIHsKICAgICAgICBjb25zdCB2YWx1ZSA9IGVsUmVjb3JkW2ZpZWxkXTsKICAgICAgICBpZiAodmFsdWUgIT09IHlNYXAuZ2V0KGZpZWxkKSkgeU1hcC5zZXQoZmllbGQsIHZhbHVlKTsKICAgIH0KCiAgICBpZiAoZWwuc3R5bGUpIHsKICAgICAgICBmb3IgKGNvbnN0IHNmIG9mIFNUWUxFX0ZJRUxEUykgewogICAgICAgICAgICBjb25zdCB2YWwgPSBlbC5zdHlsZVtzZl07CiAgICAgICAgICAgIGlmICh2YWwgIT09IHlNYXAuZ2V0KGBzdHlsZS4ke3NmfWApKSB5TWFwLnNldChgc3R5bGUuJHtzZn1gLCB2YWwpOwogICAgICAgIH0KICAgIH0KCiAgICBjb25zdCBiZUpzb24gPSBlbC5ib3VuZEVsZW1lbnRzID8gSlNPTi5zdHJpbmdpZnkoZWwuYm91bmRFbGVtZW50cykgOiBudWxsOwogICAgaWYgKGJlSnNvbiAhPT0geU1hcC5nZXQoJ2JvdW5kRWxlbWVudHMnKSkgeU1hcC5zZXQoJ2JvdW5kRWxlbWVudHMnLCBiZUpzb24pOwoKICAgIHN3aXRjaCAoZWwudHlwZSkgewogICAgICAgIGNhc2UgJ3JlY3RhbmdsZSc6CiAgICAgICAgICAgIGlmIChlbC5jb3JuZXJSYWRpdXMgIT09IHlNYXAuZ2V0KCdjb3JuZXJSYWRpdXMnKSkgeU1hcC5zZXQoJ2Nvcm5lclJhZGl1cycsIGVsLmNvcm5lclJhZGl1cyk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgJ2xpbmUnOgogICAgICAgIGNhc2UgJ2Fycm93JzogewogICAgICAgICAgICBjb25zdCBwdHNKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKHB0c0pzb24gIT09IHlNYXAuZ2V0KCdwb2ludHMnKSkgeU1hcC5zZXQoJ3BvaW50cycsIHB0c0pzb24pOwogICAgICAgICAgICBpZiAoZWwubGluZVR5cGUgIT09IHlNYXAuZ2V0KCdsaW5lVHlwZScpKSB5TWFwLnNldCgnbGluZVR5cGUnLCBlbC5saW5lVHlwZSk7CiAgICAgICAgICAgIGlmIChlbC5jdXJ2YXR1cmUgIT09IHlNYXAuZ2V0KCdjdXJ2YXR1cmUnKSkgeU1hcC5zZXQoJ2N1cnZhdHVyZScsIGVsLmN1cnZhdHVyZSk7CiAgICAgICAgICAgIGNvbnN0IHNiSnNvbiA9IGVsLnN0YXJ0QmluZGluZyA/IEpTT04uc3RyaW5naWZ5KGVsLnN0YXJ0QmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoc2JKc29uICE9PSB5TWFwLmdldCgnc3RhcnRCaW5kaW5nJykpIHlNYXAuc2V0KCdzdGFydEJpbmRpbmcnLCBzYkpzb24pOwogICAgICAgICAgICBjb25zdCBlYkpzb24gPSBlbC5lbmRCaW5kaW5nID8gSlNPTi5zdHJpbmdpZnkoZWwuZW5kQmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoZWJKc29uICE9PSB5TWFwLmdldCgnZW5kQmluZGluZycpKSB5TWFwLnNldCgnZW5kQmluZGluZycsIGViSnNvbik7CiAgICAgICAgICAgIGlmIChlbC50eXBlID09PSAnYXJyb3cnKSB7CiAgICAgICAgICAgICAgICBpZiAoZWwuc3RhcnRBcnJvd2hlYWQgIT09IHlNYXAuZ2V0KCdzdGFydEFycm93aGVhZCcpKSB5TWFwLnNldCgnc3RhcnRBcnJvd2hlYWQnLCBlbC5zdGFydEFycm93aGVhZCk7CiAgICAgICAgICAgICAgICBpZiAoZWwuZW5kQXJyb3doZWFkICE9PSB5TWFwLmdldCgnZW5kQXJyb3doZWFkJykpIHlNYXAuc2V0KCdlbmRBcnJvd2hlYWQnLCBlbC5lbmRBcnJvd2hlYWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBjYXNlICdmcmVlZHJhdyc6IHsKICAgICAgICAgICAgY29uc3QgZnBKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKGZwSnNvbiAhPT0geU1hcC5nZXQoJ3BvaW50cycpKSB5TWFwLnNldCgncG9pbnRzJywgZnBKc29uKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIGNhc2UgJ3RleHQnOgogICAgICAgICAgICBpZiAoZWwudGV4dCAhPT0geU1hcC5nZXQoJ3RleHQnKSkgeU1hcC5zZXQoJ3RleHQnLCBlbC50ZXh0KTsKICAgICAgICAgICAgaWYgKGVsLmNvbnRhaW5lcklkICE9PSB5TWFwLmdldCgnY29udGFpbmVySWQnKSkgeU1hcC5zZXQoJ2NvbnRhaW5lcklkJywgZWwuY29udGFpbmVySWQpOwogICAgICAgICAgICBpZiAoZWwudGV4dEFsaWduICE9PSB5TWFwLmdldCgndGV4dEFsaWduJykpIHlNYXAuc2V0KCd0ZXh0QWxpZ24nLCBlbC50ZXh0QWxpZ24pOwogICAgICAgICAgICBpZiAoZWwudmVydGljYWxBbGlnbiAhPT0geU1hcC5nZXQoJ3ZlcnRpY2FsQWxpZ24nKSkgeU1hcC5zZXQoJ3ZlcnRpY2FsQWxpZ24nLCBlbC52ZXJ0aWNhbEFsaWduKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSAnaW1hZ2UnOgogICAgICAgICAgICBpZiAoZWwuc3JjICE9PSB5TWFwLmdldCgnc3JjJykpIHlNYXAuc2V0KCdzcmMnLCBlbC5zcmMpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbFdpZHRoICE9PSB5TWFwLmdldCgnbmF0dXJhbFdpZHRoJykpIHlNYXAuc2V0KCduYXR1cmFsV2lkdGgnLCBlbC5uYXR1cmFsV2lkdGgpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbEhlaWdodCAhPT0geU1hcC5nZXQoJ25hdHVyYWxIZWlnaHQnKSkgeU1hcC5zZXQoJ25hdHVyYWxIZWlnaHQnLCBlbC5uYXR1cmFsSGVpZ2h0KTsKICAgICAgICAgICAgaWYgKGVsLnNjYWxlTW9kZSAhPT0geU1hcC5nZXQoJ3NjYWxlTW9kZScpKSB5TWFwLnNldCgnc2NhbGVNb2RlJywgZWwuc2NhbGVNb2RlKTsKICAgICAgICAgICAgY29uc3QgY3JvcEpzb24gPSBlbC5jcm9wID8gSlNPTi5zdHJpbmdpZnkoZWwuY3JvcCkgOiBudWxsOwogICAgICAgICAgICBpZiAoY3JvcEpzb24gIT09IHlNYXAuZ2V0KCdjcm9wJykpIHlNYXAuc2V0KCdjcm9wJywgY3JvcEpzb24pOwogICAgICAgICAgICBpZiAoZWwuY29ybmVyUmFkaXVzICE9PSB5TWFwLmdldCgnY29ybmVyUmFkaXVzJykpIHlNYXAuc2V0KCdjb3JuZXJSYWRpdXMnLCBlbC5jb3JuZXJSYWRpdXMpOwogICAgICAgICAgICBpZiAoZWwuYWx0ICE9PSB5TWFwLmdldCgnYWx0JykpIHlNYXAuc2V0KCdhbHQnLCBlbC5hbHQpOwogICAgICAgICAgICBicmVhazsKICAgIH0KfQoKLy8g4pSA4pSA4pSAIENvbm5lY3QgLyBEaXNjb25uZWN0IOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gY29ubmVjdChjb25maWc6IENvbGxhYm9yYXRpb25Db25maWcsIHN5bmNEZWJvdW5jZU1zOiBudW1iZXIpOiB2b2lkIHsKICAgIGRpc2Nvbm5lY3QoKTsKCiAgICBfc3luY0RlYm91bmNlTXMgPSBzeW5jRGVib3VuY2VNczsKICAgIF9kb2MgPSBuZXcgWS5Eb2MoKTsKCiAgICBfcHJvdmlkZXIgPSBuZXcgV2Vic29ja2V0UHJvdmlkZXIoCiAgICAgICAgY29uZmlnLnNlcnZlclVybCwKICAgICAgICBjb25maWcucm9vbU5hbWUsCiAgICAgICAgX2RvYywKICAgICAgICB7CiAgICAgICAgICAgIGNvbm5lY3Q6IHRydWUsCiAgICAgICAgICAgIHBhcmFtczogY29uZmlnLmF1dGhUb2tlbiA/IHsgdG9rZW46IGNvbmZpZy5hdXRoVG9rZW4gfSA6IHVuZGVmaW5lZCwKICAgICAgICB9LAogICAgKTsKCiAgICAvLyBBd2FyZW5lc3MKICAgIF9wcm92aWRlci5hd2FyZW5lc3Muc2V0TG9jYWxTdGF0ZSh7CiAgICAgICAgdXNlcjogY29uZmlnLnVzZXIsCiAgICAgICAgY3Vyc29yOiBudWxsLAogICAgICAgIHNlbGVjdGVkSWRzOiBbXSwKICAgIH0gc2F0aXNmaWVzIEF3YXJlbmVzc1N0YXRlKTsKCiAgICAvLyBTdGF0dXMgZXZlbnRzCiAgICBfcHJvdmlkZXIub24oJ3N0YXR1cycsIChldmVudDogeyBzdGF0dXM6IHN0cmluZyB9KSA9PiB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdzdGF0dXMnLCBzdGF0dXM6IGV2ZW50LnN0YXR1cyBhcyBXb3JrZXJPdXRNZXNzYWdlIGV4dGVuZHMgeyB0eXBlOiAnc3RhdHVzJzsgc3RhdHVzOiBpbmZlciBTIH0gPyBTIDogbmV2ZXIgfSk7CiAgICB9KTsKCiAgICAvLyBBd2FyZW5lc3MgY2hhbmdlcyDihpIgcGVlcnMKICAgIF9wcm92aWRlci5hd2FyZW5lc3Mub24oJ2NoYW5nZScsICgpID0+IHsKICAgICAgICBpZiAoIV9wcm92aWRlcikgcmV0dXJuOwogICAgICAgIGNvbnN0IGFsbCA9IF9wcm92aWRlci5hd2FyZW5lc3MuZ2V0U3RhdGVzKCk7CiAgICAgICAgY29uc3QgbG9jYWxJZCA9IF9wcm92aWRlci5hd2FyZW5lc3MuY2xpZW50SUQ7CiAgICAgICAgY29uc3QgcGVlcnM6IEF3YXJlbmVzc1N0YXRlW10gPSBbXTsKICAgICAgICBmb3IgKGNvbnN0IFtjbGllbnRJZCwgc3RhdGVdIG9mIGFsbCkgewogICAgICAgICAgICBpZiAoY2xpZW50SWQgIT09IGxvY2FsSWQgJiYgc3RhdGUgJiYgKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKS51c2VyKSB7CiAgICAgICAgICAgICAgICBwZWVycy5wdXNoKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBwb3N0KHsgdHlwZTogJ3BlZXJzJywgcGVlcnMgfSk7CiAgICB9KTsKCiAgICAvLyBTdGFydCBzeW5jCiAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgLy8gSW5pdGlhbCBzeW5jOiBpZiBZanMgaGFzIGRhdGEsIHNlbmQgdG8gbWFpbiB0aHJlYWQKICAgIGlmICh5RWxlbWVudHMuc2l6ZSA+IDApIHsKICAgICAgICBjb25zdCBlbGVtZW50cyA9IHlNYXBDb2xsZWN0aW9uVG9FbGVtZW50cyh5RWxlbWVudHMpOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKICAgICAgICBwb3N0KHsgdHlwZTogJ3JlbW90ZS11cGRhdGUnLCBlbGVtZW50cyB9KTsKICAgIH0KCiAgICAvLyBZanMgb2JzZXJ2ZXJzIOKGkiBwb3N0IHJlbW90ZS11cGRhdGUKICAgIHlFbGVtZW50cy5vYnNlcnZlKChldmVudHMsIHRyYW5zYWN0aW9uKSA9PiB7CiAgICAgICAgaWYgKHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLXN5bmMnIHx8IHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLWluaXQnKSByZXR1cm47CiAgICAgICAgaWYgKF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSB0cnVlOwogICAgICAgIGxldCBlbGVtZW50cyA9IFsuLi5fbGFzdEVsZW1lbnRzXTsKICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICBmb3IgKGNvbnN0IFtrZXksIGNoYW5nZV0gb2YgZXZlbnRzLmtleXMpIHsKICAgICAgICAgICAgaWYgKGNoYW5nZS5hY3Rpb24gPT09ICdhZGQnIHx8IGNoYW5nZS5hY3Rpb24gPT09ICd1cGRhdGUnKSB7CiAgICAgICAgICAgICAgICBjb25zdCB5TWFwID0geUVsZW1lbnRzLmdldChrZXkpOwogICAgICAgICAgICAgICAgaWYgKHlNYXApIHsKICAgICAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgaWYgKGVsKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGtleSk7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgZWxlbWVudHNbaWR4XSA9IGVsOwogICAgICAgICAgICAgICAgICAgICAgICBlbHNlIGVsZW1lbnRzLnB1c2goZWwpOwogICAgICAgICAgICAgICAgICAgICAgICBjaGFuZ2VkID0gdHJ1ZTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSBpZiAoY2hhbmdlLmFjdGlvbiA9PT0gJ2RlbGV0ZScpIHsKICAgICAgICAgICAgICAgIGVsZW1lbnRzID0gZWxlbWVudHMuZmlsdGVyKGUgPT4gZS5pZCAhPT0ga2V5KTsKICAgICAgICAgICAgICAgIGNoYW5nZWQgPSB0cnVlOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgICAgICAgICBpZiAoYS5zb3J0T3JkZXIgJiYgYi5zb3J0T3JkZXIpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gYS5zb3J0T3JkZXIgPCBiLnNvcnRPcmRlciA/IC0xIDogYS5zb3J0T3JkZXIgPiBiLnNvcnRPcmRlciA/IDEgOiAwOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgcmV0dXJuIDA7CiAgICAgICAgICAgIH0pOwogICAgICAgICAgICBfbGFzdEVsZW1lbnRzID0gZWxlbWVudHM7CiAgICAgICAgICAgIHBvc3QoeyB0eXBlOiAncmVtb3RlLXVwZGF0ZScsIGVsZW1lbnRzIH0pOwogICAgICAgIH0KICAgICAgICBfaXNBcHBseWluZ1JlbW90ZSA9IGZhbHNlOwogICAgfSk7CgogICAgeUVsZW1lbnRzLm9ic2VydmVEZWVwKChldmVudHMpID0+IHsKICAgICAgICBpZiAoX2lzQXBwbHlpbmdMb2NhbCkgcmV0dXJuOwoKICAgICAgICBmb3IgKGNvbnN0IGV2ZW50IG9mIGV2ZW50cykgewogICAgICAgICAgICBsZXQgdGFyZ2V0OiBZLkFic3RyYWN0VHlwZTx1bmtub3duPiB8IG51bGwgPSBldmVudC50YXJnZXQ7CiAgICAgICAgICAgIHdoaWxlICh0YXJnZXQgJiYgISh0YXJnZXQgaW5zdGFuY2VvZiBZLk1hcCAmJiB0YXJnZXQucGFyZW50ID09PSB5RWxlbWVudHMpKSB7CiAgICAgICAgICAgICAgICB0YXJnZXQgPSB0YXJnZXQucGFyZW50IGFzIFkuQWJzdHJhY3RUeXBlPHVua25vd24+IHwgbnVsbDsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAodGFyZ2V0IGluc3RhbmNlb2YgWS5NYXApIHsKICAgICAgICAgICAgICAgIGNvbnN0IGlkID0gdGFyZ2V0LmdldCgnaWQnKSBhcyBzdHJpbmc7CiAgICAgICAgICAgICAgICBpZiAoaWQpIF9kaXJ0eUlkcy5hZGQoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoX2RlZXBUaW1lcikgY2xlYXJUaW1lb3V0KF9kZWVwVGltZXIpOwogICAgICAgIF9kZWVwVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICAgICAgaWYgKF9kaXJ0eUlkcy5zaXplID09PSAwIHx8IF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgICAgIF9pc0FwcGx5aW5nUmVtb3RlID0gdHJ1ZTsKICAgICAgICAgICAgbGV0IGVsZW1lbnRzID0gWy4uLl9sYXN0RWxlbWVudHNdOwogICAgICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICAgICAgZm9yIChjb25zdCBpZCBvZiBfZGlydHlJZHMpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHlNYXAgPSB5RWxlbWVudHMuZ2V0KGlkKTsKICAgICAgICAgICAgICAgIGlmICgheU1hcCkgY29udGludWU7CiAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICBpZiAoIWVsKSBjb250aW51ZTsKICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGlkKTsKICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgeyBlbGVtZW50c1tpZHhdID0gZWw7IGNoYW5nZWQgPSB0cnVlOyB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2RpcnR5SWRzLmNsZWFyKCk7CgogICAgICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICAgICAgX2xhc3RFbGVtZW50cyA9IGVsZW1lbnRzOwogICAgICAgICAgICAgICAgcG9zdCh7IHR5cGU6ICdyZW1vdGUtdXBkYXRlJywgZWxlbWVudHMgfSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgICAgICB9LCAxNik7CiAgICB9KTsKfQoKZnVuY3Rpb24gZGlzY29ubmVjdCgpOiB2b2lkIHsKICAgIGlmIChfc3luY1RpbWVyKSB7IGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsgX3N5bmNUaW1lciA9IG51bGw7IH0KICAgIGlmIChfZGVlcFRpbWVyKSB7IGNsZWFyVGltZW91dChfZGVlcFRpbWVyKTsgX2RlZXBUaW1lciA9IG51bGw7IH0KICAgIF9kaXJ0eUlkcy5jbGVhcigpOwoKICAgIGlmIChfcHJvdmlkZXIpIHsKICAgICAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUobnVsbCk7CiAgICAgICAgX3Byb3ZpZGVyLmRpc2Nvbm5lY3QoKTsKICAgICAgICBfcHJvdmlkZXIuZGVzdHJveSgpOwogICAgICAgIF9wcm92aWRlciA9IG51bGw7CiAgICB9CiAgICBpZiAoX2RvYykgewogICAgICAgIF9kb2MuZGVzdHJveSgpOwogICAgICAgIF9kb2MgPSBudWxsOwogICAgfQogICAgX2xhc3RFbGVtZW50cyA9IFtdOwogICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgIF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKCiAgICBwb3N0KHsgdHlwZTogJ3N0YXR1cycsIHN0YXR1czogJ2Rpc2Nvbm5lY3RlZCcgfSk7Cn0KCi8vIOKUgOKUgOKUgCBMb2NhbCBVcGRhdGUgSGFuZGxlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIGhhbmRsZUxvY2FsVXBkYXRlKGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10pOiB2b2lkIHsKICAgIGlmICghX2RvYyB8fCBfaXNBcHBseWluZ1JlbW90ZSkgcmV0dXJuOwogICAgaWYgKGVsZW1lbnRzID09PSBfbGFzdEVsZW1lbnRzKSByZXR1cm47CgogICAgaWYgKF9zeW5jVGltZXIpIGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsKICAgIF9zeW5jVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICBpZiAoIV9kb2MpIHJldHVybjsKICAgICAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgICAgIF9pc0FwcGx5aW5nTG9jYWwgPSB0cnVlOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKCiAgICAgICAgY29uc3QgbG9jYWxNYXAgPSBuZXcgTWFwPHN0cmluZywgQ2FudmFzRWxlbWVudD4oKTsKICAgICAgICBmb3IgKGNvbnN0IGVsIG9mIGVsZW1lbnRzKSBsb2NhbE1hcC5zZXQoZWwuaWQsIGVsKTsKCiAgICAgICAgX2RvYy50cmFuc2FjdCgoKSA9PiB7CiAgICAgICAgICAgIGZvciAoY29uc3QgW2lkXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgICAgICAgICBpZiAoIWxvY2FsTWFwLmhhcyhpZCkpIHlFbGVtZW50cy5kZWxldGUoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZvciAoY29uc3QgZWwgb2YgZWxlbWVudHMpIHsKICAgICAgICAgICAgICAgIGxldCB5TWFwID0geUVsZW1lbnRzLmdldChlbC5pZCk7CiAgICAgICAgICAgICAgICBpZiAoIXlNYXApIHsKICAgICAgICAgICAgICAgICAgICB5TWFwID0gbmV3IFkuTWFwPHVua25vd24+KCk7CiAgICAgICAgICAgICAgICAgICAgZWxlbWVudFRvWU1hcChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgeUVsZW1lbnRzLnNldChlbC5pZCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LCAnbG9jYWwtc3luYycpOwoKICAgICAgICBfaXNBcHBseWluZ0xvY2FsID0gZmFsc2U7CiAgICB9LCBfc3luY0RlYm91bmNlTXMpOwp9CgovLyDilIDilIDilIAgQXdhcmVuZXNzIFVwZGF0ZSBIYW5kbGVyIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gaGFuZGxlQXdhcmVuZXNzKG1zZzogRXh0cmFjdDxXb3JrZXJJbk1lc3NhZ2UsIHsgdHlwZTogJ2F3YXJlbmVzcycgfT4pOiB2b2lkIHsKICAgIGlmICghX3Byb3ZpZGVyKSByZXR1cm47CiAgICBjb25zdCBjdXJyZW50ID0gX3Byb3ZpZGVyLmF3YXJlbmVzcy5nZXRMb2NhbFN0YXRlKCkgYXMgQXdhcmVuZXNzU3RhdGUgfCBudWxsOwogICAgY29uc3QgdXBkYXRlOiBQYXJ0aWFsPEF3YXJlbmVzc1N0YXRlPiA9IHsgY3Vyc29yOiBtc2cuY3Vyc29yIH07CiAgICBpZiAobXNnLnNlbGVjdGVkSWRzKSB1cGRhdGUuc2VsZWN0ZWRJZHMgPSBtc2cuc2VsZWN0ZWRJZHM7CiAgICBpZiAobXNnLmFjdGl2ZVRvb2wpIHVwZGF0ZS5hY3RpdmVUb29sID0gbXNnLmFjdGl2ZVRvb2w7CiAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUoeyAuLi5jdXJyZW50LCAuLi51cGRhdGUgfSk7Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIFJvdXRlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCnNlbGYub25tZXNzYWdlID0gKGU6IE1lc3NhZ2VFdmVudDxXb3JrZXJJbk1lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBlLmRhdGE7CiAgICB0cnkgewogICAgICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICAgICAgY2FzZSAnY29ubmVjdCc6CiAgICAgICAgICAgICAgICBjb25uZWN0KG1zZy5jb25maWcsIG1zZy5zeW5jRGVib3VuY2VNcyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnZGlzY29ubmVjdCc6CiAgICAgICAgICAgICAgICBkaXNjb25uZWN0KCk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnbG9jYWwtdXBkYXRlJzoKICAgICAgICAgICAgICAgIGhhbmRsZUxvY2FsVXBkYXRlKG1zZy5lbGVtZW50cyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXdhcmVuZXNzJzoKICAgICAgICAgICAgICAgIGhhbmRsZUF3YXJlbmVzcyhtc2cpOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdlcnJvcicsIG1lc3NhZ2U6IGVyciBpbnN0YW5jZW9mIEVycm9yID8gZXJyLm1lc3NhZ2UgOiBTdHJpbmcoZXJyKSB9KTsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href)),!this._worker){console.warn("[SyncWorkerBridge] Worker creation failed, collaboration disabled"),this._callbacks.onStatus("disconnected");return}this._worker.onmessage=o=>{const s=o.data;switch(s.type){case"status":this._callbacks.onStatus(s.status);break;case"remote-update":this._callbacks.onRemoteUpdate(s.elements);break;case"peers":this._callbacks.onPeers(s.peers);break;case"error":this._callbacks.onError(s.message);break}},this._worker.onerror=o=>{this._callbacks.onError(`Worker error: ${o.message}`)},this._post({type:"connect",config:e,syncDebounceMs:n})}disconnect(){this._post({type:"disconnect"})}sendLocalUpdate(e){this._post({type:"local-update",elements:e})}sendAwareness(e){this._post({type:"awareness",cursor:e.cursor??null,selectedIds:e.selectedIds,activeTool:e.activeTool})}dispose(){this._worker&&(this._worker.terminate(),this._worker=null)}_post(e){var n;(n=this._worker)==null||n.postMessage(e)}}function $e(t){return`${t.zoom}:${t.col}:${t.row}`}class Oi{constructor(e=200){ct(this,"_cache",new Map);ct(this,"_accessCounter",0);ct(this,"_maxTiles");this._maxTiles=e}get(e){const n=this._cache.get($e(e));return n?(n.accessOrder=++this._accessCounter,n.bitmap):null}set(e,n,o=0){const s=$e(e),r=this._cache.get(s);r&&r.bitmap.close(),this._cache.set(s,{key:s,bitmap:n,accessOrder:++this._accessCounter,generation:o}),this._evict()}isFresh(e,n){const o=this._cache.get($e(e));return o!=null&&o.generation>=n}invalidate(e){const n=$e(e),o=this._cache.get(n);o&&(o.bitmap.close(),this._cache.delete(n))}clear(){for(const e of this._cache.values())e.bitmap.close();this._cache.clear()}get size(){return this._cache.size}dispose(){this.clear()}_evict(){if(this._cache.size<=this._maxTiles)return;const e=Array.from(this._cache.values()).sort((o,s)=>o.accessOrder-s.accessOrder),n=e.length-this._maxTiles;for(let o=0;o<n;o++)e[o].bitmap.close(),this._cache.delete(e[o].key)}}const kn=256,so=[.1,.15,.2,.25,.33,.5,.67,.75,1,1.25,1.5,2,2.5,3,4,5];function Ni(t){let e=so[0],n=Math.abs(t-e);for(let o=1;o<so.length;o++){const s=Math.abs(t-so[o]);s<n&&(e=so[o],n=s)}return e}function Re(t){return kn/t}function Ui(t,e,n,o=1){const s=Ni(t.scale),r=Re(s),i=-t.x/t.scale,l=-t.y/t.scale,a=i+e/t.scale,c=l+n/t.scale,d=Math.floor(i/r)-o,h=Math.ceil(a/r)+o,u=Math.floor(l/r)-o,f=Math.ceil(c/r)+o,p=[];for(let y=d;y<=h;y++)for(let b=u;b<=f;b++)p.push({col:y,row:b,zoom:s});return{tiles:p,zoom:s}}function zi(t){const e=Re(t.zoom);return{minX:t.col*e,minY:t.row*e,maxX:(t.col+1)*e,maxY:(t.row+1)*e}}function nh(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function oh(t,e){const n=dn(t),o=Re(e),s=[],r=Math.floor(n.minX/o),i=Math.floor(n.maxX/o),l=Math.floor(n.minY/o),a=Math.floor(n.maxY/o);for(let c=r;c<=i;c++)for(let d=l;d<=a;d++)s.push({col:c,row:d,zoom:e});return s}class Ki{constructor(e={}){ct(this,"_cache");ct(this,"_drawFn");ct(this,"_elementTiles",new Map);ct(this,"_generation",0);this._cache=new Oi(e.maxCachedTiles??200),this._drawFn=e.drawFn??sh}getTiles(e,n,o,s){const{tiles:r,zoom:i}=Ui(e,n,o),l=[];for(const a of r){let c=this._cache.get(a);c||(c=this._rasterise(a,s),this._cache.set(a,c,this._generation));const d=Re(i);l.push({coord:a,bitmap:c,worldX:a.col*d,worldY:a.row*d,worldSize:d})}return l}invalidateElements(e){const n=new Set;for(const o of e){const s=this._elementTiles.get(o);if(s){for(const r of s)n.add(r);this._elementTiles.delete(o)}}for(const o of n){const[s,r,i]=o.split(":").map(Number);this._cache.invalidate({zoom:s,col:r,row:i})}}invalidateAll(){this._generation++,this._cache.clear(),this._elementTiles.clear()}dispose(){this._cache.dispose(),this._elementTiles.clear()}get cacheSize(){return this._cache.size}_rasterise(e,n){const o=zi(e),s=Re(e.zoom),r=[];for(const c of n){const d=dn(c);if(nh(d,o)){r.push(c);const h=$e(e),u=this._elementTiles.get(c.id);u?u.includes(h)||u.push(h):this._elementTiles.set(c.id,[h])}}const i=new OffscreenCanvas(kn,kn),l=i.getContext("2d"),a=kn/s;return l.scale(a,a),l.translate(-o.minX,-o.minY),this._drawFn(l,r,o),i.transferToImageBitmap()}}function sh(t,e,n){var o,s,r,i,l,a,c;for(const d of e){if(t.save(),d.rotation){const p=d.x+d.width/2,y=d.y+d.height/2;t.translate(p,y),t.rotate(d.rotation*Math.PI/180),t.translate(-p,-y)}t.globalAlpha=((o=d.style)==null?void 0:o.opacity)??1;const h=((s=d.style)==null?void 0:s.strokeColor)??"#000000",u=((r=d.style)==null?void 0:r.fillColor)??"transparent",f=((i=d.style)==null?void 0:i.strokeWidth)??2;switch(t.strokeStyle=h,t.fillStyle=u,t.lineWidth=f,d.type){case"rectangle":t.beginPath(),t.rect(d.x,d.y,d.width,d.height),u!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(d.x+d.width/2,d.y+d.height/2,d.width/2,d.height/2,0,0,Math.PI*2),u!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{const p=d.x+d.width/2,y=d.y+d.height/2;t.beginPath(),t.moveTo(p,d.y),t.lineTo(d.x+d.width,y),t.lineTo(p,d.y+d.height),t.lineTo(d.x,y),t.closePath(),u!=="transparent"&&t.fill(),t.stroke();break}case"line":case"arrow":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"freedraw":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"text":{const p=d;t.font=`${((l=p.style)==null?void 0:l.fontSize)??16}px ${((a=p.style)==null?void 0:a.fontFamily)??"sans-serif"}`,t.fillStyle=h,t.fillText(p.text,d.x,d.y+(((c=p.style)==null?void 0:c.fontSize)??16));break}case"image":t.strokeStyle="#ccc",t.setLineDash([4,4]),t.strokeRect(d.x,d.y,d.width,d.height);break}t.restore()}}function rh(t,e,n,o,s={}){var p;const{enabled:r=!1,maxCachedTiles:i=200,drawFn:l,elementThreshold:a=500}=s,c=I.useRef(null);I.useEffect(()=>(c.current=new Ki({maxCachedTiles:i,drawFn:l}),()=>{var y;(y=c.current)==null||y.dispose(),c.current=null}),[i,l]);const d=r&&t.length>=a,h=I.useMemo(()=>!d||!c.current||n===0||o===0?[]:c.current.getTiles(e,n,o,t).map(b=>({key:`${b.coord.zoom}:${b.coord.col}:${b.coord.row}`,bitmap:b.bitmap,worldX:b.worldX,worldY:b.worldY,worldSize:b.worldSize})),[d,e.x,e.y,e.scale,n,o,t]),u=I.useCallback(y=>{var b;(b=c.current)==null||b.invalidateElements(y)},[]),f=I.useCallback(()=>{var y;(y=c.current)==null||y.invalidateAll()},[]);return{isActive:d,tiles:h,invalidateElements:u,invalidateAll:f,cacheSize:((p=c.current)==null?void 0:p.cacheSize)??0}}const Ht=4096,ro=1024,io=16,Ji=2;class ih{constructor(e=Ht,n=Ht){ct(this,"_shelves",[]);ct(this,"_atlasWidth");ct(this,"_atlasHeight");this._atlasWidth=e,this._atlasHeight=n}pack(e,n){const o=e+Ji,s=n+Ji;for(const l of this._shelves)if(l.height>=s&&l.x+o<=this._atlasWidth){const a={x:l.x,y:l.y};return l.x+=o,a}const r=this._shelves.length>0?this._shelves[this._shelves.length-1].y+this._shelves[this._shelves.length-1].height:0;if(r+s>this._atlasHeight)return null;const i={y:r,height:s,x:o};return this._shelves.push(i),{x:0,y:r}}reset(){this._shelves=[]}}class $i{constructor(e){ct(this,"_entries",new Map);ct(this,"_packer");ct(this,"_canvas");ct(this,"_ctx");ct(this,"_drawFn");ct(this,"_dirty",!1);ct(this,"_generation",0);this._packer=new ih(Ht,Ht),this._canvas=new OffscreenCanvas(Ht,Ht),this._ctx=this._canvas.getContext("2d"),this._drawFn=e??ch}addOrUpdate(e,n){const o=this._entries.get(e.id);if(o&&o.generation>=n)return o.region;const{pw:s,ph:r}=lh(e),i=this._packer.pack(s,r);if(!i)return null;this._ctx.save(),this._ctx.clearRect(i.x,i.y,s,r),this._ctx.translate(i.x,i.y);const l=s/Math.max(e.width,1),a=r/Math.max(e.height,1);this._ctx.scale(l,a),this._drawFn(this._ctx,e,e.width,e.height),this._ctx.restore();const c={atlasIndex:0,u:i.x/Ht,v:i.y/Ht,uWidth:s/Ht,vHeight:r/Ht,pixelWidth:s,pixelHeight:r};return this._entries.set(e.id,{elementId:e.id,region:c,generation:n}),this._dirty=!0,c}getRegion(e){var n;return((n=this._entries.get(e))==null?void 0:n.region)??null}remove(e){this._entries.delete(e)}rebuild(e){this._generation++,this._packer.reset(),this._entries.clear(),this._ctx.clearRect(0,0,Ht,Ht);for(const n of e)this.addOrUpdate(n,this._generation);this._dirty=!0}get isDirty(){return this._dirty}getCanvas(){return this._dirty=!1,this._canvas}get generation(){return this._generation}get size(){return this._entries.size}dispose(){this._entries.clear()}}function lh(t){const e=Math.max(t.width,1)/Math.max(t.height,1);let n,o;return t.width>=t.height?(n=Math.min(Math.max(Math.ceil(t.width),io),ro),o=Math.min(Math.max(Math.ceil(n/e),io),ro)):(o=Math.min(Math.max(Math.ceil(t.height),io),ro),n=Math.min(Math.max(Math.ceil(o*e),io),ro)),{pw:n,ph:o}}function ch(t,e,n,o){var l,a,c,d,h,u,f;const s=((l=e.style)==null?void 0:l.strokeColor)??"#000000",r=((a=e.style)==null?void 0:a.fillColor)??"transparent",i=((c=e.style)==null?void 0:c.strokeWidth)??2;switch(t.strokeStyle=s,t.fillStyle=r,t.lineWidth=i,t.globalAlpha=((d=e.style)==null?void 0:d.opacity)??1,e.type){case"rectangle":t.beginPath(),t.rect(0,0,n,o),r!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(n/2,o/2,n/2,o/2,0,0,Math.PI*2),r!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{t.beginPath(),t.moveTo(n/2,0),t.lineTo(n,o/2),t.lineTo(n/2,o),t.lineTo(0,o/2),t.closePath(),r!=="transparent"&&t.fill(),t.stroke();break}case"text":{const p=e;t.font=`${((h=p.style)==null?void 0:h.fontSize)??16}px ${((u=p.style)==null?void 0:u.fontFamily)??"sans-serif"}`,t.fillStyle=s,t.fillText(p.text,0,((f=p.style)==null?void 0:f.fontSize)??16);break}default:t.strokeStyle="#aaa",t.strokeRect(0,0,n,o);break}}const ah=`#version 300 es
9
254
  precision highp float;
10
255
 
11
256
  // Shared unit-quad corners (0=bottom-left, 1=top-right)
@@ -49,7 +294,7 @@ void main() {
49
294
  v_texCoord = a_texRect.xy + a_position * a_texRect.zw;
50
295
  v_opacity = a_opacity;
51
296
  }
52
- `,jd=`#version 300 es
297
+ `,dh=`#version 300 es
53
298
  precision mediump float;
54
299
 
55
300
  in vec2 v_texCoord;
@@ -63,4 +308,4 @@ void main() {
63
308
  vec4 texColor = texture(u_atlas, v_texCoord);
64
309
  fragColor = texColor * v_opacity;
65
310
  }
66
- `;function Zi(t,e,n){const o=t.createShader(e);if(!o)throw new Error("Failed to create shader");if(t.shaderSource(o,n),t.compileShader(o),!t.getShaderParameter(o,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(o)??"Unknown error";throw t.deleteShader(o),new Error(`Shader compile error: ${s}`)}return o}function Qd(t,e,n){const o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,e),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)??"Unknown error";throw t.deleteProgram(o),new Error(`Program link error: ${s}`)}return o}function qd(t,e,n){const o=Zi(t,t.VERTEX_SHADER,e),s=Zi(t,t.FRAGMENT_SHADER,n),r=Qd(t,o,s);return t.deleteShader(o),t.deleteShader(s),r}function tu(t,e,n=t.STATIC_DRAW){const o=t.createBuffer();if(!o)throw new Error("Failed to create buffer");return t.bindBuffer(t.ARRAY_BUFFER,o),t.bufferData(t.ARRAY_BUFFER,e,n),o}function eu(t,e,n){const o=n??t.createTexture();if(!o)throw new Error("Failed to create texture");return t.bindTexture(t.TEXTURE_2D,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),o}function _i(t,e,n,o,s){const r=2*n/o,i=-2*n/s,l=2*t/o-1,a=-2*e/s+1;return new Float32Array([r,0,0,0,i,0,l,a,1])}const ns=10;class Mi{constructor(e={}){ct(this,"_canvas",null);ct(this,"_gl",null);ct(this,"_program",null);ct(this,"_vao",null);ct(this,"_quadVBO",null);ct(this,"_instanceVBO",null);ct(this,"_atlasTexture",null);ct(this,"_atlas");ct(this,"_viewMatrixLoc",null);ct(this,"_atlasLoc",null);ct(this,"_instanceData",new Float32Array(0));ct(this,"_instanceCount",0);ct(this,"_elementThreshold");ct(this,"_generation",0);ct(this,"_staticIds",new Set);ct(this,"_isInitialised",!1);ct(this,"_width",0);ct(this,"_height",0);this._atlas=new Bi(e.rasterFn),this._elementThreshold=e.elementThreshold??1e3}init(e){if(this._isInitialised)return!0;const n=e.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,antialias:!0,desynchronized:!0});if(!n)return console.warn("[WebGLHybrid] WebGL2 not available"),!1;this._canvas=e,this._gl=n;try{this._program=qd(n,Rd,jd)}catch(d){return console.warn("[WebGLHybrid] Shader compilation failed:",d),!1}this._viewMatrixLoc=n.getUniformLocation(this._program,"u_viewMatrix"),this._atlasLoc=n.getUniformLocation(this._program,"u_atlas"),this._vao=n.createVertexArray(),n.bindVertexArray(this._vao);const o=new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]);this._quadVBO=tu(n,o,n.STATIC_DRAW);const s=n.getAttribLocation(this._program,"a_position");n.bindBuffer(n.ARRAY_BUFFER,this._quadVBO),n.enableVertexAttribArray(s),n.vertexAttribPointer(s,2,n.FLOAT,!1,0,0),this._instanceVBO=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this._instanceVBO),n.bufferData(n.ARRAY_BUFFER,0,n.DYNAMIC_DRAW);const r=ns*4,i=n.getAttribLocation(this._program,"a_worldRect"),l=n.getAttribLocation(this._program,"a_texRect"),a=n.getAttribLocation(this._program,"a_opacity"),c=n.getAttribLocation(this._program,"a_rotation");return i>=0&&(n.enableVertexAttribArray(i),n.vertexAttribPointer(i,4,n.FLOAT,!1,r,0),n.vertexAttribDivisor(i,1)),l>=0&&(n.enableVertexAttribArray(l),n.vertexAttribPointer(l,4,n.FLOAT,!1,r,16),n.vertexAttribDivisor(l,1)),a>=0&&(n.enableVertexAttribArray(a),n.vertexAttribPointer(a,1,n.FLOAT,!1,r,32),n.vertexAttribDivisor(a,1)),c>=0&&(n.enableVertexAttribArray(c),n.vertexAttribPointer(c,1,n.FLOAT,!1,r,36),n.vertexAttribDivisor(c,1)),n.bindVertexArray(null),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),this._isInitialised=!0,!0}render(e,n,o){if(!this._isInitialised||!this._gl||!this._canvas||e.length<this._elementThreshold)return;const s=this._gl;(this._canvas.width!==this._width||this._canvas.height!==this._height)&&(this._canvas.width=this._width,this._canvas.height=this._height),s.viewport(0,0,this._width,this._height),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);const r=[];for(const l of e)n.has(l.id)||r.push(l);if(r.length===0)return;this._generation++;for(const l of r)this._atlas.addOrUpdate(l,this._generation);this._atlas.isDirty&&(this._atlasTexture=eu(s,this._atlas.getCanvas(),this._atlasTexture)),this._buildInstanceData(r),s.bindBuffer(s.ARRAY_BUFFER,this._instanceVBO),s.bufferData(s.ARRAY_BUFFER,this._instanceData,s.DYNAMIC_DRAW),s.useProgram(this._program);const i=_i(o.x,o.y,o.scale,this._width,this._height);s.uniformMatrix3fv(this._viewMatrixLoc,!1,i),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this._atlasTexture),s.uniform1i(this._atlasLoc,0),s.bindVertexArray(this._vao),s.drawArraysInstanced(s.TRIANGLES,0,6,this._instanceCount),s.bindVertexArray(null)}setSize(e,n){this._width=e,this._height=n}get isActive(){return this._isInitialised}get instanceCount(){return this._instanceCount}get elementThreshold(){return this._elementThreshold}invalidateElements(e){for(const n of e)this._atlas.remove(n)}invalidateAll(){this._atlas.rebuild([])}dispose(){const e=this._gl;e&&(this._program&&e.deleteProgram(this._program),this._vao&&e.deleteVertexArray(this._vao),this._quadVBO&&e.deleteBuffer(this._quadVBO),this._instanceVBO&&e.deleteBuffer(this._instanceVBO),this._atlasTexture&&e.deleteTexture(this._atlasTexture)),this._atlas.dispose(),this._isInitialised=!1,this._gl=null,this._canvas=null}_buildInstanceData(e){var i;const o=e.length*ns;this._instanceData.length<o&&(this._instanceData=new Float32Array(o));let s=0,r=0;for(const l of e){const a=this._atlas.getRegion(l.id);a&&(this._instanceData[s+0]=l.x,this._instanceData[s+1]=l.y,this._instanceData[s+2]=l.width,this._instanceData[s+3]=l.height,this._instanceData[s+4]=a.u,this._instanceData[s+5]=a.v,this._instanceData[s+6]=a.uWidth,this._instanceData[s+7]=a.vHeight,this._instanceData[s+8]=((i=l.style)==null?void 0:i.opacity)??1,this._instanceData[s+9]=(l.rotation??0)*Math.PI/180,s+=ns,r++)}this._instanceCount=r}}function nu(t,e,n,o,s={}){const{enabled:r=!1,rasterFn:i,elementThreshold:l}=s,a=I.useRef(null),c=I.useRef(null),d=I.useRef(!1);I.useEffect(()=>{var p;if(!r){(p=a.current)==null||p.dispose(),a.current=null,d.current=!1;return}return a.current=new Mi({rasterFn:i,elementThreshold:l}),()=>{var y;(y=a.current)==null||y.dispose(),a.current=null,d.current=!1}},[r,i,l]);const h=I.useCallback(p=>{c.current=p,p&&a.current&&(d.current=a.current.init(p))},[]);I.useEffect(()=>{var p;(p=a.current)==null||p.setSize(o.width,o.height)},[o.width,o.height]),I.useEffect(()=>{!a.current||!d.current||a.current.render(t,e,n)});const u=I.useCallback(p=>{var y;(y=a.current)==null||y.invalidateElements(p)},[]),f=I.useCallback(()=>{var p;(p=a.current)==null||p.invalidateAll()},[]);return I.useMemo(()=>{var p;return{webglCanvasRef:h,isActive:d.current,invalidateElements:u,invalidateAll:f,instanceCount:((p=a.current)==null?void 0:p.instanceCount)??0}},[h,u,f])}x.ARROWHEAD_TYPES=ao,x.CURVE_RATIO=zt,x.CollaborationManager=Yd,x.CursorOverlay=li,x.DEFAULT_ANIMATION_DURATION=js,x.DEFAULT_STYLE=wn,x.DEFAULT_THEME=zr,x.ELEMENT_TYPE_MAP=ui,x.ExportWorkerManager=Ur,x.FILL_COLORS=en,x.FlowCanvas=di,x.LINE_TYPES=uo,x.OperationLog=Fd,x.ROUGHNESS_CONFIGS=Ss,x.STROKE_COLORS=tn,x.STROKE_WIDTHS=el,x.STYLE_FIELDS=zn,x.SYNC_FIELDS=Ro,x.SpatialIndex=Uo,x.SpatialSoA=gi,x.SyncWorkerAdapter=Hd,x.TILE_SIZE=bn,x.TOOLS=co,x.TextureAtlas=Bi,x.TileCache=ki,x.TileRenderer=Wi,x.WebGLHybridRenderer=Mi,x.WorkerConfigContext=Xo,x.ZOOM_STEPS=an,x.aabbOverlaps=zs,x.addBoundElement=Os,x.animateViewport=Ee,x.applyOperation=xi,x.arrowheadSize=Lo,x.batchElementUpdates=Dl,x.buildElementMap=Ml,x.buildViewMatrix=_i,x.cancelViewportAnimation=We,x.clearElbowRouteCache=kl,x.clipboardHasImage=Ac,x.cloneElementsForHistory=Gl,x.compareFractionalKeys=Ld,x.computeCurveControlPoint=Jt,x.computeEfficientZoom=Yr,x.computeElbowPoints=on,x.computeElbowRoute=Ds,x.computeFixedPoint=Ys,x.computeImageElementDimensions=mr,x.computeZoomToFit=bo,x.createCollaborationProvider=Jr,x.createImageElement=_n,x.createWorker=Gn,x.cullToViewport=Js,x.curveArrowPrev=xo,x.destroyCollaborationProvider=Un,x.detectOperations=Pd,x.directionFromEdgePoint=il,x.directionFromFixedPoint=go,x.directionFromPoints=nn,x.directionFromShapeToPoint=ho,x.discreteZoom=Si,x.disposeElbowWorkerManager=Tr,x.disposeExportWorkerManager=Kr,x.distance=Fl,x.downloadJSON=Ka,x.downloadPNG=Ua,x.downloadSVG=rd,x.drawArrowhead=oe,x.elementToSpatialItem=No,x.elementToYMap=Cn,x.exportToDataURL=Fr,x.exportToJSON=Vr,x.exportToSVG=Ne,x.extractImageDataFromClipboard=_o,x.fileToDataURL=Zn,x.findConnectorsForElement=ln,x.findNearestSnapTarget=ke,x.flatToPoints=Dn,x.generateId=Pt,x.generateKeyBetween=ts,x.generateNKeysBetween=es,x.getAnchorPosition=vl,x.getConnectionPoints=Vs,x.getDiamondPoints=un,x.getEdgePoint=de,x.getEdgePointFromFixedPoint=ae,x.getElbowPreferredDirection=Sn,x.getElbowWorkerManager=Do,x.getElementAABB=cn,x.getElementTiles=Nd,x.getElementsBounds=Co,x.getExportWorkerManager=Cd,x.getImageFilesFromDataTransfer=Zo,x.getNextZoomStep=Qs,x.getPrevZoomStep=qs,x.getRemoteAwareness=Qr,x.getSharedSpatialIndex=dd,x.getSharedSpatialSoA=Zd,x.getStrokeDash=_t,x.getToolHandler=fn,x.getVisibleBounds=Ks,x.getVisibleTiles=vi,x.getYDoc=$r,x.getYElements=Rr,x.getYProvider=$o,x.isCollaborationActive=bd,x.isConnectable=Io,x.isPointInRect=Vl,x.isValidFractionalIndex=Xd,x.isWorkerSupported=Vc,x.loadImage=hn,x.normalizeRect=Ao,x.onStatusChange=jr,x.opAdd=fi,x.opBatch=Vd,x.opDelete=pi,x.opMove=yi,x.opReorder=mi,x.opResize=Ii,x.opRotate=bi,x.opSetText=wi,x.opStyle=Ci,x.opUpdatePoints=Ai,x.openImageFilePicker=wr,x.quadBezierAt=Ye,x.quadBezierTangent=wo,x.rafThrottle=$s,x.recomputeBoundPoints=Se,x.removeBoundElement=Ns,x.resolveImageSource=Ar,x.rotatePoint=tr,x.scheduleIdleWork=Nr,x.simplifyElbowPath=sn,x.startSync=qr,x.stopSync=Rn,x.syncBoundElements=ve,x.tileBounds=Ei,x.tileKey=ze,x.updateAwareness=Kn,x.useCanvasStore=B,x.useCollaboration=ti,x.useEfficientZoom=Hr,x.useProgressiveRender=Or,x.useTileRenderer=Kd,x.useWebGLHybrid=nu,x.useWorkerConfig=Br,x.worldTileSize=Je,x.yMapToElement=Be,x.yieldToMain=pd,x.zoomAtPoint=Wn,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})}));
311
+ `;function Ri(t,e,n){const o=t.createShader(e);if(!o)throw new Error("Failed to create shader");if(t.shaderSource(o,n),t.compileShader(o),!t.getShaderParameter(o,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(o)??"Unknown error";throw t.deleteShader(o),new Error(`Shader compile error: ${s}`)}return o}function uh(t,e,n){const o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,e),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)??"Unknown error";throw t.deleteProgram(o),new Error(`Program link error: ${s}`)}return o}function hh(t,e,n){const o=Ri(t,t.VERTEX_SHADER,e),s=Ri(t,t.FRAGMENT_SHADER,n),r=uh(t,o,s);return t.deleteShader(o),t.deleteShader(s),r}function gh(t,e,n=t.STATIC_DRAW){const o=t.createBuffer();if(!o)throw new Error("Failed to create buffer");return t.bindBuffer(t.ARRAY_BUFFER,o),t.bufferData(t.ARRAY_BUFFER,e,n),o}function fh(t,e,n){const o=n??t.createTexture();if(!o)throw new Error("Failed to create texture");return t.bindTexture(t.TEXTURE_2D,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),o}function ji(t,e,n,o,s){const r=2*n/o,i=-2*n/s,l=2*t/o-1,a=-2*e/s+1;return new Float32Array([r,0,0,0,i,0,l,a,1])}const us=10;class Qi{constructor(e={}){ct(this,"_canvas",null);ct(this,"_gl",null);ct(this,"_program",null);ct(this,"_vao",null);ct(this,"_quadVBO",null);ct(this,"_instanceVBO",null);ct(this,"_atlasTexture",null);ct(this,"_atlas");ct(this,"_viewMatrixLoc",null);ct(this,"_atlasLoc",null);ct(this,"_instanceData",new Float32Array(0));ct(this,"_instanceCount",0);ct(this,"_elementThreshold");ct(this,"_generation",0);ct(this,"_staticIds",new Set);ct(this,"_isInitialised",!1);ct(this,"_width",0);ct(this,"_height",0);this._atlas=new $i(e.rasterFn),this._elementThreshold=e.elementThreshold??1e3}init(e){if(this._isInitialised)return!0;const n=e.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,antialias:!0,desynchronized:!0});if(!n)return console.warn("[WebGLHybrid] WebGL2 not available"),!1;this._canvas=e,this._gl=n;try{this._program=hh(n,ah,dh)}catch(d){return console.warn("[WebGLHybrid] Shader compilation failed:",d),!1}this._viewMatrixLoc=n.getUniformLocation(this._program,"u_viewMatrix"),this._atlasLoc=n.getUniformLocation(this._program,"u_atlas"),this._vao=n.createVertexArray(),n.bindVertexArray(this._vao);const o=new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]);this._quadVBO=gh(n,o,n.STATIC_DRAW);const s=n.getAttribLocation(this._program,"a_position");n.bindBuffer(n.ARRAY_BUFFER,this._quadVBO),n.enableVertexAttribArray(s),n.vertexAttribPointer(s,2,n.FLOAT,!1,0,0),this._instanceVBO=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this._instanceVBO),n.bufferData(n.ARRAY_BUFFER,0,n.DYNAMIC_DRAW);const r=us*4,i=n.getAttribLocation(this._program,"a_worldRect"),l=n.getAttribLocation(this._program,"a_texRect"),a=n.getAttribLocation(this._program,"a_opacity"),c=n.getAttribLocation(this._program,"a_rotation");return i>=0&&(n.enableVertexAttribArray(i),n.vertexAttribPointer(i,4,n.FLOAT,!1,r,0),n.vertexAttribDivisor(i,1)),l>=0&&(n.enableVertexAttribArray(l),n.vertexAttribPointer(l,4,n.FLOAT,!1,r,16),n.vertexAttribDivisor(l,1)),a>=0&&(n.enableVertexAttribArray(a),n.vertexAttribPointer(a,1,n.FLOAT,!1,r,32),n.vertexAttribDivisor(a,1)),c>=0&&(n.enableVertexAttribArray(c),n.vertexAttribPointer(c,1,n.FLOAT,!1,r,36),n.vertexAttribDivisor(c,1)),n.bindVertexArray(null),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),this._isInitialised=!0,!0}render(e,n,o){if(!this._isInitialised||!this._gl||!this._canvas||e.length<this._elementThreshold)return;const s=this._gl;(this._canvas.width!==this._width||this._canvas.height!==this._height)&&(this._canvas.width=this._width,this._canvas.height=this._height),s.viewport(0,0,this._width,this._height),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);const r=[];for(const l of e)n.has(l.id)||r.push(l);if(r.length===0)return;this._generation++;for(const l of r)this._atlas.addOrUpdate(l,this._generation);this._atlas.isDirty&&(this._atlasTexture=fh(s,this._atlas.getCanvas(),this._atlasTexture)),this._buildInstanceData(r),s.bindBuffer(s.ARRAY_BUFFER,this._instanceVBO),s.bufferData(s.ARRAY_BUFFER,this._instanceData,s.DYNAMIC_DRAW),s.useProgram(this._program);const i=ji(o.x,o.y,o.scale,this._width,this._height);s.uniformMatrix3fv(this._viewMatrixLoc,!1,i),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this._atlasTexture),s.uniform1i(this._atlasLoc,0),s.bindVertexArray(this._vao),s.drawArraysInstanced(s.TRIANGLES,0,6,this._instanceCount),s.bindVertexArray(null)}setSize(e,n){this._width=e,this._height=n}get isActive(){return this._isInitialised}get instanceCount(){return this._instanceCount}get elementThreshold(){return this._elementThreshold}invalidateElements(e){for(const n of e)this._atlas.remove(n)}invalidateAll(){this._atlas.rebuild([])}dispose(){const e=this._gl;e&&(this._program&&e.deleteProgram(this._program),this._vao&&e.deleteVertexArray(this._vao),this._quadVBO&&e.deleteBuffer(this._quadVBO),this._instanceVBO&&e.deleteBuffer(this._instanceVBO),this._atlasTexture&&e.deleteTexture(this._atlasTexture)),this._atlas.dispose(),this._isInitialised=!1,this._gl=null,this._canvas=null}_buildInstanceData(e){var i;const o=e.length*us;this._instanceData.length<o&&(this._instanceData=new Float32Array(o));let s=0,r=0;for(const l of e){const a=this._atlas.getRegion(l.id);a&&(this._instanceData[s+0]=l.x,this._instanceData[s+1]=l.y,this._instanceData[s+2]=l.width,this._instanceData[s+3]=l.height,this._instanceData[s+4]=a.u,this._instanceData[s+5]=a.v,this._instanceData[s+6]=a.uWidth,this._instanceData[s+7]=a.vHeight,this._instanceData[s+8]=((i=l.style)==null?void 0:i.opacity)??1,this._instanceData[s+9]=(l.rotation??0)*Math.PI/180,s+=us,r++)}this._instanceCount=r}}function ph(t,e,n,o,s={}){const{enabled:r=!1,rasterFn:i,elementThreshold:l}=s,a=I.useRef(null),c=I.useRef(null),d=I.useRef(!1);I.useEffect(()=>{var p;if(!r){(p=a.current)==null||p.dispose(),a.current=null,d.current=!1;return}return a.current=new Qi({rasterFn:i,elementThreshold:l}),()=>{var y;(y=a.current)==null||y.dispose(),a.current=null,d.current=!1}},[r,i,l]);const h=I.useCallback(p=>{c.current=p,p&&a.current&&(d.current=a.current.init(p))},[]);I.useEffect(()=>{var p;(p=a.current)==null||p.setSize(o.width,o.height)},[o.width,o.height]),I.useEffect(()=>{!a.current||!d.current||a.current.render(t,e,n)});const u=I.useCallback(p=>{var y;(y=a.current)==null||y.invalidateElements(p)},[]),f=I.useCallback(()=>{var p;(p=a.current)==null||p.invalidateAll()},[]);return I.useMemo(()=>{var p;return{webglCanvasRef:h,isActive:d.current,invalidateElements:u,invalidateAll:f,instanceCount:((p=a.current)==null?void 0:p.instanceCount)??0}},[h,u,f])}k.ARROWHEAD_TYPES=Io,k.CURVE_RATIO=Kt,k.CollaborationManager=th,k.CursorOverlay=vi,k.DEFAULT_ANIMATION_DURATION=ir,k.DEFAULT_STYLE=En,k.DEFAULT_THEME=hi,k.ELEMENT_TYPE_MAP=Bi,k.ExportWorkerManager=di,k.FILL_COLORS=on,k.FlowCanvas=Ti,k.LINE_TYPES=Co,k.OperationLog=ju,k.ROUGHNESS_CONFIGS=Xs,k.STROKE_COLORS=nn,k.STROKE_WIDTHS=Cl,k.STYLE_FIELDS=to,k.SYNC_FIELDS=rs,k.SpatialIndex=ts,k.SpatialSoA=Zi,k.SyncWorkerAdapter=eh,k.TILE_SIZE=kn,k.TOOLS=yo,k.TextureAtlas=$i,k.TileCache=Oi,k.TileRenderer=Ki,k.WebGLHybridRenderer=Qi,k.WorkerConfigContext=Oo,k.ZOOM_STEPS=un,k.aabbOverlaps=nr,k.addBoundElement=Qs,k.animateViewport=Ee,k.applyOperation=Hi,k.arrowheadSize=No,k.batchElementUpdates=tc,k.buildElementMap=Ql,k.buildViewMatrix=ji,k.cancelViewportAnimation=We,k.clearElbowRouteCache=Pl,k.clipboardHasImage=Fc,k.cloneElementsForHistory=ql,k.compareFractionalKeys=Ru,k.computeCurveControlPoint=Jt,k.computeEfficientZoom=ii,k.computeElbowPoints=rn,k.computeElbowRoute=Ns,k.computeFixedPoint=Rs,k.computeImageElementDimensions=Tr,k.computeZoomToFit=vo,k.createCollaborationProvider=gi,k.createImageElement=Ln,k.createWorker=Vn,k.cullToViewport=or,k.curveArrowPrev=Bo,k.destroyCollaborationProvider=Qn,k.detectOperations=qu,k.directionFromEdgePoint=xl,k.directionFromFixedPoint=mo,k.directionFromPoints=sn,k.directionFromShapeToPoint=bo,k.discreteZoom=Ni,k.disposeElbowWorkerManager=Yr,k.disposeExportWorkerManager=ui,k.distance=oc,k.downloadJSON=Qd,k.downloadPNG=jd,k.downloadSVG=uu,k.drawArrowhead=oe,k.elementToSpatialItem=qo,k.elementToYMap=xn,k.exportToDataURL=ei,k.exportToJSON=ni,k.exportToSVG=Ne,k.extractImageDataFromClipboard=Vo,k.fileToDataURL=Dn,k.findConnectorsForElement=an,k.findNearestSnapTarget=ke,k.flatToPoints=Fn,k.generateId=Ft,k.generateKeyBetween=as,k.generateNKeysBetween=ds,k.getAnchorPosition=Ol,k.getConnectionPoints=Js,k.getDiamondPoints=gn,k.getEdgePoint=de,k.getEdgePointFromFixedPoint=ae,k.getElbowPreferredDirection=Bn,k.getElbowWorkerManager=Ho,k.getElementAABB=dn,k.getElementTiles=oh,k.getElementsBounds=So,k.getExportWorkerManager=Zu,k.getImageFilesFromDataTransfer=Yo,k.getNextZoomStep=lr,k.getPrevZoomStep=cr,k.getRemoteAwareness=Ii,k.getSharedSpatialIndex=xu,k.getSharedSpatialSoA=Nu,k.getStrokeDash=Mt,k.getToolHandler=yn,k.getVisibleBounds=er,k.getVisibleTiles=Ui,k.getYDoc=fi,k.getYElements=pi,k.getYProvider=ss,k.isCollaborationActive=Mu,k.isConnectable=ko,k.isPointInRect=sc,k.isValidFractionalIndex=$u,k.isWorkerSupported=sa,k.loadImage=pn,k.normalizeRect=Wo,k.onStatusChange=yi,k.opAdd=_i,k.opBatch=Qu,k.opDelete=Xi,k.opMove=Gi,k.opReorder=Vi,k.opResize=Di,k.opRotate=Yi,k.opSetText=Pi,k.opStyle=Li,k.opUpdatePoints=Fi,k.openImageFilePicker=Zr,k.quadBezierAt=Pe,k.quadBezierTangent=To,k.rafThrottle=sr,k.recomputeBoundPoints=Se,k.removeBoundElement=qs,k.resolveImageSource=Br,k.rotatePoint=ar,k.scheduleIdleWork=ai,k.simplifyElbowPath=ln,k.startSync=Ci,k.stopSync=oo,k.syncBoundElements=ve,k.tileBounds=zi,k.tileKey=$e,k.updateAwareness=qn,k.useCanvasStore=B,k.useCollaboration=mi,k.useEfficientZoom=li,k.useProgressiveRender=ci,k.useTileRenderer=rh,k.useWebGLHybrid=ph,k.useWorkerConfig=Vr,k.worldTileSize=Re,k.yMapToElement=Be,k.yieldToMain=Wu,k.zoomAtPoint=_n,Object.defineProperty(k,Symbol.toStringTag,{value:"Module"})}));