f1ow 0.1.2 → 0.1.3

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.
package/dist/f1ow.umd.cjs CHANGED
@@ -1,11 +1,11 @@
1
- (function(x,h){typeof exports=="object"&&typeof module<"u"?h(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"],h):(x=typeof globalThis<"u"?globalThis:x||self,h(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,h,I,dt,hn,es,bi,ns,It,Ai,mi,os){"use strict";var Id=Object.defineProperty;var Cd=(x,h,I)=>h in x?Id(x,h,{enumerable:!0,configurable:!0,writable:!0,value:I}):x[h]=I;var et=(x,h,I)=>Cd(x,typeof h!="symbol"?h+"":h,I);var $t=typeof document<"u"?document.currentScript:null;function wi(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 Ot=wi(mi),fn={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"},Ne=["#1a1a1a","#868e96","#b197fc","#7048e8","#4263eb","#f59f00","#e8590c","#2f9e44","#40c057","#f06595","#e03131"],Ue=["transparent","#e9ecef","#f3f0ff","#e5dbff","#edf2ff","#fff3bf","#ffe8cc","#d3f9d8","#ebfbee","#fcc2d7","#ffe3e3"],xi=[1,2,3,4,6],Qn=[{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"}],Ee=.1,We=5,ki=[12,16,20,24,28,36,48,64],Si=[{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},Te=20,qn=[{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:">||"}],to=[{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"}],rs=20,is=25,vi=36,Be=40,ls=1e4;function pn(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 yn(t){return t==="up"||t==="down"}function In(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,d=Math.abs(s)/i,c=Math.abs(r)/l;return d>c*3?s>=0?"right":"left":(c>d*3,r>=0?"down":"up")}function eo(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 Ke(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 no(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,d=s/i,c=r/l;return Math.abs(d)>=Math.abs(c)?s>=0?"right":"left":r>=0?"down":"up"}function Ei(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 Rt(t){return t.left+t.width}function jt(t){return t.top+t.height}function Wi(t,e){return e.x>t.left&&e.x<Rt(t)&&e.y>t.top&&e.y<jt(t)}function Ze(t,e,n){return{left:t.left-e,top:t.top-n,width:t.width+e*2,height:t.height+n*2}}function cs(t,e,n){const o=Math.min(e,is),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 as(t,e,n){const o=new Set(n),s=Math.min(e,is),r=o.has("left")?s:e,i=o.has("right")?s:e,l=o.has("up")?s:e,d=o.has("down")?s:e;return{left:t.left-r,top:t.top-l,width:t.width+r+i,height:t.height+l+d}}function Ti(t,e){const n=Math.min(t.left,e.left),o=Math.min(t.top,e.top),s=Math.max(Rt(t),Rt(e)),r=Math.max(jt(t),jt(e));return{left:n,top:o,width:s-n,height:r-o}}function oo(t){return{left:t.x,top:t.y,width:t.width,height:t.height}}function so(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),d=Math.sin(i),c=[{x:-s,y:-r},{x:s,y:-r},{x:s,y:r},{x:-s,y:r}].map(y=>({x:n+y.x*l-y.y*d,y:o+y.x*d+y.y*l}));let a=1/0,g=1/0,u=-1/0,f=-1/0;for(const y of c)y.x<a&&(a=y.x),y.y<g&&(g=y.y),y.x>u&&(u=y.x),y.y>f&&(f=y.y);return{x:a,y:g,width:u-a,height:f-g}}function Bi(t){switch(t){case"left":return"right";case"right":return"left";case"up":return"down";case"down":return"up"}}function Zi(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 _i(t,e){return t===null||e===null?!1:(t==="left"||t==="right"?"h":"v")!==(e==="left"||e==="right"?"h":"v")}class Mi{constructor(e){et(this,"adjacent",new Map);this.pt=e}}class Gi{constructor(){et(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 Mi(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 Xi{constructor(){et(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 Di(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,d=new Map,c=new Xi,a={node:o,dir:null,g:0},g=i(o,null);for(l.set(g,0),d.set(g,null),c.push(a,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 y=[];let p=u;for(;p;){y.push(p.node.pt);const m=i(p.node,p.dir);if(p=d.get(m),p==null)break}return y[y.length-1]!==o.pt&&y.push(o.pt),y.reverse(),y}for(const[y,p]of u.node.adjacent){const m=Zi(u.node.pt,y.pt);if(m===null)continue;const W=u.dir!==null&&m===Bi(u.dir),v=_i(u.dir,m),X=W?ls*3:v?ls:0,R=u.g+p+X,Z=i(y,m);R<(l.get(Z)??1/0)&&(l.set(Z,R),d.set(Z,u),c.push({node:y,dir:m,g:R},R+r(y.pt)))}}}return null}function Li(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 Vi(t,e,n,o){const s=n.left,r=Rt(n),i=n.top,l=jt(n),d=[...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),a=u=>o.some(f=>Wi(f,u)),g=[];for(const u of c)for(const f of d){const y={x:f,y:u};a(y)||g.push(y)}return g}function ds(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<jt(i)&&i.left<r&&Rt(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<Rt(i)&&i.top<r&&jt(i)>s)return!0}return!1}function Yi(t,e){const n=new Gi,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,d)=>l-d),i=[...s].sort((l,d)=>l-d);for(let l=0;l<i.length;l++)for(let d=0;d<r.length;d++){const c={x:r[d],y:i[l]};if(n.has(c)){for(let a=d-1;a>=0;a--){const g={x:r[a],y:i[l]};if(n.has(g)){ds(g,c,e)||n.connect(g,c);break}}for(let a=l-1;a>=0;a--){const g={x:r[d],y:i[a]};if(n.has(g)){ds(g,c,e)||n.connect(g,c);break}}}}return n}function us(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 gs(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 hs(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 Fi(t){let e=t[0],n=gs(e),o=hs(e);for(let s=1;s<t.length;s++){const r=gs(t[s]),i=hs(t[s]);(r<n||r===n&&i<o)&&(e=t[s],n=r,o=i)}return e}function ro(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=Ti(i,W);i=Ze(i,Be,Be);const l=[],d=[];for(const W of s)l.push(W.left,Rt(W)),d.push(W.top,jt(W)),l.push(W.left+W.width/2),d.push(W.top+W.height/2);l.push(t.x,e.x),d.push(t.y,e.y);const c=pn(n),a=pn(o);let g={x:t.x+c.x*r,y:t.y+c.y*r},u={x:e.x+a.x*r,y:e.y+a.y*r};g=ps(g,n,s),u=ps(u,o,s),l.push(g.x,u.x),d.push(g.y,u.y),l.push((t.x+e.x)/2),d.push((t.y+e.y)/2);const f=Vi(l,d,i,s),y=Li([g,u,...f]),p=Yi(y,s),m=Di(p,g,u);if(m){const W=[t,...m,e];return us(W)}return null}function fs(t,e,n,o,s,r,i,l){if(t.x===e.x&&t.y===e.y)return[t,e];const d=s?oo(s):{left:t.x,top:t.y,width:0,height:0},c=r?oo(r):{left:e.x,top:e.y,width:0,height:0},a=rs,g=Math.max(vi,i??0),u=(l??[]).map(K=>Ze(oo(K),a,a)),f=s?cs(d,a,n):Ze(d,a,a),y=r?cs(c,a,o):Ze(c,a,a),p=[n],m=[o];let W=!1;if(s){const K=no(s,e);K!==n&&(p.push(K),W=!0)}if(r){const K=no(r,t);K!==o&&(m.push(K),W=!0)}const v=s?as(d,a,p):Ze(d,a,a),X=r?as(c,a,m):Ze(c,a,a),R=[],Z=ro(t,e,n,o,[f,y,...u],g);if(Z&&R.push(Z),W){const K=ro(t,e,n,o,[v,X,...u],g);K&&R.push(K)}if(R.length>0)return Fi(R);if(u.length>0){const K=ro(t,e,n,o,[f,y],g);if(K)return K}return us(Pi(t,e,n,o,g))}function ps(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>=Rt(l)||s<=l.top||s>=jt(l)))switch(i=!1,e){case"left":o=l.left-1;break;case"right":o=Rt(l)+1;break;case"up":s=l.top-1;break;case"down":s=jt(l)+1;break}if(i)break}return{x:o,y:s}}function Pi(t,e,n,o,s){const r=Math.max(s,rs),i=pn(n),l=pn(o),d={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(yn(n)===yn(o))if(yn(n)){const a=(d.y+c.y)/2;return[t,d,{x:d.x,y:a},{x:c.x,y:a},c,e]}else{const a=(d.x+c.x)/2;return[t,d,{x:a,y:d.y},{x:a,y:c.y},c,e]}else return yn(n)?[t,d,{x:d.x,y:c.y},c,e]:[t,d,{x:c.x,y:d.y},c,e]}const Hi=new Set(["rectangle","ellipse","diamond","text","image"]),Oi=256,_e=new Map;function Ni(t,e,n,o,s,r,i,l){const d=c=>Math.round(c*2)/2;return[d(t.x),d(t.y),d(e.x),d(e.y),n,o,s?`${d(s.x)},${d(s.y)},${d(s.width)},${d(s.height)}`:"n",r?`${d(r.x)},${d(r.y)},${d(r.width)},${d(r.height)}`:"n",i,l??0].join("|")}function Ui(){_e.clear()}function ze(t,e,n,o,s,r){const i=new Map(s.map(V=>[V.id,V])),l=V=>!V.isPrecise||V.fixedPoint[0]===.5&&V.fixedPoint[1]===.5;let d;if(n)if(l(n)){const V=i.get(n.elementId);d=V?In(V,e):Ke(t,e)}else d=eo(n.fixedPoint);else d=Ke(t,e);let c;if(o)if(l(o)){const V=i.get(o.elementId);c=V?In(V,t):Ke(e,t)}else c=eo(o.fixedPoint);else c=Ke(e,t);const a=n?i.get(n.elementId)??null:null,g=o?i.get(o.elementId)??null:null,u=a?so(a):null,f=g?so(g):null,y=n==null?void 0:n.elementId,p=o==null?void 0:o.elementId,m=[],W=[],v=V=>Math.round(V*2)/2;for(const V of s){if(!Hi.has(V.type)||V.id===y||V.id===p||!V.isVisible)continue;const O=so(V),D=Math.min(t.x,e.x)-Be*3,J=Math.max(t.x,e.x)+Be*3,_=Math.min(t.y,e.y)-Be*3,k=Math.max(t.y,e.y)+Be*3;O.x+O.width<D||O.x>J||O.y+O.height<_||O.y>k||(m.push(O),W.push(`${V.id}:${v(O.x)},${v(O.y)},${v(O.width)},${v(O.height)}`))}W.sort();const X=W.join(";"),R=Ni(t,e,d,c,u,f,X,r),Z=_e.get(R);if(Z)return Z;const K=fs(t,e,d,c,u,f,r,m),nt=[];for(const V of K)nt.push(V.x-t.x,V.y-t.y);if(_e.size>=Oi){const V=_e.keys().next().value;V!==void 0&&_e.delete(V)}return _e.set(R,nt),nt}function Je(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],d=t[n+3];s===i&&i===d||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 Ki=new Set(["rectangle","ellipse","diamond","text","image"]);function io(t){return Ki.has(t.type)}function ys(t){return t*Math.PI/180}function Is(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 $e(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=ys(t.rotation||0);return i===0?{x:s,y:r}:Is(s,r,-i)}function Cn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=ys(t.rotation||0),r=Is(e.x,e.y,s);return{x:n+r.x,y:o+r.y}}function Cs(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 zi(t,e){return Cs(t)[e]}const bs=4;function re(t){return bs+t/2}function As(t,e){const n=t.width||1,o=t.height||1,s=$e(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 ie(t,e,n=0){const o=(e[0]-.5)*t.width,s=(e[1]-.5)*t.height;if(o===0&&s===0)return Cn(t,{x:0,y:0});const r=Cn(t,{x:o,y:s});return le(t,r,n)}function le(t,e,n=0){const o=$e(t,e),s=o.x,r=o.y;if(s===0&&r===0)return Cn(t,{x:0,y:-(t.height/2+n)});let i;switch(t.type){case"ellipse":{const l=t.width/2,d=t.height/2,c=Math.atan2(r,s);i={x:(l+n)*Math.cos(c),y:(d+n)*Math.sin(c)};break}case"diamond":{const l=t.width/2,d=t.height/2,c=Math.atan2(r,s),a=Math.cos(c),g=Math.sin(c),u=Math.abs(a),f=Math.abs(g),y=1/(u/l+f/d),p=y*a,m=y*g;if(n===0)i={x:p,y:m};else{const W=(a>=0?1:-1)/l,v=(g>=0?1:-1)/d,X=Math.sqrt(W*W+v*v);i={x:p+W/X*n,y:m+v/X*n}}break}default:{const l=t.width/2,d=t.height/2,c=Math.atan2(r,s),a=Math.abs(Math.tan(c));let g,u;a<=d/l?(g=s>0?l:-l,u=g*Math.tan(c)):(u=r>0?d:-d,g=u/Math.tan(c)),n===0?i={x:g,y:u}:a<=d/l?i={x:g+(s>0?n:-n),y:u}:i={x:g,y:u+(r>0?n:-n)};break}}return Cn(t,i)}const Ji=24,$i=20,ms=6;function Ri(t,e){const n=$e(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 d=Math.atan2(n.y,n.x),c=o*Math.cos(d),a=s*Math.sin(d);return Math.hypot(c-n.x,a-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)),d=Math.abs(Math.sin(i)),c=1/(l/o+d/s),a=c*Math.cos(i),g=c*Math.sin(i);return Math.hypot(a-n.x,g-n.y)}default:{const r=o+n.x,i=o-n.x,l=s+n.y,d=s-n.y,c=Math.min(r,i,l,d);return c>0?c:0}}}function ji(t,e){const n=$e(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 d=Math.atan2(n.y,n.x),c=o*Math.cos(d),a=s*Math.sin(d);return Math.hypot(n.x-c,n.y-a)}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)),d=Math.abs(Math.sin(i)),c=1/(l/o+d/s),a=c*Math.cos(i),g=c*Math.sin(i);return Math.hypot(n.x-a,n.y-g)}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 fe(t,e,n=Ji,o=new Set,s,r,i=bs,l){let d=null,c=1/0;for(const a of e){if(!io(a)||o.has(a.id))continue;const g=ji(t,a);if(g>n)continue;const u=g===0,f=a.x+a.width/2,y=a.y+a.height/2,p=Math.hypot(f-t.x,y-t.y),m=u?-1e6+p:g*1e3+p;if(m<c){c=m;let W;if(r!==void 0)W=r;else if(g===0){const Z=Math.min(a.width,a.height)/2,K=Math.min($i,Z*.6),nt=Ri(a,t);l===!0?W=nt<=K+ms:l===!1?W=nt<=Math.max(0,K-ms):W=nt<=K}else W=!0;let v,X;if(W)v=As(a,t),X=ie(a,v,i);else{v=[.5,.5];const R=$e(a,t);Math.abs(R.x)+Math.abs(R.y)<2?X=s?le(a,s,i):le(a,{x:f+a.width,y},i):X=le(a,t,i)}d={elementId:a.id,fixedPoint:v,position:X,isPrecise:W}}}return d}function pe(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]},d={x:t.x+r[r.length-2],y:t.y+r[r.length-1]};const c=n?s.get(n.elementId):void 0,a=o?s.get(o.elementId):void 0,g=(v,X)=>v.isPrecise?ie(X,v.fixedPoint,0):{x:X.x+X.width/2,y:X.y+X.height/2},u=t.lineType==="elbow",f=(v,X,R)=>{const Z=In(v,X),K=v.x+v.width/2,nt=v.y+v.height/2,V=Math.max(v.width,v.height)*10;let O;switch(Z){case"up":O={x:K,y:nt-V};break;case"down":O={x:K,y:nt+V};break;case"left":O={x:K-V,y:nt};break;case"right":O={x:K+V,y:nt};break}return le(v,O,R)},y=u?(v,X,R)=>f(v,X,R):le;if(n&&c&&o&&a){if(n.isPrecise)l=ie(c,n.fixedPoint,n.gap);else{const v=g(o,a);l=y(c,v,n.gap)}if(o.isPrecise)d=ie(a,o.fixedPoint,o.gap);else{const v=g(n,c);d=y(a,v,o.gap)}n.isPrecise||(l=y(c,d,n.gap)),o.isPrecise||(d=y(a,l,o.gap))}else n&&c&&(n.isPrecise?l=ie(c,n.fixedPoint,n.gap):l=y(c,d,n.gap)),o&&a&&(o.isPrecise?d=ie(a,o.fixedPoint,o.gap):d=y(a,l,o.gap));const p=[0,0];for(let v=1;v<i-1;v++){const X=t.x+r[v*2],R=t.y+r[v*2+1];p.push(X-l.x,R-l.y)}p.push(d.x-l.x,d.y-l.y);const m=d.x-l.x,W=d.y-l.y;return{x:l.x,y:l.y,points:p,width:Math.abs(m),height:Math.abs(W)}}function Re(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 Qi(t,e){return e.map(n=>{let o=!1;if(n.boundElements&&n.boundElements.length>0){const l=n.boundElements.filter(d=>!t.has(d.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 ws(t,e){const n=t.boundElements??[];return n.some(o=>o.id===e.id)?t:{...t,boundElements:[...n,e]}}function xs(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 ye(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=xs(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=ws(i,{id:t,type:e});l!==i&&r(i.id,{boundElements:l.boundElements})}}}function Lt(){return bi.nanoid(12)}function qi(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.map(n=>({...n}))),e.crop&&(e.crop={...e.crop}),e}function bn(t,e,n=20){const o=new Set(t.map(a=>a.id)),s=new Set;for(const a of t)if(a.boundElements)for(const g of a.boundElements)g.type==="text"&&!o.has(g.id)&&s.add(g.id);const r=[...t,...e.filter(a=>s.has(a.id))],i=new Map;for(const a of r)i.set(a.id,Lt());const l=new Map;for(const a of r)if(a.groupIds)for(const g of a.groupIds)l.has(g)||l.set(g,Lt());const d=r.map(a=>{const g=i.get(a.id),u=qi(a);return u.id=g,u.x=a.x+n,u.y=a.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=d.filter(a=>{var u;const g=(u=[...i.entries()].find(([,f])=>f===a.id))==null?void 0:u[0];return g?o.has(g):!1}).map(a=>a.id);return{clones:d,idMap:i,selectedCloneIds:c}}function ks(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 Ss(t,e,n,o=200){const{x:s,y:r,scale:i}=t,l=-s/i-o,d=-r/i-o,c=(-s+e)/i+o,a=(-r+n)/i+o;return{minX:l,minY:d,maxX:c,maxY:a}}function je(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],d=e[i+1];l<n&&(n=l),l>o&&(o=l),d<s&&(s=d),d>r&&(r=d)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r}}return t.type==="freedraw"&&"points"in t?{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}:{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}function vs(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Es(t,e,n,o,s,r){if(t.length<=100)return t;const i=Ss(e,n,o,r);return t.filter(l=>{if(s.has(l.id))return!0;const d=je(l);return vs(i,d)})}function tl(t){const e=new Map;for(const n of t)e.set(n.id,n);return e}function el(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,d=structuredClone(l);d.src=e.get(r.id),n[o]=d}else n[o]=structuredClone(s)}return n}return JSON.parse(JSON.stringify(t))}function Ws(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 nl(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 Ts(t){return new Set(t)}const Qe=[.1,.25,.5,.75,1,1.5,2,3,4,5],Bs=280;function An({viewport:t,point:e,targetScale:n}){const o=Math.min(We,Math.max(Ee,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 Zs(t){for(const e of Qe)if(e>t+.01)return e;return We}function _s(t){for(let e=Qe.length-1;e>=0;e--)if(Qe[e]<t-.01)return Qe[e];return Ee}function lo(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=je(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 co(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 d=(e-s*2)/(i||1),c=(n-s*2)/(l||1),a=Math.min(Math.min(d,c),r),g=Math.min(We,Math.max(Ee,a)),u=(t.minX+t.maxX)/2,f=(t.minY+t.maxY)/2;return{scale:g,x:e/2-u*g,y:n/2-f*g}}function ol(t){return 1-Math.pow(1-t,3)}let Vt=null;function Ie(t,e,n,o=Bs){Vt!==null&&(cancelAnimationFrame(Vt),Vt=null);const s=performance.now(),r=i=>{const l=i-s,d=Math.min(l/o,1),c=ol(d),a={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(a),d<1?Vt=requestAnimationFrame(r):(Vt=null,n(e))};return Vt=requestAnimationFrame(r),()=>{Vt!==null&&(cancelAnimationFrame(Vt),Vt=null)}}function Ce(){Vt!==null&&(cancelAnimationFrame(Vt),Vt=null)}const sl=100;function ce(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 T=es.create((t,e)=>({elements:[],selectedIds:[],activeTool:"select",currentStyle:{...fn},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 d=r.slice();return d[i]=l,{elements:d}})},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:d}of n){const c=r.get(l);if(c===void 0)continue;const a=i?i[c]:s[c],g={...a,...d};g!==a&&(i||(i=s.slice()),i[c]=g)}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(d=>!o.has(d.id));return{elements:Qi(o,i),selectedIds:r.selectedIds.filter(d=>!o.has(d))}}),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}=bn(s,o);t(l=>({elements:[...l.elements,...r],selectedIds:i.length>0?i:r.map(d=>d.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=Lt(),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(d=>{var a;if(!((a=d.groupIds)!=null&&a.length))return d;const c=d.groupIds.filter(g=>!r.has(g));return{...d,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=>{Ce(),t(o=>({viewport:{...o.viewport,...n}}))},zoomIn:(n,o)=>{const{viewport:s}=e(),r=Zs(s.scale),l=An({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ie(s,l,d=>t(c=>({viewport:{...c.viewport,...d}}))):(Ce(),t({viewport:l}))},zoomOut:(n,o)=>{const{viewport:s}=e(),r=_s(s.scale),l=An({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ie(s,l,d=>t(c=>({viewport:{...c.viewport,...d}}))):(Ce(),t({viewport:l}))},resetZoom:n=>{const{viewport:o}=e(),s={x:0,y:0,scale:1};n!=null&&n.animate?Ie(o,s,r=>t(i=>({viewport:{...i.viewport,...r}}))):(Ce(),t({viewport:s}))},zoomToFit:(n,o,s,r)=>{const{elements:i,viewport:l}=e(),d=s?i.filter(g=>s.includes(g.id)):i,c=lo(d);if(!c)return;const a=co(c,n,o,{padding:r==null?void 0:r.padding,maxZoom:r==null?void 0:r.maxZoom});r!=null&&r.animate?Ie(l,a,g=>t(u=>({viewport:{...u.viewport,...g}}))):(Ce(),t({viewport:a}))},zoomToSelection:(n,o,s)=>{const{elements:r,selectedIds:i,viewport:l}=e();if(i.length===0)return;const d=r.filter(g=>i.includes(g.id)),c=lo(d);if(!c)return;const a=co(c,n,o,{padding:(s==null?void 0:s.padding)??80,maxZoom:(s==null?void 0:s.maxZoom)??2});s!=null&&s.animate?Ie(l,a,g=>t(u=>({viewport:{...u.viewport,...g}}))):(Ce(),t({viewport:a}))},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 d of o)l.set(d.id,d);for(const d of o){const c=s.get(d.id);c?c!==d&&i.push({type:"modify",elementId:d.id,before:ce(c),after:ce(d)}):i.push({type:"add",elementId:d.id,after:ce(d)})}for(const[d,c]of s)l.has(d)||i.push({type:"delete",elementId:d,before:ce(c)});i.length!==0&&t(d=>{const c=d.history.slice(0,d.historyIndex+1);return c.push({diffs:i,mark:n,timestamp:Date.now()}),c.length>sl&&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 d=s.diffs.length-1;d>=0;d--){const c=s.diffs[d];switch(c.type){case"add":i=i.filter(a=>a.id!==c.elementId);break;case"modify":i=i.map(a=>a.id===c.elementId?ce(c.before):a);break;case"delete":i.push(ce(c.before));break}}const l=new Map;for(const d of i)l.set(d.id,d);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(ce(c.after));break;case"modify":l=l.map(a=>a.id===c.elementId?ce(c.after):a);break;case"delete":l=l.filter(a=>a.id!==c.elementId);break}const d=new Map;for(const c of l)d.set(c.id,c);return{historyIndex:s,elements:l,selectedIds:[],_historyBaseline:d}})},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 a of c.diffs){const g=i.get(a.elementId);g?a.type==="delete"?g.type==="add"?i.delete(a.elementId):i.set(a.elementId,{type:"delete",elementId:a.elementId,before:g.before}):a.type==="modify"&&i.set(a.elementId,{type:g.type==="add"?"add":"modify",elementId:a.elementId,before:g.before,after:a.after}):i.set(a.elementId,{...a})}const l={diffs:Array.from(i.values()),mark:r[r.length-1].mark,timestamp:Date.now()},d=[...o.history.slice(0,s),l];return{history:d,historyIndex:d.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}))})),ao={elementId:null,isEditing:!1,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1},qe=es.create(t=>({...ao,enterEditMode:e=>t({elementId:e,isEditing:!0,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1}),exitEditMode:()=>t({...ao}),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({...ao})}));function At(t,e){return Math.round(t/e)*e}function rl(t,e){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function uo(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 Ms(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 il(t,e){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function tn(t,e){return[t/2,0,t,e/2,t/2,e,0,e/2]}function ll(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,d=i>=0?t.y:t.y-s;return{x:l,y:d,width:s,height:s}}const Gs=[0,45,90,135,180,225,270,315,360],cl=Math.PI/180;function al(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=Gs[0],l=999;for(const c of Gs){const a=Math.abs(r-c);a<l&&(l=a,i=c)}i===360&&(i=0);const d=i*cl;return{x:t.x+s*Math.cos(d),y:t.y+s*Math.sin(d)}}function mn(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 Zt(t,e){switch(t){case"dashed":return[e*4,e*4];case"dotted":return[e,e*2];case"solid":default:return[]}}const Nt=.2;function Ut(t,e,n=Nt){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 d=-i/l,c=r/l,a=l*n;return{x:o+d*a,y:s+c*a}}function Me(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 go(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 ho(t,e,n,o){if(o){const s=go(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=go(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 Xs(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 Nt;const i=-s/r,l=o/r,d=(t.x+e.x)/2,c=(t.y+e.y)/2,a=n.x-d,g=n.y-c;return 2*(a*i+g*l)/r}const dl={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(uo(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,d=r.width,c=r.height;if((r.type==="arrow"||r.type==="line")&&"points"in r){const y=r.points,p=[],m=[];for(let W=0;W<y.length;W+=2)p.push(r.x+y[W]),m.push(r.y+y[W+1]);i=Math.min(...p),l=Math.min(...m),d=Math.max(...p)-i,c=Math.max(...m)-l}const a=i+d,g=l+c,u=e.x+e.width,f=e.y+e.height;return i<u&&a>e.x&&l<f&&g>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 fo=!1;const ul={name:"eraser",onMouseDown(t,e,n){var s;fo=!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(!fo)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){fo=!1},getCursor(){return"not-allowed"}},po={name:"rectangle",onMouseDown(t,e,n){var l;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Lt();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;T.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?ll(n.drawStart,o):uo(n.drawStart,o);n.updateElement(n.currentElementIdRef.current,s)},onMouseUp(t){T.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"}},gl={name:"freedraw",onMouseDown(t,e,n){var r;n.setIsDrawing(!0),n.setDrawStart(e),n.clearSelection();const o=Lt();n.currentElementIdRef.current=o;const s={id:o,type:"freedraw",x:0,y:0,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[e.x,e.y]};T.getState().pauseHistory(),n.addElement(s),(r=n.onElementCreate)==null||r.call(n,s)},onMouseMove(t,e,n){if(!n.isDrawing||!n.currentElementIdRef.current)return;const o=n.elements.find(s=>s.id===n.currentElementIdRef.current);o&&n.updateElement(o.id,{points:[...o.points,e.x,e.y]})},onMouseUp(t){if(t.currentElementIdRef.current){const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e&&e.points.length>=4){let n=1/0,o=1/0,s=-1/0,r=-1/0;for(let i=0;i<e.points.length;i+=2)n=Math.min(n,e.points[i]),o=Math.min(o,e.points[i+1]),s=Math.max(s,e.points[i]),r=Math.max(r,e.points[i+1]);t.updateElement(e.id,{x:n,y:o,width:s-n,height:r-o,points:e.points.map((i,l)=>l%2===0?i-n:i-o)})}t.setSelectedIds([t.currentElementIdRef.current]),T.getState().resumeHistory(),t.pushHistory()}t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null},getCursor(){return"crosshair"}},hl={name:"text",onMouseDown(t,e,n){var i;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Lt(),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"}},fl=800,pl=600;function wn(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 en(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 Ds(t,e,n=fl,o=pl){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 xn(t,e,n,o,s,r={...fn}){const i=Ds(e,n);return{id:Lt(),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 Io(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 yl(t){const{file:e,imgUrl:n}=Io(t);return e!==null||n!==null}async function Ls(t){if(t.file)return wn(t.file);if(t.imgUrl)try{const e=await en(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 Vs(){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 Il={name:"image",onMouseDown(t,e,n){n.setIsDrawing(!1);const o=n.snapPos(e);n.clearSelection(),Vs().then(async s=>{var r;for(const i of s)try{const l=await wn(i),d=await en(l),c=xn(l,d.naturalWidth,d.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 kn=null,Ge;const Ys={name:"line",onMouseDown(t,e,n){var y;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Lt();n.currentElementIdRef.current=s;const r=re(n.currentStyle.strokeWidth??2),i=fe(e,n.elements,24,void 0,void 0,void 0,r);let l=e,d=null;Ge=void 0,i?(l=i.position,d={elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}):l=o,n.startBindingRef.current=d,T.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:d,endBinding:null},{currentLineType:a,currentStartArrowhead:g,currentEndArrowhead:u}=T.getState(),f=n.activeTool==="arrow"?{...c,type:"arrow",startArrowhead:g,endArrowhead:u,lineType:a}:{...c,type:"line",lineType:a};n.addElement(f),(y=n.onElementCreate)==null||y.call(n,f)},onMouseMove(t,e,n){if(!n.isDrawing){const g=re(n.currentStyle.strokeWidth??2),u=fe(e,n.elements,24,void 0,void 0,void 0,g);n.setSnapTarget(u);return}if(!n.currentElementIdRef.current)return;const o=n.elements.find(g=>g.id===n.currentElementIdRef.current);if(!o)return;kn=e;const s=new Set([o.id]);o.startBinding&&s.add(o.startBinding.elementId);const r=re(o.style.strokeWidth??2),i=fe(e,n.elements,24,s,{x:o.x,y:o.y},void 0,r,Ge);n.setSnapTarget(i),Ge=i==null?void 0:i.isPrecise;let l=i?i.position:n.snapPos(e);!i&&n.shiftKeyRef.current&&(l=al({x:o.x,y:o.y},l));const d=i?{elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}:null,c=l.x-o.x,a=l.y-o.y;if(o.startBinding){const g=n.elements.find(u=>u.id===o.startBinding.elementId);if(g){let u;o.startBinding.isPrecise?u=ie(g,o.startBinding.fixedPoint,o.startBinding.gap):u=le(g,l,o.startBinding.gap);const f=l.x-u.x,y=l.y-u.y;n.updateElement(o.id,{x:u.x,y:u.y,points:[0,0,f,y],width:Math.abs(f),height:Math.abs(y),endBinding:d});return}}n.updateElement(o.id,{points:[0,0,c,a],width:Math.abs(c),height:Math.abs(a),endBinding:d})},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)T.getState().resumeHistory(),t.deleteElements([t.currentElementIdRef.current]),t.currentElementIdRef.current=null,t.startBindingRef.current=null,t.setSnapTarget(null),kn=null,Ge=void 0;else{const s=kn??{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=re(e.style.strokeWidth??2),l=fe(s,t.elements,24,r,void 0,void 0,i,Ge),d=re(e.style.strokeWidth??2),c=l?{elementId:l.elementId,fixedPoint:l.fixedPoint,gap:d,isPrecise:l.isPrecise}:null,a=e.startBinding??t.startBindingRef.current,g=c&&a&&c.elementId===a.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:a,endBinding:g},y={...e,...f},p=pe(y,t.elements);p&&Object.assign(f,p),t.updateElement(e.id,f);const m=e.type,W=T.getState().elements;ye(e.id,m,null,a,W,t.updateElement);const v=T.getState().elements;ye(e.id,m,null,g,v,t.updateElement),t.startBindingRef.current=null,t.setSnapTarget(null),t.setSelectedIds([t.currentElementIdRef.current]),T.getState().resumeHistory(),t.pushHistory()}}kn=null,Ge=void 0,T.getState().resumeHistory(),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},Cl={select:dl,rectangle:po,ellipse:po,diamond:po,line:Ys,arrow:Ys,freedraw:gl,text:hl,image:Il,eraser:ul};function nn(t){return Cl[t]}function be(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 on(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 Fs(t,e){return t===0?0:Math.max(e*(t===1?1.2:2),t===1?1.5:3)}function bl(t,e,n,o){const s=n-t,r=o-e;return Math.sqrt(s*s+r*r)}function Al(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 ml(t,e,n,o,s,r,i,l=!0){const d=o-e,c=s-n,a=Math.sqrt(d*d+c*c);if(a<.5){l&&t.moveTo(e,n),t.lineTo(o,s);return}const g=-c/a,u=d/a,f=Math.min(r,a*.25),y=f*.15,p=e+i()*y,m=n+i()*y,W=o+i()*y,v=s+i()*y,X=p+d*.33+g*i()*f,R=m+c*.33+u*i()*f,Z=p+d*.67+g*i()*f,K=m+c*.67+u*i()*f;l&&t.moveTo(p,m),t.bezierCurveTo(X,R,Z,K,W,v)}function Ps(t,e,n,o,s){const r=e.length;if(r<3)return;const i=[];for(let l=0;l<r;l++){const[d,c]=e[l],[a,g]=e[(l+1)%r];i.push(bl(d,c,a,g))}for(let l=0;l<r;l++){const d=e[(l-1+r)%r],c=e[l],a=e[(l+1)%r],g=i[(l-1+r)%r],u=i[l],f=c[0]-d[0],y=c[1]-d[1],p=a[0]-c[0],m=a[1]-c[1],v=1-Al(-f,-y,p,m)/Math.PI;let X=o*v;const R=Math.min(g,u);X=Math.min(X,R*.4),X=Math.max(X,0);const Z=g>1e-6?X/g:0,K=u>1e-6?X/u:0,nt=c[0]-f*Z,V=c[1]-y*Z,O=c[0]+p*K,D=c[1]+m*K,J=nt+s()*n,_=V+s()*n,k=O+s()*n,b=D+s()*n,w=c[0]+s()*n,S=c[1]+s()*n;l===0?t.moveTo(J,_):t.lineTo(J,_),X>.5?t.quadraticCurveTo(w,S,k,b):t.lineTo(k,b)}t.closePath()}function sn(t){return t>=2?2:1}function wl(t,e,n,o,s,r,i,l=1,d=2){const c=on(r,d),a=Fs(r,d),g=[[e,n],[e+o,n],[e+o,n+s],[e,n+s]];for(let u=0;u<l;u++)t.beginPath(),Ps(t,g,c,a,i)}function xl(t,e,n,o,s,r,i,l=1,d=2){const c=on(r,d),a=Math.PI*2*Math.sqrt((o*o+s*s)/2),g=Math.max(16,Math.min(64,Math.floor(a*.08))),u=Math.PI*2/g,f=4/3*Math.tan(u/4);for(let y=0;y<l;y++){const p=[];for(let m=0;m<=g;m++){const W=m*u,v=i()*c*1.8;p.push({x:e+(o+v)*Math.cos(W),y:n+(s+v)*Math.sin(W),angle:W})}t.moveTo(p[0].x,p[0].y);for(let m=0;m<g;m++){const W=p[m],v=p[m+1],X=Math.cos(W.angle),R=Math.sin(W.angle),Z=Math.cos(v.angle),K=Math.sin(v.angle),nt=-R,V=X,O=-K,D=Z;o+i()*c,s+i()*c;const J=W.x+nt*o*f+i()*c*.8,_=W.y+V*s*f+i()*c*.8,k=v.x-O*o*f+i()*c*.8,b=v.y-D*s*f+i()*c*.8;t.bezierCurveTo(J,_,k,b,v.x,v.y)}}}function kl(t,e,n,o,s,r=1,i=2){const l=on(o,i),d=Fs(o,i),c=[[e/2,0],[e,n/2],[e/2,n],[0,n/2]];for(let a=0;a<r;a++)t.beginPath(),Ps(t,c,l,d,s)}function Hs(t,e,n,o,s=1,r=2){if(e.length<4)return;const i=on(n,r);for(let l=0;l<s;l++)for(let d=0;d<e.length-2;d+=2)ml(t,e[d],e[d+1],e[d+2],e[d+3],i,o,!0)}function Os(t,e,n,o,s,r,i=1,l=2){const d=on(s,l),c=d*2;for(let a=0;a<i;a++){const g=e.x+r()*d*.6,u=e.y+r()*d*.6,f=o.x+r()*d*.6,y=o.y+r()*d*.6,p=n.x+r()*c,m=n.y+r()*c;t.moveTo(g,u),t.quadraticCurveTo(p,m,f,y)}}function Sl(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 vl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:d})=>{const{id:c,x:a,y:g,width:u,height:f,rotation:y,cornerRadius:p,style:m,isLocked:W}=t,v=!W&&!n,X=m.roughness,R=I.useCallback(()=>o(c),[o,c]),Z=I.useCallback(()=>i==null?void 0:i(c),[i,c]),K=I.useCallback(k=>{let b=k.target.x(),w=k.target.y();if(l&&(b=At(b,l),w=At(w,l),k.target.x(b),k.target.y(w)),!l&&d){const S=d(c,{x:b,y:w,width:u,height:f});S&&(b=S.x,w=S.y,k.target.x(b),k.target.y(w))}r==null||r(c,{x:b,y:w})},[c,l,u,f,r,d]),nt=I.useCallback(k=>{let b=k.target.x(),w=k.target.y();l&&(b=At(b,l),w=At(w,l)),s(c,{x:b,y:w})},[c,l,s]),V=I.useCallback(k=>{const b=k.target,w=b.scaleX(),S=b.scaleY(),M=Math.max(5,b.width()*w),j=Math.max(5,b.height()*S);b.setAttrs({scaleX:1,scaleY:1,width:M,height:j}),r==null||r(c,{x:b.x(),y:b.y(),width:M,height:j})},[c,r]),O=I.useCallback(k=>{const b=k.target,w=Math.max(5,b.width()*b.scaleX()),S=Math.max(5,b.height()*b.scaleY());b.setAttrs({scaleX:1,scaleY:1,width:w,height:S}),s(c,{x:b.x(),y:b.y(),width:w,height:S,rotation:b.rotation()})},[c,s]),D=e?Tt.color:void 0,J=e?Tt.blur:0,_=e?Tt.opacity:0;if(X>0){const k=sn(X),b=Zt(m.strokeStyle,m.strokeWidth);return h.jsx(dt.Shape,{id:c,x:a,y:g,width:u,height:f,rotation:y,transformsEnabled:y?"all":"position",sceneFunc:(w,S)=>{p>0?Sl(w,0,0,u,f,p):(w.beginPath(),w.rect(0,0,u,f)),w.fillShape(S);for(let M=0;M<k;M++){const j=be(c+":"+M);w.beginPath(),wl(w,0,0,u,f,X,j,1,m.strokeWidth),w.strokeShape(S)}},fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:b,lineCap:"round",lineJoin:"round",draggable:v,onClick:R,onTap:R,onDblClick:Z,onDblTap:Z,shadowColor:D,shadowBlur:J,shadowOpacity:_,onDragMove:K,onDragEnd:nt,onTransform:V,onTransformEnd:O,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return h.jsx(dt.Rect,{id:c,x:a,y:g,width:u,height:f,rotation:y,transformsEnabled:y?"all":"position",cornerRadius:p,fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:Zt(m.strokeStyle,m.strokeWidth),draggable:v,onClick:R,onTap:R,onDblClick:Z,onDblTap:Z,shadowColor:D,shadowBlur:J,shadowOpacity:_,onDragMove:K,onDragEnd:nt,onTransform:V,onTransformEnd:O,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},El=I.memo(vl),Wl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:d})=>{const{id:c,x:a,y:g,width:u,height:f,rotation:y,style:p,isLocked:m}=t,W=!m&&!n,v=p.roughness,X=I.useCallback(()=>o(c),[o,c]),R=I.useCallback(()=>i==null?void 0:i(c),[i,c]),Z=I.useCallback(_=>{let k=_.target.x(),b=_.target.y();if(l){const w=At(k-u/2,l),S=At(b-f/2,l);k=w+u/2,b=S+f/2,_.target.x(k),_.target.y(b)}if(!l&&d){const w=d(c,{x:k-u/2,y:b-f/2,width:u,height:f});w&&(k=w.x+u/2,b=w.y+f/2,_.target.x(k),_.target.y(b))}r==null||r(c,{x:k-u/2,y:b-f/2})},[c,l,u,f,r,d]),K=I.useCallback(_=>{let k=_.target.x(),b=_.target.y();if(l){const w=At(k-u/2,l),S=At(b-f/2,l);k=w+u/2,b=S+f/2}s(c,{x:k-u/2,y:b-f/2})},[c,l,u,f,s]),nt=I.useCallback(_=>{const k=_.target,b=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*b/2),M=Math.max(5,f*w/2);k.setAttrs({scaleX:1,scaleY:1,radiusX:S,radiusY:M});const j=S*2,ht=M*2;r==null||r(c,{x:k.x()-S,y:k.y()-M,width:j,height:ht})},[c,u,f,r]),V=I.useCallback(_=>{const k=_.target,b=k.getAttr("radiusX"),w=k.getAttr("radiusY");k.setAttrs({scaleX:1,scaleY:1});const S=Math.max(5,b*2),M=Math.max(5,w*2);s(c,{x:k.x()-b,y:k.y()-w,width:S,height:M,rotation:k.rotation()})},[c,s]),O=e?Tt.color:void 0,D=e?Tt.blur:0,J=e?Tt.opacity:0;if(v>0){const _=sn(v),k=u/2,b=f/2;return h.jsx(dt.Shape,{id:c,x:a+k,y:g+b,rotation:y,transformsEnabled:y?"all":"position",sceneFunc:(w,S)=>{w.beginPath(),w.ellipse(0,0,k,b,0,0,Math.PI*2),w.fillShape(S);for(let M=0;M<_;M++){const j=be(c+":"+M);w.beginPath(),xl(w,0,0,k,b,v,j,1,p.strokeWidth),w.strokeShape(S)}},fill:p.fillColor,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",draggable:W,onClick:X,onTap:X,onDblClick:R,onDblTap:R,shadowColor:O,shadowBlur:D,shadowOpacity:J,onDragMove:Z,onDragEnd:K,onTransform:nt,onTransformEnd:V,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return h.jsx(dt.Ellipse,{id:c,x:a+u/2,y:g+f/2,radiusX:u/2,radiusY:f/2,rotation:y,transformsEnabled:y?"all":"position",fill:p.fillColor,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),draggable:W,onClick:X,onTap:X,onDblClick:R,onDblTap:R,shadowColor:O,shadowBlur:D,shadowOpacity:J,onDragMove:Z,onDragEnd:K,onTransform:nt,onTransformEnd:V,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Tl=I.memo(Wl),Bl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:d})=>{const{id:c,x:a,y:g,width:u,height:f,rotation:y,style:p,isLocked:m}=t,W=!m&&!n,v=p.roughness,X=I.useCallback(()=>o(c),[o,c]),R=I.useCallback(()=>i==null?void 0:i(c),[i,c]),Z=I.useCallback(_=>{let k=_.target.x(),b=_.target.y();if(l&&(k=At(k,l),b=At(b,l),_.target.x(k),_.target.y(b)),!l&&d){const w=d(c,{x:k,y:b,width:u,height:f});w&&(k=w.x,b=w.y,_.target.x(k),_.target.y(b))}r==null||r(c,{x:k,y:b})},[c,l,u,f,r,d]),K=I.useCallback(_=>{let k=_.target.x(),b=_.target.y();l&&(k=At(k,l),b=At(b,l)),s(c,{x:k,y:b})},[c,l,s]),nt=I.useCallback(_=>{const k=_.target,b=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*b),M=Math.max(5,f*w);k.setAttrs({scaleX:1,scaleY:1,points:tn(S,M)}),r==null||r(c,{x:k.x(),y:k.y(),width:S,height:M})},[c,u,f,r]),V=I.useCallback(_=>{const k=_.target;k.setAttrs({scaleX:1,scaleY:1});const b=k.getAttr("points"),w=b?b[2]:u,S=b?b[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]),O=e?Tt.color:void 0,D=e?Tt.blur:0,J=e?Tt.opacity:0;if(v>0){const _=sn(v),k=Zt(p.strokeStyle,p.strokeWidth);return h.jsx(dt.Shape,{id:c,x:a,y:g,rotation:y,transformsEnabled:y?"all":"position",sceneFunc:(b,w)=>{const S=tn(u,f);b.beginPath(),b.moveTo(S[0],S[1]);for(let M=2;M<S.length;M+=2)b.lineTo(S[M],S[M+1]);b.closePath(),b.fillShape(w);for(let M=0;M<_;M++){const j=be(c+":"+M);b.beginPath(),kl(b,u,f,v,j,1,p.strokeWidth),b.strokeShape(w)}},fill:p.fillColor,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:k,lineCap:"round",lineJoin:"round",draggable:W,onClick:X,onTap:X,onDblClick:R,onDblTap:R,shadowColor:O,shadowBlur:D,shadowOpacity:J,onDragMove:Z,onDragEnd:K,onTransform:nt,onTransformEnd:V,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return h.jsx(dt.Line,{id:c,x:a,y:g,points:tn(u,f),closed:!0,rotation:y,transformsEnabled:y?"all":"position",fill:p.fillColor,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),draggable:W,onClick:X,onTap:X,onDblClick:R,onDblTap:R,shadowColor:O,shadowBlur:D,shadowOpacity:J,onDragMove:Z,onDragEnd:K,onTransform:nt,onTransformEnd:V,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Zl=I.memo(Bl),_l=new Set(["rectangle","ellipse","diamond","text","image"]);function Ns(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)_l.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 Ml(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 d=0;d<l.length;d++)r[d]=l.charCodeAt(d)}else{const l=decodeURIComponent(s);r=new TextEncoder().encode(l)}const i=new Blob([r],{type:"application/javascript"});return URL.createObjectURL(i)}function Sn(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=Ml(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 Gl(){return typeof Worker<"u"&&typeof URL<"u"}function Xl(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 Us=50;class Dl{constructor(e){et(this,"worker",null);et(this,"requestIdCounter",0);et(this,"pending",new Map);et(this,"cachedElements",[]);et(this,"workerSupported",!0);et(this,"workerConfig");et(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=Sn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGVsYm93V29ya2VyLnRzIOKAlCBXZWIgV29ya2VyIGZvciBvZmYtbWFpbi10aHJlYWQgZWxib3cgY29ubmVjdG9yIHJvdXRpbmcuCiAqCiAqIFJ1bnMgdGhlIGV4cGVuc2l2ZSBBKiBncmlkLXNlYXJjaCBhbGdvcml0aG0gaW4gYSBiYWNrZ3JvdW5kIHRocmVhZCBzbwogKiB0aGUgbWFpbiB0aHJlYWQgc3RheXMgYXQgNjBmcHMgZHVyaW5nIGludGVuc2l2ZSBkcmFnIG9wZXJhdGlvbnMgdGhhdAogKiB0cmlnZ2VyIG1hbnkgc2ltdWx0YW5lb3VzIHJvdXRlIHJlY29tcHV0YXRpb25zLgogKgogKiBDb21tdW5pY2F0aW9uIHByb3RvY29sOgogKiAgIE1haW4g4oaSIFdvcmtlcjoKICogICAgIHsgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJywgZWxlbWVudHM6IFNlcmlhbGl6ZWRFbGVtZW50W10gfQogKiAgICAgeyB0eXBlOiAnY29tcHV0ZVJvdXRlJywgcmVxdWVzdElkLCBwYXJhbXM6IFJvdXRlUGFyYW1zIH0KICogICBXb3JrZXIg4oaSIE1haW46CiAqICAgICB7IHR5cGU6ICdyb3V0ZVJlc3VsdCcsIHJlcXVlc3RJZCwgcG9pbnRzOiBudW1iZXJbXSB9CiAqCiAqIFVzZXMgVml0ZSdzIG5hdGl2ZSBXb3JrZXIgbW9kdWxlIHN1cHBvcnQg4oCUIGltcG9ydGVkIHdpdGg6CiAqICAgbmV3IFdvcmtlcihuZXcgVVJMKCcuL2VsYm93V29ya2VyLnRzJywgaW1wb3J0Lm1ldGEudXJsKSwgeyB0eXBlOiAnbW9kdWxlJyB9KQogKi8KCi8vIE5PVEU6IFdlIGltcG9ydCB0aGUgZnVsbCBlbGJvdyBtb2R1bGUgaGVyZS4gIFZpdGUgYnVuZGxlcyBpdCBpbnRvIHRoZQovLyBXb3JrZXIgY2h1bmsgYXV0b21hdGljYWxseS4gIFRoZSBgQC9gIHBhdGggYWxpYXMgaXMgcmVzb2x2ZWQgYnkgVml0ZS4KaW1wb3J0IHsgY29tcHV0ZUVsYm93UG9pbnRzLCBzaW1wbGlmeUVsYm93UGF0aCB9IGZyb20gJ0AvdXRpbHMvZWxib3cnOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQsIEJpbmRpbmcsIFBvaW50IH0gZnJvbSAnQC90eXBlcyc7CgovLyDilIDilIDilIAgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgU2VyaWFsaXplZEVsZW1lbnQgewogICAgaWQ6IHN0cmluZzsKICAgIHR5cGU6IHN0cmluZzsKICAgIHg6IG51bWJlcjsKICAgIHk6IG51bWJlcjsKICAgIHdpZHRoOiBudW1iZXI7CiAgICBoZWlnaHQ6IG51bWJlcjsKICAgIHJvdGF0aW9uOiBudW1iZXI7CiAgICBpc1Zpc2libGU6IGJvb2xlYW47CiAgICAvLyBNaW5pbWFsIGZpZWxkcyBuZWVkZWQgZm9yIG9ic3RhY2xlIGRldGVjdGlvbiDigJQgc3R5bGUsIHRleHQsIGV0Yy4gYXJlIG9taXR0ZWQuCiAgICAvLyBXZSByZWNvbnN0cnVjdCBhICJwc2V1ZG8tQ2FudmFzRWxlbWVudCIgZnJvbSB0aGVzZSBmaWVsZHMuCn0KCmludGVyZmFjZSBSb3V0ZVBhcmFtcyB7CiAgICBzdGFydFdvcmxkOiBQb2ludDsKICAgIGVuZFdvcmxkOiBQb2ludDsKICAgIHN0YXJ0QmluZGluZzogQmluZGluZyB8IG51bGw7CiAgICBlbmRCaW5kaW5nOiBCaW5kaW5nIHwgbnVsbDsKICAgIG1pblN0dWJMZW5ndGg/OiBudW1iZXI7Cn0KCmludGVyZmFjZSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgewogICAgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJzsKICAgIGVsZW1lbnRzOiBTZXJpYWxpemVkRWxlbWVudFtdOwp9CgppbnRlcmZhY2UgQ29tcHV0ZVJvdXRlTWVzc2FnZSB7CiAgICB0eXBlOiAnY29tcHV0ZVJvdXRlJzsKICAgIHJlcXVlc3RJZDogbnVtYmVyOwogICAgcGFyYW1zOiBSb3V0ZVBhcmFtczsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgfCBDb21wdXRlUm91dGVNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBzdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCi8qKiBMaWdodHdlaWdodCBlbGVtZW50IHByb3hpZXMgdXNlZCBmb3Igb2JzdGFjbGUgZGV0ZWN0aW9uIGluIHJvdXRpbmcgKi8KbGV0IGNhY2hlZEVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gPSBbXTsKCi8qKgogKiBSZWNvbnN0cnVjdCBtaW5pbWFsIENhbnZhc0VsZW1lbnQtc2hhcGVkIG9iamVjdHMgZnJvbSBzZXJpYWxpemVkIGRhdGEuCiAqIE9ubHkgdGhlIGZpZWxkcyB1c2VkIGJ5IGNvbXB1dGVFbGJvd1BvaW50cyBhcmUgbmVlZGVkOgogKiAgIGlkLCB0eXBlLCB4LCB5LCB3aWR0aCwgaGVpZ2h0LCByb3RhdGlvbiwgaXNWaXNpYmxlCiAqLwpmdW5jdGlvbiBkZXNlcmlhbGl6ZUVsZW1lbnRzKHNlcmlhbGl6ZWQ6IFNlcmlhbGl6ZWRFbGVtZW50W10pOiBDYW52YXNFbGVtZW50W10gewogICAgLy8gQ2FzdCBpcyBzYWZlIGJlY2F1c2UgY29tcHV0ZUVsYm93UG9pbnRzIG9ubHkgcmVhZHMgc3BhdGlhbCBmaWVsZHMKICAgIC8vIGFuZCBjaGVja3MgYHR5cGVgIG1lbWJlcnNoaXAgaW4gT0JTVEFDTEVfVFlQRVMgc2V0LgogICAgcmV0dXJuIHNlcmlhbGl6ZWQgYXMgdW5rbm93biBhcyBDYW52YXNFbGVtZW50W107Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIGhhbmRsZXIg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpzZWxmLm9ubWVzc2FnZSA9IChlOiBNZXNzYWdlRXZlbnQ8SW5jb21pbmdNZXNzYWdlPikgPT4gewogICAgY29uc3QgbXNnID0gZS5kYXRhOwoKICAgIGlmIChtc2cudHlwZSA9PT0gJ3VwZGF0ZUVsZW1lbnRzJykgewogICAgICAgIGNhY2hlZEVsZW1lbnRzID0gZGVzZXJpYWxpemVFbGVtZW50cyhtc2cuZWxlbWVudHMpOwogICAgICAgIHJldHVybjsKICAgIH0KCiAgICBpZiAobXNnLnR5cGUgPT09ICdjb21wdXRlUm91dGUnKSB7CiAgICAgICAgY29uc3QgeyByZXF1ZXN0SWQsIHBhcmFtcyB9ID0gbXNnOwogICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHJhdyA9IGNvbXB1dGVFbGJvd1BvaW50cygKICAgICAgICAgICAgICAgIHBhcmFtcy5zdGFydFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLmVuZFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLnN0YXJ0QmluZGluZywKICAgICAgICAgICAgICAgIHBhcmFtcy5lbmRCaW5kaW5nLAogICAgICAgICAgICAgICAgY2FjaGVkRWxlbWVudHMsCiAgICAgICAgICAgICAgICBwYXJhbXMubWluU3R1Ykxlbmd0aCwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc2ltcGxpZmllZCA9IHNpbXBsaWZ5RWxib3dQYXRoKHJhdyk7CiAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UoeyB0eXBlOiAncm91dGVSZXN1bHQnLCByZXF1ZXN0SWQsIHBvaW50czogc2ltcGxpZmllZCB9KTsKICAgICAgICB9IGNhdGNoIHsKICAgICAgICAgICAgLy8gT24gZXJyb3IsIHJldHVybiBhIHN0cmFpZ2h0IGxpbmUgZmFsbGJhY2sKICAgICAgICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICB0eXBlOiAncm91dGVSZXN1bHQnLAogICAgICAgICAgICAgICAgcmVxdWVzdElkLAogICAgICAgICAgICAgICAgcG9pbnRzOiBbMCwgMCwgcGFyYW1zLmVuZFdvcmxkLnggLSBwYXJhbXMuc3RhcnRXb3JsZC54LCBwYXJhbXMuZW5kV29ybGQueSAtIHBhcmFtcy5zdGFydFdvcmxkLnldLAogICAgICAgICAgICB9KTsKICAgICAgICB9CiAgICB9Cn07Cg==",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:$t&&$t.tagName.toUpperCase()==="SCRIPT"&&$t.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>=Us&&n.postMessage({type:"updateElements",elements:Xl(e)})}async computeRoute(e){const n=this._getWorker();if(!n||this.cachedElements.length<Us)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=ze(e.startWorld,e.endWorld,e.startBinding,e.endBinding,this.cachedElements,e.minStubLength);return Je(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 Qt=null,Co;function bo(t){return Qt&&t&&JSON.stringify(t)!==JSON.stringify(Co)&&(Qt.dispose(),Qt=null),Qt||(Co=t,Qt=new Dl(t)),Qt}function Ks(){Qt&&(Qt.dispose(),Qt=null,Co=void 0)}const Ao=I.createContext(void 0);function zs(){return I.useContext(Ao)}function Js(t,e,n,o){const[s,r]=I.useState(null),i=I.useRef(n),l=zs(),d=l==null?void 0:l.elbowWorkerConfig;return i.current=n,I.useEffect(()=>{bo(d).updateElements(n)},[o,d]),I.useEffect(()=>()=>{},[]),I.useEffect(()=>{if(!t){r(null);return}const c=bo(d);let a=!1;const g={startWorld:e.startWorld,endWorld:e.endWorld,startBinding:e.startBinding,endBinding:e.endBinding,minStubLength:e.minStubLength};if(c.isWorkerActive)c.computeRoute(g).then(u=>{a||r(u)});else{const u=ze(e.startWorld,e.endWorld,e.startBinding,e.endBinding,i.current,e.minStubLength),f=Je(u);r(f)}return()=>{a=!0}},[t,e.startWorld.x,e.startWorld.y,e.endWorld.x,e.endWorld.y,e.startBinding,e.endBinding,e.minStubLength,o]),s}const Ll=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:d,allElements:c})=>{const{id:a,x:g,y:u,points:f,rotation:y,style:p,startBinding:m,endBinding:W,lineType:v,isLocked:X}=t,R=!X&&!o,Z=I.useRef(null),K=p.roughness,nt=v==="curved",V=v==="elbow",{fingerprint:O,elementsRef:D}=Ns(c),J=I.useMemo(()=>({x:g+f[0],y:u+f[1]}),[g,u,f[0],f[1]]),_=I.useMemo(()=>({x:g+f[f.length-2],y:u+f[f.length-1]}),[g,u,f]),k=Js(V,{startWorld:J,endWorld:_,startBinding:m,endBinding:W},c??[],O),b=I.useMemo(()=>{if(!V)return f;const U=ze(J,_,m,W,D.current);return Je(U)},[V,g,u,f,m,W,O]),w=V?k??b:f,S=I.useMemo(()=>{if(!V)return f;const U=[...w],ot=f[0],it=f[1];if(ot!==0||it!==0)for(let yt=0;yt<U.length;yt+=2)U[yt]+=ot,U[yt+1]+=it;return U},[V,w,f]),M=I.useMemo(()=>{if(!nt)return null;const U={x:f[0],y:f[1]},ot={x:f[f.length-2],y:f[f.length-1]},it=Ut(U,ot,t.curvature??Nt);return{start:U,end:ot,cp:it}},[nt,f,t.curvature]),j=I.useCallback(()=>s(a),[s,a]),ht=I.useCallback(()=>l==null?void 0:l(a),[l,a]),$=I.useCallback(U=>{let ot=U.target.x(),it=U.target.y();d&&(ot=At(ot,d),it=At(it,d),U.target.x(ot),U.target.y(it)),i==null||i(a,{x:ot,y:it})},[a,d,i]),F=I.useCallback(U=>{let ot=U.target.x(),it=U.target.y();d&&(ot=At(ot,d),it=At(it,d)),r(a,{x:ot,y:it})},[a,d,r]),gt=I.useCallback(U=>{const ot=U.target,it=ot.scaleX(),yt=ot.scaleY();ot.setAttrs({scaleX:1,scaleY:1});const pt=f.map((C,G)=>G%2===0?C*it:C*yt),st=mn(pt);r(a,{x:ot.x(),y:ot.y(),points:pt,rotation:ot.rotation(),width:st.width,height:st.height})},[a,f,r]),rt=sn(K),E=e?Tt.color:void 0,H=e?Tt.blur:0,z=e?Tt.opacity:0;return h.jsx(dt.Group,{id:a,ref:Z,x:g,y:u,rotation:y,transformsEnabled:y?"all":"position",draggable:R,onClick:j,onTap:j,onDblClick:ht,onDblTap:ht,onDragMove:$,onDragEnd:F,onTransformEnd:gt,children:V?h.jsxs(h.Fragment,{children:[h.jsx(dt.Line,{points:S,stroke:"transparent",strokeWidth:Math.max(20,p.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),h.jsx(dt.Line,{points:S,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:E,shadowBlur:H,shadowOpacity:z,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]}):nt?h.jsx(dt.Shape,{sceneFunc:(U,ot)=>{if(M){if(U.beginPath(),K>0){const it=be(a);Os(U,M.start,M.cp,M.end,K,it,rt,p.strokeWidth)}else U.moveTo(M.start.x,M.start.y),U.quadraticCurveTo(M.cp.x,M.cp.y,M.end.x,M.end.y);U.fillStrokeShape(ot)}},stroke:p.strokeColor,strokeWidth:p.strokeWidth,hitStrokeWidth:Math.max(20,p.strokeWidth+16),dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:p.opacity,shadowColor:E,shadowBlur:H,shadowOpacity:z,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):K>0?h.jsx(dt.Shape,{sceneFunc:(U,ot)=>{const it=be(a);U.beginPath(),Hs(U,f,K,it,rt,p.strokeWidth),U.fillStrokeShape(ot)},stroke:p.strokeColor,strokeWidth:p.strokeWidth,hitStrokeWidth:Math.max(20,p.strokeWidth+16),dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:p.opacity,shadowColor:E,shadowBlur:H,shadowOpacity:z,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):h.jsxs(h.Fragment,{children:[h.jsx(dt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,p.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),h.jsx(dt.Line,{points:f,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:E,shadowBlur:H,shadowOpacity:z,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]})})},Vl=I.memo(Ll);function Yl(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 Fl(t){return{x:-t.y,y:t.x}}function mo(t){return Math.max(10,t*4)}function qt(t,e,n,o,s,r,i){const l=Yl(n,o),d=Fl(l),c=s*.45,a=t._context;switch(a.save(),a.strokeStyle=r,a.fillStyle=r,a.lineWidth=i,a.lineJoin="round",a.lineCap="round",e){case"arrow":{const g={x:n.x-l.x*s+d.x*c,y:n.y-l.y*s+d.y*c},u={x:n.x-l.x*s-d.x*c,y:n.y-l.y*s-d.y*c};a.beginPath(),a.moveTo(g.x,g.y),a.lineTo(n.x,n.y),a.lineTo(u.x,u.y),a.stroke();break}case"triangle":{const g={x:n.x-l.x*s+d.x*c,y:n.y-l.y*s+d.y*c},u={x:n.x-l.x*s-d.x*c,y:n.y-l.y*s-d.y*c};a.beginPath(),a.moveTo(n.x,n.y),a.lineTo(g.x,g.y),a.lineTo(u.x,u.y),a.closePath(),a.fill(),a.stroke();break}case"triangle_outline":{const g={x:n.x-l.x*s+d.x*c,y:n.y-l.y*s+d.y*c},u={x:n.x-l.x*s-d.x*c,y:n.y-l.y*s-d.y*c};a.fillStyle="#ffffff",a.beginPath(),a.moveTo(n.x,n.y),a.lineTo(g.x,g.y),a.lineTo(u.x,u.y),a.closePath(),a.fill(),a.stroke();break}case"circle":{const g=s*.35,u=n.x-l.x*g,f=n.y-l.y*g;a.beginPath(),a.arc(u,f,g,0,Math.PI*2),a.fill(),a.stroke();break}case"circle_outline":{const g=s*.35,u=n.x-l.x*g,f=n.y-l.y*g;a.fillStyle="#ffffff",a.beginPath(),a.arc(u,f,g,0,Math.PI*2),a.fill(),a.stroke();break}case"diamond":{const g=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};a.beginPath(),a.moveTo(n.x,n.y),a.lineTo(f.x+d.x*g,f.y+d.y*g),a.lineTo(f.x-l.x*u,f.y-l.y*u),a.lineTo(f.x-d.x*g,f.y-d.y*g),a.closePath(),a.fill(),a.stroke();break}case"diamond_outline":{const g=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};a.fillStyle="#ffffff",a.beginPath(),a.moveTo(n.x,n.y),a.lineTo(f.x+d.x*g,f.y+d.y*g),a.lineTo(f.x-l.x*u,f.y-l.y*u),a.lineTo(f.x-d.x*g,f.y-d.y*g),a.closePath(),a.fill(),a.stroke();break}case"bar":{const g=c*1.2;a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();break}case"crowfoot_one":{const g=c*1,u=s*.25;a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};a.beginPath(),a.moveTo(f.x+d.x*g,f.y+d.y*g),a.lineTo(f.x-d.x*g,f.y-d.y*g),a.stroke();break}case"crowfoot_many":{const g=c*1,u=s*.6;a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(f.x,f.y),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();break}case"crowfoot_one_or_many":{const g=c*1,u=s*.6,f=s*.25;a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();const y={x:n.x-l.x*f,y:n.y-l.y*f};a.beginPath(),a.moveTo(y.x+d.x*g,y.y+d.y*g),a.lineTo(y.x-d.x*g,y.y-d.y*g),a.stroke();const p={x:n.x-l.x*u,y:n.y-l.y*u};a.beginPath(),a.moveTo(n.x+d.x*g,n.y+d.y*g),a.lineTo(p.x,p.y),a.lineTo(n.x-d.x*g,n.y-d.y*g),a.stroke();break}}a.restore()}function vn(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Pl(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 Hl=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:d,allElements:c})=>{const{id:a,x:g,y:u,points:f,rotation:y,style:p,startBinding:m,endBinding:W,lineType:v,isLocked:X}=t,R=!X&&!o,Z=I.useRef(null),K=p.roughness,{start:nt,end:V}=Pl(t),O=nt!=null||V!=null,D=v==="curved",J=v==="elbow",_=mo(p.strokeWidth),k=sn(K),{fingerprint:b,elementsRef:w}=Ns(c),S=I.useMemo(()=>({x:g+f[0],y:u+f[1]}),[g,u,f[0],f[1]]),M=I.useMemo(()=>({x:g+f[f.length-2],y:u+f[f.length-1]}),[g,u,f]),j=O?Math.ceil(_*1.5):void 0,ht=Js(J,{startWorld:S,endWorld:M,startBinding:m,endBinding:W,minStubLength:j},c??[],b),$=I.useMemo(()=>{if(!J)return f;const st=ze(S,M,m,W,w.current,j);return Je(st)},[J,g,u,f,m,W,b]),F=J?ht??$:f,gt=I.useMemo(()=>{if(!J)return f;const st=[...F],C=f[0],G=f[1];if(C!==0||G!==0)for(let Ct=0;Ct<st.length;Ct+=2)st[Ct]+=C,st[Ct+1]+=G;return st},[J,F,f]),rt=I.useMemo(()=>{if(!D)return null;const st={x:f[0],y:f[1]},C={x:f[f.length-2],y:f[f.length-1]},G=Ut(st,C,t.curvature??Nt);return{start:st,end:C,cp:G}},[D,f,t.curvature]),E=I.useCallback(()=>s(a),[s,a]),H=I.useCallback(()=>l==null?void 0:l(a),[l,a]),z=I.useCallback(st=>{let C=st.target.x(),G=st.target.y();d&&(C=At(C,d),G=At(G,d),st.target.x(C),st.target.y(G)),i==null||i(a,{x:C,y:G})},[a,d,i]),U=I.useCallback(st=>{let C=st.target.x(),G=st.target.y();d&&(C=At(C,d),G=At(G,d)),r(a,{x:C,y:G})},[a,d,r]),ot=I.useCallback(st=>{const C=st.target,G=C.scaleX(),Ct=C.scaleY();C.setAttrs({scaleX:1,scaleY:1});const bt=f.map((ct,Se)=>Se%2===0?ct*G:ct*Ct),St=mn(bt);r(a,{x:C.x(),y:C.y(),points:bt,rotation:C.rotation(),width:St.width,height:St.height})},[a,f,r]),it=e?Tt.color:void 0,yt=e?Tt.blur:0,pt=e?Tt.opacity:0;return h.jsx(dt.Group,{id:a,ref:Z,x:g,y:u,rotation:y,transformsEnabled:y?"all":"position",draggable:R,onClick:E,onTap:E,onDblClick:H,onDblTap:H,onDragMove:z,onDragEnd:U,onTransformEnd:ot,children:J?h.jsxs(h.Fragment,{children:[h.jsx(dt.Line,{points:gt,stroke:"transparent",strokeWidth:Math.max(20,p.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),h.jsx(dt.Line,{points:gt,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:it,shadowBlur:yt,shadowOpacity:pt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),O&&h.jsx(dt.Shape,{sceneFunc:(st,C)=>{const G=vn(gt);if(!(G.length<2)){if(nt&&qt(st,nt,G[0],G[1],_,p.strokeColor,p.strokeWidth),V){const Ct=G[G.length-1],bt=G[G.length-2];qt(st,V,Ct,bt,_,p.strokeColor,p.strokeWidth)}st.fillStrokeShape(C)}},listening:!1,opacity:p.opacity})]}):D?h.jsxs(h.Fragment,{children:[h.jsx(dt.Shape,{sceneFunc:(st,C)=>{if(rt){if(st.beginPath(),K>0){const G=be(a);Os(st,rt.start,rt.cp,rt.end,K,G,k,p.strokeWidth)}else st.moveTo(rt.start.x,rt.start.y),st.quadraticCurveTo(rt.cp.x,rt.cp.y,rt.end.x,rt.end.y);st.fillStrokeShape(C)}},stroke:p.strokeColor,strokeWidth:p.strokeWidth,hitStrokeWidth:Math.max(20,p.strokeWidth+16),dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:p.opacity,shadowColor:it,shadowBlur:yt,shadowOpacity:pt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),O&&rt&&h.jsx(dt.Shape,{sceneFunc:st=>{if(nt){const C=ho(rt.start,rt.cp,rt.end,!1);qt(st,nt,rt.start,C,_,p.strokeColor,p.strokeWidth)}if(V){const C=ho(rt.start,rt.cp,rt.end,!0);qt(st,V,rt.end,C,_,p.strokeColor,p.strokeWidth)}},listening:!1,opacity:p.opacity})]}):K>0?h.jsxs(h.Fragment,{children:[h.jsx(dt.Shape,{sceneFunc:(st,C)=>{const G=be(a);st.beginPath(),Hs(st,f,K,G,k,p.strokeWidth),st.fillStrokeShape(C)},stroke:p.strokeColor,strokeWidth:p.strokeWidth,hitStrokeWidth:Math.max(20,p.strokeWidth+16),dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:p.opacity,shadowColor:it,shadowBlur:yt,shadowOpacity:pt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),O&&h.jsx(dt.Shape,{sceneFunc:(st,C)=>{const G=vn(f);if(!(G.length<2)){if(nt&&qt(st,nt,G[0],G[1],_,p.strokeColor,p.strokeWidth),V){const Ct=G[G.length-1],bt=G[G.length-2];qt(st,V,Ct,bt,_,p.strokeColor,p.strokeWidth)}st.fillStrokeShape(C)}},listening:!1,opacity:p.opacity})]}):h.jsxs(h.Fragment,{children:[h.jsx(dt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,p.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),h.jsx(dt.Line,{points:f,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,dash:Zt(p.strokeStyle,p.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:it,shadowBlur:yt,shadowOpacity:pt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),O&&h.jsx(dt.Shape,{sceneFunc:(st,C)=>{const G=vn(f);if(!(G.length<2)){if(nt&&qt(st,nt,G[0],G[1],_,p.strokeColor,p.strokeWidth),V){const Ct=G[G.length-1],bt=G[G.length-2];qt(st,V,Ct,bt,_,p.strokeColor,p.strokeWidth)}st.fillStrokeShape(C)}},listening:!1,opacity:p.opacity})]})})},Ol=I.memo(Hl),Nl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:d})=>{const{id:c,x:a,y:g,points:u,rotation:f,style:y,isLocked:p}=t,m=!p&&!n,W=I.useCallback(()=>o(c),[o,c]),v=I.useCallback(()=>i==null?void 0:i(c),[i,c]),X=I.useCallback(O=>{let D=O.target.x(),J=O.target.y();if(l&&(D=At(D,l),J=At(J,l),O.target.x(D),O.target.y(J)),!l&&d){let _=0,k=0,b=0,w=0;for(let M=0;M<u.length;M+=2)_=Math.min(_,u[M]),b=Math.max(b,u[M]),k=Math.min(k,u[M+1]),w=Math.max(w,u[M+1]);const S=d(c,{x:D+_,y:J+k,width:b-_,height:w-k});S&&(D=S.x-_,J=S.y-k,O.target.x(D),O.target.y(J))}r==null||r(c,{x:D,y:J})},[c,l,u,r,d]),R=I.useCallback(O=>{let D=O.target.x(),J=O.target.y();l&&(D=At(D,l),J=At(J,l)),s(c,{x:D,y:J})},[c,l,s]),Z=I.useCallback(O=>{const D=O.target,J=D.scaleX(),_=D.scaleY();D.setAttrs({scaleX:1,scaleY:1});const k=u.map((b,w)=>w%2===0?b*J:b*_);s(c,{x:D.x(),y:D.y(),points:k,rotation:D.rotation()})},[c,u,s]),K=e?Tt.color:void 0,nt=e?Tt.blur:0,V=e?Tt.opacity:0;return h.jsx(dt.Line,{id:c,x:a,y:g,points:u,rotation:f,transformsEnabled:f?"all":"position",stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,lineCap:"round",lineJoin:"round",tension:.5,globalCompositeOperation:"source-over",draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:K,shadowBlur:nt,shadowOpacity:V,hitStrokeWidth:20,onDragMove:X,onDragEnd:R,onTransformEnd:Z,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Ul=I.memo(Nl),En=1.18,Kl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,autoEdit:i,onEditStart:l,onEditEnd:d,allElements:c,gridSnap:a})=>{const{id:g,x:u,y:f,width:y,height:p,rotation:m,style:W,text:v,containerId:X,textAlign:R,verticalAlign:Z,isLocked:K}=t,nt=I.useRef(null),V=I.useRef(!1),O=I.useRef(!1),D=!!X,J=!D&&!K&&!n,_=I.useMemo(()=>!X||!c?null:c.find($=>$.id===X)??null,[X,c]),k=I.useMemo(()=>{var z,U;if(!_)return{x:u,y:f};if(_.type==="arrow"||_.type==="line"){const ot=_,it=ot.points,yt={x:it[0],y:it[1]},pt={x:it[it.length-2],y:it[it.length-1]};let st,C;if(ot.lineType==="curved"){const bt=Ut(yt,pt,ot.curvature??Nt),St=Me(yt,bt,pt,.5);st=ot.x+St.x,C=ot.y+St.y}else st=ot.x+(yt.x+pt.x)/2,C=ot.y+(yt.y+pt.y)/2;const G=Math.max(80,y||80),Ct=((z=nt.current)==null?void 0:z.height())??p;return{x:st-G/2,y:C-Ct/2,width:G}}const $=4,F=_.width-$*2,gt=Math.max(20,F),rt=_.x+$,E=((U=nt.current)==null?void 0:U.height())??p;let H;return Z==="top"?H=_.y+$:Z==="bottom"?H=_.y+_.height-E-$:H=_.y+(_.height-E)/2,{x:rt,y:H,width:gt}},[_,u,f,p,Z]),b=I.useCallback(()=>{const $=nt.current;if(!$||V.current)return;const F=$.height(),gt={};let rt=!1;if(Math.abs(F-p)>1&&(gt.height=F,rt=!0),!D){const E=Math.ceil($.getTextWidth());Math.abs(E-y)>1&&(gt.width=E,rt=!0)}rt&&s(g,gt)},[g,p,y,D,s]);I.useEffect(()=>{requestAnimationFrame(b)},[v,W.fontSize,W.fontFamily,b]);const w=I.useCallback(()=>{const $=nt.current;if(!$||V.current)return;const F=$.getStage();if(!F)return;V.current=!0,l==null||l(g);const gt=F.container(),E=$.getAbsoluteTransform().copy().point({x:0,y:0}),H=F.scaleX(),z=W.fontSize*H,U=z*(En-1.07)/2;let ot=0,it=0,yt=0,pt=0;const C=4*H;if(D&&_){const Xt=F.getAbsoluteTransform().copy().point({x:_.x,y:_.y});ot=Xt.x,it=Xt.y,yt=_.width*H,pt=_.height*H}const G=$.width(),Ct=D?yt-C*2:Math.max(G,100)*H,bt=D?ot+C:E.x,St=v,ct=document.createElement("textarea");if(gt.appendChild(ct),ct.value=v,ct.style.position="absolute",D&&_){const vt=Z||"middle",Xt=$.height()*H;let Ht;vt==="top"?Ht=it+C-U:vt==="bottom"?Ht=it+pt-Xt-C-U:Ht=it+(pt-Xt)/2-U,ct.style.top=`${Ht}px`}else ct.style.top=`${E.y-U}px`;ct.style.left=`${bt}px`,ct.style.width=`${Ct}px`,ct.style.fontSize=`${z}px`,ct.style.fontFamily=W.fontFamily,ct.style.color=W.strokeColor,ct.style.lineHeight=`${En}`,ct.style.border="none",ct.style.borderRadius="0",ct.style.padding="0",ct.style.margin="0",ct.style.outline="none",ct.style.resize="none",ct.style.overflow="hidden",ct.style.background="transparent",ct.style.zIndex="1000",ct.rows=1,ct.style.minHeight=`${Math.max(20,z*En)}px`,ct.style.boxSizing="border-box",ct.style.transformOrigin="left top",ct.style.letterSpacing="normal",ct.style.caretColor=W.strokeColor;const Se=D?R||"center":"left";ct.style.textAlign=Se,D?(ct.style.whiteSpace="pre-wrap",ct.style.wordBreak="break-word"):(ct.style.whiteSpace="pre",ct.style.wordBreak="normal");const zt=D?(_==null?void 0:_.rotation)??m:m;zt&&(ct.style.transform=`rotateZ(${zt}deg)`);const Ft=()=>{ct.style.height="auto";const vt=ct.scrollHeight;if(ct.style.height=`${vt}px`,D&&_){const Xt=Z||"middle";let Ht;Xt==="top"?Ht=it+C-U:Xt==="bottom"?Ht=it+pt-vt-C-U:Ht=it+(pt-vt)/2-U,ct.style.top=`${Ht}px`}D||(ct.style.width="auto",ct.style.width=`${Math.max(ct.scrollWidth,100*H)}px`)};ct.addEventListener("input",Ft),requestAnimationFrame(Ft),$.hide(),F.batchDraw(),ct.focus(),ct.select();let dn=!1;const Jt=()=>{if(!V.current)return;V.current=!1;const vt=dn?St:ct.value,Xt=vt.trim()==="";ct.removeEventListener("input",Ft),ct.removeEventListener("blur",un),ct.removeEventListener("keydown",Pt),ct.parentNode&&ct.parentNode.removeChild(ct),$.show(),F.batchDraw(),dn||s(g,{text:vt}),d==null||d(g,Xt)},un=()=>{Jt()},Pt=vt=>{vt.stopPropagation(),vt.key==="Escape"&&(dn=!0,ct.blur()),vt.key==="Enter"&&!vt.shiftKey&&(vt.preventDefault(),ct.blur()),vt.key==="Tab"&&(vt.preventDefault(),ct.blur())};ct.addEventListener("blur",un),ct.addEventListener("keydown",Pt)},[g,v,m,W,D,_,R,Z,s,l,d]);I.useEffect(()=>{i||(O.current=!1)},[i]),I.useEffect(()=>{i&&!O.current&&nt.current&&(O.current=!0,w())},[i,w]);const S=D?k.x:u,M=D?k.y:f,j=D&&k.width?k.width:void 0,ht=D?R||"center":void 0;return h.jsx(dt.Text,{ref:nt,id:g,x:S,y:M,text:v||(D?"":"Double-click to edit"),fontSize:W.fontSize,fontFamily:W.fontFamily,fill:W.strokeColor,lineHeight:En,width:j,align:ht,wrap:D?"word":"none",rotation:D?(_==null?void 0:_.rotation)??m:m,transformsEnabled:(D?(_==null?void 0:_.rotation)??m:m)?"all":"position",visible:!(i&&!V.current&&!v),opacity:v?W.opacity:D?0:.4,draggable:J,listening:!D,onClick:D?void 0:()=>o(g),onTap:D?void 0:()=>o(g),onDblClick:w,onDblTap:w,shadowColor:!D&&e?"#4f8df7":void 0,shadowBlur:!D&&e?6:0,shadowOpacity:!D&&e?.5:0,hitStrokeWidth:D?0:10,perfectDrawEnabled:!1,onDragMove:D?void 0:$=>{let F=$.target.x(),gt=$.target.y();a&&(F=At(F,a),gt=At(gt,a),$.target.x(F),$.target.y(gt)),r==null||r(g,{x:F,y:gt})},onDragEnd:D?void 0:$=>{let F=$.target.x(),gt=$.target.y();a&&(F=At(F,a),gt=At(gt,a)),s(g,{x:F,y:gt})},onTransformEnd:D?void 0:$=>{const F=$.target,gt=F.scaleX(),rt=F.scaleY(),E=Math.max(Math.abs(gt),Math.abs(rt)),H=Math.max(8,Math.round(W.fontSize*E));F.scaleX(1),F.scaleY(1),s(g,{x:F.x(),y:F.y(),rotation:F.rotation(),style:{...W,fontSize:H}})}})},zl=I.memo(Kl),Jl=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:d})=>{const{id:c,x:a,y:g,width:u,height:f,rotation:y,src:p,style:m,crop:W,cornerRadius:v,scaleMode:X,isLocked:R}=t,[Z,K]=I.useState(null),[nt,V]=I.useState(!1),[O,D]=I.useState({w:u,h:f});I.useEffect(()=>{D({w:u,h:f})},[u,f]);const J=O.w,_=O.h;I.useEffect(()=>{if(!p){K(null),V(!0);return}const E=new window.Image;return E.crossOrigin="anonymous",E.onload=()=>{K(E),V(!1)},E.onerror=()=>{K(null),V(!0)},E.src=p,()=>{E.onload=null,E.onerror=null}},[p]);const k=I.useCallback(E=>{let H=E.target.x(),z=E.target.y();if(l&&(H=At(H,l),z=At(z,l),E.target.x(H),E.target.y(z)),!l&&d){const U=d(c,{x:H,y:z,width:u,height:f});U&&(H=U.x,z=U.y,E.target.x(H),E.target.y(z))}r==null||r(c,{x:H,y:z})},[c,u,f,l,d,r]),b=I.useCallback(E=>{let H=E.target.x(),z=E.target.y();l&&(H=At(H,l),z=At(z,l)),s(c,{x:H,y:z})},[c,l,s]),w=I.useCallback(E=>{const H=E.target,z=H.scaleX(),U=H.scaleY(),ot=Math.max(10,H.width()*z),it=Math.max(10,H.height()*U);H.setAttrs({scaleX:1,scaleY:1,width:ot,height:it}),D({w:ot,h:it}),r==null||r(c,{x:H.x(),y:H.y(),width:ot,height:it})},[c,r]),S=I.useCallback(E=>{const H=E.target;s(c,{x:H.x(),y:H.y(),width:Math.max(10,H.width()),height:Math.max(10,H.height()),rotation:H.rotation()})},[c,s]);let M=0,j=0,ht=J,$=_,F;if(W&&(F={x:W.x,y:W.y,width:W.width,height:W.height}),Z){const E=W?W.width:Z.naturalWidth,H=W?W.height:Z.naturalHeight;if(X==="fit"){const z=E/H,U=J/_;z>U?(ht=J,$=J/z,j=(_-$)/2):($=_,ht=_*z,M=(J-ht)/2)}else if(X==="fill"&&!W){const z=Z.naturalWidth,U=Z.naturalHeight,ot=z/U,it=J/_;if(ot>it){const yt=U*it;F={x:(z-yt)/2,y:0,width:yt,height:U}}else{const yt=z/it;F={x:0,y:(U-yt)/2,width:z,height:yt}}ht=J,$=_}}const gt=v>0?E=>{const H=Math.min(v,J/2,_/2);E.beginPath(),E.moveTo(H,0),E.lineTo(J-H,0),E.arcTo(J,0,J,H,H),E.lineTo(J,_-H),E.arcTo(J,_,J-H,_,H),E.lineTo(H,_),E.arcTo(0,_,0,_-H,H),E.lineTo(0,H),E.arcTo(0,0,H,0,H),E.closePath()}:void 0,rt={id:c,x:a,y:g,width:J,height:_,rotation:y,transformsEnabled:y?"all":"position",draggable:!R&&!n,clipFunc:gt,onClick:()=>o(c),onTap:()=>o(c),onDblClick:()=>i==null?void 0:i(c),onDblTap:()=>i==null?void 0:i(c),onDragMove:k,onDragEnd:b,onTransform:w,onTransformEnd:S};return!Z||nt?h.jsx(dt.Group,{...rt,children:h.jsx(dt.Rect,{width:J,height:_,fill:"#f0f0f0",stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,opacity:m.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}):h.jsxs(dt.Group,{...rt,shadowColor:e?"#4f8df7":void 0,shadowBlur:e?6:0,shadowOpacity:e?.5:0,children:[X==="fit"&&h.jsx(dt.Rect,{width:J,height:_,fill:m.fillColor==="transparent"?void 0:m.fillColor,cornerRadius:v}),h.jsx(dt.Image,{image:Z,x:M,y:j,width:ht,height:$,crop:F,opacity:m.opacity,listening:!1,perfectDrawEnabled:!1}),m.strokeWidth>0&&m.strokeColor!=="transparent"&&h.jsx(dt.Rect,{width:J,height:_,stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,listening:!1})]})},$l=I.memo(Jl),Rl=2,jl=24,Ql=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,autoEditText:d,onTextEditStart:c,onTextEditEnd:a,allElements:g,gridSnap:u,onDragSnap:f,viewportScale:y})=>{var m,W,v;const p=I.useCallback(()=>s(t.id),[s,t.id]);if(!t.isVisible)return null;if(y!==void 0&&!e&&!n){const X=Math.max(t.width,t.height)*y;if(X<Rl)return null;if(X<jl)return h.jsx(dt.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/y,opacity:((v=t.style)==null?void 0:v.opacity)??1,onClick:p,onTap:p,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,transformsEnabled:"position"})}switch(t.type){case"rectangle":return h.jsx(El,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"ellipse":return h.jsx(Tl,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"diamond":return h.jsx(Zl,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"line":return h.jsx(Vl,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:g});case"arrow":return h.jsx(Ol,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:g});case"freedraw":return h.jsx(Ul,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"text":return h.jsx(zl,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,autoEdit:d,onEditStart:c,onEditEnd:a,allElements:g,gridSnap:u});case"image":return h.jsx($l,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});default:return null}};function ql(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 wo=I.memo(Ql,ql);function tc(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 ec=({selectedIds:t,selectionColor:e="#4f8df7"})=>{const n=I.useRef(null),o=T(c=>tc(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 a=0,g=0;for(const u of c){const f=u.split(":");f[1]==="1"&&a++,f[2]==="text"&&g++}return{hasLocked:a>0,allLocked:a===c.length,allText:g===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 a=c.getStage();if(!a)return;const g=t.map(f=>a.findOne(`#${f}`)).filter(Boolean);c.nodes(g),(u=c.getLayer())==null||u.batchDraw()},[t]),t.length===0)return null;const d=s?"#ff9500":e;return h.jsx(dt.Transformer,{ref:n,flipEnabled:!1,keepRatio:i,resizeEnabled:!r,rotateEnabled:!r,boundBoxFunc:(c,a)=>r||Math.abs(a.width)<5||Math.abs(a.height)<5?c:a,anchorFill:r?"#ff9500":"#ffffff",anchorStroke:d,anchorSize:r?0:8,anchorCornerRadius:2,borderStroke:d,borderStrokeWidth:1,borderDash:r?[6,3]:[4,4],rotateAnchorOffset:25,enabledAnchors:r?[]:l})},nc=I.memo(ec),oc=({width:t,height:e,viewport:n,gridColor:o="#e5e5e5"})=>{const{x:s,y:r,scale:i}=n,l=Te,d=I.useMemo(()=>{const c=Math.floor((-s/i-l)/l)*l,a=Math.ceil((-s/i+t/i+l)/l)*l,g=Math.floor((-r/i-l)/l)*l,u=Math.ceil((-r/i+e/i+l)/l)*l;return{startX:c,endX:a,startY:g,endY:u}},[s,r,i,t,e,l]);return h.jsx(dt.Shape,{sceneFunc:c=>{const{startX:a,endX:g,startY:u,endY:f}=d,y=1/i,p=c._context;p.beginPath(),p.strokeStyle=o,p.lineWidth=y;for(let m=a;m<=g;m+=l)p.moveTo(m,u),p.lineTo(m,f);for(let m=u;m<=f;m+=l)p.moveTo(a,m),p.lineTo(g,m);p.stroke()},listening:!1,perfectDrawEnabled:!1})},sc=I.memo(oc),rc=({box:t,selectionColor:e="#4f8df7"})=>t?h.jsx(dt.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:`${e}14`,stroke:e,strokeWidth:1,dash:[4,4],listening:!1}):null,ic=I.memo(rc),ae=6,lc=({el:t,color:e})=>{const n=t.x+t.width/2,o=t.y+t.height/2,s=t.rotation||0;switch(t.type){case"ellipse":return h.jsx(dt.Ellipse,{x:n,y:o,radiusX:t.width/2+ae,radiusY:t.height/2+ae,rotation:s,stroke:e,strokeWidth:2,dash:[8,4],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1});case"diamond":{const r=t.width+ae*2,i=t.height+ae*2,l=[r/2,0,r,i/2,r/2,i,0,i/2];return h.jsx(dt.Line,{x:n-r/2,y:o-i/2,points:l,closed:!0,rotation:s,offsetX:0,offsetY:0,stroke:e,strokeWidth:2,dash:[8,4],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}default:return h.jsx(dt.Rect,{x:n,y:o,offsetX:t.width/2+ae,offsetY:t.height/2+ae,width:t.width+ae*2,height:t.height+ae*2,rotation:s,stroke:e,strokeWidth:2,dash:[8,4],cornerRadius:6,fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}},cc=({elements:t,snapTarget:e,visible:n,color:o="#4f8df7"})=>{if(!n||!e)return null;const s=t.find(r=>r.id===e.elementId&&io(r));return s?h.jsxs(h.Fragment,{children:[h.jsx(lc,{el:s,color:o}),h.jsx(dt.Circle,{x:e.position.x,y:e.position.y,radius:6,fill:o,stroke:"white",strokeWidth:2,listening:!1,perfectDrawEnabled:!1}),!e.isPrecise&&(()=>{const r=s.rotation||0,i={x:s.x+s.width/2,y:s.y+s.height/2},l=r!==0?Ms(i,{x:s.x,y:s.y},r*Math.PI/180):i;return h.jsx(dt.Circle,{x:l.x,y:l.y,radius:4,fill:"white",stroke:o,strokeWidth:2,listening:!1,perfectDrawEnabled:!1})})()]}):null},ac=I.memo(cc),$s=4,dc=3,uc="#ffffff",gc="#4f8df7",hc="#2563eb",fc="#4f8df7",pc=5,yc="#ff6b35",Ic="#ffffff";function Cc(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Rs(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const bc=({element:t,allElements:e,onPointsChange:n,onPointDragMove:o,onSnapTargetChange:s,color:r="#4f8df7"})=>{const{selectedPointIndices:i,hoveredPointIndex:l,hoveredMidpointIndex:d,setSelectedPoints:c,togglePointSelection:a,setHoveredPoint:g,setHoveredMidpoint:u,setIsDraggingPoint:f}=qe(),{id:y,x:p,y:m,points:W}=t,v=Cc(W),X=I.useRef(null),R=I.useRef(null),Z=I.useRef(void 0),K="lineType"in t&&t.lineType==="curved",nt="lineType"in t&&t.lineType==="elbow",V=K||nt,O=I.useCallback(w=>w===0||w===v.length-1,[v.length]),D=I.useCallback(w=>{f(!0),X.current={points:[...W],x:p,y:m},Z.current=void 0,i.includes(w)||c([w])},[W,p,m,i,c,f]),J=I.useCallback((w,S)=>{const M=S.target,j=M.x(),ht=M.y(),$=[...W];$[w*2]=j-p,$[w*2+1]=ht-m;const F={};if(O(w)){const gt=M.getStage(),rt=gt==null?void 0:gt.getRelativePointerPosition(),E=(rt==null?void 0:rt.x)??j,H=(rt==null?void 0:rt.y)??ht;R.current={x:E,y:H};const z={x:E,y:H},U=new Set([y]),ot=w===0?t.endBinding:t.startBinding;ot&&U.add(ot.elementId);const it=re(t.style.strokeWidth??2),yt=fe(z,e,24,U,void 0,void 0,it,Z.current);if(s==null||s(yt),Z.current=yt==null?void 0:yt.isPrecise,yt){const pt=yt.position;$[w*2]=pt.x-p,$[w*2+1]=pt.y-m,M.x(pt.x),M.y(pt.y);const st={elementId:yt.elementId,fixedPoint:yt.fixedPoint,gap:it,isPrecise:yt.isPrecise};w===0?F.startBinding=st:F.endBinding=st}else w===0?F.startBinding=null:F.endBinding=null}o==null||o(y,{points:$,x:p,y:m,...F})},[W,p,m,y,t,e,O,o,s]),_=I.useCallback((w,S)=>{f(!1);const M=S.target;let j,ht;O(w)&&R.current?(j=R.current.x,ht=R.current.y):(j=M.x(),ht=M.y()),R.current=null;const $=[...W];$[w*2]=j-p,$[w*2+1]=ht-m;const F={points:$};if(O(w)){const U={x:j,y:ht},ot=new Set([y]),it=w===0?t.endBinding:t.startBinding;it&&ot.add(it.elementId);const yt=re(t.style.strokeWidth??2),pt=fe(U,e,24,ot,void 0,void 0,yt,Z.current);if(s==null||s(null),Z.current=void 0,pt){const st=re(t.style.strokeWidth??2),C={elementId:pt.elementId,fixedPoint:pt.fixedPoint,gap:st,isPrecise:pt.isPrecise};w===0?F.startBinding=C:F.endBinding=C,$[w*2]=pt.position.x-p,$[w*2+1]=pt.position.y-m,F.points=$}else w===0?F.startBinding=null:F.endBinding=null}const gt=F.points??$,rt=gt[0],E=gt[1];if(rt!==0||E!==0){const U=[];for(let ot=0;ot<gt.length;ot+=2)U.push(gt[ot]-rt,gt[ot+1]-E);F.x=p+rt,F.y=m+E,F.points=U}const H=F.points??gt,z=mn(H);F.width=z.width,F.height=z.height,n(y,F),X.current=null},[W,p,m,y,v,t,e,O,f,n,s]),k=I.useCallback((w,S)=>{S.cancelBubble=!0,S.evt.shiftKey?a(w):c([w])},[c,a]),b=I.useCallback((w,S)=>{S.cancelBubble=!0;const M=v[w],j=v[w+1],ht=Rs(M,j),$=w+1,F=[];for(let rt=0;rt<v.length;rt++)F.push(v[rt].x,v[rt].y),rt===w&&F.push(ht.x,ht.y);const gt=mn(F);c([$]),u(null),n(y,{points:F,width:gt.width,height:gt.height})},[y,v,c,u,n]);return h.jsxs(dt.Group,{children:[!V&&v.length>=2&&v.slice(0,-1).map((w,S)=>{const M=v[S+1],j=Rs(w,M),ht=d===S;return h.jsx(dt.Circle,{x:p+j.x,y:m+j.y,radius:dc,fill:ht?hc:gc,opacity:ht?.9:.5,stroke:"white",strokeWidth:1.5,onMouseEnter:()=>u(S),onMouseLeave:()=>u(null),onClick:$=>b(S,$),onTap:$=>b(S,$),hitStrokeWidth:10,perfectDrawEnabled:!1},`mid-${S}`)}),v.map((w,S)=>{const M=O(S);if(V&&!M)return null;const j=i.includes(S),ht=l===S,$=M?$s+1:$s;return h.jsx(dt.Circle,{x:p+w.x,y:m+w.y,radius:$,fill:j?fc:uc,stroke:ht||j?"#2563eb":r,strokeWidth:j?2.5:2,draggable:!0,onMouseEnter:()=>g(S),onMouseLeave:()=>g(-1),onClick:F=>k(S,F),onTap:F=>k(S,F),onDragStart:()=>D(S),onDragMove:F=>J(S,F),onDragEnd:F=>_(S,F),hitStrokeWidth:10,perfectDrawEnabled:!1},`pt-${S}`)}),K&&v.length>=2&&(()=>{const w=v[0],S=v[v.length-1],M=t.curvature??Nt,j=Ut(w,S,M),ht=Me(w,j,S,.5);return h.jsx(dt.Circle,{x:p+ht.x,y:m+ht.y,radius:pc,fill:yc,stroke:Ic,strokeWidth:2,draggable:!0,onDragStart:()=>f(!0),onDragMove:$=>{const F=$.target,gt={x:p+w.x,y:m+w.y},rt={x:p+S.x,y:m+S.y},E={x:F.x(),y:F.y()},H=Xs(gt,rt,E),z=Ut(w,S,H),U=Me(w,z,S,.5);F.x(p+U.x),F.y(m+U.y),o==null||o(y,{curvature:H})},onDragEnd:$=>{f(!1);const F=$.target,gt={x:p+w.x,y:m+w.y},rt={x:p+S.x,y:m+S.y},E={x:F.x(),y:F.y()},H=Xs(gt,rt,E),z=Ut(w,S,H),U=Me(w,z,S,.5);F.x(p+U.x),F.y(m+U.y),n(y,{curvature:H})},hitStrokeWidth:12,perfectDrawEnabled:!1},"curve-handle")})()]})},Ac=I.memo(bc),mc={Hand:h.jsx(It.Hand,{size:18}),MousePointer2:h.jsx(It.MousePointer2,{size:18}),Square:h.jsx(It.Square,{size:18}),Circle:h.jsx(It.Circle,{size:18}),Diamond:h.jsx(It.Diamond,{size:18}),Minus:h.jsx(It.Minus,{size:18}),ArrowUpRight:h.jsx(It.ArrowUpRight,{size:18}),Pencil:h.jsx(It.Pencil,{size:18}),Type:h.jsx(It.Type,{size:18}),ImageIcon:h.jsx(It.ImageIcon,{size:18}),Eraser:h.jsx(It.Eraser,{size:18}),StickyNote:h.jsx(It.StickyNote,{size:18})},de=(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}),Wn=t=>({width:1,height:22,background:t.toolbarBorder,margin:"0 3px",flexShrink:0}),js=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 wc(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 xo=({anchorRef:t,onClose:e,theme:n,placement:o,computePos:s,transform:r,dataAttribute:i,style:l,children:d,isOpen:c})=>{const a=wc(t,g=>s(g,o),c);return I.useEffect(()=>{if(!c)return;const g=f=>{t.current&&t.current.contains(f.target)||f.target.closest(`[${i}]`)||e()},u=()=>e();return document.addEventListener("mousedown",g),window.addEventListener("resize",u),()=>{document.removeEventListener("mousedown",g),window.removeEventListener("resize",u)}},[c,e,i,t]),!c||!a?null:ns.createPortal(h.jsx("div",{[i]:"true",style:{position:"fixed",top:a.top,left:a.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:d}),document.body)},Qs=({icon:t,label:e,disabled:n,isActive:o,onClick:s,theme:r,size:i=36})=>h.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}),xc=({actions:t,anchorRef:e,onClose:n,theme:o,placement:s="bottom"})=>h.jsx(xo,{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)=>h.jsx(Qs,{icon:r.icon,label:r.label,disabled:r.disabled,onClick:()=>{r.onClick(),n()},theme:o},i))}),kc=({shapes:t,activeTool:e,anchorRef:n,onSelect:o,onClose:s,theme:r,placement:i="bottom"})=>h.jsx(xo,{isOpen:!0,anchorRef:n,onClose:s,theme:r,placement:i,computePos:(l,d)=>d==="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,d)=>h.jsx(Qs,{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},d))}),Sc=({scale:t,theme:e,onZoomIn:n,onZoomOut:o,onReset:s,placement:r="bottom"})=>{const[i,l]=I.useState(!1),d=I.useRef(null);return h.jsxs("div",{ref:d,style:{position:"relative"},children:[h.jsxs("button",{style:{...de(i,e),width:"auto",padding:"0 6px",gap:2,fontSize:11,minWidth:52},onClick:()=>l(!i),title:"Zoom",children:[h.jsxs("span",{style:{minWidth:32,textAlign:"center",userSelect:"none"},children:[Math.round(t*100),"%"]}),h.jsx(It.ChevronDown,{size:12})]}),h.jsx(xo,{isOpen:i,anchorRef:d,onClose:()=>l(!1),theme:e,placement:r,computePos:(c,a)=>a==="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:h.jsx(It.ZoomIn,{size:14}),label:"Zoom In",fn:()=>{n(),l(!1)}},{icon:h.jsx(It.ZoomOut,{size:14}),label:"Zoom Out",fn:()=>{o(),l(!1)}},{icon:h.jsx(It.Maximize,{size:14}),label:"Reset Zoom",fn:()=>{s(),l(!1)}}].map(({icon:c,label:a,fn:g})=>h.jsxs("button",{onClick:g,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,h.jsx("span",{children:a})]},a))})]})},vc=({visibleTools:t,theme:e,position:n="bottom"})=>{const o=T(E=>E.activeTool),s=T(E=>E.setActiveTool),r=T(E=>E.undo),i=T(E=>E.redo),l=T(E=>E.selectedIds),d=T(E=>E.elements),c=T(E=>E.deleteElements),a=T(E=>E.duplicateElements),g=T(E=>E.bringToFront),u=T(E=>E.bringForward),f=T(E=>E.sendBackward),y=T(E=>E.sendToBack),p=T(E=>E.toggleLockElements),m=T(E=>E.ungroupElements),W=T(E=>E.pushHistory),v=T(E=>E.showGrid),X=T(E=>E.toggleGrid),R=T(E=>E.zoomIn),Z=T(E=>E.zoomOut),K=T(E=>E.resetZoom),nt=T(E=>E.viewport.scale),[V,O]=I.useState(!1),D=I.useRef(null),[J,_]=I.useState(!1),k=I.useRef(null),b=l.length>0,w=l.length>1,S=b&&d.filter(E=>l.includes(E.id)).every(E=>E.isLocked),M=()=>{const E=new Blob([JSON.stringify(d,null,2)],{type:"application/json"}),H=URL.createObjectURL(E),z=Object.assign(document.createElement("a"),{href:H,download:"canvas.json"});document.body.appendChild(z),z.click(),document.body.removeChild(z),URL.revokeObjectURL(H)},j=[{icon:h.jsx(It.AlignLeft,{size:16}),label:"Align Left",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.AlignCenter,{size:16}),label:"Align Center H",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.AlignRight,{size:16}),label:"Align Right",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.AlignCenterVertical,{size:16}),label:"Align Center V",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.AlignStartVertical,{size:16}),label:"Align Top",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.AlignEndVertical,{size:16}),label:"Align Bottom",disabled:!w,onClick:()=>{}},{icon:h.jsx(It.FlipHorizontal,{size:16}),label:"Flip H",disabled:!b,onClick:()=>{}},{icon:h.jsx(It.FlipVertical,{size:16}),label:"Flip V",disabled:!b,onClick:()=>{}},{icon:h.jsx(It.ChevronsUp,{size:16}),label:"Bring to Front",disabled:!b,onClick:()=>{g(l),W()}},{icon:h.jsx(It.ArrowUp,{size:16}),label:"Bring Forward",disabled:!b,onClick:()=>{u(l),W()}},{icon:h.jsx(It.ArrowDown,{size:16}),label:"Send Backward",disabled:!b,onClick:()=>{f(l),W()}},{icon:h.jsx(It.ChevronsDown,{size:16}),label:"Send to Back",disabled:!b,onClick:()=>{y(l),W()}},{icon:h.jsx(It.RotateCcw,{size:16}),label:"Rotate Left 90°",disabled:!b,onClick:()=>{}},{icon:h.jsx(It.RotateCw,{size:16}),label:"Rotate Right 90°",disabled:!b,onClick:()=>{}},{icon:S?h.jsx(It.Unlock,{size:16}):h.jsx(It.Lock,{size:16}),label:S?"Unlock":"Lock",disabled:!b,onClick:()=>{p(l),W()}},{icon:h.jsx(It.Ungroup,{size:16}),label:"Ungroup",disabled:!b,onClick:()=>{m(l),W()}},{icon:h.jsx(It.Grid3x3,{size:16}),label:v?"Hide Grid":"Show Grid",disabled:!1,onClick:X},{icon:h.jsx(It.Download,{size:16}),label:"Export JSON",disabled:!1,onClick:M},{icon:h.jsx(It.Maximize,{size:16}),label:"Reset Zoom",disabled:!1,onClick:K},{icon:h.jsx(It.Group,{size:16}),label:"Select All",disabled:!1,onClick:()=>{}}],$=[{icon:h.jsx(It.Square,{size:16}),label:"Rectangle",tool:"rectangle"},{icon:h.jsx(It.Circle,{size:16}),label:"Ellipse",tool:"ellipse"},{icon:h.jsx(It.Diamond,{size:16}),label:"Diamond",tool:"diamond"},{icon:h.jsx(It.Minus,{size:16}),label:"Line",tool:"line"},{icon:h.jsx(It.ArrowUpRight,{size:16}),label:"Arrow",tool:"arrow"}].filter(E=>E.tool===null?!0:!t.some(H=>H.type===E.tool)),F=E=>s(E),gt=j.filter(E=>!["Undo","Redo","Delete","Duplicate"].includes(E.label)),rt=n==="top";return h.jsx("div",{style:{position:"absolute",...rt?{top:16}:{bottom:16},left:0,right:0,zIndex:50,display:"flex",justifyContent:"center",alignItems:rt?"flex-start":"flex-end",pointerEvents:"none"},children:h.jsxs("div",{style:{display:"flex",flexDirection:rt?"column-reverse":"column",alignItems:"center",maxWidth:"calc(100% - 32px)",gap:0,pointerEvents:"none"},children:[h.jsxs("div",{style:{...js(e),pointerEvents:"auto",...rt?{borderRadius:"0 0 12px 12px",borderTop:"none"}:{borderRadius:"12px 12px 0 0",borderBottom:"none"}},children:[h.jsx("button",{style:de(!1,e),onClick:r,title:"Undo (⌘Z)",children:h.jsx(It.Undo2,{size:16})}),h.jsx("button",{style:de(!1,e),onClick:i,title:"Redo (⌘⇧Z)",children:h.jsx(It.Redo2,{size:16})}),h.jsx("div",{style:Wn(e)}),h.jsx("button",{style:de(!1,e,!b),disabled:!b,onClick:()=>{b&&c(l)},title:"Delete (⌫)",children:h.jsx(It.Trash2,{size:16})}),h.jsx("button",{style:de(!1,e,!b),disabled:!b,onClick:()=>{b&&a(l)},title:"Duplicate (⌘D)",children:h.jsx(It.Copy,{size:16})}),gt.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("div",{style:Wn(e)}),h.jsx("button",{ref:D,style:de(V,e),onClick:()=>{O(!V),_(!1)},title:"More actions",children:h.jsx(It.MoreHorizontal,{size:16})})]})]}),h.jsxs("div",{style:{...js(e),pointerEvents:"auto",...rt?{borderRadius:"12px 12px 0 0",borderBottom:"none"}:{}},children:[t.map(E=>h.jsx("button",{style:de(o===E.type,e),onClick:()=>s(E.type),title:`${E.label} (${E.shortcut})`,children:mc[E.icon]},E.type)),h.jsx("div",{style:Wn(e)}),h.jsx(Sc,{scale:nt,theme:e,onZoomIn:R,onZoomOut:Z,onReset:K,placement:n}),$.length>0&&h.jsxs(h.Fragment,{children:[h.jsx("div",{style:Wn(e)}),h.jsx("button",{ref:k,style:de(J,e),onClick:()=>{_(!J),O(!1)},title:"More shapes",children:h.jsx(It.ChevronUp,{size:16})})]})]}),V&&gt.length>0&&h.jsx(xc,{actions:gt,anchorRef:D,onClose:()=>O(!1),theme:e,placement:n}),J&&$.length>0&&h.jsx(kc,{shapes:$,activeTool:o,anchorRef:k,onSelect:F,onClose:()=>_(!1),theme:e,placement:n})]})})},Ae=({theme:t,variant:e="toggle",isActive:n=!1,dangerHover:o=!1,onClick:s,title:r,disabled:i=!1,width:l=28,height:d=28,style:c,children:a})=>{const[g,u]=I.useState(!1),f=n||g,y=()=>e==="toggle"&&n?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",p=()=>e==="toggle"&&n?`${t.activeToolColor}10`:g?"#f3f4f6":"transparent";return h.jsx("button",{title:r,onClick:i?void 0:s,disabled:i,onMouseEnter:()=>!i&&u(!0),onMouseLeave:()=>u(!1),style:{width:l,height:d,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:5,border:y(),background:p(),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 a=="function"?a(f):a})},ko=({theme:t,isActive:e=!1,onClick:n,title:o,disabled:s,flex:r=1,width:i,children:l,style:d})=>h.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",...d},children:l}),_t=({theme:t,label:e,headerAction:n,children:o,style:s})=>h.jsxs("div",{style:{marginBottom:10,...s},children:[e&&h.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:n?"space-between":"flex-start",marginBottom:n?0:5},children:[h.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:e}),n]}),o]}),Xe=({children:t,gap:e=5,wrap:n=!1,style:o})=>h.jsx("div",{style:{display:"flex",gap:e,justifyContent:"flex-start",flexWrap:n?"wrap":"nowrap",...o},children:t}),Tn=({options:t,value:e,onChange:n,theme:o,label:s,isOpen:r,onToggle:i,pickerRef:l,columns:d})=>{const c=t.find(f=>f.value===e)??t[0],a=I.useRef(null),[g,u]=I.useState(null);return I.useEffect(()=>{if(r&&a.current){const f=a.current.getBoundingClientRect();u({top:f.bottom+3,left:f.left})}else u(null)},[r]),h.jsxs("div",{ref:l,style:{position:"relative",display:"inline-flex"},children:[h.jsx("button",{ref:a,title:`${s}: ${c.label}`,onClick:i,style:{display:"flex",alignItems:"center",gap:3,height:24,padding:"0 5px",borderRadius:5,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.1s"},children:typeof c.icon=="function"?c.icon(r?o.activeToolColor:o.textColor):c.icon}),r&&g&&ns.createPortal(h.jsx("div",{"data-compact-dropdown":"true",style:{position:"fixed",top:g.top,left:g.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:d?`repeat(${d}, 26px)`:`repeat(${t.length}, 26px)`,gap:1},children:t.map(f=>{const y=f.value===e,p=y?o.activeToolColor:o.textColor;return h.jsx("button",{title:f.label,onClick:()=>{n(f.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:p,outline:"none"},children:typeof f.icon=="function"?f.icon(p):f.icon},String(f.value))})}),document.body)]})},So=20,Ec=4,Wc=6,Tc=[{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}],Bc=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],Zc=({thickness:t,color:e})=>h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:h.jsx("line",{x1:"2",y1:"7",x2:"12",y2:"7",stroke:e,strokeWidth:t,strokeLinecap:"round"})}),_c=({style:t,color:e})=>h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:h.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})}),Mc=({level:t,color:e})=>h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t===0?h.jsx("path",{d:"M2,9 Q5,5 7,7 Q9,9 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):t===1?h.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"}):h.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"})}),Gc=({type:t,color:e})=>h.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t==="sharp"?h.jsx("polyline",{points:"2,11 7,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}):t==="elbow"?h.jsx("polyline",{points:"2,11 2,3 12,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"square",strokeLinejoin:"miter"}):h.jsx("path",{d:"M2,11 Q7,0 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round"})}),qs=({arrowhead:t,end:e,color:n})=>{let l=18,d=null;switch(t){case null:break;case"arrow":l=16,d=h.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,d=h.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:n});break;case"triangle_outline":l=12,d=h.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,d=h.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:n});break;case"circle_outline":l=11,d=h.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"diamond":l=10,d=h.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:n});break;case"diamond_outline":l=10,d=h.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":d=h.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,d=h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:14,y1:6-3.5,x2:14,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),h.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,d=h.jsxs(h.Fragment,{children:[h.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),h.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,d=h.jsxs(h.Fragment,{children:[h.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),h.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"}),h.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 h.jsx("svg",{width:20,height:12,viewBox:"0 0 20 12",fill:"none",style:{overflow:"visible"},children:h.jsxs("g",{transform:c,children:[h.jsx("line",{x1:2,y1:6,x2:l,y2:6,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"}),d]})})},ue=({children:t,color:e,size:n=12})=>h.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t}),Bn={sendToBack:t=>h.jsxs(ue,{color:t,children:[h.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),h.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"}),h.jsx("polyline",{points:"12 12 12 18"}),h.jsx("polyline",{points:"9 15 12 18 15 15"})]}),sendBackward:t=>h.jsxs(ue,{color:t,children:[h.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),h.jsx("polyline",{points:"19 12 12 19 5 12"})]}),bringForward:t=>h.jsxs(ue,{color:t,children:[h.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),h.jsx("polyline",{points:"5 12 12 5 19 12"})]}),bringToFront:t=>h.jsxs(ue,{color:t,children:[h.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),h.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"}),h.jsx("polyline",{points:"12 18 12 12"}),h.jsx("polyline",{points:"9 15 12 12 15 15"})]})},Zn={duplicate:t=>h.jsxs(ue,{color:t,children:[h.jsx("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"}),h.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=>h.jsxs(ue,{color:t,children:[h.jsx("polyline",{points:"3 6 5 6 21 6"}),h.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),h.jsx("path",{d:"M10 11v6"}),h.jsx("path",{d:"M14 11v6"}),h.jsx("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),link:t=>h.jsxs(ue,{color:t,children:[h.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"}),h.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=>h.jsxs(ue,{color:t,children:[h.jsx("rect",{x:"2",y:"2",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),h.jsx("rect",{x:"14",y:"14",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),h.jsx("path",{d:"M14 2h4a2 2 0 0 1 2 2v4"}),h.jsx("path",{d:"M2 14v4a2 2 0 0 0 2 2h4"})]})},Xc=({theme:t})=>{const e=T(C=>C.currentStyle),n=T(C=>C.setCurrentStyle),o=T(C=>C.selectedIds),s=T(C=>C.elements),r=T(C=>C.updateElement),i=T(C=>C.pushHistory),l=T(C=>C.toggleLockElements),d=T(C=>C.deleteElements),c=T(C=>C.duplicateElements),a=T(C=>C.bringToFront),g=T(C=>C.sendToBack),u=T(C=>C.bringForward),f=T(C=>C.sendBackward),y=T(C=>C.activeTool),p=T(C=>C.currentLineType),m=T(C=>C.setCurrentLineType),W=T(C=>C.currentStartArrowhead),v=T(C=>C.setCurrentStartArrowhead),X=T(C=>C.currentEndArrowhead),R=T(C=>C.setCurrentEndArrowhead),[Z,K]=I.useState(null),nt=I.useRef(null),V=I.useRef(null),[O,D]=I.useState(null),J=I.useRef(null),_=I.useRef(null),k=I.useRef(null),b=I.useRef(null);I.useEffect(()=>{if(!Z)return;const C=G=>{const Ct=Z==="start"?nt:V,bt=Ct.current&&Ct.current.contains(G.target),St=G.target.closest('[data-compact-dropdown="true"]');!bt&&!St&&K(null)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[Z]),I.useEffect(()=>{if(!O)return;const C=G=>{const Ct=O==="sloppiness"?J:_,bt=Ct.current&&Ct.current.contains(G.target),St=G.target.closest('[data-compact-dropdown="true"]');!bt&&!St&&D(null)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[O]);const w=I.useMemo(()=>o.some(C=>{var G;return((G=s.find(Ct=>Ct.id===C))==null?void 0:G.type)==="text"}),[o,s]),S=I.useMemo(()=>{const C=o.length===1?s.find(G=>G.id===o[0]):null;return C&&(C.type==="arrow"||C.type==="line")?C:null},[o,s]),M=I.useMemo(()=>{const C=o.length===1?s.find(G=>G.id===o[0]):null;return!C||C.type!=="image"?null:C},[o,s]),j=I.useMemo(()=>{if(o.length===0)return null;const C=s.filter(bt=>o.includes(bt.id)),G=C.every(bt=>bt.isLocked),Ct=C.some(bt=>bt.isLocked);return{allLocked:G,anyLocked:Ct}},[o,s]),ht=(S==null?void 0:S.type)==="arrow",$=S!=null,F=o.length>0,gt=y==="arrow"||y==="line",rt=y==="arrow",E=$||gt,H=ht||rt,z=I.useMemo(()=>{if(o.length===0)return e;if(o.length===1){const G=s.find(Ct=>Ct.id===o[0]);if(G)return G.style}const C=s.find(G=>o.includes(G.id));return C?C.style:e},[o,s,e]),U=C=>{n(C),o.length>0&&(o.forEach(G=>{const Ct=s.find(bt=>bt.id===G);Ct&&r(G,{style:{...Ct.style,...C}})}),i())},ot=Math.round(z.opacity*100),it={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"},yt=(C,G)=>({width:So,height:So,borderRadius:4,border:G?`2px solid ${t.activeToolColor}`:"1.5px solid #d5d8dc",cursor:"pointer",background:C==="transparent"?"repeating-conic-gradient(#d1d5db 0% 25%, transparent 0% 50%) 50%/6px 6px":C,boxShadow:G?`0 0 0 1.5px ${t.activeToolColor}30`:"none",outline:"none",flexShrink:0,transition:"border-color 0.1s, box-shadow 0.1s",padding:0}),pt={height:1,background:t.toolbarBorder,margin:"10px 0",border:"none"},st={display:"grid",gridTemplateColumns:`repeat(${Wc}, ${So}px)`,gap:Ec};return h.jsxs("div",{style:it,children:[h.jsx(_t,{label:"Stroke",theme:t,children:h.jsxs("div",{style:st,children:[Ne.map(C=>h.jsx("button",{style:yt(C,z.strokeColor===C),onClick:()=>U({strokeColor:C}),title:C},C)),h.jsx("button",{title:"Custom color",onClick:()=>{var C;return(C=k.current)==null?void 0:C.click()},style:{...yt(z.strokeColor,!Ne.includes(z.strokeColor)),background:Ne.includes(z.strokeColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":z.strokeColor,border:Ne.includes(z.strokeColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),h.jsx("input",{ref:k,type:"color",value:z.strokeColor.startsWith("#")?z.strokeColor:"#000000",onChange:C=>U({strokeColor:C.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),!$&&!gt&&h.jsx(_t,{label:"Background",theme:t,children:h.jsxs("div",{style:st,children:[Ue.map(C=>h.jsx("button",{style:yt(C,z.fillColor===C),onClick:()=>U({fillColor:C}),title:C==="transparent"?"None":C},C)),h.jsx("button",{title:"Custom color",onClick:()=>{var C;return(C=b.current)==null?void 0:C.click()},style:{...yt(z.fillColor,!Ue.includes(z.fillColor)),background:Ue.includes(z.fillColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":z.fillColor,border:Ue.includes(z.fillColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),h.jsx("input",{ref:b,type:"color",value:z.fillColor.startsWith("#")?z.fillColor:"#ffffff",onChange:C=>U({fillColor:C.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),h.jsx(_t,{label:"Stroke width",theme:t,children:h.jsx(Xe,{children:Tc.map(C=>h.jsx(Ae,{isActive:z.strokeWidth===C.value,theme:t,onClick:()=>U({strokeWidth:C.value}),title:C.label,children:G=>h.jsx(Zc,{thickness:C.thickness,color:G?t.activeToolColor:t.textColor})},C.value))})}),h.jsx(_t,{label:"Stroke style",theme:t,children:h.jsx(Xe,{children:Bc.map(C=>h.jsx(Ae,{isActive:z.strokeStyle===C.value,theme:t,onClick:()=>U({strokeStyle:C.value}),title:C.label,children:G=>h.jsx(_c,{style:C.value,color:G?t.activeToolColor:t.textColor})},C.value))})}),h.jsx(_t,{label:"Sloppiness",theme:t,headerAction:h.jsx(Tn,{label:"Sloppiness",value:z.roughness,options:ss.map(C=>({value:C.value,label:C.label,icon:G=>h.jsx(Mc,{level:C.value,color:G})})),onChange:C=>{U({roughness:C})},theme:t,isOpen:O==="sloppiness",onToggle:()=>D(O==="sloppiness"?null:"sloppiness"),pickerRef:J})}),E&&h.jsx(_t,{label:ht||rt?"Arrow type":"Line type",theme:t,headerAction:h.jsx(Tn,{label:ht||rt?"Arrow type":"Line type",value:S?S.lineType:p,options:to.map(C=>({value:C.type,label:C.label,icon:G=>h.jsx(Gc,{type:C.type,color:G})})),onChange:C=>{const G=to.find(Ct=>Ct.type===C);if(G){if(S){const Ct={lineType:G.type};if(G.type==="curved"||G.type==="elbow"){const bt=S;bt.points.length>4&&(Ct.points=[bt.points[0],bt.points[1],bt.points[bt.points.length-2],bt.points[bt.points.length-1]])}r(S.id,Ct),i()}m(G.type),D(null)}},theme:t,isOpen:O==="lineType",onToggle:()=>D(O==="lineType"?null:"lineType"),pickerRef:_})}),H&&h.jsx(_t,{label:"Arrows",theme:t,headerAction:h.jsxs("div",{style:{display:"flex",gap:4},children:[h.jsx(Tn,{label:"Start arrowhead",value:(S?S.startArrowhead:W)??"__none__",options:qn.map(C=>({value:C.type??"__none__",label:C.label,icon:G=>h.jsx(qs,{arrowhead:C.type,end:"start",color:G})})),onChange:C=>{const G=C==="__none__"?null:C;S&&(r(S.id,{startArrowhead:G}),i()),v(G)},columns:4,theme:t,isOpen:Z==="start",onToggle:()=>K(Z==="start"?null:"start"),pickerRef:nt}),h.jsx(Tn,{label:"End arrowhead",value:(S?S.endArrowhead:X)??"__none__",options:qn.map(C=>({value:C.type??"__none__",label:C.label,icon:G=>h.jsx(qs,{arrowhead:C.type,end:"end",color:G})})),onChange:C=>{const G=C==="__none__"?null:C;S&&(r(S.id,{endArrowhead:G}),i()),R(G)},columns:4,theme:t,isOpen:Z==="end",onToggle:()=>K(Z==="end"?null:"end"),pickerRef:V})]})}),h.jsxs(h.Fragment,{children:[h.jsx("hr",{style:pt}),h.jsxs(_t,{theme:t,children:[h.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[h.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Opacity"}),h.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[ot,"%"]})]}),h.jsx("input",{type:"range",min:"0",max:"100",step:"1",value:ot,onChange:C=>U({opacity:parseInt(C.target.value)/100}),style:{width:"100%",accentColor:t.activeToolColor,height:4}})]})]}),w&&h.jsxs(h.Fragment,{children:[h.jsx("hr",{style:pt}),h.jsx(_t,{label:"Font size",theme:t,children:h.jsx(Xe,{wrap:!0,gap:2,children:ki.map(C=>h.jsx(ko,{isActive:z.fontSize===C,theme:t,onClick:()=>U({fontSize:C}),flex:"none",style:{width:28,padding:"2px 0"},children:C},C))})}),h.jsx(_t,{label:"Font family",theme:t,children:h.jsx("select",{value:z.fontFamily,onChange:C=>U({fontFamily:C.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:Si.map(C=>h.jsx("option",{value:C.value,children:C.label},C.value))})})]}),M&&h.jsxs(h.Fragment,{children:[h.jsx("hr",{style:pt}),h.jsx(_t,{label:"Scale mode",theme:t,children:h.jsx(Xe,{children:["stretch","fit","fill"].map(C=>h.jsx(ko,{isActive:M.scaleMode===C,theme:t,title:C==="stretch"?"Stretch to fill":C==="fit"?"Fit (contain)":"Fill (cover)",onClick:()=>{r(M.id,{scaleMode:C}),i()},children:C.charAt(0).toUpperCase()+C.slice(1)},C))})}),h.jsxs(_t,{theme:t,children:[h.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[h.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Corner radius"}),h.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[M.cornerRadius,"px"]})]}),h.jsx("input",{type:"range",min:"0",max:"50",step:"1",value:M.cornerRadius,onChange:C=>{r(M.id,{cornerRadius:parseInt(C.target.value)}),i()},style:{width:"100%",accentColor:t.activeToolColor,height:4}})]}),h.jsx(_t,{theme:t,children:h.jsx(ko,{theme:t,style:{width:"100%",padding:"5px 0",borderRadius:4},onClick:()=>{const C=document.createElement("input");C.type="file",C.accept="image/*",C.onchange=async()=>{var bt;const G=(bt=C.files)==null?void 0:bt[0];if(!G)return;const Ct=new FileReader;Ct.onload=()=>{const St=Ct.result,ct=new window.Image;ct.onload=()=>{r(M.id,{src:St,naturalWidth:ct.naturalWidth,naturalHeight:ct.naturalHeight}),i()},ct.src=St},Ct.readAsDataURL(G)},C.click()},children:"Replace Image…"})})]}),F&&h.jsxs(h.Fragment,{children:[h.jsx("hr",{style:pt}),h.jsx(_t,{label:"Layers",theme:t,children:h.jsx(Xe,{children:[{fn:g,icon:Bn.sendToBack,tip:"Send to back"},{fn:f,icon:Bn.sendBackward,tip:"Send backward"},{fn:u,icon:Bn.bringForward,tip:"Bring forward"},{fn:a,icon:Bn.bringToFront,tip:"Bring to front"}].map(({fn:C,icon:G,tip:Ct})=>h.jsx(Ae,{variant:"action",theme:t,title:Ct,onClick:()=>{C(o),i()},children:bt=>G(bt?t.activeToolColor:t.textColor)},Ct))})}),h.jsx(_t,{label:"Actions",theme:t,children:h.jsxs(Xe,{children:[h.jsx(Ae,{variant:"action",theme:t,title:"Duplicate (⌘D)",onClick:()=>c(o),children:C=>Zn.duplicate(C?t.activeToolColor:t.textColor)}),h.jsx(Ae,{variant:"action",theme:t,title:"Delete (⌫)",dangerHover:!0,onClick:()=>{d(o),i()},children:C=>Zn.delete(C?"#e03131":t.textColor)}),h.jsx(Ae,{variant:"action",theme:t,title:"Add link (coming soon)",disabled:!0,children:Zn.link(t.mutedTextColor)}),h.jsx(Ae,{variant:"action",theme:t,title:"Ungroup",onClick:()=>{T.getState().ungroupElements(o),i()},children:C=>Zn.ungroup(C?t.activeToolColor:t.textColor)})]})})]}),j&&F&&h.jsxs(h.Fragment,{children:[h.jsx("hr",{style:pt}),h.jsx("button",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",padding:"5px 0",borderRadius:6,border:j.allLocked?"1.5px solid #ff9500":`1px solid ${t.toolbarBorder}`,background:j.allLocked?"#ff950010":"transparent",cursor:"pointer",fontSize:10,fontWeight:600,color:j.allLocked?"#ff9500":t.textColor,letterSpacing:.2,transition:"all 0.1s ease",outline:"none",marginBottom:2},title:j.allLocked?"Unlock position (⌘⇧L)":"Lock position (⌘⇧L)",onClick:()=>l(o),children:j.allLocked?h.jsxs(h.Fragment,{children:[h.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),h.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}),"Unlock"]}):h.jsxs(h.Fragment,{children:[h.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),h.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),"Lock Position"]})})]})]})},Dc=({x:t,y:e,items:n,onClose:o,theme:s})=>{const r=I.useRef(null),[i,l]=I.useState({x:t,y:e}),[d,c]=I.useState(!1),a=I.useRef(o);a.current=o,I.useEffect(()=>{const u=r.current;if(!u)return;const f=u.getBoundingClientRect(),y=u.parentElement;if(!y)return;const p=y.getBoundingClientRect();let m=t,W=e;t+f.width>p.width&&(m=Math.max(0,t-f.width)),e+f.height>p.height&&(W=Math.max(0,e-f.height)),l({x:m,y:W}),requestAnimationFrame(()=>c(!0))},[t,e]);const g=I.useCallback(()=>{a.current()},[]);return I.useEffect(()=>{const u=m=>{r.current&&!r.current.contains(m.target)&&g()},f=m=>{m.key==="Escape"&&g()},y=()=>g(),p=requestAnimationFrame(()=>{document.addEventListener("pointerdown",u,!0),document.addEventListener("keydown",f,!0),window.addEventListener("scroll",y,!0)});return()=>{cancelAnimationFrame(p),document.removeEventListener("pointerdown",u,!0),document.removeEventListener("keydown",f,!0),window.removeEventListener("scroll",y,!0)}},[g]),h.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:d?1:0,transform:d?"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)=>h.jsxs(I.Fragment,{children:[u.divider&&h.jsx("div",{style:{height:1,background:s.toolbarBorder,margin:"4px 0"}}),h.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:y=>{u.disabled||(y.currentTarget.style.background=s.activeToolColor+"18")},onMouseLeave:y=>{y.currentTarget.style.background="transparent"},children:[h.jsx("span",{children:u.label}),u.shortcut&&h.jsx("span",{style:{color:s.mutedTextColor,fontSize:11,marginLeft:24,opacity:.8},children:u.shortcut})]})]},f))})},Lc=I.memo(Dc);let vo=[];function rn(t){vo=structuredClone(t)}function Eo(){return structuredClone(vo)}function Vc(){return vo.length>0}function tr(t){return t.toDataURL({pixelRatio:2})}function Yc(t,e="canvas.png"){const n=tr(t),o=document.createElement("a");o.download=e,o.href=n,document.body.appendChild(o),o.click(),document.body.removeChild(o)}function er(t){return JSON.stringify(t,null,2)}function Fc(t,e="canvas.json"){const n=er(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 _n=20;function kt(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ln(t,e){const n=Zt(t,e);return n.length>0?n.join(","):"none"}function Wo(t){const{strokeColor:e,fillColor:n,strokeWidth:o,opacity:s,strokeStyle:r}=t.style,i=ln(r,o),l=[`fill="${kt(n==="transparent"?"none":n)}"`,`stroke="${kt(e)}"`,`stroke-width="${o}"`,`opacity="${s}"`];return i!=="none"&&l.push(`stroke-dasharray="${i}"`),l.join(" ")}function Mn(t,e,n,o){return e.rotation?`<g transform="rotate(${e.rotation} ${n} ${o})">${t}</g>`:t}function Pc(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} ${Wo(t)} />`;return Mn(l,t,e+o/2,n+s/2)}function Hc(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}" ${Wo(t)} />`;return Mn(o,t,e,n)}function Oc(t){const e=tn(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(" ")}" ${Wo(t)} />`;return Mn(o,t,t.x+t.width/2,t.y+t.height/2)}function Nc(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="${kt(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round"${ln(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${ln(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function Uc(t){const e=t.points,n={x:e[0],y:e[1]},o={x:e[e.length-2],y:e[e.length-1]},s=Ut(n,o,t.curvature??Nt),r=t.x+n.x,i=t.y+n.y,l=t.x+s.x,d=t.y+s.y,c=t.x+o.x,a=t.y+o.y;return`<path d="M ${r} ${i} Q ${l} ${d} ${c} ${a}" fill="none" stroke="${kt(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round"${ln(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${ln(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function Kc(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 zc(t){return{x:-t.y,y:t.x}}function Gn(t,e,n,o,s,r){const i=Kc(e,n),l=zc(i),d=o*.45;switch(t){case"arrow":{const c={x:e.x-i.x*o+l.x*d,y:e.y-i.y*o+l.y*d},a={x:e.x-i.x*o-l.x*d,y:e.y-i.y*o-l.y*d};return`<polyline points="${c.x},${c.y} ${e.x},${e.y} ${a.x},${a.y}" fill="none" stroke="${kt(s)}" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round" />`}case"triangle":{const c={x:e.x-i.x*o+l.x*d,y:e.y-i.y*o+l.y*d},a={x:e.x-i.x*o-l.x*d,y:e.y-i.y*o-l.y*d};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${a.x},${a.y}" fill="${kt(s)}" stroke="${kt(s)}" stroke-width="${r}" />`}case"triangle_outline":{const c={x:e.x-i.x*o+l.x*d,y:e.y-i.y*o+l.y*d},a={x:e.x-i.x*o-l.x*d,y:e.y-i.y*o-l.y*d};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${a.x},${a.y}" fill="#ffffff" stroke="${kt(s)}" stroke-width="${r}" />`}case"circle":{const c=o*.35,a=e.x-i.x*c,g=e.y-i.y*c;return`<circle cx="${a}" cy="${g}" r="${c}" fill="${kt(s)}" stroke="${kt(s)}" stroke-width="${r}" />`}case"circle_outline":{const c=o*.35,a=e.x-i.x*c,g=e.y-i.y*c;return`<circle cx="${a}" cy="${g}" r="${c}" fill="#ffffff" stroke="${kt(s)}" stroke-width="${r}" />`}case"bar":{const c=d*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="${kt(s)}" stroke-width="${r}" />`}case"diamond":case"diamond_outline":{const c=d*.7,a=o*.55,g={x:e.x-i.x*a,y:e.y-i.y*a},u=t==="diamond"?kt(s):"#ffffff";return`<polygon points="${e.x},${e.y} ${g.x+l.x*c},${g.y+l.y*c} ${g.x-i.x*a},${g.y-i.y*a} ${g.x-l.x*c},${g.y-l.y*c}" fill="${u}" stroke="${kt(s)}" stroke-width="${r}" />`}case"crowfoot_one":{const c=d*1,a=o*.25,g={x:e.x-i.x*a,y:e.y-i.y*a};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="${kt(s)}" stroke-width="${r}" />`,`<line x1="${g.x+l.x*c}" y1="${g.y+l.y*c}" x2="${g.x-l.x*c}" y2="${g.y-l.y*c}" stroke="${kt(s)}" stroke-width="${r}" />`].join(`
2
- `)}case"crowfoot_many":{const c=d*1,a=o*.6,g={x:e.x-i.x*a,y:e.y-i.y*a};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="${kt(s)}" stroke-width="${r}" />`,`<polyline points="${e.x+l.x*c},${e.y+l.y*c} ${g.x},${g.y} ${e.x-l.x*c},${e.y-l.y*c}" fill="none" stroke="${kt(s)}" stroke-width="${r}" />`].join(`
3
- `)}case"crowfoot_one_or_many":{const c=d*1,a=o*.6,g=o*.25,u={x:e.x-i.x*g,y:e.y-i.y*g},f={x:e.x-i.x*a,y:e.y-i.y*a};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="${kt(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="${kt(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="${kt(s)}" stroke-width="${r}" />`].join(`
4
- `)}default:return""}}function Jc(t){const e=[],n=t.lineType==="curved";if(e.push(n?Uc(t):Nc(t)),t.type==="arrow"){const o=t,s=o.startArrowhead??(o.startArrow?"arrow":null),r=o.endArrowhead??(o.endArrow?"arrow":null),i=mo(t.style.strokeWidth),l=t.points;if(n){const d={x:l[0],y:l[1]},c={x:l[l.length-2],y:l[l.length-1]},a=Ut(d,c,o.curvature??Nt),g={x:t.x+d.x,y:t.y+d.y},u={x:t.x+c.x,y:t.y+c.y},f={x:t.x+a.x*.1+d.x*.9,y:t.y+a.y*.1+d.y*.9},y={x:t.x+a.x*.1+c.x*.9,y:t.y+a.y*.1+c.y*.9};s&&e.push(Gn(s,g,f,i,t.style.strokeColor,t.style.strokeWidth)),r&&e.push(Gn(r,u,y,i,t.style.strokeColor,t.style.strokeWidth))}else{if(s&&l.length>=4){const d={x:t.x+l[0],y:t.y+l[1]},c={x:t.x+l[2],y:t.y+l[3]};e.push(Gn(s,d,c,i,t.style.strokeColor,t.style.strokeWidth))}if(r&&l.length>=4){const d={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(Gn(r,d,c,i,t.style.strokeColor,t.style.strokeWidth))}}}return e.join(`
5
- `)}function $c(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="${kt(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round" />`}function Rc(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 d="start",c=0;r==="center"?(d="middle",c=t.width/2):r==="right"&&(d="end",c=t.width);const a=i.map((u,f)=>`<tspan x="${n+c}" dy="${f===0?0:l}">${kt(u)}</tspan>`).join(""),g=[`font-family="${kt(e.fontFamily)}"`,`font-size="${e.fontSize}"`,`fill="${kt(e.strokeColor)}"`,`opacity="${e.opacity}"`,`text-anchor="${d}"`];return`<text x="${n+c}" y="${o+e.fontSize}" ${g.join(" ")}>${a}</text>`}function jc(t){const{x:e,y:n,width:o,height:s,src:r,cornerRadius:i,style:l}=t,d=[],c=i>0?`clip-${t.id}`:"";c&&d.push(`<defs><clipPath id="${c}"><rect x="${e}" y="${n}" width="${o}" height="${s}" rx="${i}" ry="${i}" /></clipPath></defs>`);const a=`<image href="${kt(r)}" x="${e}" y="${n}" width="${o}" height="${s}" opacity="${l.opacity}" preserveAspectRatio="none"${c?` clip-path="url(#${c})"`:""} />`;let g="";if(l.strokeWidth>0&&l.strokeColor!=="transparent"){const f=i?` rx="${i}" ry="${i}"`:"";g=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${f} fill="none" stroke="${kt(l.strokeColor)}" stroke-width="${l.strokeWidth}" opacity="${l.opacity}" />`}const u=d.join("")+a+g;return Mn(u,t,e+o/2,n+s/2)}function Qc(t){switch(t.type){case"rectangle":return Pc(t);case"ellipse":return Hc(t);case"diamond":return Oc(t);case"line":case"arrow":return Jc(t);case"freedraw":return $c(t);case"text":return Rc(t);case"image":return jc(t);default:return""}}function De(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 a of t)if(a.isVisible)if(a.type==="line"||a.type==="arrow"||a.type==="freedraw"){const g=a.points;for(let u=0;u<g.length;u+=2){const f=a.x+g[u],y=a.y+g[u+1];e=Math.min(e,f),n=Math.min(n,y),o=Math.max(o,f),s=Math.max(s,y)}}else e=Math.min(e,a.x),n=Math.min(n,a.y),o=Math.max(o,a.x+a.width),s=Math.max(s,a.y+a.height);const r=o-e+_n*2,i=s-n+_n*2,l=-e+_n,d=-n+_n,c=t.filter(a=>a.isVisible).map(a=>Qc(a)).filter(Boolean).join(`
7
- `);return[`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${i}" viewBox="0 0 ${r} ${i}">`,` <g transform="translate(${l} ${d})">`,` ${c}`," </g>","</svg>"].join(`
8
- `)}function qc(t,e="canvas.svg"){const n=De(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 ta=5;function ea(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],d=t.y+e[i+1];n=Math.min(n,l),o=Math.max(o,l),s=Math.min(s,d),r=Math.max(r,d)}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 na(t,e,n,o=ta){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 d of e){if(n.has(d.id)||!d.isVisible||d.type==="text"&&d.containerId)continue;const c=ea(d),a=[[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,y]of a)Math.abs(u-y)<o&&r.push({value:y,edge:f,other:c});const g=[[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,y]of g)Math.abs(u-y)<o&&i.push({value:y,edge:f,other:c})}const l={guides:[]};if(r.length>0){r.sort((y,p)=>Math.abs(y.value-s[y.edge])-Math.abs(p.value-s[p.edge]));const d=r[0],c=d.value-s[d.edge];l.x=t.x+c;const a=d.value,g=r.filter(y=>Math.abs(y.value-a)<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 y of g)u=Math.min(u,y.other.top),f=Math.max(f,y.other.bottom);l.guides.push({orientation:"v",position:a,start:u-10,end:f+10})}if(i.length>0){i.sort((y,p)=>Math.abs(y.value-s[y.edge])-Math.abs(p.value-s[p.edge]));const d=i[0],c=d.value-s[d.edge];l.y=t.y+c;const a=d.value,g=i.filter(y=>Math.abs(y.value-a)<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 y of g)u=Math.min(u,y.other.left),f=Math.max(f,y.other.right);l.guides.push({orientation:"h",position:a,start:u-10,end:f+10})}return l}function oa(t=!0,e){const n=T(k=>k.setActiveTool),o=T(k=>k.undo),s=T(k=>k.redo),r=T(k=>k.selectedIds),i=T(k=>k.elements),l=T(k=>k.deleteElements),d=T(k=>k.duplicateElements),c=T(k=>k.bringToFront),a=T(k=>k.sendToBack),g=T(k=>k.bringForward),u=T(k=>k.sendBackward),f=T(k=>k.toggleGrid),y=T(k=>k.showGrid),p=T(k=>k.zoomIn),m=T(k=>k.zoomOut),W=T(k=>k.resetZoom),v=T(k=>k.zoomToFit),X=T(k=>k.zoomToSelection),R=T(k=>k.clearSelection),Z=T(k=>k.updateElement),K=T(k=>k.addElement),nt=T(k=>k.setSelectedIds),V=T(k=>k.pushHistory),O=qe(),D=I.useCallback(()=>{r.length!==0&&rn(ks(r,i))},[r,i]),J=I.useCallback(()=>{const k=Eo();if(k.length===0)return;const b=20,{clones:w,selectedCloneIds:S}=bn(k,k,b);w.forEach(M=>K(M)),nt(S.length>0?S:w.map(M=>M.id)),V(),rn(k.map(M=>({...M,x:M.x+b,y:M.y+b})))},[K,nt,V]),_=I.useCallback((k,b)=>{r.length!==0&&(r.forEach(w=>{const S=i.find(M=>M.id===w);S&&!S.isLocked&&Z(w,{x:S.x+k,y:S.y+b})}),V())},[r,i,Z,V]);I.useEffect(()=>{if(!t)return;const k=b=>{const w=b.target.tagName;if(w==="INPUT"||w==="TEXTAREA"||w==="SELECT")return;const S=b.metaKey||b.ctrlKey;if(!S&&!b.shiftKey){const j={v:"select",h:"hand",r:"rectangle",o:"ellipse",d:"diamond",l:"line",a:"arrow",p:"freedraw",t:"text",i:"image",e:"eraser"}[b.key.toLowerCase()];if(j){b.preventDefault(),n(j);return}}if(S&&b.key==="z"&&!b.shiftKey){b.preventDefault(),o();return}if(S&&b.key==="z"&&b.shiftKey){b.preventDefault(),s();return}if(S&&b.key==="y"){b.preventDefault(),s();return}if((b.key==="Delete"||b.key==="Backspace")&&!S){if(O.isEditing&&O.selectedPointIndices.length>0){b.preventDefault();const{elements:M,updateElement:j,pushHistory:ht}=T.getState(),$=M.find(F=>F.id===O.elementId);if($){const F=$.points.length/2,gt=new Set(O.selectedPointIndices);if(F-gt.size>=2){const E=[];for(let C=0;C<F;C++)gt.has(C)||E.push($.points[C*2],$.points[C*2+1]);const H=E[0],z=E[1],U=[];for(let C=0;C<E.length;C+=2)U.push(E[C]-H,E[C+1]-z);let ot=0,it=0,yt=0,pt=0;for(let C=0;C<U.length;C+=2)ot=Math.min(ot,U[C]),it=Math.max(it,U[C]),yt=Math.min(yt,U[C+1]),pt=Math.max(pt,U[C+1]);const st={x:$.x+H,y:$.y+z,points:U,width:it-ot,height:pt-yt};gt.has(0)&&(st.startBinding=null),gt.has(F-1)&&(st.endBinding=null),j($.id,st),ht(),O.setSelectedPoints([])}}return}if(r.length>0){b.preventDefault();const M=r.filter(j=>{const ht=i.find($=>$.id===j);return ht&&!ht.isLocked});M.length>0&&l(M)}return}if(S&&b.key==="d"){b.preventDefault(),r.length>0&&d(r);return}if(b.key==="]"&&S&&b.shiftKey){b.preventDefault(),c(r);return}if(b.key==="["&&S&&b.shiftKey){b.preventDefault(),a(r);return}if(b.key==="]"&&S&&!b.shiftKey){b.preventDefault(),g(r);return}if(b.key==="["&&S&&!b.shiftKey){b.preventDefault(),u(r);return}if(b.key==="g"&&!S){b.preventDefault(),f();return}if(S&&(b.key==="="||b.key==="+")){b.preventDefault(),p();return}if(S&&b.key==="-"){b.preventDefault(),m();return}if(S&&b.key==="0"){b.preventDefault(),W();return}if(S&&b.shiftKey&&b.key==="1"){if(b.preventDefault(),e!=null&&e.current){const M=e.current.getBoundingClientRect();v(M.width,M.height,void 0,{animate:!0})}return}if(S&&b.shiftKey&&b.key==="2"){if(b.preventDefault(),e!=null&&e.current){const M=e.current.getBoundingClientRect();X(M.width,M.height,{animate:!0})}return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(b.key)&&!S&&r.length>0&&!O.isEditing){b.preventDefault();const M=y?Te:1,j=b.shiftKey?M*10:M,ht=b.key==="ArrowLeft"?-j:b.key==="ArrowRight"?j:0,$=b.key==="ArrowUp"?-j:b.key==="ArrowDown"?j:0;_(ht,$);return}if(S&&b.key==="c"){r.length>0&&(b.preventDefault(),D());return}if(!(S&&b.key==="v")){if(S&&b.key==="x"){r.length>0&&(b.preventDefault(),D(),l(r));return}if(S&&b.key==="g"&&!b.shiftKey){if(b.preventDefault(),r.length>=2){const{groupElements:M}=T.getState();M(r)}return}if(S&&b.key==="g"&&b.shiftKey){if(b.preventDefault(),r.length>0){const{ungroupElements:M}=T.getState();M(r)}return}if(S&&b.shiftKey&&b.key==="l"){if(b.preventDefault(),r.length>0){const{toggleLockElements:M}=T.getState();M(r)}return}if(b.key==="Escape"){if(b.preventDefault(),O.isEditing){O.exitEditMode();return}R(),n("select");return}if(S&&b.key==="a"){b.preventDefault();const{elements:M,setSelectedIds:j}=T.getState();j(M.map(ht=>ht.id));return}}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,n,o,s,r,i,l,d,c,a,g,u,f,y,p,m,W,v,X,e,R,O,_,D,J])}function To(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],d=e[i+1];l<n&&(n=l),l>o&&(o=l),d<s&&(s=d),d>r&&(r=d)}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 Bo{constructor(e=9){et(this,"tree");et(this,"_elementMap",new Map);et(this,"_fattenedMap",new Map);et(this,"_margin",50);this.tree=new Ai(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=To(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=To(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,d)=>l.id===d.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,d=-r/l-s,c=-i/l-s,a=(-r+n)/l+s,g=(-i+o)/l+s,u=this.tree.search({minX:d,minY:c,maxX:a,maxY:g}),f=new Array(u.length);for(let y=0;y<u.length;y++)f[y]=u[y].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 Zo=null;function sa(){return Zo||(Zo=new Bo),Zo}const nr=200;function ra(t,e,n,o,s,r){const i=I.useRef(new Bo),l=I.useMemo(()=>Ts(s),[s]),d=I.useRef([]),c=I.useRef([]),a=I.useRef(0);if(t!==c.current){const g=c.current;if(c.current=t,t.length>nr)if(t.length!==a.current)i.current.rebuild(t);else{const f=i.current;for(let y=0;y<t.length;y++)t[y]!==g[y]&&f.update(t[y])}a.current=t.length}return I.useMemo(()=>{if(t.length<=nr)return Es(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 y=[];for(const m of t)f.has(m.id)&&y.push(m);const p=d.current;if(y.length===p.length){let m=!0;for(let W=0;W<y.length;W++)if(y[W]!==p[W]){m=!1;break}if(m)return p}return d.current=y,y},[t,e.x,e.y,e.scale,n,o,l,s,r])}const ia=[.0625,.125,.25,.5,1,2,4,8];function or(t){const e=ia;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 sr(t){return I.useMemo(()=>or(t),[t])}const la=500,ca=500;function rr(t,e={}){const{batchSize:n=ca,threshold:o=la,enabled:s=!0}=e,r=I.useRef(0),[i,l]=I.useState(0),d=I.useRef([]),c=I.useRef(!1),a=I.useRef(0);t!==d.current&&(d.current=t);const u=s&&t.length>o;I.useEffect(()=>{if(!u){l(t.length),c.current=!0,a.current=t.length;return}const m=a.current;if(c.current&&Math.abs(t.length-m)<n){l(t.length),a.current=t.length;return}const W=++r.current;c.current=!1,a.current=t.length,l(Math.min(n,t.length));let v=n;function X(){r.current===W&&(v=Math.min(v+n,t.length),l(v),v<t.length?requestAnimationFrame(X):c.current=!0)}return n<t.length?requestAnimationFrame(X):c.current=!0,()=>{r.current++}},[t,u,n]);const f=I.useMemo(()=>!u||i>=t.length?t:t.slice(0,i),[t,i,u]),y=u&&i<t.length,p=t.length>0?Math.min(i/t.length,1):1;return{visibleElements:f,isLoading:y,progress:p}}function ir(t,e){const n=(e==null?void 0:e.timeout)??1e3;"requestIdleCallback"in window?window.requestIdleCallback(o=>{o.timeRemaining()>5?t():ir(t,e)},{timeout:n}):setTimeout(t,100)}function aa(){return new Promise(t=>setTimeout(t,0))}const da=200,ua=1e4;class lr{constructor(e){et(this,"_worker",null);et(this,"_pending",new Map);et(this,"_workerSupported",!0);et(this,"_workerConfig");et(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=Sn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGV4cG9ydFdvcmtlci50cyDigJQgV2ViIFdvcmtlciBmb3Igb2ZmLW1haW4tdGhyZWFkIFNWRyBleHBvcnQuCiAqCiAqIEdlbmVyYXRlcyBTVkcgc3RyaW5ncyBmcm9tIHNlcmlhbGl6ZWQgZWxlbWVudCBkYXRhIGluIGEgYmFja2dyb3VuZAogKiB0aHJlYWQsIGtlZXBpbmcgdGhlIG1haW4gdGhyZWFkIHJlc3BvbnNpdmUgZHVyaW5nIGV4cG9ydCBvZiBsYXJnZQogKiBjYW52YXNlcyAoMTBLKyBlbGVtZW50cykuCiAqCiAqIENvbW11bmljYXRpb24gcHJvdG9jb2w6CiAqICAgTWFpbiDihpIgV29ya2VyOgogKiAgICAgeyB0eXBlOiAnZXhwb3J0U1ZHJywgcmVxdWVzdElkOiBzdHJpbmcsIGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gfQogKiAgIFdvcmtlciDihpIgTWFpbjoKICogICAgIHsgdHlwZTogJ3N2Z1Jlc3VsdCcsIHJlcXVlc3RJZDogc3RyaW5nLCBzdmc6IHN0cmluZyB9CiAqICAgICB7IHR5cGU6ICdlcnJvcicsIHJlcXVlc3RJZDogc3RyaW5nLCBtZXNzYWdlOiBzdHJpbmcgfQogKgogKiBVc2VzIFZpdGUncyBuYXRpdmUgV29ya2VyIG1vZHVsZSBzdXBwb3J0IOKAlCBpbXBvcnRlZCB3aXRoOgogKiAgIG5ldyBXb3JrZXIobmV3IFVSTCgnLi9leHBvcnRXb3JrZXIudHMnLCBpbXBvcnQubWV0YS51cmwpLCB7IHR5cGU6ICdtb2R1bGUnIH0pCiAqLwoKaW1wb3J0IHsgZXhwb3J0VG9TVkcgfSBmcm9tICdAL3V0aWxzL2V4cG9ydCc7CmltcG9ydCB0eXBlIHsgQ2FudmFzRWxlbWVudCB9IGZyb20gJ0AvdHlwZXMnOwoKLy8g4pSA4pSA4pSAIE1lc3NhZ2UgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgRXhwb3J0U1ZHTWVzc2FnZSB7CiAgICB0eXBlOiAnZXhwb3J0U1ZHJzsKICAgIHJlcXVlc3RJZDogc3RyaW5nOwogICAgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXTsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBFeHBvcnRTVkdNZXNzYWdlOwoKaW50ZXJmYWNlIFNWR1Jlc3VsdE1lc3NhZ2UgewogICAgdHlwZTogJ3N2Z1Jlc3VsdCc7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIHN2Zzogc3RyaW5nOwp9CgppbnRlcmZhY2UgRXJyb3JNZXNzYWdlIHsKICAgIHR5cGU6ICdlcnJvcic7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIG1lc3NhZ2U6IHN0cmluZzsKfQoKdHlwZSBPdXRnb2luZ01lc3NhZ2UgPSBTVkdSZXN1bHRNZXNzYWdlIHwgRXJyb3JNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBtYWluIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKc2VsZi5vbm1lc3NhZ2UgPSAoZXY6IE1lc3NhZ2VFdmVudDxJbmNvbWluZ01lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBldi5kYXRhOwoKICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICBjYXNlICdleHBvcnRTVkcnOiB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBjb25zdCBzdmcgPSBleHBvcnRUb1NWRyhtc2cuZWxlbWVudHMpOwogICAgICAgICAgICAgICAgY29uc3QgcmVzcG9uc2U6IE91dGdvaW5nTWVzc2FnZSA9IHsKICAgICAgICAgICAgICAgICAgICB0eXBlOiAnc3ZnUmVzdWx0JywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgc3ZnLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9IGNhdGNoIChlcnIpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHJlc3BvbnNlOiBPdXRnb2luZ01lc3NhZ2UgPSB7CiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2Vycm9yJywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgbWVzc2FnZTogZXJyIGluc3RhbmNlb2YgRXJyb3IgPyBlcnIubWVzc2FnZSA6IFN0cmluZyhlcnIpLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBicmVhazsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:$t&&$t.tagName.toUpperCase()==="SCRIPT"&&$t.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<=da)return De(e);const n=this._getWorker();if(!n)return De(e);const o=Lt();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(De(e))}catch(a){r(a)}}},ua),l=s,d=r,c=this._pending.get(o);c&&(c.resolve=a=>{clearTimeout(i),l(a)},c.reject=a=>{clearTimeout(i),d(a)}),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 te=null,_o;function ga(t){return te&&t&&JSON.stringify(t)!==JSON.stringify(_o)&&(te.dispose(),te=null),te||(_o=t,te=new lr(t)),te}function cr(){te&&(te.dispose(),te=null,_o=void 0)}const ar={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 Kt=null,Wt=null,Mo=new Set;function dr(t){return Wt&&Xn(),Kt=new Ot.Doc,Wt=new os.WebsocketProvider(t.serverUrl,t.roomName,Kt,{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 Mo)o(n)}),{doc:Kt,provider:Wt}}function Xn(){Wt&&(Wt.awareness.setLocalState(null),Wt.disconnect(),Wt.destroy(),Wt=null),Kt&&(Kt.destroy(),Kt=null)}function ur(){return Kt}function Go(){return Wt}function gr(){return Kt==null?void 0:Kt.getMap("elements")}function ha(){return Wt!==null&&Wt.wsconnected}function hr(t){return Mo.add(t),()=>{Mo.delete(t)}}function Dn(t){if(!Wt)return;const e=Wt.awareness.getLocalState();Wt.awareness.setLocalState({...e,...t})}function fr(){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 Xo=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],Ln=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"];function cn(t,e){const n=t;for(const o of Xo){const s=n[o];s!==void 0&&e.set(o,s)}if(t.style)for(const o of Ln)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 me(t){const e=t.get("type"),n=t.get("id");if(!e||!n)return null;const o={};for(const r of Ln){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:we(t.get("boundElements"))??null,groupIds:we(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=we(t.get("points"))??[0,0,100,0],s.lineType=t.get("lineType")??"sharp",s.curvature=t.get("curvature")??void 0,s.startBinding=we(t.get("startBinding")),s.endBinding=we(t.get("endBinding")),e==="arrow"&&(s.startArrowhead=t.get("startArrowhead")??null,s.endArrowhead=t.get("endArrowhead")??"arrow");break;case"freedraw":s.points=we(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=we(t.get("crop"))??null,s.cornerRadius=t.get("cornerRadius")??0,s.alt=t.get("alt")??"";break}return s}function we(t){if(t==null)return null;try{return JSON.parse(t)}catch{return null}}let xe=!1,ke=!1,Vn=null,Yn=null,Le=null,ee=[];function pr(t=50){const e=ur(),n=gr();if(!e||!n){console.warn("[SyncBridge] Cannot start sync — no Yjs doc");return}if(Fn(),n.size>0){xe=!0;const l=ya(n);T.getState().setElements(l),ee=l,xe=!1}else{const l=T.getState().elements;l.length>0&&(ke=!0,e.transact(()=>{for(const d of l){const c=new Ot.Map;cn(d,c),n.set(d.id,c)}},"local-init"),ke=!1),ee=l}const o=(l,d)=>{if(d.origin==="local-sync"||d.origin==="local-init"||ke)return;xe=!0;const c=T.getState();let a=[...ee],g=!1;for(const[u,f]of l.keys)if(f.action==="add"||f.action==="update"){const y=n.get(u);if(y){const p=me(y);if(p){const m=a.findIndex(W=>W.id===u);m>=0?a[m]=p:a.push(p),g=!0}}}else f.action==="delete"&&(a=a.filter(y=>y.id!==u),g=!0);g&&(a.sort((u,f)=>u.sortOrder&&f.sortOrder?u.sortOrder<f.sortOrder?-1:u.sortOrder>f.sortOrder?1:0:0),c.setElements(a),ee=a),xe=!1};let s=null;const r=new Set,i=l=>{if(!ke){for(const d of l){let c=d.target;for(;c&&!(c instanceof Ot.Map&&c.parent===n);)c=c.parent;if(c instanceof Ot.Map){const a=c.get("id");a&&r.add(a)}}s&&clearTimeout(s),s=setTimeout(()=>{if(r.size===0||ke)return;xe=!0;let d=[...ee],c=!1;for(const a of r){const g=n.get(a);if(!g)continue;const u=me(g);if(!u)continue;const f=d.findIndex(y=>y.id===a);f>=0&&(d[f]=u,c=!0)}r.clear(),c&&(T.getState().setElements(d),ee=d),xe=!1},16)}};n.observe(o),n.observeDeep(i),Yn=()=>{n.unobserve(o),n.unobserveDeep(i),s&&clearTimeout(s),r.clear()},Vn=T.subscribe(l=>{xe||l.elements!==ee&&(Le&&clearTimeout(Le),Le=setTimeout(()=>{fa(l.elements,n,e)},t))})}function Fn(){Vn&&(Vn(),Vn=null),Yn&&(Yn(),Yn=null),Le&&(clearTimeout(Le),Le=null),ee=[]}function fa(t,e,n){ke=!0,ee=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?pa(s,r):(r=new Ot.Map,cn(s,r),e.set(s.id,r))}},"local-sync"),ke=!1}function pa(t,e){const n=t;for(const s of Xo){const r=n[s];r!==e.get(s)&&e.set(s,r)}if(t.style)for(const s of Ln){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 ya(t){const e=[];for(const[,n]of t.entries()){const o=me(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 yr(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){Xn(),Fn(),n("disconnected"),s([]);return}const{provider:g}=dr(t);pr(t.syncDebounceMs??50);const u=hr(n),f=()=>{const p=fr();s(Array.from(p.values()))};g.awareness.on("change",f);const y=T.subscribe((p,m)=>{p.selectedIds!==m.selectedIds&&Dn({selectedIds:p.selectedIds}),p.activeTool!==m.activeTool&&Dn({activeTool:p.activeTool})});return()=>{u(),y(),g.awareness.off("change",f),Fn(),Xn(),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 d=I.useCallback(g=>{const u=Date.now();u-l.current<i.current||(l.current=u,Dn({cursor:g}))},[]),c=I.useCallback(()=>{const g=Go();g&&g.disconnect()},[]),a=I.useCallback(()=>{const g=Go();g&&g.connect()},[]);return{isConnected:e==="connected",connectionStatus:e,peers:o,disconnect:c,reconnect:a,updateCursor:d}}const Ia=[0,0,0,18,4.5,14.5,9,20,12,18,7.5,12.5,14,12.5,0,0],Do=12,Ir="system-ui, -apple-system, sans-serif",Cr=6,br=4,Ar=14,mr=18,ne={ctx:null,cache:new Map};function Ca(t){const e=ne.cache.get(t);if(e!==void 0)return e;if(!ne.ctx)try{const o=document.createElement("canvas");ne.ctx=o.getContext("2d")}catch{}let n;return ne.ctx?(ne.ctx.font=`${Do}px ${Ir}`,n=ne.ctx.measureText(t).width):n=t.length*7,ne.cache.size>200&&ne.cache.clear(),ne.cache.set(t,n),n}function wr(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 ba(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 wr(r,i,e,n,o,s+l*e.scale)}const Aa=({peers:t,viewport:e,stageWidth:n,stageHeight:o,elements:s})=>{const r=I.useMemo(()=>{const d=new Map;for(const c of s)d.set(c.id,c);return d},[s]),i=1/e.scale,l=150;return h.jsx(h.Fragment,{children:t.map(d=>{if(!d.cursor&&d.selectedIds.length===0)return null;const{user:c}=d;return h.jsxs(dt.Group,{children:[d.selectedIds.map(a=>{const g=r.get(a);if(!g||!ba(g,e,n,o,l))return null;const u=3*i;return h.jsx(dt.Rect,{x:g.x+g.width/2,y:g.y+g.height/2,offsetX:g.width/2+u,offsetY:g.height/2+u,width:g.width+u*2,height:g.height+u*2,rotation:g.rotation??0,stroke:c.color,strokeWidth:2*i,dash:[6*i,4*i],cornerRadius:3*i,listening:!1,perfectDrawEnabled:!1},a)}),d.cursor&&wr(d.cursor.x,d.cursor.y,e,n,o,l)&&h.jsxs(dt.Group,{x:d.cursor.x,y:d.cursor.y,scaleX:i,scaleY:i,listening:!1,children:[h.jsx(dt.Line,{points:Ia,fill:c.color,stroke:"#ffffff",strokeWidth:1,closed:!0,perfectDrawEnabled:!1}),h.jsx(dt.Rect,{x:Ar,y:mr,width:Ca(c.name)+Cr*2,height:Do+br*2,fill:c.color,cornerRadius:4,listening:!1,perfectDrawEnabled:!1}),h.jsx(dt.Text,{x:Ar+Cr,y:mr+br,text:c.name,fontSize:Do,fontFamily:Ir,fill:"#ffffff",listening:!1,perfectDrawEnabled:!1})]})]},c.id)})})},xr=I.memo(Aa);function kr(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 Sr=10,ma=({elements:t,listening:e,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditTextId:i,onTextEditStart:l,onTextEditEnd:d,allElements:c,gridSnap:a,onDragSnap:g,viewportScale:u,onGroupDragEnd:f})=>{const y=I.useRef(null);I.useEffect(()=>{const v=y.current;if(!v||t.length===0)return;const X=window.devicePixelRatio||1,R=Math.max(.5,Math.min(u*X,X)),Z=requestAnimationFrame(()=>{if(!y.current)return;const K=v.getClientRect({skipTransform:!0}),nt=K.width*R,V=K.height*R,O=8192;if(nt>O||V>O||K.width===0||K.height===0){v.clearCache();return}v.cache({pixelRatio:R}),v.batchDraw()});return()=>{cancelAnimationFrame(Z),v.clearCache()}},[t,u,i]);const{ungrouped:p,groups:m}=I.useMemo(()=>{var R;const v=[],X=new Map;for(const Z of t)if((R=Z.groupIds)!=null&&R.length){const K=Z.groupIds[Z.groupIds.length-1];X.has(K)||X.set(K,[]),X.get(K).push(Z)}else v.push(Z);return{ungrouped:v,groups:X}},[t]),W=I.useCallback(v=>{var X;(X=y.current)==null||X.clearCache()},[]);return h.jsxs(dt.Layer,{ref:y,listening:e,children:[p.map(v=>h.jsx(wo,{element:v,isSelected:!1,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===v.id,onTextEditStart:l,onTextEditEnd:d,allElements:c,gridSnap:a,onDragSnap:g,viewportScale:u},v.id)),Array.from(m.entries()).map(([v,X])=>{const R=X.some(Z=>Z.isLocked);return h.jsx(dt.Group,{draggable:!R,onDragStart:W,onDragEnd:Z=>{const K=Z.target.x(),nt=Z.target.y();Z.target.x(0),Z.target.y(0),f==null||f(v,K,nt)},children:X.map(Z=>h.jsx(wo,{element:Z,isSelected:!1,isGrouped:!0,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===Z.id,onTextEditStart:l,onTextEditEnd:d,allElements:c,gridSnap:a,onDragSnap:g,viewportScale:u},Z.id))},v)})]})},wa=I.memo(ma,(t,e)=>!(t.elements!==e.elements||t.listening!==e.listening||t.autoEditTextId!==e.autoEditTextId||t.gridSnap!==e.gridSnap||t.viewportScale!==e.viewportScale)),xa=({element:t,scale:e})=>{const n=20/e,o=n/24;return h.jsxs(dt.Group,{x:t.x-n/2,y:t.y-n/2,listening:!1,children:[h.jsx(dt.Rect,{width:n,height:n,fill:"#ff9500",cornerRadius:n/4,opacity:.9}),h.jsx(dt.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})]})},vr=I.forwardRef((t,e)=>{const{initialElements:n,elements:o,onChange:s,onSelectionChange:r,onElementCreate:i,onElementDelete:l,onElementDoubleClick:d,width:c="100%",height:a="100%",tools:g,defaultStyle:u,showToolbar:f=!0,toolbarPosition:y="bottom",defaultTool:p,showStylePanel:m=!0,showStatusBar:W=!0,showGrid:v=!1,enableShortcuts:X=!0,theme:R,readOnly:Z=!1,className:K,contextMenuItems:nt,renderContextMenu:V,collaboration:O,workerConfig:D}=t,J={...ar,...R},_=I.useMemo(()=>({elbowWorkerConfig:D!=null&&D.disabled?{disabled:!0}:D!=null&&D.elbowWorkerUrl?{url:D.elbowWorkerUrl}:void 0,exportWorkerConfig:D!=null&&D.disabled?{disabled:!0}:D!=null&&D.exportWorkerUrl?{url:D.exportWorkerUrl}:void 0}),[D]),k=T(),{elements:b,selectedIds:w,activeTool:S,currentStyle:M,viewport:j,showGrid:ht,isDrawing:$,setIsDrawing:F,setDrawStart:gt,drawStart:rt,addElement:E,updateElement:H,setSelectedIds:z,clearSelection:U,setActiveTool:ot,setViewport:it,deleteElements:yt,pushHistory:pt,setElements:st,setCurrentStyle:C,undo:G,redo:Ct,toggleGrid:bt}=k,St=I.useMemo(()=>Ts(w),[w]),{peers:ct,updateCursor:Se}=yr(O??null),zt=I.useRef(null),Ft=I.useRef(null),dn=I.useRef(null),Jt=qe(),un=Jt.isEditing,[Pt,vt]=I.useState({width:800,height:600}),[Xt,Ht]=I.useState(null),[ja,Rr]=I.useState(null),Qa=I.useRef(null),[qa,jr]=I.useState(null),[Qr,Pe]=I.useState(null),[oe,He]=I.useState(null),[td,Ho]=I.useState([]),Oo=I.useRef(!1),Nn=I.useRef(!1),[ve,No]=I.useState(!1),ge=I.useRef(!1),{isDraggingPoint:Uo,elementId:qr}=Jt,ti=I.useRef([]),se=I.useMemo(()=>{let A=null;for(let L=0;L<b.length;L++){const q=b[L];if(q.type!=="line"&&q.type!=="arrow"){A&&(A[L]=q);continue}const tt=q;if(!tt.startBinding&&!tt.endBinding){A&&(A[L]=q);continue}if(Uo&&qr===q.id){A&&(A[L]=q);continue}const P=pe(tt,b);P?(A||(A=b.slice(0,L)),A[L]={...tt,...P}):A&&(A[L]=q)}const B=A??b,N=ti.current;if(B.length===N.length){let L=!0;for(let q=0;q<B.length;q++)if(B[q]!==N[q]){L=!1;break}if(L)return N}return ti.current=B,B},[b,Uo,qr]),ei=I.useMemo(()=>{const A=new Map;for(const B of se)A.set(B.id,B);return A},[se]),Un=ra(se,j,Pt.width,Pt.height,w),ni=sr(j.scale),Ko=I.useRef([]),zo=I.useRef([]),{staticElements:ed,interactiveElements:nd}=I.useMemo(()=>{var tt,P;let A=St;if(St.size>0){const Y=new Set(St);for(const Q of Un)if(Y.has(Q.id)&&((tt=Q.groupIds)!=null&&tt.length)){const at=Q.groupIds[Q.groupIds.length-1];for(const lt of Un)(P=lt.groupIds)!=null&&P.includes(at)&&Y.add(lt.id)}Y.size!==St.size&&(A=Y)}const B=[],N=[];for(const Y of Un)A.has(Y.id)?N.push(Y):B.push(Y);const L=kr(B,Ko.current)?Ko.current:B,q=kr(N,zo.current)?zo.current:N;return Ko.current=L,zo.current=q,{staticElements:L,interactiveElements:q}},[Un,St]),{visibleElements:od}=rr(ed,{batchSize:500,threshold:500,enabled:!0});oa(X&&!Z,Ft),I.useEffect(()=>{u&&C({...fn,...u})},[]),I.useEffect(()=>{n&&n.length>0&&(st(n),pt())},[]),I.useEffect(()=>{v!==ht&&bt()},[]),I.useEffect(()=>{p&&ot(p)},[]),I.useEffect(()=>{o&&st(o)},[o,st]);const oi=I.useRef(b);I.useEffect(()=>{s&&b!==oi.current&&s(b),oi.current=b},[b,s]),I.useEffect(()=>{r&&r(w)},[w,r]),I.useEffect(()=>{const A=qe.getState();if(!A.isEditing)return;if(S!=="select"){A.exitEditMode();return}if(w.length!==1||w[0]!==A.elementId){A.exitEditMode();return}const B=b.find(N=>N.id===w[0]);B&&(B.type==="line"||B.type==="arrow")&&(!A.isEditing||A.elementId!==B.id)&&A.enterEditMode(B.id)},[w,S,b]),I.useEffect(()=>{const A=N=>{N.key==="Shift"&&(Oo.current=!0)},B=N=>{N.key==="Shift"&&(Oo.current=!1)};return window.addEventListener("keydown",A),window.addEventListener("keyup",B),()=>{window.removeEventListener("keydown",A),window.removeEventListener("keyup",B)}},[]),I.useEffect(()=>{const A=L=>{const q=L.target.tagName;q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||L.code==="Space"&&!ge.current&&(L.preventDefault(),ge.current=!0,No(!0))},B=L=>{L.code==="Space"&&(ge.current=!1,No(!1))},N=()=>{ge.current&&(ge.current=!1,No(!1))};return window.addEventListener("keydown",A),window.addEventListener("keyup",B),window.addEventListener("blur",N),()=>{window.removeEventListener("keydown",A),window.removeEventListener("keyup",B),window.removeEventListener("blur",N)}},[]),I.useEffect(()=>{const A=Ft.current;if(!A||Z)return;const B=L=>{L.preventDefault(),L.stopPropagation(),L.dataTransfer&&(L.dataTransfer.dropEffect="copy")},N=async L=>{if(L.preventDefault(),L.stopPropagation(),!L.dataTransfer)return;const q=yo(L.dataTransfer);if(q.length===0)return;const tt=A.getBoundingClientRect();zt.current;const P=T.getState().viewport,Y=(L.clientX-tt.left-P.x)/P.scale,Q=(L.clientY-tt.top-P.y)/P.scale,at=T.getState().currentStyle;for(const lt of q)try{const ut=await wn(lt),ft=await en(ut),wt=xn(ut,ft.naturalWidth,ft.naturalHeight,Y,Q,{...at});E(wt),i==null||i(wt),z([wt.id]),pt()}catch{}ot("select")};return A.addEventListener("dragover",B),A.addEventListener("drop",N),()=>{A.removeEventListener("dragover",B),A.removeEventListener("drop",N)}},[Z,E,z,pt,ot,i]),I.useEffect(()=>{if(Z)return;const A=B=>{const N=B.target.tagName;if(N==="INPUT"||N==="TEXTAREA"||N==="SELECT")return;const L=Io(B);if(L.file||L.imgUrl)B.preventDefault(),B.stopPropagation(),(async()=>{try{const q=await Ls(L);if(!q)return;const tt=await en(q),P=T.getState().viewport,Y=Ft.current,Q=Y==null?void 0:Y.getBoundingClientRect(),at=Q?(Q.width/2-P.x)/P.scale:400,lt=Q?(Q.height/2-P.y)/P.scale:300,ut=T.getState().currentStyle,ft=xn(q,tt.naturalWidth,tt.naturalHeight,at,lt,{...ut});E(ft),i==null||i(ft),z([ft.id]),pt(),ot("select")}catch{}})();else{B.preventDefault(),B.stopPropagation();const q=Eo();if(q.length===0)return;const tt=20,{clones:P,selectedCloneIds:Y}=bn(q,q,tt);P.forEach(Q=>E(Q)),z(Y.length>0?Y:P.map(Q=>Q.id)),pt(),rn(q.map(Q=>({...Q,x:Q.x+tt,y:Q.y+tt})))}};return window.addEventListener("paste",A,!0),()=>window.removeEventListener("paste",A,!0)},[Z,E,z,pt,ot,i]),I.useEffect(()=>{const A=Ft.current;if(!A)return;const B=new ResizeObserver(N=>{for(const L of N){const{width:q,height:tt}=L.contentRect;vt({width:Math.floor(q),height:Math.floor(tt)})}});return B.observe(A),()=>B.disconnect()},[]);const sd=I.useCallback(()=>{const A=zt.current;if(!A)return null;const B=A.getPointerPosition();return B?{x:(B.x-j.x)/j.scale,y:(B.y-j.y)/j.scale}:null},[j]),rd=I.useCallback(A=>ht?{x:At(A.x,Te),y:At(A.y,Te)}:A,[ht]),Kn=I.useRef(null);Kn.current={elements:b,selectedIds:w,activeTool:S,currentStyle:M,isDrawing:$,drawStart:rt,showGrid:ht,addElement:E,updateElement:H,deleteElements:yt,setSelectedIds:z,clearSelection:U,setActiveTool:ot,setIsDrawing:F,setDrawStart:gt,pushHistory:pt,getPointerPos:sd,snapPos:rd,currentElementIdRef:dn,shiftKeyRef:Oo,startBindingRef:Qa,setSnapTarget:Rr,selectionBox:Xt,setSelectionBox:Ht,setAutoEditTextId:Pe,linearEdit:{isEditing:Jt.isEditing,elementId:Jt.elementId,exitEditMode:Jt.exitEditMode,enterEditMode:Jt.enterEditMode},onElementCreate:i,onElementDelete:l};const si=I.useCallback(A=>{if(Z||ge.current)return;if(A.evt.button===2){Nn.current=!0,oe&&He(null);return}Nn.current=!1;const N=Kn.current,L=N.getPointerPos();if(!L||(oe&&He(null),N.activeTool==="hand"||ve))return;const q=nn(N.activeTool);q==null||q.onMouseDown(A,L,N)},[Z,oe,ve]),ri=I.useCallback(A=>{if(ge.current||Z)return;const B=Kn.current,N=B.getPointerPos();if(!N)return;Se(N);const L=nn(B.activeTool);L==null||L.onMouseMove(A,N,B)},[Z,Se]),Jo=I.useRef(null),ii=I.useRef(ri);ii.current=ri;const li=I.useMemo(()=>{var B,N;(N=(B=Jo.current)==null?void 0:B.cancel)==null||N.call(B);const A=Ws(L=>{ii.current(L)});return Jo.current=A,A},[]);I.useEffect(()=>()=>{var A,B;(B=(A=Jo.current)==null?void 0:A.cancel)==null||B.call(A),Ks(),cr()},[]);const ci=I.useCallback(()=>{const A=Kn.current,B=nn(A.activeTool);B==null||B.onMouseUp(A)},[]),id=I.useCallback(A=>{A.evt.preventDefault();const B=zt.current;if(!B)return;const N=B.getPointerPosition();if(!N)return;const L=1.05,q=A.evt.deltaY>0?-1:1,tt=Math.min(We,Math.max(Ee,q>0?j.scale*L:j.scale/L));it(An({viewport:j,point:N,targetScale:tt}))},[j,it]),ld=I.useCallback(A=>{S!=="hand"&&!ge.current&&!ve||it({x:A.target.x(),y:A.target.y()})},[S,it,ve]),ai=I.useCallback(A=>{var Q;const{activeTool:B,elements:N,selectedIds:L,setSelectedIds:q}=T.getState();if(B!=="select"||Z)return;if(Nn.current){Nn.current=!1;return}const tt=N.find(at=>at.id===A),P=tt&&(tt.type==="line"||tt.type==="arrow"),Y=qe.getState();if(P?(!Y.isEditing||Y.elementId!==A)&&Y.enterEditMode(A):Y.isEditing&&Y.exitEditMode(),(Q=tt==null?void 0:tt.groupIds)!=null&&Q.length){const at=tt.groupIds[tt.groupIds.length-1],lt=N.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.includes(at)}).map(ut=>ut.id);q(lt)}else q([A])},[Z]),zn=I.useRef(null),$o=I.useRef(!1),Ro=I.useRef(!1),he=I.useRef(null),di=I.useCallback(()=>{$o.current=!1;const A=zn.current;if(!A||A.size===0)return;const B=Array.from(A,([N,L])=>({id:N,updates:L}));A.clear(),T.getState().batchUpdateElements(B)},[]),Jn=I.useRef(new Set),ui=I.useCallback((A,B)=>{if(Z)return;he.current===null&&(he.current=hn.pixelRatio,hn.pixelRatio=1);const{elements:N,selectedIds:L}=T.getState();if(L.length>Sr){Ro.current=!0;return}Ro.current=!1;const q=N.find(tt=>tt.id===A);if(q&&(q.type==="line"||q.type==="arrow")&&!Jn.current.has(A)){const tt=q;if(tt.startBinding||tt.endBinding){Jn.current.add(A);const P={},Y=tt.type;if(tt.startBinding){const Q=T.getState().elements;ye(A,Y,tt.startBinding,null,Q,T.getState().updateElement),P.startBinding=null}if(tt.endBinding){const Q=T.getState().elements;ye(A,Y,tt.endBinding,null,Q,T.getState().updateElement),P.endBinding=null}T.getState().updateElement(A,{...B,...P});return}}zn.current||(zn.current=new Map),zn.current.set(A,B),$o.current||($o.current=!0,queueMicrotask(di))},[Z,di]),gi=I.useCallback((A,B)=>{const{elements:N,selectedIds:L}=T.getState();if(L.length>1)return null;const q=new Set(L),tt=na(B,N,q);return Ho(tt.guides),tt.x!==void 0||tt.y!==void 0?{x:tt.x??B.x,y:tt.y??B.y}:null},[]),$n=I.useRef(null),jo=I.useRef(!1),hi=I.useCallback(()=>{jo.current=!1;const A=$n.current;if(!A||A.size===0)return;const B=Array.from(A);A.clear(),Ro.current=!1,T.getState().batchUpdateElements(B.map(([Y,Q])=>({id:Y,updates:Q}))),Ho([]);const L=T.getState().elements,q=new Map;for(const Y of L)q.set(Y.id,Y);const tt=[],P=new Set;for(const[Y]of B){Jn.current.delete(Y);const Q=Re(Y,L);for(const lt of Q){if(P.has(lt.id))continue;P.add(lt.id);const ut=q.get(lt.id);if(!ut)continue;const ft=pe(ut,L);ft&&tt.push({id:ut.id,updates:ft})}const at=q.get(Y);if(at!=null&&at.boundElements&&["rectangle","ellipse","diamond","image"].includes(at.type))for(const ut of at.boundElements){if(ut.type!=="text")continue;const ft=q.get(ut.id);if(!ft)continue;const wt=Math.max(20,at.width-8);let mt;ft.verticalAlign==="top"?mt=at.y+4:ft.verticalAlign==="bottom"?mt=at.y+at.height-ft.height-4:mt=at.y+(at.height-ft.height)/2,tt.push({id:ut.id,updates:{x:at.x+4,y:mt,width:wt}})}}tt.length>0&&T.getState().batchUpdateElements(tt),T.getState().pushHistory(),he.current!==null&&(hn.pixelRatio=he.current,he.current=null)},[]),fi=I.useCallback((A,B)=>{if(Z)return;const{selectedIds:N}=T.getState();if(N.length>Sr){$n.current||($n.current=new Map),$n.current.set(A,B),jo.current||(jo.current=!0,queueMicrotask(hi));return}H(A,B),Ho([]),Jn.current.delete(A);const L=T.getState().elements,q=new Map;for(const Y of L)q.set(Y.id,Y);const tt=Re(A,L);for(const Y of tt){const Q=q.get(Y.id);if(!Q)continue;const at=pe(Q,L);at&&H(Q.id,at)}const P=q.get(A);if(P!=null&&P.boundElements&&["rectangle","ellipse","diamond","image"].includes(P.type))for(const Q of P.boundElements){if(Q.type!=="text")continue;const at=q.get(Q.id);if(!at)continue;const lt=Math.max(20,P.width-8);let ut;at.verticalAlign==="top"?ut=P.y+4:at.verticalAlign==="bottom"?ut=P.y+P.height-at.height-4:ut=P.y+(P.height-at.height)/2,H(Q.id,{x:P.x+4,y:ut,width:lt})}if((P==null?void 0:P.type)==="text"){const Y=P;if(Y.containerId){const Q=q.get(Y.containerId);if(Q&&["rectangle","ellipse","diamond","image"].includes(Q.type)){const lt=Y.height+8;if(Q.height<lt){H(Q.id,{height:lt});const ut=T.getState().elements;for(const ft of Re(Q.id,ut)){const wt=ut.find(Et=>Et.id===ft.id);if(!wt)continue;const mt=pe(wt,ut);mt&&H(wt.id,mt)}}}}}pt(),he.current!==null&&(hn.pixelRatio=he.current,he.current=null)},[H,pt,Z,hi]),cd=I.useCallback((A,B,N)=>{if(Z||B===0&&N===0)return;const L=T.getState(),tt=L.elements.filter(ft=>{var wt;return(wt=ft.groupIds)==null?void 0:wt.includes(A)});if(tt.length===0)return;const P=tt.map(ft=>({id:ft.id,updates:{x:ft.x+B,y:ft.y+N}}));L.batchUpdateElements(P);const Y=T.getState().elements,Q=new Map;for(const ft of Y)Q.set(ft.id,ft);const at=new Set(tt.map(ft=>ft.id)),lt=[],ut=new Set;for(const ft of tt){const wt=Re(ft.id,Y);for(const Et of wt){if(ut.has(Et.id)||(ut.add(Et.id),at.has(Et.id)))continue;const Bt=Q.get(Et.id);if(!Bt)continue;const xt=pe(Bt,Y);xt&&lt.push({id:Bt.id,updates:xt})}const mt=Q.get(ft.id);if(mt!=null&&mt.boundElements&&["rectangle","ellipse","diamond","image"].includes(mt.type))for(const Bt of mt.boundElements){if(Bt.type!=="text"||at.has(Bt.id))continue;const xt=Q.get(Bt.id);if(!xt)continue;const Dt=Math.max(20,mt.width-8);let Mt;xt.verticalAlign==="top"?Mt=mt.y+4:xt.verticalAlign==="bottom"?Mt=mt.y+mt.height-xt.height-4:Mt=mt.y+(mt.height-xt.height)/2,lt.push({id:Bt.id,updates:{x:mt.x+4,y:Mt,width:Dt}})}}lt.length>0&&T.getState().batchUpdateElements(lt),L.pushHistory()},[Z]),pi=I.useCallback(A=>{var Q,at;if(Z)return;const{activeTool:B,elements:N,currentStyle:L,addElement:q,updateElement:tt,setSelectedIds:P}=T.getState();if(B!=="select")return;const Y=N.find(lt=>lt.id===A);if(Y&&(d==null?void 0:d(A,Y))!==!0){if(Y.type==="line"||Y.type==="arrow"){const lt=(Q=Y.boundElements)==null?void 0:Q.find(Oe=>Oe.type==="text");if(lt){P([lt.id]),Pe(lt.id);return}const ut=Lt(),ft=Y,wt=ft.points,mt={x:wt[0],y:wt[1]},Et={x:wt[wt.length-2],y:wt[wt.length-1]};let Bt,xt;if(ft.lineType==="curved"){const Oe=Ut(mt,Et,ft.curvature??Nt),gn=Me(mt,Oe,Et,.5);Bt=ft.x+gn.x,xt=ft.y+gn.y}else Bt=ft.x+(mt.x+Et.x)/2,xt=ft.y+(mt.y+Et.y)/2;const Dt={id:ut,type:"text",x:Bt,y:xt,width:100,height:30,rotation:0,style:{...L,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:A,textAlign:"center",verticalAlign:"middle"};q(Dt),i==null||i(Dt);const Mt=Y.boundElements??[];tt(A,{boundElements:[...Mt,{id:ut,type:"text"}]}),P([ut]),Pe(ut);return}if(Y.type==="rectangle"||Y.type==="ellipse"||Y.type==="diamond"||Y.type==="image"){const lt=(at=Y.boundElements)==null?void 0:at.find(mt=>mt.type==="text");if(lt){P([lt.id]),Pe(lt.id);return}const ut=Lt(),ft={id:ut,type:"text",x:Y.x,y:Y.y,width:Y.width,height:30,rotation:0,style:{...L,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:A,textAlign:"center",verticalAlign:"middle"};q(ft),i==null||i(ft);const wt=Y.boundElements??[];tt(A,{boundElements:[...wt,{id:ut,type:"text"}]}),P([ut]),Pe(ut);return}}},[Z,d,i]),ad=I.useCallback((A,B)=>{if(Z)return;const{elements:N,updateElement:L,pushHistory:q}=T.getState(),tt=N.find(P=>P.id===A);if(L(A,B),tt&&(B.startBinding!==void 0||B.endBinding!==void 0)){const P=tt.type;if(B.startBinding!==void 0){const Y=T.getState().elements;ye(A,P,tt.startBinding,B.startBinding??null,Y,T.getState().updateElement)}if(B.endBinding!==void 0){const Y=T.getState().elements;ye(A,P,tt.endBinding,B.endBinding??null,Y,T.getState().updateElement)}}q()},[Z]),dd=I.useCallback((A,B)=>{Z||T.getState().updateElement(A,B)},[Z]),ud=I.useCallback(A=>{Rr(A)},[]),yi=I.useCallback(A=>{jr(A)},[]),Ii=I.useCallback((A,B)=>{if(jr(null),Pe(null),B){const{elements:N,updateElement:L,deleteElements:q,pushHistory:tt}=T.getState(),P=N.find(Y=>Y.id===A);if((P==null?void 0:P.type)==="text"&&P.containerId){const Y=P.containerId,Q=N.find(at=>at.id===Y);Q!=null&&Q.boundElements&&L(Y,{boundElements:Q.boundElements.filter(at=>at.id!==A)})}q([A]),l==null||l([A])}else T.getState().pushHistory()},[l]),gd=I.useCallback(A=>{var q,tt;if(Z)return;A.preventDefault();const B=Ft.current;if(!B)return;const N=B.getBoundingClientRect(),L=zt.current;if(L){const P=L.getPointerPosition(),Y=(P==null?void 0:P.x)??A.clientX-N.left,Q=(P==null?void 0:P.y)??A.clientY-N.top,at=T.getState().viewport,lt=(Y-at.x)/at.scale,ut=(Q-at.y)/at.scale,{elements:ft,selectedIds:wt,setSelectedIds:mt}=T.getState();let Et=null;for(let Bt=ft.length-1;Bt>=0;Bt--){const xt=ft[Bt];if(xt.type==="text"&&xt.containerId)continue;let Dt=xt.x,Mt=xt.y,Oe=xt.width,gn=xt.height;if((xt.type==="arrow"||xt.type==="line")&&"points"in xt){const Qo=xt.points,qo=[],ts=[];for(let jn=0;jn<Qo.length;jn+=2)qo.push(xt.x+Qo[jn]),ts.push(xt.y+Qo[jn+1]);Dt=Math.min(...qo),Mt=Math.min(...ts),Oe=Math.max(...qo)-Dt,gn=Math.max(...ts)-Mt}const Rn=Math.max(4,((q=xt.style)==null?void 0:q.strokeWidth)??2);if(lt>=Dt-Rn&&lt<=Dt+Oe+Rn&&ut>=Mt-Rn&&ut<=Mt+gn+Rn){Et=xt;break}}if(Et&&!wt.includes(Et.id))if((tt=Et.groupIds)!=null&&tt.length){const Bt=Et.groupIds[Et.groupIds.length-1],xt=ft.filter(Dt=>{var Mt;return(Mt=Dt.groupIds)==null?void 0:Mt.includes(Bt)}).map(Dt=>Dt.id);mt(xt)}else mt([Et.id])}He({x:A.clientX-N.left,y:A.clientY-N.top})},[Z]),hd=I.useMemo(()=>{var tt;const A=w.length>0,N=navigator.platform.includes("Mac")?"⌘":"Ctrl+",L=[];L.push({label:"Copy",shortcut:`${N}C`,disabled:!A,action:()=>{A&&rn(ks(w,b))}}),L.push({label:"Paste",shortcut:`${N}V`,disabled:!Vc(),action:()=>{const P=Eo();if(P.length===0)return;const Y=20,{clones:Q,selectedCloneIds:at}=bn(P,P,Y);Q.forEach(lt=>E(lt)),z(at.length>0?at:Q.map(lt=>lt.id)),pt(),rn(P.map(lt=>({...lt,x:lt.x+Y,y:lt.y+Y})))}}),L.push({label:"Duplicate",shortcut:`${N}D`,disabled:!A,action:()=>{A&&k.duplicateElements(w)}}),L.push({label:"Delete",shortcut:"Del",disabled:!A,divider:!0,action:()=>{A&&(yt(w),l==null||l(w))}}),L.push({label:"Bring to Front",shortcut:`${N}⇧]`,disabled:!A,divider:!0,action:()=>{A&&k.bringToFront(w)}}),L.push({label:"Send to Back",shortcut:`${N}⇧[`,disabled:!A,action:()=>{A&&k.sendToBack(w)}});let q=!1;if(w.length>=2){const P=b.filter(lt=>w.includes(lt.id)),Y=new Set(P.filter(lt=>{var ut;return(ut=lt.groupIds)==null?void 0:ut.length}).map(lt=>lt.groupIds[lt.groupIds.length-1]));P.every(lt=>{var ut;return(ut=lt.groupIds)==null?void 0:ut.length})&&Y.size===1||(L.push({label:"Group",shortcut:`${N}G`,divider:!0,action:()=>k.groupElements(w)}),q=!0)}if(A){const P=b.filter(Q=>w.includes(Q.id));if(P.some(Q=>{var at;return(at=Q.groupIds)==null?void 0:at.length})){const Q=new Set;for(const lt of P)(tt=lt.groupIds)!=null&&tt.length&&Q.add(lt.groupIds[lt.groupIds.length-1]);const at=b.filter(lt=>{var ut;return(ut=lt.groupIds)==null?void 0:ut.some(ft=>Q.has(ft))}).map(lt=>lt.id);L.push({label:"Ungroup",shortcut:`${N}⇧G`,divider:!q,action:()=>k.ungroupElements(at)})}}if(L.push({label:"Select All",shortcut:`${N}A`,divider:!0,action:()=>z(b.map(P=>P.id))}),A){const P=b.filter(at=>w.includes(at.id)),Y=P.every(at=>at.isLocked),Q=P.some(at=>at.isLocked);L.push({label:Y?"Unlock":Q?"Unlock All":"Lock",shortcut:`${N}⇧L`,divider:!0,action:()=>k.toggleLockElements(w)})}if(A){const P=new Set(["rectangle","ellipse","diamond"]),Y=b.filter(Q=>w.includes(Q.id)&&P.has(Q.type));if(Y.length>0){const Q=new Set(Y.map(ut=>ut.type)),lt=[{label:"Rectangle",type:"rectangle"},{label:"Ellipse",type:"ellipse"},{label:"Diamond",type:"diamond"}].filter(ut=>!Q.has(ut.type)||Q.size>1);lt.length>0&&lt.forEach((ut,ft)=>{L.push({label:`Convert to ${ut.label}`,divider:ft===0,action:()=>k.convertElementType(Y.map(wt=>wt.id),ut.type)})})}}if(nt){const P=typeof nt=="function"?nt({selectedIds:w,elements:b,position:oe??{x:0,y:0},close:()=>He(null)}):nt;if(P.length>0){L.push({...P[0],divider:!0});for(let Y=1;Y<P.length;Y++)L.push(P[Y])}}return L},[w,b,k,E,yt,z,pt,l,nt,oe]);I.useImperativeHandle(e,()=>({getElements:()=>T.getState().elements,setElements:A=>{st(A),pt()},addElement:A=>{E(A)},deleteElements:A=>{yt(A)},getSelectedIds:()=>T.getState().selectedIds,setSelectedIds:A=>{z(A)},clearSelection:()=>{U()},setActiveTool:A=>{ot(A)},getActiveTool:()=>T.getState().activeTool,undo:()=>{G()},redo:()=>{Ct()},zoomTo:A=>{it({scale:Math.min(We,Math.max(Ee,A))})},resetView:()=>{it({x:0,y:0,scale:1})},scrollToElement:(A,B)=>{const N=T.getState().elements.find(mt=>mt.id===A);if(!N)return;const L=Ft.current;if(!L)return;const q=L.getBoundingClientRect(),tt=q.width,P=q.height,Y=(B==null?void 0:B.zoom)??Math.max(T.getState().viewport.scale,1),Q=Math.min(We,Math.max(Ee,Y)),at=N.x+(N.width??0)/2,lt=N.y+(N.height??0)/2,ut=tt/2-at*Q,ft=P/2-lt*Q,wt={x:ut,y:ft,scale:Q};B!=null&&B.animate?Ie(T.getState().viewport,wt,it):it(wt)},zoomToFit:(A,B)=>{const N=Ft.current;if(!N)return;const L=N.getBoundingClientRect(),q=L.width,tt=L.height;T.getState().zoomToFit(q,tt,A,{padding:B==null?void 0:B.padding,maxZoom:B==null?void 0:B.maxZoom,animate:B==null?void 0:B.animate})},exportPNG:()=>{var A;return((A=zt.current)==null?void 0:A.toDataURL({pixelRatio:2}))??null},exportJSON:()=>JSON.stringify(T.getState().elements,null,2),exportSVG:()=>De(T.getState().elements),importJSON:A=>{try{const B=JSON.parse(A);Array.isArray(B)&&(st(B),pt())}catch{}},getStage:()=>zt.current}));const fd=()=>{var B;if(Z)return"default";if(ve||S==="hand")return"grab";const A=nn(S);return((B=A==null?void 0:A.getCursor)==null?void 0:B.call(A))??"default"},pd=g?Qn.filter(A=>g.includes(A.type)):Qn,yd=m&&!Z&&(!["hand","select","eraser"].includes(S)||S==="select"&&w.length>0),Ci=!ve&&["select","eraser","image"].includes(S);return h.jsx(Ao.Provider,{value:_,children:h.jsxs("div",{ref:Ft,className:K,onContextMenu:gd,onMouseLeave:()=>Se(null),style:{position:"relative",width:c,height:a,overflow:"hidden",background:J.canvasBackground},children:[f&&!Z&&y!=="hidden"&&h.jsx(vc,{visibleTools:pd,theme:J,position:y}),yd&&h.jsx(Xc,{theme:J}),h.jsx("div",{style:{cursor:fd(),position:"absolute",top:0,left:0,right:0,bottom:0},children:h.jsxs(dt.Stage,{ref:zt,width:Pt.width,height:Pt.height,x:j.x,y:j.y,scaleX:j.scale,scaleY:j.scale,draggable:(S==="hand"||ve)&&!Z,onMouseDown:si,onMouseMove:li,onMouseUp:ci,onWheel:id,onDragEnd:ld,onTouchStart:si,onTouchMove:li,onTouchEnd:ci,children:[ht&&h.jsx(dt.Layer,{listening:!1,hitGraphEnabled:!1,children:h.jsx(sc,{width:Pt.width,height:Pt.height,viewport:j,gridColor:J.gridColor})}),h.jsx(wa,{elements:od,listening:Ci,onSelect:ai,onChange:fi,onDragMove:ui,onDoubleClick:pi,autoEditTextId:Qr,onTextEditStart:yi,onTextEditEnd:Ii,allElements:se,gridSnap:ht?Te:void 0,onDragSnap:ht?void 0:gi,viewportScale:ni,onGroupDragEnd:cd}),h.jsxs(dt.Layer,{listening:Ci,children:[nd.map(A=>h.jsx(wo,{element:A,isSelected:!0,isEditing:un&&Jt.elementId===A.id,onSelect:ai,onChange:fi,onDragMove:ui,onDoubleClick:pi,autoEditText:Qr===A.id,onTextEditStart:yi,onTextEditEnd:Ii,allElements:se,gridSnap:ht?Te:void 0,onDragSnap:ht?void 0:gi,viewportScale:ni},A.id)),S==="select"&&!Z&&(()=>{const A=w.filter(B=>{const N=ei.get(B);return!(!N||N.type==="line"||N.type==="arrow"||N.type==="text"&&N.containerId||B===qa)});return A.length===0?null:h.jsx(nc,{selectedIds:A,selectionColor:J.selectionColor})})(),un&&(()=>{const A=ei.get(Jt.elementId??"");return A?h.jsx(Ac,{element:A,allElements:se,onPointsChange:ad,onPointDragMove:dd,onSnapTargetChange:ud,color:J.selectionColor}):null})()]}),h.jsxs(dt.Layer,{listening:!1,hitGraphEnabled:!1,children:[h.jsx(ic,{box:Xt,selectionColor:J.selectionColor}),h.jsx(ac,{elements:se,snapTarget:ja,visible:(S==="line"||S==="arrow"||Uo)&&!Z,color:J.selectionColor}),td.map((A,B)=>A.orientation==="v"?h.jsx(dt.Line,{points:[A.position,A.start,A.position,A.end],stroke:J.selectionColor,strokeWidth:1,dash:[4,4],listening:!1,perfectDrawEnabled:!1},`ag-${B}`):h.jsx(dt.Line,{points:[A.start,A.position,A.end,A.position],stroke:J.selectionColor,strokeWidth:1,dash:[4,4],listening:!1,perfectDrawEnabled:!1},`ag-${B}`)),se.filter(A=>A.isLocked&&St.has(A.id)).map(A=>h.jsx(xa,{element:A,scale:j.scale},`lock-${A.id}`)),ct.length>0&&h.jsx(xr,{peers:ct,viewport:j,stageWidth:Pt.width,stageHeight:Pt.height,elements:se})]})]})}),oe&&(V?V({selectedIds:w,elements:b,position:oe,close:()=>He(null)}):h.jsx(Lc,{x:oe.x,y:oe.y,items:hd,onClose:()=>He(null),theme:J})),W&&h.jsx(ka,{theme:J})]})})});vr.displayName="FlowCanvas";const ka=I.memo(({theme:t})=>{const e=T(s=>s.elements.length),n=T(s=>s.activeTool),o=T(s=>s.selectedIds.length);return h.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:[h.jsxs("span",{children:["Tool: ",h.jsx("strong",{style:{color:t.textColor,textTransform:"capitalize"},children:n})]}),h.jsx("span",{style:{opacity:.4},children:"|"}),h.jsxs("span",{children:["Elements: ",h.jsx("strong",{style:{color:t.textColor},children:e})]}),o>0&&h.jsxs(h.Fragment,{children:[h.jsx("span",{style:{opacity:.4},children:"|"}),h.jsxs("span",{children:["Selected: ",h.jsx("strong",{style:{color:t.activeToolColor},children:o})]})]})]})}),Er={rectangle:0,ellipse:1,diamond:2,line:3,arrow:4,freedraw:5,text:6,image:7};class Wr{constructor(e=1024){et(this,"_data");et(this,"_capacity",0);et(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:d}=this._data;for(let c=0;c<n;c++){const a=e[c];o[c]=a.id,s[c]=a.x,r[c]=a.y,i[c]=a.width,l[c]=a.height,d[c]=Er[a.type]??0,this._indexMap.set(a.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,d=-r/l-s,c=-i/l-s,a=(-r+n)/l+s,g=(-i+o)/l+s,{ids:u,x:f,y,w:p,h:m,length:W}=this._data,v=[];for(let X=0;X<W;X++){const R=f[X],Z=y[X],K=p[X],nt=m[X];R+K>=d&&R<=a&&Z+nt>=c&&Z<=g&&v.push(u[X])}return v}queryRect(e,n,o,s){const{ids:r,x:i,y:l,w:d,h:c,length:a}=this._data,g=[];for(let u=0;u<a;u++){const f=i[u],y=l[u],p=d[u],m=c[u];f+p>=e&&f<=o&&y+m>=n&&y<=s&&g.push(r[u])}return g}queryPoint(e,n){const{ids:o,x:s,y:r,w:i,h:l,length:d}=this._data,c=[];for(let a=0;a<d;a++)e>=s[a]&&e<=s[a]+i[a]&&n>=r[a]&&n<=r[a]+l[a]&&c.push(o[a]);return c}clear(){this._data.length=0,this._indexMap.clear()}}let Lo=null;function Sa(){return Lo||(Lo=new Wr),Lo}const Gt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Vo=Gt.length,Ve=Gt[0],va=Gt[Vo-1];function Ea(t,e){const n=Gt.indexOf(t),o=Gt.indexOf(e);if(o-n<=1)return null;const s=Math.floor((n+o)/2);return Gt[s]}function Yo(t,e){return t===null&&e===null?"a0":e===null?Tr(t):t===null?Wa(e):Ta(t,e)}function Fo(t,e,n){if(n===0)return[];if(n===1)return[Yo(t,e)];const o=Math.floor(n/2),s=Yo(t,e),r=Fo(t,s,o),i=Fo(s,e,n-o-1);return[...r,s,...i]}function Tr(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Gt.indexOf(e[n]);if(o<Vo-1)return e[n]=Gt[o+1],e.join("");e[n]=Ve}return t+Gt[1]}function Wa(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Gt.indexOf(e[n]);if(o>0){e[n]=Gt[o-1];let s=e.join("");for(;s.length>1&&s.endsWith(Ve);)s=s.slice(0,-1);return s}e[n]=va}return Ve+t}function Ta(t,e){const n=Math.max(t.length,e.length),o=t.padEnd(n,Ve),s=e.padEnd(n,Ve);let r="";for(let i=0;i<n;i++){if(o[i]===s[i]){r+=o[i];continue}const l=Ea(o[i],s[i]);return l!==null?r+l:r+o[i]+Tr(o.slice(i+1).replace(/0+$/,"")||Ve)}return t+Gt[Math.floor(Vo/2)]}function Ba(t){if(!t||t.length===0)return!1;for(const e of t)if(Gt.indexOf(e)===-1)return!1;return!0}function Za(t,e){return t===e?0:t<e?-1:1}class _a{constructor(e=1e4){et(this,"_entries",[]);et(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 Br(t){return{type:"add",element:t}}function Zr(t){return{type:"delete",elementId:t}}function _r(t,e,n){return{type:"move",elementId:t,dx:e,dy:n}}function Mr(t,e,n,o,s){return{type:"resize",elementId:t,width:e,height:n,x:o,y:s}}function Gr(t,e){return{type:"style",elementId:t,changes:e}}function Xr(t,e){return{type:"rotate",elementId:t,rotation:e}}function Dr(t,e){return{type:"reorder",elementId:t,sortOrder:e}}function Lr(t,e){return{type:"updatePoints",elementId:t,points:e}}function Vr(t,e){return{type:"setText",elementId:t,text:e}}function Ma(...t){return{type:"batch",operations:t}}function Yr(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=Yr(n,o);return n}default:return t}}function Ga(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(Br(r));for(const r of t)s.has(r.id)||n.push(Zr(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(_r(r.id,r.x-i.x,r.y-i.y)),(i.width!==r.width||i.height!==r.height)&&n.push(Mr(r.id,r.width,r.height)),i.rotation!==r.rotation&&n.push(Xr(r.id,r.rotation));const l={};let d=!1;for(const c of Object.keys(r.style))i.style[c]!==r.style[c]&&(l[c]=r.style[c],d=!0);if(d&&n.push(Gr(r.id,l)),r.type==="text"&&i.type==="text"&&r.text!==i.text&&n.push(Vr(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,a=i.points;(c.length!==a.length||c.some((g,u)=>g!==a[u]))&&n.push(Lr(r.id,c))}i.sortOrder!==r.sortOrder&&r.sortOrder!==void 0&&n.push(Dr(r.id,r.sortOrder))}return n}class Xa{constructor(){et(this,"_doc",null);et(this,"_provider",null);et(this,"_config",null);et(this,"_isApplyingRemote",!1);et(this,"_isApplyingLocal",!1);et(this,"_lastElements",[]);et(this,"_syncTimer",null);et(this,"_deepTimer",null);et(this,"_dirtyIds",new Set);et(this,"_storeUnsub",null);et(this,"_yObserverCleanup",null);et(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 Ot.Doc,this._provider=new os.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 d of l){const c=new Ot.Map;cn(d,c),s.set(d.id,c)}},"local-init"),this._isApplyingLocal=!1),this._lastElements=l}const r=(l,d)=>{if(d.origin==="local-sync"||d.origin==="local-init"||this._isApplyingLocal)return;this._isApplyingRemote=!0;let c=[...this._lastElements],a=!1;for(const[g,u]of l.keys)if(u.action==="add"||u.action==="update"){const f=s.get(g);if(f){const y=me(f);if(y){const p=c.findIndex(m=>m.id===g);p>=0?c[p]=y:c.push(y),a=!0}}}else u.action==="delete"&&(c=c.filter(f=>f.id!==g),a=!0);a&&(c.sort((g,u)=>g.sortOrder&&u.sortOrder?g.sortOrder<u.sortOrder?-1:g.sortOrder>u.sortOrder?1:0:0),e.setElements(c),this._lastElements=c),this._isApplyingRemote=!1},i=l=>{if(!this._isApplyingLocal){for(const d of l){let c=d.target;for(;c&&!(c instanceof Ot.Map&&c.parent===s);)c=c.parent;if(c instanceof Ot.Map){const a=c.get("id");a&&this._dirtyIds.add(a)}}this._deepTimer&&clearTimeout(this._deepTimer),this._deepTimer=setTimeout(()=>{if(this._dirtyIds.size===0||this._isApplyingLocal)return;this._isApplyingRemote=!0;let d=[...this._lastElements],c=!1;for(const a of this._dirtyIds){const g=s.get(a);if(!g)continue;const u=me(g);if(!u)continue;const f=d.findIndex(y=>y.id===a);f>=0&&(d[f]=u,c=!0)}this._dirtyIds.clear(),c&&(e.setElements(d),this._lastElements=d),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 Ot.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 d=r[l];d!==n.get(l)&&n.set(l,d)}if(e.style)for(const l of s){const d=e.style[l];d!==n.get(`style.${l}`)&&n.set(`style.${l}`,d)}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 d=JSON.stringify(e.points);d!==n.get("points")&&n.set("points",d),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 a=e.endBinding?JSON.stringify(e.endBinding):null;a!==n.get("endBinding")&&n.set("endBinding",a),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 d=JSON.stringify(e.points);d!==n.get("points")&&n.set("points",d);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=me(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 Da{constructor(e){et(this,"_worker",null);et(this,"_callbacks");this._callbacks=e}connect(e,n){if(this.dispose(),this._worker=Sn(()=>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:$t&&$t.tagName.toUpperCase()==="SCRIPT"&&$t.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 Ye(t){return`${t.zoom}:${t.col}:${t.row}`}class Fr{constructor(e=200){et(this,"_cache",new Map);et(this,"_accessCounter",0);et(this,"_maxTiles");this._maxTiles=e}get(e){const n=this._cache.get(Ye(e));return n?(n.accessOrder=++this._accessCounter,n.bitmap):null}set(e,n,o=0){const s=Ye(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(Ye(e));return o!=null&&o.generation>=n}invalidate(e){const n=Ye(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 an=256,Pn=[.1,.15,.2,.25,.33,.5,.67,.75,1,1.25,1.5,2,2.5,3,4,5];function Pr(t){let e=Pn[0],n=Math.abs(t-e);for(let o=1;o<Pn.length;o++){const s=Math.abs(t-Pn[o]);s<n&&(e=Pn[o],n=s)}return e}function Fe(t){return an/t}function Hr(t,e,n,o=1){const s=Pr(t.scale),r=Fe(s),i=-t.x/t.scale,l=-t.y/t.scale,d=i+e/t.scale,c=l+n/t.scale,a=Math.floor(i/r)-o,g=Math.ceil(d/r)+o,u=Math.floor(l/r)-o,f=Math.ceil(c/r)+o,y=[];for(let p=a;p<=g;p++)for(let m=u;m<=f;m++)y.push({col:p,row:m,zoom:s});return{tiles:y,zoom:s}}function Or(t){const e=Fe(t.zoom);return{minX:t.col*e,minY:t.row*e,maxX:(t.col+1)*e,maxY:(t.row+1)*e}}function La(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Va(t,e){const n=je(t),o=Fe(e),s=[],r=Math.floor(n.minX/o),i=Math.floor(n.maxX/o),l=Math.floor(n.minY/o),d=Math.floor(n.maxY/o);for(let c=r;c<=i;c++)for(let a=l;a<=d;a++)s.push({col:c,row:a,zoom:e});return s}class Nr{constructor(e={}){et(this,"_cache");et(this,"_drawFn");et(this,"_elementTiles",new Map);et(this,"_generation",0);this._cache=new Fr(e.maxCachedTiles??200),this._drawFn=e.drawFn??Ya}getTiles(e,n,o,s){const{tiles:r,zoom:i}=Hr(e,n,o),l=[];for(const d of r){let c=this._cache.get(d);c||(c=this._rasterise(d,s),this._cache.set(d,c,this._generation));const a=Fe(i);l.push({coord:d,bitmap:c,worldX:d.col*a,worldY:d.row*a,worldSize:a})}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=Or(e),s=Fe(e.zoom),r=[];for(const c of n){const a=je(c);if(La(a,o)){r.push(c);const g=Ye(e),u=this._elementTiles.get(c.id);u?u.includes(g)||u.push(g):this._elementTiles.set(c.id,[g])}}const i=new OffscreenCanvas(an,an),l=i.getContext("2d"),d=an/s;return l.scale(d,d),l.translate(-o.minX,-o.minY),this._drawFn(l,r,o),i.transferToImageBitmap()}}function Ya(t,e,n){var o,s,r,i,l,d,c;for(const a of e){if(t.save(),a.rotation){const y=a.x+a.width/2,p=a.y+a.height/2;t.translate(y,p),t.rotate(a.rotation*Math.PI/180),t.translate(-y,-p)}t.globalAlpha=((o=a.style)==null?void 0:o.opacity)??1;const g=((s=a.style)==null?void 0:s.strokeColor)??"#000000",u=((r=a.style)==null?void 0:r.fillColor)??"transparent",f=((i=a.style)==null?void 0:i.strokeWidth)??2;switch(t.strokeStyle=g,t.fillStyle=u,t.lineWidth=f,a.type){case"rectangle":t.beginPath(),t.rect(a.x,a.y,a.width,a.height),u!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(a.x+a.width/2,a.y+a.height/2,a.width/2,a.height/2,0,0,Math.PI*2),u!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{const y=a.x+a.width/2,p=a.y+a.height/2;t.beginPath(),t.moveTo(y,a.y),t.lineTo(a.x+a.width,p),t.lineTo(y,a.y+a.height),t.lineTo(a.x,p),t.closePath(),u!=="transparent"&&t.fill(),t.stroke();break}case"line":case"arrow":{const y=a.points;if(y.length>=4){t.beginPath(),t.moveTo(a.x+y[0],a.y+y[1]);for(let p=2;p<y.length;p+=2)t.lineTo(a.x+y[p],a.y+y[p+1]);t.stroke()}break}case"freedraw":{const y=a.points;if(y.length>=4){t.beginPath(),t.moveTo(a.x+y[0],a.y+y[1]);for(let p=2;p<y.length;p+=2)t.lineTo(a.x+y[p],a.y+y[p+1]);t.stroke()}break}case"text":{const y=a;t.font=`${((l=y.style)==null?void 0:l.fontSize)??16}px ${((d=y.style)==null?void 0:d.fontFamily)??"sans-serif"}`,t.fillStyle=g,t.fillText(y.text,a.x,a.y+(((c=y.style)==null?void 0:c.fontSize)??16));break}case"image":t.strokeStyle="#ccc",t.setLineDash([4,4]),t.strokeRect(a.x,a.y,a.width,a.height);break}t.restore()}}function Fa(t,e,n,o,s={}){var y;const{enabled:r=!1,maxCachedTiles:i=200,drawFn:l,elementThreshold:d=500}=s,c=I.useRef(null);I.useEffect(()=>(c.current=new Nr({maxCachedTiles:i,drawFn:l}),()=>{var p;(p=c.current)==null||p.dispose(),c.current=null}),[i,l]);const a=r&&t.length>=d,g=I.useMemo(()=>!a||!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})),[a,e.x,e.y,e.scale,n,o,t]),u=I.useCallback(p=>{var m;(m=c.current)==null||m.invalidateElements(p)},[]),f=I.useCallback(()=>{var p;(p=c.current)==null||p.invalidateAll()},[]);return{isActive:a,tiles:g,invalidateElements:u,invalidateAll:f,cacheSize:((y=c.current)==null?void 0:y.cacheSize)??0}}const Yt=4096,Hn=1024,On=16,Ur=2;class Pa{constructor(e=Yt,n=Yt){et(this,"_shelves",[]);et(this,"_atlasWidth");et(this,"_atlasHeight");this._atlasWidth=e,this._atlasHeight=n}pack(e,n){const o=e+Ur,s=n+Ur;for(const l of this._shelves)if(l.height>=s&&l.x+o<=this._atlasWidth){const d={x:l.x,y:l.y};return l.x+=o,d}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 Kr{constructor(e){et(this,"_entries",new Map);et(this,"_packer");et(this,"_canvas");et(this,"_ctx");et(this,"_drawFn");et(this,"_dirty",!1);et(this,"_generation",0);this._packer=new Pa(Yt,Yt),this._canvas=new OffscreenCanvas(Yt,Yt),this._ctx=this._canvas.getContext("2d"),this._drawFn=e??Oa}addOrUpdate(e,n){const o=this._entries.get(e.id);if(o&&o.generation>=n)return o.region;const{pw:s,ph:r}=Ha(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),d=r/Math.max(e.height,1);this._ctx.scale(l,d),this._drawFn(this._ctx,e,e.width,e.height),this._ctx.restore();const c={atlasIndex:0,u:i.x/Yt,v:i.y/Yt,uWidth:s/Yt,vHeight:r/Yt,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,Yt,Yt);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 Ha(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),On),Hn),o=Math.min(Math.max(Math.ceil(n/e),On),Hn)):(o=Math.min(Math.max(Math.ceil(t.height),On),Hn),n=Math.min(Math.max(Math.ceil(o*e),On),Hn)),{pw:n,ph:o}}function Oa(t,e,n,o){var l,d,c,a,g,u,f;const s=((l=e.style)==null?void 0:l.strokeColor)??"#000000",r=((d=e.style)==null?void 0:d.fillColor)??"transparent",i=((c=e.style)==null?void 0:c.strokeWidth)??2;switch(t.strokeStyle=s,t.fillStyle=r,t.lineWidth=i,t.globalAlpha=((a=e.style)==null?void 0:a.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 y=e;t.font=`${((g=y.style)==null?void 0:g.fontSize)??16}px ${((u=y.style)==null?void 0:u.fontFamily)??"sans-serif"}`,t.fillStyle=s,t.fillText(y.text,0,((f=y.style)==null?void 0:f.fontSize)??16);break}default:t.strokeStyle="#aaa",t.strokeRect(0,0,n,o);break}}const Na=`#version 300 es
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(`
2
+ `)}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
+ `)}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(`
7
+ `);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
9
9
  precision highp float;
10
10
 
11
11
  // Shared unit-quad corners (0=bottom-left, 1=top-right)
@@ -49,7 +49,7 @@ void main() {
49
49
  v_texCoord = a_texRect.xy + a_position * a_texRect.zw;
50
50
  v_opacity = a_opacity;
51
51
  }
52
- `,Ua=`#version 300 es
52
+ `,jd=`#version 300 es
53
53
  precision mediump float;
54
54
 
55
55
  in vec2 v_texCoord;
@@ -63,4 +63,4 @@ void main() {
63
63
  vec4 texColor = texture(u_atlas, v_texCoord);
64
64
  fragColor = texColor * v_opacity;
65
65
  }
66
- `;function zr(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 Ka(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 za(t,e,n){const o=zr(t,t.VERTEX_SHADER,e),s=zr(t,t.FRAGMENT_SHADER,n),r=Ka(t,o,s);return t.deleteShader(o),t.deleteShader(s),r}function Ja(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 $a(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 Jr(t,e,n,o,s){const r=2*n/o,i=-2*n/s,l=2*t/o-1,d=-2*e/s+1;return new Float32Array([r,0,0,0,i,0,l,d,1])}const Po=10;class $r{constructor(e={}){et(this,"_canvas",null);et(this,"_gl",null);et(this,"_program",null);et(this,"_vao",null);et(this,"_quadVBO",null);et(this,"_instanceVBO",null);et(this,"_atlasTexture",null);et(this,"_atlas");et(this,"_viewMatrixLoc",null);et(this,"_atlasLoc",null);et(this,"_instanceData",new Float32Array(0));et(this,"_instanceCount",0);et(this,"_elementThreshold");et(this,"_generation",0);et(this,"_staticIds",new Set);et(this,"_isInitialised",!1);et(this,"_width",0);et(this,"_height",0);this._atlas=new Kr(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=za(n,Na,Ua)}catch(a){return console.warn("[WebGLHybrid] Shader compilation failed:",a),!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=Ja(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=Po*4,i=n.getAttribLocation(this._program,"a_worldRect"),l=n.getAttribLocation(this._program,"a_texRect"),d=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)),d>=0&&(n.enableVertexAttribArray(d),n.vertexAttribPointer(d,1,n.FLOAT,!1,r,32),n.vertexAttribDivisor(d,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=$a(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=Jr(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*Po;this._instanceData.length<o&&(this._instanceData=new Float32Array(o));let s=0,r=0;for(const l of e){const d=this._atlas.getRegion(l.id);d&&(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]=d.u,this._instanceData[s+5]=d.v,this._instanceData[s+6]=d.uWidth,this._instanceData[s+7]=d.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+=Po,r++)}this._instanceCount=r}}function Ra(t,e,n,o,s={}){const{enabled:r=!1,rasterFn:i,elementThreshold:l}=s,d=I.useRef(null),c=I.useRef(null),a=I.useRef(!1);I.useEffect(()=>{var y;if(!r){(y=d.current)==null||y.dispose(),d.current=null,a.current=!1;return}return d.current=new $r({rasterFn:i,elementThreshold:l}),()=>{var p;(p=d.current)==null||p.dispose(),d.current=null,a.current=!1}},[r,i,l]);const g=I.useCallback(y=>{c.current=y,y&&d.current&&(a.current=d.current.init(y))},[]);I.useEffect(()=>{var y;(y=d.current)==null||y.setSize(o.width,o.height)},[o.width,o.height]),I.useEffect(()=>{!d.current||!a.current||d.current.render(t,e,n)});const u=I.useCallback(y=>{var p;(p=d.current)==null||p.invalidateElements(y)},[]),f=I.useCallback(()=>{var y;(y=d.current)==null||y.invalidateAll()},[]);return I.useMemo(()=>{var y;return{webglCanvasRef:g,isActive:a.current,invalidateElements:u,invalidateAll:f,instanceCount:((y=d.current)==null?void 0:y.instanceCount)??0}},[g,u,f])}x.ARROWHEAD_TYPES=qn,x.CURVE_RATIO=Nt,x.CollaborationManager=Xa,x.CursorOverlay=xr,x.DEFAULT_ANIMATION_DURATION=Bs,x.DEFAULT_STYLE=fn,x.DEFAULT_THEME=ar,x.ELEMENT_TYPE_MAP=Er,x.ExportWorkerManager=lr,x.FILL_COLORS=Ue,x.FlowCanvas=vr,x.LINE_TYPES=to,x.OperationLog=_a,x.ROUGHNESS_CONFIGS=ss,x.STROKE_COLORS=Ne,x.STROKE_WIDTHS=xi,x.STYLE_FIELDS=Ln,x.SYNC_FIELDS=Xo,x.SpatialIndex=Bo,x.SpatialSoA=Wr,x.SyncWorkerAdapter=Da,x.TILE_SIZE=an,x.TOOLS=Qn,x.TextureAtlas=Kr,x.TileCache=Fr,x.TileRenderer=Nr,x.WebGLHybridRenderer=$r,x.WorkerConfigContext=Ao,x.ZOOM_STEPS=Qe,x.aabbOverlaps=vs,x.addBoundElement=ws,x.animateViewport=Ie,x.applyOperation=Yr,x.arrowheadSize=mo,x.batchElementUpdates=nl,x.buildElementMap=tl,x.buildViewMatrix=Jr,x.cancelViewportAnimation=Ce,x.clearElbowRouteCache=Ui,x.clipboardHasImage=yl,x.cloneElementsForHistory=el,x.compareFractionalKeys=Za,x.computeCurveControlPoint=Ut,x.computeEfficientZoom=or,x.computeElbowPoints=ze,x.computeElbowRoute=fs,x.computeFixedPoint=As,x.computeImageElementDimensions=Ds,x.computeZoomToFit=co,x.createCollaborationProvider=dr,x.createImageElement=xn,x.createWorker=Sn,x.cullToViewport=Es,x.curveArrowPrev=ho,x.destroyCollaborationProvider=Xn,x.detectOperations=Ga,x.directionFromEdgePoint=Ei,x.directionFromFixedPoint=eo,x.directionFromPoints=Ke,x.directionFromShapeToPoint=no,x.discreteZoom=Pr,x.disposeElbowWorkerManager=Ks,x.disposeExportWorkerManager=cr,x.distance=rl,x.downloadJSON=Fc,x.downloadPNG=Yc,x.downloadSVG=qc,x.drawArrowhead=qt,x.elementToSpatialItem=To,x.elementToYMap=cn,x.exportToDataURL=tr,x.exportToJSON=er,x.exportToSVG=De,x.extractImageDataFromClipboard=Io,x.fileToDataURL=wn,x.findConnectorsForElement=Re,x.findNearestSnapTarget=fe,x.flatToPoints=vn,x.generateId=Lt,x.generateKeyBetween=Yo,x.generateNKeysBetween=Fo,x.getAnchorPosition=zi,x.getConnectionPoints=Cs,x.getDiamondPoints=tn,x.getEdgePoint=le,x.getEdgePointFromFixedPoint=ie,x.getElbowPreferredDirection=In,x.getElbowWorkerManager=bo,x.getElementAABB=je,x.getElementTiles=Va,x.getElementsBounds=lo,x.getExportWorkerManager=ga,x.getImageFilesFromDataTransfer=yo,x.getNextZoomStep=Zs,x.getPrevZoomStep=_s,x.getRemoteAwareness=fr,x.getSharedSpatialIndex=sa,x.getSharedSpatialSoA=Sa,x.getStrokeDash=Zt,x.getToolHandler=nn,x.getVisibleBounds=Ss,x.getVisibleTiles=Hr,x.getYDoc=ur,x.getYElements=gr,x.getYProvider=Go,x.isCollaborationActive=ha,x.isConnectable=io,x.isPointInRect=il,x.isValidFractionalIndex=Ba,x.isWorkerSupported=Gl,x.loadImage=en,x.normalizeRect=uo,x.onStatusChange=hr,x.opAdd=Br,x.opBatch=Ma,x.opDelete=Zr,x.opMove=_r,x.opReorder=Dr,x.opResize=Mr,x.opRotate=Xr,x.opSetText=Vr,x.opStyle=Gr,x.opUpdatePoints=Lr,x.openImageFilePicker=Vs,x.quadBezierAt=Me,x.quadBezierTangent=go,x.rafThrottle=Ws,x.recomputeBoundPoints=pe,x.removeBoundElement=xs,x.resolveImageSource=Ls,x.rotatePoint=Ms,x.scheduleIdleWork=ir,x.simplifyElbowPath=Je,x.startSync=pr,x.stopSync=Fn,x.syncBoundElements=ye,x.tileBounds=Or,x.tileKey=Ye,x.updateAwareness=Dn,x.useCanvasStore=T,x.useCollaboration=yr,x.useEfficientZoom=sr,x.useProgressiveRender=rr,x.useTileRenderer=Fa,x.useWebGLHybrid=Ra,x.useWorkerConfig=zs,x.worldTileSize=Fe,x.yMapToElement=me,x.yieldToMain=aa,x.zoomAtPoint=An,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})}));
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"})}));