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