f1ow 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -39
- package/dist/components/Canvas/ConnectionPoints.d.ts +2 -0
- package/dist/components/Canvas/SelectionBox.d.ts +1 -0
- package/dist/components/StylePanel/ui.d.ts +6 -0
- package/dist/components/Toolbar/Toolbar.d.ts +1 -0
- package/dist/constants/index.d.ts +13 -0
- package/dist/f1ow.js +4250 -3812
- package/dist/f1ow.umd.cjs +9 -9
- package/dist/lib/FlowCanvasProps.d.ts +9 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/utils/freehand.d.ts +58 -0
- package/package.json +10 -4
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=a*1,d=o*.6,
|
|
3
|
-
`)}case"crowfoot_one_or_many":{const c=a*1,d=o*.6,
|
|
4
|
-
`)}default:return""}}function
|
|
5
|
-
`)}function
|
|
6
|
-
`),l=e.fontSize*1.18;let a="start",c=0;r==="center"?(a="middle",c=t.width/2):r==="right"&&(a="end",c=t.width);const d=i.map((u,f)=>`<tspan x="${n+c}" dy="${f===0?0:l}">${
|
|
1
|
+
(function(x,g){typeof exports=="object"&&typeof module<"u"?g(exports,require("react/jsx-runtime"),require("react"),require("react-konva"),require("konva"),require("zustand"),require("nanoid"),require("react-dom"),require("lucide-react"),require("rbush"),require("yjs"),require("y-websocket")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react","react-konva","konva","zustand","nanoid","react-dom","lucide-react","rbush","yjs","y-websocket"],g):(x=typeof globalThis<"u"?globalThis:x||self,g(x.FlowCanvas={},x.jsxRuntime,x.React,x.ReactKonva,x.Konva,x.zustand,x.nanoid,x.ReactDOM,x.LucideReact,x.RBush,x.Y,x.yWebsocket))})(this,(function(x,g,I,gt,qe,ws,ji,xs,It,Qi,qi,ks){"use strict";var ku=Object.defineProperty;var Su=(x,g,I)=>g in x?ku(x,g,{enumerable:!0,configurable:!0,writable:!0,value:I}):x[g]=I;var ct=(x,g,I)=>Su(x,typeof g!="symbol"?g+"":g,I);var qt=typeof document<"u"?document.currentScript:null;function tl(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const o=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,o.get?o:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Kt=tl(qi),wn={strokeColor:"#1e1e1e",fillColor:"transparent",strokeWidth:2,opacity:1,strokeStyle:"solid",roughness:0,fontSize:20,fontFamily:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif",freehandStyle:"standard"},tn=["#1a1a1a","#868e96","#b197fc","#7048e8","#4263eb","#f59f00","#e8590c","#2f9e44","#40c057","#f06595","#e03131"],en=["transparent","#e9ecef","#f3f0ff","#e5dbff","#edf2ff","#fff3bf","#ffe8cc","#d3f9d8","#ebfbee","#fcc2d7","#ffe3e3"],el=[1,2,3,4,6],co=[{type:"hand",label:"Hand (Pan)",shortcut:"H",icon:"Hand"},{type:"select",label:"Select",shortcut:"V",icon:"MousePointer2"},{type:"rectangle",label:"Rectangle",shortcut:"R",icon:"Square"},{type:"ellipse",label:"Ellipse",shortcut:"O",icon:"Circle"},{type:"diamond",label:"Diamond",shortcut:"D",icon:"Diamond"},{type:"line",label:"Line",shortcut:"L",icon:"Minus"},{type:"arrow",label:"Arrow",shortcut:"A",icon:"ArrowUpRight"},{type:"freedraw",label:"Pencil",shortcut:"P",icon:"Pencil"},{type:"text",label:"Text",shortcut:"T",icon:"Type"},{type:"image",label:"Image",shortcut:"I",icon:"ImageIcon"},{type:"eraser",label:"Eraser",shortcut:"E",icon:"Eraser"}],Xe=.1,Le=5,nl=[12,16,20,24,28,36,48,64],ol=[{label:"Sans-serif",value:"system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif"},{label:"Serif",value:"Georgia, Cambria, Times New Roman, Times, serif"},{label:"Monospace",value:"SF Mono, Menlo, Consolas, Liberation Mono, monospace"},{label:"Hand-drawn",value:"Segoe Print, Comic Sans MS, cursive"}],Tt={color:"#4f8df7",blur:6,opacity:.5},xe=20,sl=[{value:"standard",label:"Standard"},{value:"pen",label:"Pen"},{value:"pencil",label:"Pencil"},{value:"brush",label:"Brush"}],ao=[{type:null,label:"None",preview:"—"},{type:"arrow",label:"Arrow",preview:"▷"},{type:"triangle",label:"Triangle",preview:"▶"},{type:"triangle_outline",label:"Triangle Outline",preview:"△"},{type:"circle",label:"Circle",preview:"●"},{type:"circle_outline",label:"Circle Outline",preview:"○"},{type:"diamond",label:"Diamond",preview:"◆"},{type:"diamond_outline",label:"Diamond Outline",preview:"◇"},{type:"bar",label:"Bar",preview:"|"},{type:"crowfoot_one",label:"One",preview:"||"},{type:"crowfoot_many",label:"Many",preview:">|"},{type:"crowfoot_one_or_many",label:"One or Many",preview:">||"}],uo=[{type:"sharp",label:"Sharp",preview:"╱"},{type:"curved",label:"Curved",preview:"∿"},{type:"elbow",label:"Elbow",preview:"⌐"}],Ss=[{value:0,label:"Architect"},{value:1,label:"Artist"},{value:2,label:"Cartoonist"}],vs=20,Es=25,rl=36,Fe=40,Ws=1e4;function xn(t){switch(t){case"up":return{x:0,y:-1};case"down":return{x:0,y:1};case"left":return{x:-1,y:0};case"right":return{x:1,y:0}}}function kn(t){return t==="up"||t==="down"}function Sn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=(t.width||1)/2,l=(t.height||1)/2,a=Math.abs(s)/i,c=Math.abs(r)/l;return a>c*3?s>=0?"right":"left":(c>a*3,r>=0?"down":"up")}function go(t){const[e,n]=t,o=n,s=1-n,r=e,i=1-e,l=Math.min(o,s,r,i);return l===o?"up":l===s?"down":l===r?"left":"right"}function nn(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.abs(n)>=Math.abs(o)?n>=0?"right":"left":o>=0?"down":"up"}function ho(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=t.width/2||1,l=t.height/2||1,a=s/i,c=r/l;return Math.abs(a)>=Math.abs(c)?s>=0?"right":"left":r>=0?"down":"up"}function il(t,e){const n=Math.abs(e.y-t.y),o=Math.abs(e.y-(t.y+t.height)),s=Math.abs(e.x-t.x),r=Math.abs(e.x-(t.x+t.width)),i=Math.min(n,o,s,r);return i===n?"up":i===o?"down":i===s?"left":"right"}function te(t){return t.left+t.width}function ee(t){return t.top+t.height}function ll(t,e){return e.x>t.left&&e.x<te(t)&&e.y>t.top&&e.y<ee(t)}function Ve(t,e,n){return{left:t.left-e,top:t.top-n,width:t.width+e*2,height:t.height+n*2}}function Ts(t,e,n){const o=Math.min(e,Es),s=n==="left"?o:e,r=n==="right"?o:e,i=n==="up"?o:e,l=n==="down"?o:e;return{left:t.left-s,top:t.top-i,width:t.width+s+r,height:t.height+i+l}}function Bs(t,e,n){const o=new Set(n),s=Math.min(e,Es),r=o.has("left")?s:e,i=o.has("right")?s:e,l=o.has("up")?s:e,a=o.has("down")?s:e;return{left:t.left-r,top:t.top-l,width:t.width+r+i,height:t.height+l+a}}function cl(t,e){const n=Math.min(t.left,e.left),o=Math.min(t.top,e.top),s=Math.max(te(t),te(e)),r=Math.max(ee(t),ee(e));return{left:n,top:o,width:s-n,height:r-o}}function fo(t){return{left:t.x,top:t.y,width:t.width,height:t.height}}function po(t){const e=t.rotation||0;if(e===0)return{x:t.x,y:t.y,width:t.width,height:t.height};const n=t.x+t.width/2,o=t.y+t.height/2,s=t.width/2,r=t.height/2,i=e*Math.PI/180,l=Math.cos(i),a=Math.sin(i),c=[{x:-s,y:-r},{x:s,y:-r},{x:s,y:r},{x:-s,y:r}].map(p=>({x:n+p.x*l-p.y*a,y:o+p.x*a+p.y*l}));let d=1/0,h=1/0,u=-1/0,f=-1/0;for(const p of c)p.x<d&&(d=p.x),p.y<h&&(h=p.y),p.x>u&&(u=p.x),p.y>f&&(f=p.y);return{x:d,y:h,width:u-d,height:f-h}}function al(t){switch(t){case"left":return"right";case"right":return"left";case"up":return"down";case"down":return"up"}}function dl(t,e){return e.x<t.x?"left":e.x>t.x?"right":e.y<t.y?"up":e.y>t.y?"down":null}function ul(t,e){return t===null||e===null?!1:(t==="left"||t==="right"?"h":"v")!==(e==="left"||e==="right"?"h":"v")}class gl{constructor(e){ct(this,"adjacent",new Map);this.pt=e}}class hl{constructor(){ct(this,"idx",{})}add(e){const n=String(e.x),o=String(e.y);n in this.idx||(this.idx[n]={}),o in this.idx[n]||(this.idx[n][o]=new gl(e))}get(e){var s;const n=String(e.x),o=String(e.y);return((s=this.idx[n])==null?void 0:s[o])??null}has(e){return this.get(e)!==null}connect(e,n){const o=this.get(e),s=this.get(n);if(!o||!s)return;const r=Math.abs(n.x-e.x)+Math.abs(n.y-e.y);o.adjacent.set(s,r),s.adjacent.set(o,r)}}class fl{constructor(){ct(this,"data",[])}get size(){return this.data.length}push(e,n){this.data.push({item:e,priority:n}),this.bubbleUp(this.data.length-1)}pop(){if(this.data.length===0)return;const e=this.data[0],n=this.data.pop();return this.data.length>0&&(this.data[0]=n,this.sinkDown(0)),e.item}bubbleUp(e){for(;e>0;){const n=e-1>>1;if(this.data[n].priority<=this.data[e].priority)break;[this.data[n],this.data[e]]=[this.data[e],this.data[n]],e=n}}sinkDown(e){const n=this.data.length;for(;;){let o=e;const s=2*e+1,r=2*e+2;if(s<n&&this.data[s].priority<this.data[o].priority&&(o=s),r<n&&this.data[r].priority<this.data[o].priority&&(o=r),o===e)break;[this.data[o],this.data[e]]=[this.data[e],this.data[o]],e=o}}}function pl(t,e,n){const o=t.get(e),s=t.get(n);if(!o||!s)return null;const r=u=>Math.abs(u.x-n.x)+Math.abs(u.y-n.y),i=(u,f)=>`${u.pt.x},${u.pt.y},${f??"n"}`,l=new Map,a=new Map,c=new fl,d={node:o,dir:null,g:0},h=i(o,null);for(l.set(h,0),a.set(h,null),c.push(d,r(o.pt));c.size>0;){const u=c.pop(),f=i(u.node,u.dir);if(!(u.g>(l.get(f)??1/0))){if(u.node===s){const p=[];let y=u;for(;y;){p.push(y.node.pt);const m=i(y.node,y.dir);if(y=a.get(m),y==null)break}return p[p.length-1]!==o.pt&&p.push(o.pt),p.reverse(),p}for(const[p,y]of u.node.adjacent){const m=dl(u.node.pt,p.pt);if(m===null)continue;const W=u.dir!==null&&m===al(u.dir),v=ul(u.dir,m),D=W?Ws*3:v?Ws:0,$=u.g+y+D,T=i(p,m);$<(l.get(T)??1/0)&&(l.set(T,$),a.set(T,u),c.push({node:p,dir:m,g:$},$+r(p.pt)))}}}return null}function yl(t){const e=new Map,n=[];for(const o of t){let s=e.get(o.x);s||(s=new Set,e.set(o.x,s)),s.has(o.y)||(s.add(o.y),n.push(o))}return n}function Il(t,e,n,o){const s=n.left,r=te(n),i=n.top,l=ee(n),a=[...new Set([s,...t.filter(u=>u>=s&&u<=r),r])].sort((u,f)=>u-f),c=[...new Set([i,...e.filter(u=>u>=i&&u<=l),l])].sort((u,f)=>u-f),d=u=>o.some(f=>ll(f,u)),h=[];for(const u of c)for(const f of a){const p={x:f,y:u};d(p)||h.push(p)}return h}function Zs(t,e,n){if(t.y===e.y){const o=t.y,s=Math.min(t.x,e.x),r=Math.max(t.x,e.x);for(const i of n)if(i.top<o&&o<ee(i)&&i.left<r&&te(i)>s)return!0}else if(t.x===e.x){const o=t.x,s=Math.min(t.y,e.y),r=Math.max(t.y,e.y);for(const i of n)if(i.left<o&&o<te(i)&&i.top<r&&ee(i)>s)return!0}return!1}function Cl(t,e){const n=new hl,o=new Set,s=new Set;for(const l of t)n.add(l),o.add(l.x),s.add(l.y);const r=[...o].sort((l,a)=>l-a),i=[...s].sort((l,a)=>l-a);for(let l=0;l<i.length;l++)for(let a=0;a<r.length;a++){const c={x:r[a],y:i[l]};if(n.has(c)){for(let d=a-1;d>=0;d--){const h={x:r[d],y:i[l]};if(n.has(h)){Zs(h,c,e)||n.connect(h,c);break}}for(let d=l-1;d>=0;d--){const h={x:r[a],y:i[d]};if(n.has(h)){Zs(h,c,e)||n.connect(h,c);break}}}}return n}function _s(t){if(t.length<=2)return t;const e=[t[0]];for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;i||l||o.x===s.x&&o.y===s.y||e.push(s)}return e.push(t[t.length-1]),e}function Ms(t){if(t.length<=2)return 0;let e=0;for(let n=1;n<t.length-1;n++){const o=t[n-1],s=t[n],r=t[n+1],i=o.x===s.x&&s.x===r.x,l=o.y===s.y&&s.y===r.y;!i&&!l&&e++}return e}function Gs(t){let e=0;for(let n=1;n<t.length;n++)e+=Math.abs(t[n].x-t[n-1].x)+Math.abs(t[n].y-t[n-1].y);return e}function bl(t){let e=t[0],n=Ms(e),o=Gs(e);for(let s=1;s<t.length;s++){const r=Ms(t[s]),i=Gs(t[s]);(r<n||r===n&&i<o)&&(e=t[s],n=r,o=i)}return e}function yo(t,e,n,o,s,r){let i={left:Math.min(t.x,e.x),top:Math.min(t.y,e.y),width:Math.abs(e.x-t.x)||1,height:Math.abs(e.y-t.y)||1};for(const W of s)i=cl(i,W);i=Ve(i,Fe,Fe);const l=[],a=[];for(const W of s)l.push(W.left,te(W)),a.push(W.top,ee(W)),l.push(W.left+W.width/2),a.push(W.top+W.height/2);l.push(t.x,e.x),a.push(t.y,e.y);const c=xn(n),d=xn(o);let h={x:t.x+c.x*r,y:t.y+c.y*r},u={x:e.x+d.x*r,y:e.y+d.y*r};h=Xs(h,n,s),u=Xs(u,o,s),l.push(h.x,u.x),a.push(h.y,u.y),l.push((t.x+e.x)/2),a.push((t.y+e.y)/2);const f=Il(l,a,i,s),p=yl([h,u,...f]),y=Cl(p,s),m=pl(y,h,u);if(m){const W=[t,...m,e];return _s(W)}return null}function Ds(t,e,n,o,s,r,i,l){if(t.x===e.x&&t.y===e.y)return[t,e];const a=s?fo(s):{left:t.x,top:t.y,width:0,height:0},c=r?fo(r):{left:e.x,top:e.y,width:0,height:0},d=vs,h=Math.max(rl,i??0),u=(l??[]).map(O=>Ve(fo(O),d,d)),f=s?Ts(a,d,n):Ve(a,d,d),p=r?Ts(c,d,o):Ve(c,d,d),y=[n],m=[o];let W=!1;if(s){const O=ho(s,e);O!==n&&(y.push(O),W=!0)}if(r){const O=ho(r,t);O!==o&&(m.push(O),W=!0)}const v=s?Bs(a,d,y):Ve(a,d,d),D=r?Bs(c,d,m):Ve(c,d,d),$=[],T=yo(t,e,n,o,[f,p,...u],h);if(T&&$.push(T),W){const O=yo(t,e,n,o,[v,D,...u],h);O&&$.push(O)}if($.length>0)return bl($);if(u.length>0){const O=yo(t,e,n,o,[f,p],h);if(O)return O}return _s(ml(t,e,n,o,h))}function Xs(t,e,n){let{x:o,y:s}=t;for(let r=0;r<n.length;r++){let i=!0;for(const l of n)if(!(o<=l.left||o>=te(l)||s<=l.top||s>=ee(l)))switch(i=!1,e){case"left":o=l.left-1;break;case"right":o=te(l)+1;break;case"up":s=l.top-1;break;case"down":s=ee(l)+1;break}if(i)break}return{x:o,y:s}}function ml(t,e,n,o,s){const r=Math.max(s,vs),i=xn(n),l=xn(o),a={x:t.x+i.x*r,y:t.y+i.y*r},c={x:e.x+l.x*r,y:e.y+l.y*r};if(kn(n)===kn(o))if(kn(n)){const d=(a.y+c.y)/2;return[t,a,{x:a.x,y:d},{x:c.x,y:d},c,e]}else{const d=(a.x+c.x)/2;return[t,a,{x:d,y:a.y},{x:d,y:c.y},c,e]}else return kn(n)?[t,a,{x:a.x,y:c.y},c,e]:[t,a,{x:c.x,y:a.y},c,e]}const Al=new Set(["rectangle","ellipse","diamond","text","image"]),wl=256,Pe=new Map;function xl(t,e,n,o,s,r,i,l){const a=c=>Math.round(c*2)/2;return[a(t.x),a(t.y),a(e.x),a(e.y),n,o,s?`${a(s.x)},${a(s.y)},${a(s.width)},${a(s.height)}`:"n",r?`${a(r.x)},${a(r.y)},${a(r.width)},${a(r.height)}`:"n",i,l??0].join("|")}function kl(){Pe.clear()}function on(t,e,n,o,s,r){const i=new Map(s.map(F=>[F.id,F])),l=F=>!F.isPrecise||F.fixedPoint[0]===.5&&F.fixedPoint[1]===.5;let a;if(n)if(l(n)){const F=i.get(n.elementId);a=F?Sn(F,e):nn(t,e)}else a=go(n.fixedPoint);else a=nn(t,e);let c;if(o)if(l(o)){const F=i.get(o.elementId);c=F?Sn(F,t):nn(e,t)}else c=go(o.fixedPoint);else c=nn(e,t);const d=n?i.get(n.elementId)??null:null,h=o?i.get(o.elementId)??null:null,u=d?po(d):null,f=h?po(h):null,p=n==null?void 0:n.elementId,y=o==null?void 0:o.elementId,m=[],W=[],v=F=>Math.round(F*2)/2;for(const F of s){if(!Al.has(F.type)||F.id===p||F.id===y||!F.isVisible)continue;const J=po(F),Y=Math.min(t.x,e.x)-Fe*3,Q=Math.max(t.x,e.x)+Fe*3,M=Math.min(t.y,e.y)-Fe*3,k=Math.max(t.y,e.y)+Fe*3;J.x+J.width<Y||J.x>Q||J.y+J.height<M||J.y>k||(m.push(J),W.push(`${F.id}:${v(J.x)},${v(J.y)},${v(J.width)},${v(J.height)}`))}W.sort();const D=W.join(";"),$=xl(t,e,a,c,u,f,D,r),T=Pe.get($);if(T)return T;const O=Ds(t,e,a,c,u,f,r,m),ot=[];for(const F of O)ot.push(F.x-t.x,F.y-t.y);if(Pe.size>=wl){const F=Pe.keys().next().value;F!==void 0&&Pe.delete(F)}return Pe.set($,ot),ot}function sn(t){if(t.length<=4)return t;const e=[t[0],t[1]];for(let n=2;n<t.length-2;n+=2){const o=e[e.length-2],s=e[e.length-1],r=t[n],i=t[n+1],l=t[n+2],a=t[n+3];s===i&&i===a||o===r&&r===l||o===r&&s===i||e.push(r,i)}return e.push(t[t.length-2],t[t.length-1]),e}const Sl=new Set(["rectangle","ellipse","diamond","text","image"]);function Io(t){return Sl.has(t.type)}function Ls(t){return t*Math.PI/180}function Fs(t,e,n){if(n===0)return{x:t,y:e};const o=Math.cos(n),s=Math.sin(n);return{x:t*o-e*s,y:t*s+e*o}}function rn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=e.x-n,r=e.y-o,i=Ls(t.rotation||0);return i===0?{x:s,y:r}:Fs(s,r,-i)}function vn(t,e){const n=t.x+t.width/2,o=t.y+t.height/2,s=Ls(t.rotation||0),r=Fs(e.x,e.y,s);return{x:n+r.x,y:o+r.y}}function Vs(t){const{x:e,y:n,width:o,height:s}=t,r=e+o/2,i=n+s/2;return{top:{x:r,y:n},bottom:{x:r,y:n+s},left:{x:e,y:i},right:{x:e+o,y:i},center:{x:r,y:i}}}function vl(t,e){return Vs(t)[e]}const Ps=4;function ce(t){return Ps+t/2}function Ys(t,e){const n=t.width||1,o=t.height||1,s=rn(t,e),r=Math.max(0,Math.min(1,(s.x+n/2)/n)),i=Math.max(0,Math.min(1,(s.y+o/2)/o));return[r,i]}function ae(t,e,n=0){const o=(e[0]-.5)*t.width,s=(e[1]-.5)*t.height;if(o===0&&s===0)return vn(t,{x:0,y:0});const r=vn(t,{x:o,y:s});return de(t,r,n)}function de(t,e,n=0){const o=rn(t,e),s=o.x,r=o.y;if(s===0&&r===0)return vn(t,{x:0,y:-(t.height/2+n)});let i;switch(t.type){case"ellipse":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s);i={x:(l+n)*Math.cos(c),y:(a+n)*Math.sin(c)};break}case"diamond":{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.cos(c),h=Math.sin(c),u=Math.abs(d),f=Math.abs(h),p=1/(u/l+f/a),y=p*d,m=p*h;if(n===0)i={x:y,y:m};else{const W=(d>=0?1:-1)/l,v=(h>=0?1:-1)/a,D=Math.sqrt(W*W+v*v);i={x:y+W/D*n,y:m+v/D*n}}break}default:{const l=t.width/2,a=t.height/2,c=Math.atan2(r,s),d=Math.abs(Math.tan(c));let h,u;d<=a/l?(h=s>0?l:-l,u=h*Math.tan(c)):(u=r>0?a:-a,h=u/Math.tan(c)),n===0?i={x:h,y:u}:d<=a/l?i={x:h+(s>0?n:-n),y:u}:i={x:h,y:u+(r>0?n:-n)};break}}return vn(t,i)}const El=24,Wl=20,Hs=6;function Tl(t,e){const n=rn(t,e),o=t.width/2||1,s=t.height/2||1;switch(t.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)>=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(c-n.x,d-n.y)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s>=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(d-n.x,h-n.y)}default:{const r=o+n.x,i=o-n.x,l=s+n.y,a=s-n.y,c=Math.min(r,i,l,a);return c>0?c:0}}}function Bl(t,e){const n=rn(e,t),o=e.width/2,s=e.height/2;switch(e.type){case"ellipse":{const r=n.x/o,i=n.y/s;if(Math.sqrt(r*r+i*i)<=1)return 0;const a=Math.atan2(n.y,n.x),c=o*Math.cos(a),d=s*Math.sin(a);return Math.hypot(n.x-c,n.y-d)}case"diamond":{if(Math.abs(n.x)/o+Math.abs(n.y)/s<=1)return 0;const i=Math.atan2(n.y,n.x),l=Math.abs(Math.cos(i)),a=Math.abs(Math.sin(i)),c=1/(l/o+a/s),d=c*Math.cos(i),h=c*Math.sin(i);return Math.hypot(n.x-d,n.y-h)}default:{const r=Math.max(-o-n.x,0,n.x-o),i=Math.max(-s-n.y,0,n.y-s);return Math.hypot(r,i)}}}function ke(t,e,n=El,o=new Set,s,r,i=Ps,l){let a=null,c=1/0;for(const d of e){if(!Io(d)||o.has(d.id))continue;const h=Bl(t,d);if(h>n)continue;const u=h===0,f=d.x+d.width/2,p=d.y+d.height/2,y=Math.hypot(f-t.x,p-t.y),m=u?-1e6+y:h*1e3+y;if(m<c){c=m;let W;if(r!==void 0)W=r;else if(h===0){const T=Math.min(d.width,d.height)/2,O=Math.min(Wl,T*.6),ot=Tl(d,t);l===!0?W=ot<=O+Hs:l===!1?W=ot<=Math.max(0,O-Hs):W=ot<=O}else W=!0;let v,D;if(W)v=Ys(d,t),D=ae(d,v,i);else{v=[.5,.5];const $=rn(d,t);Math.abs($.x)+Math.abs($.y)<2?D=s?de(d,s,i):de(d,{x:f+d.width,y:p},i):D=de(d,t,i)}a={elementId:d.id,fixedPoint:v,position:D,isPrecise:W}}}return a}function Se(t,e){const{startBinding:n,endBinding:o}=t;if(!n&&!o)return null;const s=new Map(e.map(v=>[v.id,v])),r=t.points,i=r.length/2;let l={x:t.x+r[0],y:t.y+r[1]},a={x:t.x+r[r.length-2],y:t.y+r[r.length-1]};const c=n?s.get(n.elementId):void 0,d=o?s.get(o.elementId):void 0,h=(v,D)=>v.isPrecise?ae(D,v.fixedPoint,0):{x:D.x+D.width/2,y:D.y+D.height/2},u=t.lineType==="elbow",f=(v,D,$)=>{const T=Sn(v,D),O=v.x+v.width/2,ot=v.y+v.height/2,F=Math.max(v.width,v.height)*10;let J;switch(T){case"up":J={x:O,y:ot-F};break;case"down":J={x:O,y:ot+F};break;case"left":J={x:O-F,y:ot};break;case"right":J={x:O+F,y:ot};break}return de(v,J,$)},p=u?(v,D,$)=>f(v,D,$):de;if(n&&c&&o&&d){if(n.isPrecise)l=ae(c,n.fixedPoint,n.gap);else{const v=h(o,d);l=p(c,v,n.gap)}if(o.isPrecise)a=ae(d,o.fixedPoint,o.gap);else{const v=h(n,c);a=p(d,v,o.gap)}n.isPrecise||(l=p(c,a,n.gap)),o.isPrecise||(a=p(d,l,o.gap))}else n&&c&&(n.isPrecise?l=ae(c,n.fixedPoint,n.gap):l=p(c,a,n.gap)),o&&d&&(o.isPrecise?a=ae(d,o.fixedPoint,o.gap):a=p(d,l,o.gap));const y=[0,0];for(let v=1;v<i-1;v++){const D=t.x+r[v*2],$=t.y+r[v*2+1];y.push(D-l.x,$-l.y)}y.push(a.x-l.x,a.y-l.y);const m=a.x-l.x,W=a.y-l.y;return{x:l.x,y:l.y,points:y,width:Math.abs(m),height:Math.abs(W)}}function ln(t,e){return e.filter(n=>{var s,r;if(n.type!=="line"&&n.type!=="arrow")return!1;const o=n;return((s=o.startBinding)==null?void 0:s.elementId)===t||((r=o.endBinding)==null?void 0:r.elementId)===t})}function Zl(t,e){return e.map(n=>{let o=!1;if(n.boundElements&&n.boundElements.length>0){const l=n.boundElements.filter(a=>!t.has(a.id));l.length!==n.boundElements.length&&(n={...n,boundElements:l.length>0?l:null},o=!0)}if(n.type!=="line"&&n.type!=="arrow")return n;const s=n;let r=s.startBinding,i=s.endBinding;return r&&t.has(r.elementId)&&(r=null,o=!0),i&&t.has(i.elementId)&&(i=null,o=!0),o?{...n,startBinding:r,endBinding:i}:n})}function Os(t,e){const n=t.boundElements??[];return n.some(o=>o.id===e.id)?t:{...t,boundElements:[...n,e]}}function Ns(t,e){const n=t.boundElements;if(!n||n.length===0)return t;const o=n.filter(s=>s.id!==e);return{...t,boundElements:o.length>0?o:null}}function ve(t,e,n,o,s,r){if(n&&n.elementId!==(o==null?void 0:o.elementId)){const i=s.find(l=>l.id===n.elementId);if(i){const l=Ns(i,t);l!==i&&r(i.id,{boundElements:l.boundElements})}}if(o&&o.elementId!==(n==null?void 0:n.elementId)){const i=s.find(l=>l.id===o.elementId);if(i){const l=Os(i,{id:t,type:e});l!==i&&r(i.id,{boundElements:l.boundElements})}}}function Pt(){return ji.nanoid(12)}function _l(t){const e={...t};return e.style&&(e.style={...e.style}),e.boundElements&&(e.boundElements=e.boundElements.map(n=>({...n}))),e.startBinding&&(e.startBinding={...e.startBinding}),e.endBinding&&(e.endBinding={...e.endBinding}),e.groupIds&&(e.groupIds=[...e.groupIds]),Array.isArray(e.points)&&(e.points=[...e.points]),Array.isArray(e.pressures)&&(e.pressures=[...e.pressures]),e.crop&&(e.crop={...e.crop}),e}function En(t,e,n=20){const o=new Set(t.map(d=>d.id)),s=new Set;for(const d of t)if(d.boundElements)for(const h of d.boundElements)h.type==="text"&&!o.has(h.id)&&s.add(h.id);const r=[...t,...e.filter(d=>s.has(d.id))],i=new Map;for(const d of r)i.set(d.id,Pt());const l=new Map;for(const d of r)if(d.groupIds)for(const h of d.groupIds)l.has(h)||l.set(h,Pt());const a=r.map(d=>{const h=i.get(d.id),u=_l(d);return u.id=h,u.x=d.x+n,u.y=d.y+n,u.containerId&&i.has(u.containerId)?u.containerId=i.get(u.containerId):u.containerId&&(u.containerId=null),u.boundElements&&(u.boundElements=u.boundElements.map(f=>i.has(f.id)?{...f,id:i.get(f.id)}:null).filter(Boolean),u.boundElements.length===0&&(u.boundElements=null)),u.startBinding&&i.has(u.startBinding.elementId)?u.startBinding={...u.startBinding,elementId:i.get(u.startBinding.elementId)}:u.startBinding&&(u.startBinding=null),u.endBinding&&i.has(u.endBinding.elementId)?u.endBinding={...u.endBinding,elementId:i.get(u.endBinding.elementId)}:u.endBinding&&(u.endBinding=null),u.groupIds&&u.groupIds.length>0&&(u.groupIds=u.groupIds.map(f=>l.get(f)??f)),u}),c=a.filter(d=>{var u;const h=(u=[...i.entries()].find(([,f])=>f===d.id))==null?void 0:u[0];return h?o.has(h):!1}).map(d=>d.id);return{clones:a,idMap:i,selectedCloneIds:c}}function Us(t,e){const n=new Set(t),o=new Set;for(const s of e)if(n.has(s.id)&&s.groupIds)for(const r of s.groupIds)o.add(r);if(o.size>0){for(const s of e)if(!n.has(s.id)&&s.groupIds){for(const r of s.groupIds)if(o.has(r)){n.add(s.id);break}}}for(const s of e)if(n.has(s.id)&&s.boundElements)for(const r of s.boundElements)r.type==="text"&&!n.has(r.id)&&n.add(r.id);return e.filter(s=>n.has(s.id))}function Ks(t,e,n,o=200){const{x:s,y:r,scale:i}=t,l=-s/i-o,a=-r/i-o,c=(-s+e)/i+o,d=(-r+n)/i+o;return{minX:l,minY:a,maxX:c,maxY:d}}function cn(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r}}if(t.type==="freedraw"&&"points"in t){if(t.isComplete===!1){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return n===1/0?{minX:t.x,minY:t.y,maxX:t.x+1,maxY:t.y+1}:{minX:n,minY:s,maxX:o,maxY:r}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}return{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}}function zs(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Js(t,e,n,o,s,r){if(t.length<=100)return t;const i=Ks(e,n,o,r);return t.filter(l=>{if(s.has(l.id))return!0;const a=cn(l);return zs(i,a)})}function Ml(t){const e=new Map;for(const n of t)e.set(n.id,n);return e}function Gl(t){if(typeof structuredClone=="function"){const e=new Map,n=new Array(t.length);for(let o=0;o<t.length;o++){const s=t[o];if(s.type==="image"&&"src"in s){const r=s;e.has(r.id)||e.set(r.id,r.src);const{src:i,...l}=r,a=structuredClone(l);a.src=e.get(r.id),n[o]=a}else n[o]=structuredClone(s)}return n}return JSON.parse(JSON.stringify(t))}function $s(t){let e=null,n=null;const o=(...s)=>{n=s,e===null&&(e=requestAnimationFrame(()=>{e=null,n&&(t(...n),n=null)}))};return o.cancel=()=>{e!==null&&(cancelAnimationFrame(e),e=null),n=null},o}function Dl(t,e){if(e.length===0)return t;const n=new Map;for(const o of e){const s=n.get(o.id);n.set(o.id,s?{...s,...o.changes}:o.changes)}return t.map(o=>{const s=n.get(o.id);return s?{...o,...s}:o})}function Rs(t){return new Set(t)}const an=[.1,.25,.5,.75,1,1.5,2,3,4,5],js=280;function Wn({viewport:t,point:e,targetScale:n}){const o=Math.min(Le,Math.max(Xe,n)),s=(e.x-t.x)/t.scale,r=(e.y-t.y)/t.scale;return{scale:o,x:e.x-s*o,y:e.y-r*o}}function Qs(t){for(const e of an)if(e>t+.01)return e;return Le}function qs(t){for(let e=an.length-1;e>=0;e--)if(an[e]<t-.01)return an[e];return Xe}function Co(t){if(t.length===0)return null;let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const r of t){const i=cn(r);i.minX<e&&(e=i.minX),i.minY<n&&(n=i.minY),i.maxX>o&&(o=i.maxX),i.maxY>s&&(s=i.maxY)}return{minX:e,minY:n,maxX:o,maxY:s}}function bo(t,e,n,o={}){const s=o.padding??50,r=o.maxZoom??2,i=t.maxX-t.minX,l=t.maxY-t.minY;if(i===0&&l===0)return{scale:1,x:e/2-t.minX,y:n/2-t.minY};const a=(e-s*2)/(i||1),c=(n-s*2)/(l||1),d=Math.min(Math.min(a,c),r),h=Math.min(Le,Math.max(Xe,d)),u=(t.minX+t.maxX)/2,f=(t.minY+t.maxY)/2;return{scale:h,x:e/2-u*h,y:n/2-f*h}}function Xl(t){return 1-Math.pow(1-t,3)}let Yt=null;function Ee(t,e,n,o=js){Yt!==null&&(cancelAnimationFrame(Yt),Yt=null);const s=performance.now(),r=i=>{const l=i-s,a=Math.min(l/o,1),c=Xl(a),d={x:t.x+(e.x-t.x)*c,y:t.y+(e.y-t.y)*c,scale:t.scale+(e.scale-t.scale)*c};n(d),a<1?Yt=requestAnimationFrame(r):(Yt=null,n(e))};return Yt=requestAnimationFrame(r),()=>{Yt!==null&&(cancelAnimationFrame(Yt),Yt=null)}}function We(){Yt!==null&&(cancelAnimationFrame(Yt),Yt=null)}const Ll=100;function ue(t){if(t.type==="image"&&"src"in t){const{src:e,...n}=t,o=structuredClone(n);return o.src=e,o}return structuredClone(t)}const B=ws.create((t,e)=>({elements:[],selectedIds:[],activeTool:"select",currentStyle:{...wn},currentLineType:"sharp",currentStartArrowhead:null,currentEndArrowhead:"arrow",viewport:{x:0,y:0,scale:1},isDrawing:!1,drawStart:null,history:[],historyIndex:-1,_historyBaseline:new Map,_historyPaused:!1,showGrid:!1,addElement:n=>{t(o=>({elements:[...o.elements,n]})),e().pushHistory()},updateElement:(n,o)=>{t(s=>{const r=s.elements,i=r.findIndex(c=>c.id===n);if(i===-1)return s;const l={...r[i],...o};if(l===r[i])return s;const a=r.slice();return a[i]=l,{elements:a}})},batchUpdateElements:n=>{if(n.length!==0){if(n.length===1){e().updateElement(n[0].id,n[0].updates);return}t(o=>{const s=o.elements,r=new Map;for(let l=0;l<s.length;l++)r.set(s[l].id,l);let i=null;for(const{id:l,updates:a}of n){const c=r.get(l);if(c===void 0)continue;const d=i?i[c]:s[c],h={...d,...a};h!==d&&(i||(i=s.slice()),i[c]=h)}return i?{elements:i}:o})}},deleteElements:n=>{const o=new Set(n),{elements:s}=e();for(const r of s)if(o.has(r.id)&&r.boundElements)for(const i of r.boundElements)i.type==="text"&&o.add(i.id);for(const r of s)r.type==="text"&&"containerId"in r&&r.containerId&&o.has(r.containerId)&&o.add(r.id);t(r=>{const i=r.elements.filter(a=>!o.has(a.id));return{elements:Zl(o,i),selectedIds:r.selectedIds.filter(a=>!o.has(a))}}),e().pushHistory()},setElements:n=>{const o=new Map;for(const s of n)o.set(s.id,s);t({elements:n,_historyBaseline:o})},duplicateElements:n=>{const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),{clones:r,selectedCloneIds:i}=En(s,o);t(l=>({elements:[...l.elements,...r],selectedIds:i.length>0?i:r.map(a=>a.id)})),e().pushHistory()},convertElementType:(n,o)=>{const s=new Set(["rectangle","ellipse","diamond"]);s.has(o)&&(t(r=>({elements:r.elements.map(i=>{if(!n.includes(i.id)||!s.has(i.type)||i.type===o)return i;const l={...i,type:o};return o==="rectangle"?{...l,cornerRadius:0}:l})})),e().pushHistory())},bringToFront:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id)),r=o.elements.filter(i=>n.includes(i.id));return{elements:[...s,...r]}}),e().pushHistory()},sendToBack:n=>{t(o=>{const s=o.elements.filter(i=>!n.includes(i.id));return{elements:[...o.elements.filter(i=>n.includes(i.id)),...s]}}),e().pushHistory()},bringForward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=s.length-2;i>=0;i--)r.has(s[i].id)&&!r.has(s[i+1].id)&&([s[i],s[i+1]]=[s[i+1],s[i]]);return{elements:s}}),e().pushHistory()},sendBackward:n=>{t(o=>{const s=[...o.elements],r=new Set(n);for(let i=1;i<s.length;i++)r.has(s[i].id)&&!r.has(s[i-1].id)&&([s[i],s[i-1]]=[s[i-1],s[i]]);return{elements:s}}),e().pushHistory()},toggleLockElements:n=>{t(o=>({elements:o.elements.map(s=>n.includes(s.id)?{...s,isLocked:!s.isLocked}:s)})),e().pushHistory()},groupElements:n=>{if(n.length<2)return;const o=Pt(),s=new Set(n),{elements:r}=e();for(const i of r)if(s.has(i.id)&&i.boundElements)for(const l of i.boundElements)l.type==="text"&&s.add(l.id);t(i=>({elements:i.elements.map(l=>s.has(l.id)?{...l,groupIds:[...l.groupIds??[],o]}:l)})),e().pushHistory()},ungroupElements:n=>{var i;const{elements:o}=e(),s=o.filter(l=>n.includes(l.id)),r=new Set;for(const l of s)(i=l.groupIds)!=null&&i.length&&r.add(l.groupIds[l.groupIds.length-1]);r.size!==0&&(t(l=>({elements:l.elements.map(a=>{var d;if(!((d=a.groupIds)!=null&&d.length))return a;const c=a.groupIds.filter(h=>!r.has(h));return{...a,groupIds:c.length>0?c:void 0}})})),e().pushHistory())},setSelectedIds:n=>t({selectedIds:n}),clearSelection:()=>t({selectedIds:[]}),setActiveTool:n=>t(o=>({activeTool:n,selectedIds:n==="select"?o.selectedIds:[]})),setCurrentStyle:n=>t(o=>({currentStyle:{...o.currentStyle,...n}})),setCurrentLineType:n=>t({currentLineType:n}),setCurrentStartArrowhead:n=>t({currentStartArrowhead:n}),setCurrentEndArrowhead:n=>t({currentEndArrowhead:n}),setViewport:n=>{We(),t(o=>({viewport:{...o.viewport,...n}}))},zoomIn:(n,o)=>{const{viewport:s}=e(),r=Qs(s.scale),l=Wn({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},zoomOut:(n,o)=>{const{viewport:s}=e(),r=qs(s.scale),l=Wn({viewport:s,point:n??{x:400,y:300},targetScale:r});o!=null&&o.animate?Ee(s,l,a=>t(c=>({viewport:{...c.viewport,...a}}))):(We(),t({viewport:l}))},resetZoom:n=>{const{viewport:o}=e(),s={x:0,y:0,scale:1};n!=null&&n.animate?Ee(o,s,r=>t(i=>({viewport:{...i.viewport,...r}}))):(We(),t({viewport:s}))},zoomToFit:(n,o,s,r)=>{const{elements:i,viewport:l}=e(),a=s?i.filter(h=>s.includes(h.id)):i,c=Co(a);if(!c)return;const d=bo(c,n,o,{padding:r==null?void 0:r.padding,maxZoom:r==null?void 0:r.maxZoom});r!=null&&r.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},zoomToSelection:(n,o,s)=>{const{elements:r,selectedIds:i,viewport:l}=e();if(i.length===0)return;const a=r.filter(h=>i.includes(h.id)),c=Co(a);if(!c)return;const d=bo(c,n,o,{padding:(s==null?void 0:s.padding)??80,maxZoom:(s==null?void 0:s.maxZoom)??2});s!=null&&s.animate?Ee(l,d,h=>t(u=>({viewport:{...u.viewport,...h}}))):(We(),t({viewport:d}))},setIsDrawing:n=>t({isDrawing:n}),setDrawStart:n=>t({drawStart:n}),pushHistory:n=>{const{elements:o,_historyBaseline:s,_historyPaused:r}=e();if(r)return;const i=[],l=new Map;for(const a of o)l.set(a.id,a);for(const a of o){const c=s.get(a.id);c?c!==a&&i.push({type:"modify",elementId:a.id,before:ue(c),after:ue(a)}):i.push({type:"add",elementId:a.id,after:ue(a)})}for(const[a,c]of s)l.has(a)||i.push({type:"delete",elementId:a,before:ue(c)});i.length!==0&&t(a=>{const c=a.history.slice(0,a.historyIndex+1);return c.push({diffs:i,mark:n,timestamp:Date.now()}),c.length>Ll&&c.shift(),{history:c,historyIndex:c.length-1,_historyBaseline:new Map(l)}})},undo:()=>{const{historyIndex:n,history:o}=e();if(n<0)return;const s=o[n];t(r=>{let i=[...r.elements];for(let a=s.diffs.length-1;a>=0;a--){const c=s.diffs[a];switch(c.type){case"add":i=i.filter(d=>d.id!==c.elementId);break;case"modify":i=i.map(d=>d.id===c.elementId?ue(c.before):d);break;case"delete":i.push(ue(c.before));break}}const l=new Map;for(const a of i)l.set(a.id,a);return{historyIndex:n-1,elements:i,selectedIds:[],_historyBaseline:l}})},redo:()=>{const{historyIndex:n,history:o}=e();if(n>=o.length-1)return;const s=n+1,r=o[s];t(i=>{let l=[...i.elements];for(const c of r.diffs)switch(c.type){case"add":l.push(ue(c.after));break;case"modify":l=l.map(d=>d.id===c.elementId?ue(c.after):d);break;case"delete":l=l.filter(d=>d.id!==c.elementId);break}const a=new Map;for(const c of l)a.set(c.id,c);return{historyIndex:s,elements:l,selectedIds:[],_historyBaseline:a}})},squashHistory:(n=2)=>{t(o=>{if(o.history.length<n)return o;const s=Math.max(0,o.history.length-n),r=o.history.slice(s),i=new Map;for(const c of r)for(const d of c.diffs){const h=i.get(d.elementId);h?d.type==="delete"?h.type==="add"?i.delete(d.elementId):i.set(d.elementId,{type:"delete",elementId:d.elementId,before:h.before}):d.type==="modify"&&i.set(d.elementId,{type:h.type==="add"?"add":"modify",elementId:d.elementId,before:h.before,after:d.after}):i.set(d.elementId,{...d})}const l={diffs:Array.from(i.values()),mark:r[r.length-1].mark,timestamp:Date.now()},a=[...o.history.slice(0,s),l];return{history:a,historyIndex:a.length-1}})},pauseHistory:()=>t({_historyPaused:!0}),resumeHistory:()=>t({_historyPaused:!1}),canUndo:()=>e().historyIndex>=0,canRedo:()=>{const{historyIndex:n,history:o}=e();return n<o.length-1},toggleGrid:()=>t(n=>({showGrid:!n.showGrid}))})),mo={elementId:null,isEditing:!1,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1},dn=ws.create(t=>({...mo,enterEditMode:e=>t({elementId:e,isEditing:!0,selectedPointIndices:[],hoveredPointIndex:-1,hoveredMidpointIndex:null,isDraggingPoint:!1}),exitEditMode:()=>t({...mo}),setSelectedPoints:e=>t({selectedPointIndices:e}),togglePointSelection:e=>t(n=>({selectedPointIndices:n.selectedPointIndices.includes(e)?n.selectedPointIndices.filter(s=>s!==e):[...n.selectedPointIndices,e]})),setHoveredPoint:e=>t({hoveredPointIndex:e}),setHoveredMidpoint:e=>t({hoveredMidpointIndex:e}),setIsDraggingPoint:e=>t({isDraggingPoint:e}),reset:()=>t({...mo})}));function At(t,e){return Math.round(t/e)*e}function Fl(t,e){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function Ao(t,e){return{x:Math.min(t.x,e.x),y:Math.min(t.y,e.y),width:Math.abs(e.x-t.x),height:Math.abs(e.y-t.y)}}function tr(t,e,n){const o=Math.cos(n),s=Math.sin(n),r=t.x-e.x,i=t.y-e.y;return{x:e.x+r*o-i*s,y:e.y+r*s+i*o}}function Vl(t,e){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}function un(t,e){return[t/2,0,t,e/2,t/2,e,0,e/2]}function Pl(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.max(Math.abs(n),Math.abs(o)),r=n>=0?1:-1,i=o>=0?1:-1,l=r>=0?t.x:t.x-s,a=i>=0?t.y:t.y-s;return{x:l,y:a,width:s,height:s}}const er=[0,45,90,135,180,225,270,315,360],Yl=Math.PI/180;function Hl(t,e){const n=e.x-t.x,o=e.y-t.y,s=Math.sqrt(n*n+o*o);if(s===0)return{...e};let r=Math.atan2(o,n)*180/Math.PI;r<0&&(r+=360);let i=er[0],l=999;for(const c of er){const d=Math.abs(r-c);d<l&&(l=d,i=c)}i===360&&(i=0);const a=i*Yl;return{x:t.x+s*Math.cos(a),y:t.y+s*Math.sin(a)}}function Tn(t){let e=0,n=0,o=0,s=0;for(let r=0;r<t.length;r+=2)e=Math.min(e,t[r]),n=Math.max(n,t[r]),o=Math.min(o,t[r+1]),s=Math.max(s,t[r+1]);return{width:n-e,height:s-o}}function _t(t,e){switch(t){case"dashed":return[e*4,e*4];case"dotted":return[e,e*2];case"solid":default:return[]}}const zt=.2;function Jt(t,e,n=zt){const o=(t.x+e.x)/2,s=(t.y+e.y)/2,r=e.x-t.x,i=e.y-t.y,l=Math.sqrt(r*r+i*i);if(l===0)return{x:o,y:s};const a=-i/l,c=r/l,d=l*n;return{x:o+a*d,y:s+c*d}}function Ye(t,e,n,o){const s=1-o;return{x:s*s*t.x+2*s*o*e.x+o*o*n.x,y:s*s*t.y+2*s*o*e.y+o*o*n.y}}function wo(t,e,n,o){const s=1-o;return{x:2*s*(e.x-t.x)+2*o*(n.x-e.x),y:2*s*(e.y-t.y)+2*o*(n.y-e.y)}}function xo(t,e,n,o){if(o){const s=wo(t,e,n,1),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:n.x-s.x/r*20,y:n.y-s.y/r*20}}else{const s=wo(t,e,n,0),r=Math.sqrt(s.x*s.x+s.y*s.y)||1;return{x:t.x+s.x/r*20,y:t.y+s.y/r*20}}}function nr(t,e,n){const o=e.x-t.x,s=e.y-t.y,r=Math.sqrt(o*o+s*s);if(r===0)return zt;const i=-s/r,l=o/r,a=(t.x+e.x)/2,c=(t.y+e.y)/2,d=n.x-a,h=n.y-c;return 2*(d*i+h*l)/r}const Ol={name:"select",onMouseDown(t,e,n){t.target===t.target.getStage()&&(n.linearEdit.isEditing&&n.linearEdit.exitEditMode(),n.clearSelection(),n.setIsDrawing(!0),n.setDrawStart(e),n.setSelectionBox({x:e.x,y:e.y,width:0,height:0}))},onMouseMove(t,e,n){!n.isDrawing||!n.drawStart||n.setSelectionBox(Ao(n.drawStart,e))},onMouseUp(t){if(!t.isDrawing)return;const e=t.selectionBox;if(e&&(e.width>2||e.height>2)){const n=t.elements.filter(r=>{let i=r.x,l=r.y,a=r.width,c=r.height;if((r.type==="arrow"||r.type==="line")&&"points"in r){const p=r.points,y=[],m=[];for(let W=0;W<p.length;W+=2)y.push(r.x+p[W]),m.push(r.y+p[W+1]);i=Math.min(...y),l=Math.min(...m),a=Math.max(...y)-i,c=Math.max(...m)-l}const d=i+a,h=l+c,u=e.x+e.width,f=e.y+e.height;return i<u&&d>e.x&&l<f&&h>e.y}).map(r=>r.id),o=new Set(n),s=new Set;for(const r of n){const i=t.elements.find(l=>l.id===r);if(i!=null&&i.groupIds)for(const l of i.groupIds)s.add(l)}if(s.size>0){for(const r of t.elements)if(!o.has(r.id)&&r.groupIds){for(const i of r.groupIds)if(s.has(i)){o.add(r.id);break}}}t.setSelectedIds([...o])}t.setSelectionBox(null),t.setIsDrawing(!1),t.setDrawStart(null)}};let ko=!1;const Nl={name:"eraser",onMouseDown(t,e,n){var s;ko=!0;const o=t.target.id();o&&(n.deleteElements([o]),(s=n.onElementDelete)==null||s.call(n,[o]))},onMouseMove(t,e,n){var r,i;if(!ko)return;const o=t.target,s=(r=o.id)==null?void 0:r.call(o);s&&o!==o.getStage()&&(n.deleteElements([s]),(i=n.onElementDelete)==null||i.call(n,[s]))},onMouseUp(t){ko=!1},getCursor(){return"not-allowed"}},So={name:"rectangle",onMouseDown(t,e,n){var l;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt();n.currentElementIdRef.current=s;const r={id:s,type:n.activeTool,x:o.x,y:o.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null},i=n.activeTool==="rectangle"?{...r,type:"rectangle",cornerRadius:0}:r;B.getState().pauseHistory(),n.addElement(i),(l=n.onElementCreate)==null||l.call(n,i)},onMouseMove(t,e,n){if(!n.isDrawing||!n.drawStart||!n.currentElementIdRef.current)return;const o=n.snapPos(e),s=n.shiftKeyRef.current?Pl(n.drawStart,o):Ao(n.drawStart,o);n.updateElement(n.currentElementIdRef.current,s)},onMouseUp(t){B.getState().resumeHistory(),t.currentElementIdRef.current&&(t.setSelectedIds([t.currentElementIdRef.current]),t.pushHistory()),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},{PI:Ul}=Math,Kl=.275,gn=Ul+1e-4,or=13,zl=29,Jl=13,$l=3,Rl=.15,jl=.85,Ql=.01,ql=.25,sr=.5,rr=[1,1];function tc(t){return[-t[0],-t[1]]}function $t(t,e){return[t[0]+e[0],t[1]+e[1]]}function ir(t,e,n){return t[0]=e[0]+n[0],t[1]=e[1]+n[1],t}function ge(t,e){return[t[0]-e[0],t[1]-e[1]]}function vo(t,e,n){return t[0]=e[0]-n[0],t[1]=e[1]-n[1],t}function he(t,e){return[t[0]*e,t[1]*e]}function Eo(t,e,n){return t[0]=e[0]*n,t[1]=e[1]*n,t}function ec(t,e){return[t[0]/e,t[1]/e]}function lr(t){return[t[1],-t[0]]}function Wo(t,e){const n=e[0];return t[0]=e[1],t[1]=-n,t}function cr(t,e){return t[0]*e[0]+t[1]*e[1]}function nc(t,e){return t[0]===e[0]&&t[1]===e[1]}function oc(t){return Math.hypot(t[0],t[1])}function ar(t,e){const n=t[0]-e[0],o=t[1]-e[1];return n*n+o*o}function dr(t){return ec(t,oc(t))}function sc(t,e){return Math.hypot(t[1]-e[1],t[0]-e[0])}function To(t,e,n){const o=Math.sin(n),s=Math.cos(n),r=t[0]-e[0],i=t[1]-e[1];return[r*s-i*o+e[0],r*o+i*s+e[1]]}function ur(t,e,n,o){const s=Math.sin(o),r=Math.cos(o),i=e[0]-n[0],l=e[1]-n[1];return t[0]=i*r-l*s+n[0],t[1]=i*s+l*r+n[1],t}function gr(t,e,n){return $t(t,he(ge(e,t),n))}function rc(t,e,n,o){return t[0]=e[0]+(n[0]-e[0])*o,t[1]=e[1]+(n[1]-e[1])*o,t}function hr(t,e,n){return $t(t,he(e,n))}function fr(t,e,n){const o=Math.min(1,e/n),s=Math.min(1,1-o);return Math.min(1,t+(s-t)*(o*Kl))}function pr(t,e,n,o=s=>s){return t*o(.5-e*(.5-n))}const yr=[0,0];function Ir(t){return t!=null&&t>=0}function ic(t,e={}){var u;const{streamline:n=.5,size:o=16,last:s=!1}=e;if(t.length===0)return[];const r=Rl+(1-n)*jl;let i=t.map(({x:f,y:p,pressure:y=sr})=>[f,p,y]);if(i.length===2){const f=i[1];i=i.slice(0,-1);for(let p=1;p<5;p++)i.push([...gr(i[0],f,p/4)])}i.length===1&&(i=[...i,[...$t(i[0],rr),...i[0].slice(2)]]);const l=[{point:[i[0][0],i[0][1]],pressure:Ir(i[0][2])?i[0][2]:ql,vector:[...rr],distance:0,runningLength:0}];let a=!1,c=0,d=l[0];const h=i.length-1;for(let f=1;f<i.length;f++){const p=s&&f===h?[i[f][0],i[f][1]]:gr(d.point,i[f],r);if(nc(d.point,p))continue;const y=sc(p,d.point);if(c+=y,f<h&&!a){if(c<o)continue;a=!0}vo(yr,d.point,p),d={point:p,pressure:Ir(i[f][2])?i[f][2]:sr,vector:dr(yr),distance:y,runningLength:c},l.push(d)}return l[0].vector=((u=l[1])==null?void 0:u.vector)||[0,0],l}const Zt=[0,0],fe=[0,0],pe=[0,0];function lc(t,e){const n=$t(t,[1,1]),o=hr(t,dr(lr(ge(t,n))),-e),s=[],r=1/or;for(let i=r;i<=1;i+=r)s.push(To(o,t,gn*2*i));return s}function cc(t,e,n){const o=[],s=1/n;for(let r=s;r<=1;r+=s)o.push(To(e,t,gn*r));return o}function ac(t,e,n){const o=ge(e,n),s=he(o,.5),r=he(o,.51);return[ge(t,s),ge(t,r),$t(t,r),$t(t,s)]}function dc(t,e,n,o){const s=[],r=hr(t,e,n),i=1/o;for(let l=i;l<1;l+=i)s.push(To(r,t,gn*3*l));return s}function uc(t,e,n){return[$t(t,he(e,n)),$t(t,he(e,n*.99)),ge(t,he(e,n*.99)),ge(t,he(e,n))]}function Cr(t,e,n){return t===!1||t===void 0?0:t===!0?Math.max(e,n):t}function gc(t,e,n){return t.slice(0,10).reduce((o,s)=>{let r=s.pressure;return e&&(r=fr(o,s.distance,n)),(o+r)/2},t[0].pressure)}function hc(t,e={}){const{size:n=16,smoothing:o=.5,thinning:s=.5,simulatePressure:r=!0,easing:i=Z=>Z,start:l={},end:a={},last:c=!1}=e,{cap:d=!0,easing:h=Z=>Z*(2-Z)}=l,{cap:u=!0,easing:f=Z=>--Z*Z*Z+1}=a;if(t.length===0||n<=0)return[];const p=t[t.length-1].runningLength,y=Cr(l.taper,n,p),m=Cr(a.taper,n,p),W=Math.pow(n*o,2),v=[],D=[];let $=gc(t,r,n),T=pr(n,s,t[t.length-1].pressure,i),O,ot=t[0].vector,F=t[0].point,J=F,Y=F,Q=J,M=!1;for(let Z=0;Z<t.length;Z++){let{pressure:G}=t[Z];const{point:U,vector:X,distance:L,runningLength:at}=t[Z],tt=Z===t.length-1;if(!tt&&p-at<$l)continue;s?(r&&(G=fr($,L,n)),T=pr(n,s,G,i)):T=n/2,O===void 0&&(O=T);const E=at<y?h(at/y):1,V=p-at<m?f((p-at)/m):1;T=Math.max(Ql,T*Math.min(E,V));const dt=(tt?t[Z]:t[Z+1]).vector,R=tt?1:cr(X,dt),et=cr(X,ot)<0&&!M,Ct=R!==null&&R<0;if(et||Ct){Wo(Zt,ot),Eo(Zt,Zt,T);const bt=1/Jl;for(let rt=0;rt<=1;rt+=bt)vo(fe,U,Zt),ur(fe,fe,U,gn*rt),Y=[fe[0],fe[1]],v.push(Y),ir(pe,U,Zt),ur(pe,pe,U,gn*-rt),Q=[pe[0],pe[1]],D.push(Q);F=Y,J=Q,Ct&&(M=!0);continue}if(M=!1,tt){Wo(Zt,X),Eo(Zt,Zt,T),v.push(ge(U,Zt)),D.push($t(U,Zt));continue}rc(Zt,dt,X,R),Wo(Zt,Zt),Eo(Zt,Zt,T),vo(fe,U,Zt),Y=[fe[0],fe[1]],(Z<=1||ar(F,Y)>W)&&(v.push(Y),F=Y),ir(pe,U,Zt),Q=[pe[0],pe[1]],(Z<=1||ar(J,Q)>W)&&(D.push(Q),J=Q),$=G,ot=X}const k=[t[0].point[0],t[0].point[1]],C=t.length>1?[t[t.length-1].point[0],t[t.length-1].point[1]]:$t(t[0].point,[1,1]),w=[],S=[];if(t.length===1){if(!(y||m)||c)return lc(k,O||T)}else{y||m&&t.length===1||(d?w.push(...cc(k,D[0],or)):w.push(...ac(k,v[0],D[0])));const Z=lr(tc(t[t.length-1].vector));m||y&&t.length===1?S.push(C):u?S.push(...dc(C,Z,T,zl)):S.push(...uc(C,Z,T))}return v.concat(S,D.reverse(),w)}function fc(t,e={}){return hc(ic(t,e),e)}const Bn=(t,e)=>(t+e)/2;function pc(t,e=!0){const n=t.length;if(n<4)return"";let o=t[0],s=t[1];const r=t[2];let i=`M${o[0].toFixed(2)},${o[1].toFixed(2)} Q${s[0].toFixed(2)},${s[1].toFixed(2)} ${Bn(s[0],r[0]).toFixed(2)},${Bn(s[1],r[1]).toFixed(2)} T`;for(let l=2,a=n-1;l<a;l++)o=t[l],s=t[l+1],i+=`${Bn(o[0],s[0]).toFixed(2)},${Bn(o[1],s[1]).toFixed(2)} `;return e&&(i+="Z"),i}function Bo(t){let e=1/0,n=1/0,o=-1/0,s=-1/0;for(let r=0;r<t.length;r+=2){const i=t[r],l=t[r+1];i<e&&(e=i),i>o&&(o=i),l<n&&(n=l),l>s&&(s=l)}return isFinite(e)||(e=0,o=0,n=0,s=0),{minX:e,minY:n,maxX:o,maxY:s,width:Math.max(1,o-e),height:Math.max(1,s-n)}}function br(t,e,n={}){if(t.length<4)return"";const o=[];for(let r=0;r<t.length;r+=2)o.push({x:t[r],y:t[r+1],pressure:e&&e[r/2]!==void 0?e[r/2]:.5});const s=fc(o,n);return pc(s)}const yc=9,Ic={name:"freedraw",onMouseDown(t,e,n){var i;n.setIsDrawing(!0),n.setDrawStart(e),n.clearSelection();let o=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(o=t.evt.pressure===0?.5:t.evt.pressure);const s=Pt();n.currentElementIdRef.current=s;const r={id:s,type:"freedraw",x:e.x,y:e.y,width:1,height:1,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[e.x,e.y],pressures:[o],isComplete:!1};B.getState().pauseHistory(),n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r)},onMouseMove(t,e,n){if(!n.isDrawing||!n.currentElementIdRef.current)return;const o=n.elements.find(s=>s.id===n.currentElementIdRef.current);if(o){let s=.5;t.evt instanceof PointerEvent&&t.evt.pressure!==void 0&&(s=t.evt.pressure===0?.5:t.evt.pressure);const r=o.points;if(r.length>=2){const h=r[r.length-2],u=r[r.length-1],f=e.x-h,p=e.y-u;if(f*f+p*p<yc)return}const i=[...o.points,e.x,e.y],{minX:l,minY:a,width:c,height:d}=Bo(i);n.updateElement(o.id,{points:i,pressures:o.pressures?[...o.pressures,s]:[s],isComplete:!1,x:l,y:a,width:c,height:d})}},onMouseUp(t){if(t.currentElementIdRef.current){const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const{minX:n,minY:o,width:s,height:r}=Bo(e.points);t.updateElement(e.id,{x:n,y:o,width:s,height:r,points:e.points.map((i,l)=>l%2===0?i-n:i-o),isComplete:!0})}B.getState().resumeHistory(),t.pushHistory()}t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null},getCursor(){return"crosshair"}},Cc={name:"text",onMouseDown(t,e,n){var i;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt(),r={id:s,type:"text",x:o.x,y:o.y,width:10,height:30,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:null,textAlign:"left",verticalAlign:"top"};n.addElement(r),(i=n.onElementCreate)==null||i.call(n,r),n.setSelectedIds([s]),n.setActiveTool("select"),n.setIsDrawing(!1),n.setAutoEditTextId(s)},onMouseMove(){},onMouseUp(){},getCursor(){return"text"}},bc=800,mc=600;function Zn(t){return new Promise((e,n)=>{const o=new FileReader;o.onload=()=>e(o.result),o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function hn(t){return new Promise((e,n)=>{const o=new Image;o.crossOrigin="anonymous",o.onload=()=>e(o),o.onerror=()=>n(new Error("Failed to load image")),o.src=t})}function mr(t,e,n=bc,o=mc){if(t<=n&&e<=o)return{width:t,height:e};const s=t/e,r=n/o;return s>r?{width:n,height:n/s}:{width:o*s,height:o}}function _n(t,e,n,o,s,r={...wn}){const i=mr(e,n);return{id:Pt(),type:"image",x:o-i.width/2,y:s-i.height/2,width:i.width,height:i.height,rotation:0,style:{...r,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,src:t,naturalWidth:e,naturalHeight:n,scaleMode:"stretch",crop:null,cornerRadius:0,alt:""}}function Zo(t){const e=[];if(t.files)for(let n=0;n<t.files.length;n++){const o=t.files[n];o.type.startsWith("image/")&&e.push(o)}return e}function _o(t){const e=t.clipboardData;if(!e)return{file:null,imgUrl:null};const n=Zo(e);if(n.length>0)return{file:n[0],imgUrl:null};const o=e.getData("text/html");if(o){const s=o.match(/<img[^>]+src=["']([^"']+)["']/i);if(s!=null&&s[1])return{file:null,imgUrl:s[1]}}return{file:null,imgUrl:null}}function Ac(t){const{file:e,imgUrl:n}=_o(t);return e!==null||n!==null}async function Ar(t){if(t.file)return Zn(t.file);if(t.imgUrl)try{const e=await hn(t.imgUrl),n=document.createElement("canvas");n.width=e.naturalWidth,n.height=e.naturalHeight;const o=n.getContext("2d");if(o)return o.drawImage(e,0,0),n.toDataURL("image/png")}catch{return t.imgUrl}return null}function wr(){return new Promise(t=>{const e=document.createElement("input");e.type="file",e.accept="image/*",e.multiple=!0,e.style.display="none",e.onchange=()=>{const n=[];if(e.files)for(let o=0;o<e.files.length;o++)n.push(e.files[o]);t(n),document.body.removeChild(e)},e.oncancel=()=>{t([]),document.body.removeChild(e)},document.body.appendChild(e),e.click()})}const wc={name:"image",onMouseDown(t,e,n){n.setIsDrawing(!1);const o=n.snapPos(e);n.clearSelection(),wr().then(async s=>{var r;for(const i of s)try{const l=await Zn(i),a=await hn(l),c=_n(l,a.naturalWidth,a.naturalHeight,o.x,o.y,{...n.currentStyle});n.addElement(c),(r=n.onElementCreate)==null||r.call(n,c),n.setSelectedIds([c.id]),n.pushHistory()}catch{}n.setActiveTool("select")})},onMouseMove(){},onMouseUp(){},getCursor(){return"copy"}};let Mn=null,He;const xr={name:"line",onMouseDown(t,e,n){var p;n.setIsDrawing(!0);const o=n.snapPos(e);n.setDrawStart(o),n.clearSelection();const s=Pt();n.currentElementIdRef.current=s;const r=ce(n.currentStyle.strokeWidth??2),i=ke(e,n.elements,24,void 0,void 0,void 0,r);let l=e,a=null;He=void 0,i?(l=i.position,a={elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}):l=o,n.startBindingRef.current=a,B.getState().pauseHistory();const c={id:s,x:l.x,y:l.y,width:0,height:0,rotation:0,style:{...n.currentStyle},isLocked:!1,isVisible:!0,boundElements:null,points:[0,0,0,0],startBinding:a,endBinding:null},{currentLineType:d,currentStartArrowhead:h,currentEndArrowhead:u}=B.getState(),f=n.activeTool==="arrow"?{...c,type:"arrow",startArrowhead:h,endArrowhead:u,lineType:d}:{...c,type:"line",lineType:d};n.addElement(f),(p=n.onElementCreate)==null||p.call(n,f)},onMouseMove(t,e,n){if(!n.isDrawing){const h=ce(n.currentStyle.strokeWidth??2),u=ke(e,n.elements,24,void 0,void 0,void 0,h);n.setSnapTarget(u);return}if(!n.currentElementIdRef.current)return;const o=n.elements.find(h=>h.id===n.currentElementIdRef.current);if(!o)return;Mn=e;const s=new Set([o.id]);o.startBinding&&s.add(o.startBinding.elementId);const r=ce(o.style.strokeWidth??2),i=ke(e,n.elements,24,s,{x:o.x,y:o.y},void 0,r,He);n.setSnapTarget(i),He=i==null?void 0:i.isPrecise;let l=i?i.position:n.snapPos(e);!i&&n.shiftKeyRef.current&&(l=Hl({x:o.x,y:o.y},l));const a=i?{elementId:i.elementId,fixedPoint:i.fixedPoint,gap:r,isPrecise:i.isPrecise}:null,c=l.x-o.x,d=l.y-o.y;if(o.startBinding){const h=n.elements.find(u=>u.id===o.startBinding.elementId);if(h){let u;o.startBinding.isPrecise?u=ae(h,o.startBinding.fixedPoint,o.startBinding.gap):u=de(h,l,o.startBinding.gap);const f=l.x-u.x,p=l.y-u.y;n.updateElement(o.id,{x:u.x,y:u.y,points:[0,0,f,p],width:Math.abs(f),height:Math.abs(p),endBinding:a});return}}n.updateElement(o.id,{points:[0,0,c,d],width:Math.abs(c),height:Math.abs(d),endBinding:a})},onMouseUp(t){if(!t.currentElementIdRef.current)return;const e=t.elements.find(n=>n.id===t.currentElementIdRef.current);if(e){const n=e.points;if(Math.sqrt((n[n.length-2]-n[0])**2+(n[n.length-1]-n[1])**2)<2)B.getState().resumeHistory(),t.deleteElements([t.currentElementIdRef.current]),t.currentElementIdRef.current=null,t.startBindingRef.current=null,t.setSnapTarget(null),Mn=null,He=void 0;else{const s=Mn??{x:e.x+n[n.length-2],y:e.y+n[n.length-1]},r=new Set([e.id]);e.startBinding&&r.add(e.startBinding.elementId);const i=ce(e.style.strokeWidth??2),l=ke(s,t.elements,24,r,void 0,void 0,i,He),a=ce(e.style.strokeWidth??2),c=l?{elementId:l.elementId,fixedPoint:l.fixedPoint,gap:a,isPrecise:l.isPrecise}:null,d=e.startBinding??t.startBindingRef.current,h=c&&d&&c.elementId===d.elementId?null:c,u=[...n];l&&(u[u.length-2]=l.position.x-e.x,u[u.length-1]=l.position.y-e.y);const f={points:u,width:Math.abs(u[u.length-2]-u[0]),height:Math.abs(u[u.length-1]-u[1]),startBinding:d,endBinding:h},p={...e,...f},y=Se(p,t.elements);y&&Object.assign(f,y),t.updateElement(e.id,f);const m=e.type,W=B.getState().elements;ve(e.id,m,null,d,W,t.updateElement);const v=B.getState().elements;ve(e.id,m,null,h,v,t.updateElement),t.startBindingRef.current=null,t.setSnapTarget(null),t.setSelectedIds([t.currentElementIdRef.current]),B.getState().resumeHistory(),t.pushHistory()}}Mn=null,He=void 0,B.getState().resumeHistory(),t.setIsDrawing(!1),t.setDrawStart(null),t.currentElementIdRef.current=null,t.setActiveTool("select")},getCursor(){return"crosshair"}},xc={select:Ol,rectangle:So,ellipse:So,diamond:So,line:xr,arrow:xr,freedraw:Ic,text:Cc,image:wc,eraser:Nl};function fn(t){return xc[t]}function ye(t){const e=typeof t=="number"?String(t):t;let n=0,o=0,s=0,r=0;function i(){const l=n^n<<11;return n=o,o=s,s=r,r^=(r>>>19^l^l>>>8)>>>0,r/4294967296*2}for(let l=0;l<e.length+64;l++)n^=e.charCodeAt(l)|0,i();return i}function pn(t,e){if(t===0)return 0;const n=t===1?.8:1.5,o=e*(t===1?.4:.8);return Math.max(n,o)}function kr(t,e){return t===0?0:Math.max(e*(t===1?1.2:2),t===1?1.5:3)}function kc(t,e,n,o){const s=n-t,r=o-e;return Math.sqrt(s*s+r*r)}function Sc(t,e,n,o){const s=t*n+e*o,r=Math.sqrt(t*t+e*e),i=Math.sqrt(n*n+o*o);return r<1e-6||i<1e-6?0:Math.acos(Math.max(-1,Math.min(1,s/(r*i))))}function vc(t,e,n,o,s,r,i,l=!0){const a=o-e,c=s-n,d=Math.sqrt(a*a+c*c);if(d<.5){l&&t.moveTo(e,n),t.lineTo(o,s);return}const h=-c/d,u=a/d,f=Math.min(r,d*.25),p=f*.15,y=e+i()*p,m=n+i()*p,W=o+i()*p,v=s+i()*p,D=y+a*.33+h*i()*f,$=m+c*.33+u*i()*f,T=y+a*.67+h*i()*f,O=m+c*.67+u*i()*f;l&&t.moveTo(y,m),t.bezierCurveTo(D,$,T,O,W,v)}function Sr(t,e,n,o,s){const r=e.length;if(r<3)return;const i=[];for(let l=0;l<r;l++){const[a,c]=e[l],[d,h]=e[(l+1)%r];i.push(kc(a,c,d,h))}for(let l=0;l<r;l++){const a=e[(l-1+r)%r],c=e[l],d=e[(l+1)%r],h=i[(l-1+r)%r],u=i[l],f=c[0]-a[0],p=c[1]-a[1],y=d[0]-c[0],m=d[1]-c[1],v=1-Sc(-f,-p,y,m)/Math.PI;let D=o*v;const $=Math.min(h,u);D=Math.min(D,$*.4),D=Math.max(D,0);const T=h>1e-6?D/h:0,O=u>1e-6?D/u:0,ot=c[0]-f*T,F=c[1]-p*T,J=c[0]+y*O,Y=c[1]+m*O,Q=ot+s()*n,M=F+s()*n,k=J+s()*n,C=Y+s()*n,w=c[0]+s()*n,S=c[1]+s()*n;l===0?t.moveTo(Q,M):t.lineTo(Q,M),D>.5?t.quadraticCurveTo(w,S,k,C):t.lineTo(k,C)}t.closePath()}function Oe(t){return t>=2?2:1}function Ec(t,e,n,o,s,r,i,l=1,a=2){const c=pn(r,a),d=kr(r,a),h=[[e,n],[e+o,n],[e+o,n+s],[e,n+s]];for(let u=0;u<l;u++)t.beginPath(),Sr(t,h,c,d,i)}function Wc(t,e,n,o,s,r,i,l=1,a=2){const c=pn(r,a),d=Math.PI*2*Math.sqrt((o*o+s*s)/2),h=Math.max(16,Math.min(64,Math.floor(d*.08))),u=Math.PI*2/h,f=4/3*Math.tan(u/4);for(let p=0;p<l;p++){const y=[];for(let m=0;m<=h;m++){const W=m*u,v=i()*c*1.8;y.push({x:e+(o+v)*Math.cos(W),y:n+(s+v)*Math.sin(W),angle:W})}t.moveTo(y[0].x,y[0].y);for(let m=0;m<h;m++){const W=y[m],v=y[m+1],D=Math.cos(W.angle),$=Math.sin(W.angle),T=Math.cos(v.angle),O=Math.sin(v.angle),ot=-$,F=D,J=-O,Y=T;o+i()*c,s+i()*c;const Q=W.x+ot*o*f+i()*c*.8,M=W.y+F*s*f+i()*c*.8,k=v.x-J*o*f+i()*c*.8,C=v.y-Y*s*f+i()*c*.8;t.bezierCurveTo(Q,M,k,C,v.x,v.y)}}}function Tc(t,e,n,o,s,r=1,i=2){const l=pn(o,i),a=kr(o,i),c=[[e/2,0],[e,n/2],[e/2,n],[0,n/2]];for(let d=0;d<r;d++)t.beginPath(),Sr(t,c,l,a,s)}function Mo(t,e,n,o,s=1,r=2){if(e.length<4)return;const i=pn(n,r);for(let l=0;l<s;l++)for(let a=0;a<e.length-2;a+=2)vc(t,e[a],e[a+1],e[a+2],e[a+3],i,o,!0)}function vr(t,e,n,o,s,r,i=1,l=2){const a=pn(s,l),c=a*2;for(let d=0;d<i;d++){const h=e.x+r()*a*.6,u=e.y+r()*a*.6,f=o.x+r()*a*.6,p=o.y+r()*a*.6,y=n.x+r()*c,m=n.y+r()*c;t.moveTo(h,u),t.quadraticCurveTo(y,m,f,p)}}function Bc(t,e,n,o,s,r){const i=Math.min(r,o/2,s/2);t.beginPath(),t.moveTo(e+i,n),t.lineTo(e+o-i,n),t.arcTo(e+o,n,e+o,n+i,i),t.lineTo(e+o,n+s-i),t.arcTo(e+o,n+s,e+o-i,n+s,i),t.lineTo(e+i,n+s),t.arcTo(e,n+s,e,n+s-i,i),t.lineTo(e,n+i),t.arcTo(e,n,e+i,n,i),t.closePath()}const Zc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,cornerRadius:y,style:m,isLocked:W}=t,v=!W&&!n,D=m.roughness,$=I.useCallback(()=>o(c),[o,c]),T=I.useCallback(()=>i==null?void 0:i(c),[i,c]),O=I.useCallback(k=>{let C=k.target.x(),w=k.target.y();if(l&&(C=At(C,l),w=At(w,l),k.target.x(C),k.target.y(w)),!l&&a){const S=a(c,{x:C,y:w,width:u,height:f});S&&(C=S.x,w=S.y,k.target.x(C),k.target.y(w))}r==null||r(c,{x:C,y:w})},[c,l,u,f,r,a]),ot=I.useCallback(k=>{let C=k.target.x(),w=k.target.y();l&&(C=At(C,l),w=At(w,l)),s(c,{x:C,y:w})},[c,l,s]),F=I.useCallback(k=>{const C=k.target,w=C.scaleX(),S=C.scaleY(),Z=Math.max(5,C.width()*w),G=Math.max(5,C.height()*S);C.setAttrs({scaleX:1,scaleY:1,width:Z,height:G}),r==null||r(c,{x:C.x(),y:C.y(),width:Z,height:G})},[c,r]),J=I.useCallback(k=>{const C=k.target,w=Math.max(5,C.width()*C.scaleX()),S=Math.max(5,C.height()*C.scaleY());C.setAttrs({scaleX:1,scaleY:1,width:w,height:S}),s(c,{x:C.x(),y:C.y(),width:w,height:S,rotation:C.rotation()})},[c,s]),Y=e?Tt.color:void 0,Q=e?Tt.blur:0,M=e?Tt.opacity:0;if(D>0){const k=Oe(D),C=_t(m.strokeStyle,m.strokeWidth);return g.jsx(gt.Shape,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{y>0?Bc(w,0,0,u,f,y):(w.beginPath(),w.rect(0,0,u,f)),w.fillShape(S);for(let Z=0;Z<k;Z++){const G=ye(c+":"+Z);w.beginPath(),Ec(w,0,0,u,f,D,G,1,m.strokeWidth),w.strokeShape(S)}},fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:C,lineCap:"round",lineJoin:"round",draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:Y,shadowBlur:Q,shadowOpacity:M,onDragMove:O,onDragEnd:ot,onTransform:F,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Rect,{id:c,x:d,y:h,width:u,height:f,rotation:p,transformsEnabled:p?"all":"position",cornerRadius:y,fill:m.fillColor,stroke:m.strokeColor,strokeWidth:m.strokeWidth,opacity:m.opacity,dash:_t(m.strokeStyle,m.strokeWidth),draggable:v,onClick:$,onTap:$,onDblClick:T,onDblTap:T,shadowColor:Y,shadowBlur:Q,shadowOpacity:M,onDragMove:O,onDragEnd:ot,onTransform:F,onTransformEnd:J,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},_c=I.memo(Zc),Mc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:m}=t,W=!m&&!n,v=y.roughness,D=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l){const w=At(k-u/2,l),S=At(C-f/2,l);k=w+u/2,C=S+f/2,M.target.x(k),M.target.y(C)}if(!l&&a){const w=a(c,{x:k-u/2,y:C-f/2,width:u,height:f});w&&(k=w.x+u/2,C=w.y+f/2,M.target.x(k),M.target.y(C))}r==null||r(c,{x:k-u/2,y:C-f/2})},[c,l,u,f,r,a]),O=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l){const w=At(k-u/2,l),S=At(C-f/2,l);k=w+u/2,C=S+f/2}s(c,{x:k-u/2,y:C-f/2})},[c,l,u,f,s]),ot=I.useCallback(M=>{const k=M.target,C=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*C/2),Z=Math.max(5,f*w/2);k.setAttrs({scaleX:1,scaleY:1,radiusX:S,radiusY:Z});const G=S*2,U=Z*2;r==null||r(c,{x:k.x()-S,y:k.y()-Z,width:G,height:U})},[c,u,f,r]),F=I.useCallback(M=>{const k=M.target,C=k.getAttr("radiusX"),w=k.getAttr("radiusY");k.setAttrs({scaleX:1,scaleY:1});const S=Math.max(5,C*2),Z=Math.max(5,w*2);s(c,{x:k.x()-C,y:k.y()-w,width:S,height:Z,rotation:k.rotation()})},[c,s]),J=e?Tt.color:void 0,Y=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const M=Oe(v),k=u/2,C=f/2;return g.jsx(gt.Shape,{id:c,x:d+k,y:h+C,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(w,S)=>{w.beginPath(),w.ellipse(0,0,k,C,0,0,Math.PI*2),w.fillShape(S);for(let Z=0;Z<M;Z++){const G=ye(c+":"+Z);w.beginPath(),Wc(w,0,0,k,C,v,G,1,y.strokeWidth),w.strokeShape(S)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Ellipse,{id:c,x:d+u/2,y:h+f/2,radiusX:u/2,radiusY:f/2,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Gc=I.memo(Mc),Dc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,style:y,isLocked:m}=t,W=!m&&!n,v=y.roughness,D=I.useCallback(()=>o(c),[o,c]),$=I.useCallback(()=>i==null?void 0:i(c),[i,c]),T=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();if(l&&(k=At(k,l),C=At(C,l),M.target.x(k),M.target.y(C)),!l&&a){const w=a(c,{x:k,y:C,width:u,height:f});w&&(k=w.x,C=w.y,M.target.x(k),M.target.y(C))}r==null||r(c,{x:k,y:C})},[c,l,u,f,r,a]),O=I.useCallback(M=>{let k=M.target.x(),C=M.target.y();l&&(k=At(k,l),C=At(C,l)),s(c,{x:k,y:C})},[c,l,s]),ot=I.useCallback(M=>{const k=M.target,C=k.scaleX(),w=k.scaleY(),S=Math.max(5,u*C),Z=Math.max(5,f*w);k.setAttrs({scaleX:1,scaleY:1,points:un(S,Z)}),r==null||r(c,{x:k.x(),y:k.y(),width:S,height:Z})},[c,u,f,r]),F=I.useCallback(M=>{const k=M.target;k.setAttrs({scaleX:1,scaleY:1});const C=k.getAttr("points"),w=C?C[2]:u,S=C?C[5]:f;s(c,{x:k.x(),y:k.y(),width:Math.max(5,w),height:Math.max(5,S),rotation:k.rotation()})},[c,u,f,s]),J=e?Tt.color:void 0,Y=e?Tt.blur:0,Q=e?Tt.opacity:0;if(v>0){const M=Oe(v),k=_t(y.strokeStyle,y.strokeWidth);return g.jsx(gt.Shape,{id:c,x:d,y:h,rotation:p,transformsEnabled:p?"all":"position",sceneFunc:(C,w)=>{const S=un(u,f);C.beginPath(),C.moveTo(S[0],S[1]);for(let Z=2;Z<S.length;Z+=2)C.lineTo(S[Z],S[Z+1]);C.closePath(),C.fillShape(w);for(let Z=0;Z<M;Z++){const G=ye(c+":"+Z);C.beginPath(),Tc(C,u,f,v,G,1,y.strokeWidth),C.strokeShape(w)}},fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:k,lineCap:"round",lineJoin:"round",draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}return g.jsx(gt.Line,{id:c,x:d,y:h,points:un(u,f),closed:!0,rotation:p,transformsEnabled:p?"all":"position",fill:y.fillColor,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),draggable:W,onClick:D,onTap:D,onDblClick:$,onDblTap:$,shadowColor:J,shadowBlur:Y,shadowOpacity:Q,onDragMove:T,onDragEnd:O,onTransform:ot,onTransformEnd:F,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Xc=I.memo(Dc),Lc=new Set(["rectangle","ellipse","diamond","text","image"]);function Er(t){const e=I.useRef(t??[]);return e.current=t??[],{fingerprint:I.useMemo(()=>{if(!t||t.length===0)return"";const o=r=>Math.round(r*2)/2,s=[];for(const r of t)Lc.has(r.type)&&r.isVisible&&s.push(`${r.id}:${o(r.x)},${o(r.y)},${o(r.width)},${o(r.height)},${o(r.rotation||0)}`);return s.join(";")},[t]),elementsRef:e}}function Fc(t){const e=t.indexOf(",");if(e===-1)throw new Error("Invalid data URL");const o=t.slice(5,e).endsWith(";base64"),s=t.slice(e+1);let r;if(o){const l=atob(s);r=new Uint8Array(l.length);for(let a=0;a<l.length;a++)r[a]=l.charCodeAt(a)}else{const l=decodeURIComponent(s);r=new TextEncoder().encode(l)}const i=new Blob([r],{type:"application/javascript"});return URL.createObjectURL(i)}function Gn(t,e){if(typeof Worker>"u"||e!=null&&e.disabled)return null;if(e!=null&&e.url)try{return new Worker(e.url,{type:"module"})}catch(n){return console.warn("[workerFactory] Failed to create worker from custom URL:",e.url,n),null}try{const n=typeof t=="function"?t():t,o=n instanceof URL?n.href:String(n);if(o.startsWith("data:")){const s=Fc(o);return new Worker(s)}return new Worker(n instanceof URL?n:new URL(o),{type:"module"})}catch(n){return console.warn("[workerFactory] Worker creation failed, using sync fallback:",n),null}}function Vc(){return typeof Worker<"u"&&typeof URL<"u"}function Pc(t){const e=new Array(t.length);for(let n=0;n<t.length;n++){const o=t[n];e[n]={id:o.id,type:o.type,x:o.x,y:o.y,width:o.width,height:o.height,rotation:o.rotation,isVisible:o.isVisible}}return e}const Wr=50;class Yc{constructor(e){ct(this,"worker",null);ct(this,"requestIdCounter",0);ct(this,"pending",new Map);ct(this,"cachedElements",[]);ct(this,"workerSupported",!0);ct(this,"workerConfig");ct(this,"handleMessage",e=>{const{type:n,requestId:o,points:s}=e.data;if(n==="routeResult"){const r=this.pending.get(o);r&&(this.pending.delete(o),r.timerId!==void 0&&clearTimeout(r.timerId),r.resolve(s))}});this.workerConfig=e}_getWorker(){if(!this.workerSupported)return null;if(this.worker)return this.worker;try{return this.worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGVsYm93V29ya2VyLnRzIOKAlCBXZWIgV29ya2VyIGZvciBvZmYtbWFpbi10aHJlYWQgZWxib3cgY29ubmVjdG9yIHJvdXRpbmcuCiAqCiAqIFJ1bnMgdGhlIGV4cGVuc2l2ZSBBKiBncmlkLXNlYXJjaCBhbGdvcml0aG0gaW4gYSBiYWNrZ3JvdW5kIHRocmVhZCBzbwogKiB0aGUgbWFpbiB0aHJlYWQgc3RheXMgYXQgNjBmcHMgZHVyaW5nIGludGVuc2l2ZSBkcmFnIG9wZXJhdGlvbnMgdGhhdAogKiB0cmlnZ2VyIG1hbnkgc2ltdWx0YW5lb3VzIHJvdXRlIHJlY29tcHV0YXRpb25zLgogKgogKiBDb21tdW5pY2F0aW9uIHByb3RvY29sOgogKiAgIE1haW4g4oaSIFdvcmtlcjoKICogICAgIHsgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJywgZWxlbWVudHM6IFNlcmlhbGl6ZWRFbGVtZW50W10gfQogKiAgICAgeyB0eXBlOiAnY29tcHV0ZVJvdXRlJywgcmVxdWVzdElkLCBwYXJhbXM6IFJvdXRlUGFyYW1zIH0KICogICBXb3JrZXIg4oaSIE1haW46CiAqICAgICB7IHR5cGU6ICdyb3V0ZVJlc3VsdCcsIHJlcXVlc3RJZCwgcG9pbnRzOiBudW1iZXJbXSB9CiAqCiAqIFVzZXMgVml0ZSdzIG5hdGl2ZSBXb3JrZXIgbW9kdWxlIHN1cHBvcnQg4oCUIGltcG9ydGVkIHdpdGg6CiAqICAgbmV3IFdvcmtlcihuZXcgVVJMKCcuL2VsYm93V29ya2VyLnRzJywgaW1wb3J0Lm1ldGEudXJsKSwgeyB0eXBlOiAnbW9kdWxlJyB9KQogKi8KCi8vIE5PVEU6IFdlIGltcG9ydCB0aGUgZnVsbCBlbGJvdyBtb2R1bGUgaGVyZS4gIFZpdGUgYnVuZGxlcyBpdCBpbnRvIHRoZQovLyBXb3JrZXIgY2h1bmsgYXV0b21hdGljYWxseS4gIFRoZSBgQC9gIHBhdGggYWxpYXMgaXMgcmVzb2x2ZWQgYnkgVml0ZS4KaW1wb3J0IHsgY29tcHV0ZUVsYm93UG9pbnRzLCBzaW1wbGlmeUVsYm93UGF0aCB9IGZyb20gJ0AvdXRpbHMvZWxib3cnOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQsIEJpbmRpbmcsIFBvaW50IH0gZnJvbSAnQC90eXBlcyc7CgovLyDilIDilIDilIAgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgU2VyaWFsaXplZEVsZW1lbnQgewogICAgaWQ6IHN0cmluZzsKICAgIHR5cGU6IHN0cmluZzsKICAgIHg6IG51bWJlcjsKICAgIHk6IG51bWJlcjsKICAgIHdpZHRoOiBudW1iZXI7CiAgICBoZWlnaHQ6IG51bWJlcjsKICAgIHJvdGF0aW9uOiBudW1iZXI7CiAgICBpc1Zpc2libGU6IGJvb2xlYW47CiAgICAvLyBNaW5pbWFsIGZpZWxkcyBuZWVkZWQgZm9yIG9ic3RhY2xlIGRldGVjdGlvbiDigJQgc3R5bGUsIHRleHQsIGV0Yy4gYXJlIG9taXR0ZWQuCiAgICAvLyBXZSByZWNvbnN0cnVjdCBhICJwc2V1ZG8tQ2FudmFzRWxlbWVudCIgZnJvbSB0aGVzZSBmaWVsZHMuCn0KCmludGVyZmFjZSBSb3V0ZVBhcmFtcyB7CiAgICBzdGFydFdvcmxkOiBQb2ludDsKICAgIGVuZFdvcmxkOiBQb2ludDsKICAgIHN0YXJ0QmluZGluZzogQmluZGluZyB8IG51bGw7CiAgICBlbmRCaW5kaW5nOiBCaW5kaW5nIHwgbnVsbDsKICAgIG1pblN0dWJMZW5ndGg/OiBudW1iZXI7Cn0KCmludGVyZmFjZSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgewogICAgdHlwZTogJ3VwZGF0ZUVsZW1lbnRzJzsKICAgIGVsZW1lbnRzOiBTZXJpYWxpemVkRWxlbWVudFtdOwp9CgppbnRlcmZhY2UgQ29tcHV0ZVJvdXRlTWVzc2FnZSB7CiAgICB0eXBlOiAnY29tcHV0ZVJvdXRlJzsKICAgIHJlcXVlc3RJZDogbnVtYmVyOwogICAgcGFyYW1zOiBSb3V0ZVBhcmFtczsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBVcGRhdGVFbGVtZW50c01lc3NhZ2UgfCBDb21wdXRlUm91dGVNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBzdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCi8qKiBMaWdodHdlaWdodCBlbGVtZW50IHByb3hpZXMgdXNlZCBmb3Igb2JzdGFjbGUgZGV0ZWN0aW9uIGluIHJvdXRpbmcgKi8KbGV0IGNhY2hlZEVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gPSBbXTsKCi8qKgogKiBSZWNvbnN0cnVjdCBtaW5pbWFsIENhbnZhc0VsZW1lbnQtc2hhcGVkIG9iamVjdHMgZnJvbSBzZXJpYWxpemVkIGRhdGEuCiAqIE9ubHkgdGhlIGZpZWxkcyB1c2VkIGJ5IGNvbXB1dGVFbGJvd1BvaW50cyBhcmUgbmVlZGVkOgogKiAgIGlkLCB0eXBlLCB4LCB5LCB3aWR0aCwgaGVpZ2h0LCByb3RhdGlvbiwgaXNWaXNpYmxlCiAqLwpmdW5jdGlvbiBkZXNlcmlhbGl6ZUVsZW1lbnRzKHNlcmlhbGl6ZWQ6IFNlcmlhbGl6ZWRFbGVtZW50W10pOiBDYW52YXNFbGVtZW50W10gewogICAgLy8gQ2FzdCBpcyBzYWZlIGJlY2F1c2UgY29tcHV0ZUVsYm93UG9pbnRzIG9ubHkgcmVhZHMgc3BhdGlhbCBmaWVsZHMKICAgIC8vIGFuZCBjaGVja3MgYHR5cGVgIG1lbWJlcnNoaXAgaW4gT0JTVEFDTEVfVFlQRVMgc2V0LgogICAgcmV0dXJuIHNlcmlhbGl6ZWQgYXMgdW5rbm93biBhcyBDYW52YXNFbGVtZW50W107Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIGhhbmRsZXIg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpzZWxmLm9ubWVzc2FnZSA9IChlOiBNZXNzYWdlRXZlbnQ8SW5jb21pbmdNZXNzYWdlPikgPT4gewogICAgY29uc3QgbXNnID0gZS5kYXRhOwoKICAgIGlmIChtc2cudHlwZSA9PT0gJ3VwZGF0ZUVsZW1lbnRzJykgewogICAgICAgIGNhY2hlZEVsZW1lbnRzID0gZGVzZXJpYWxpemVFbGVtZW50cyhtc2cuZWxlbWVudHMpOwogICAgICAgIHJldHVybjsKICAgIH0KCiAgICBpZiAobXNnLnR5cGUgPT09ICdjb21wdXRlUm91dGUnKSB7CiAgICAgICAgY29uc3QgeyByZXF1ZXN0SWQsIHBhcmFtcyB9ID0gbXNnOwogICAgICAgIHRyeSB7CiAgICAgICAgICAgIGNvbnN0IHJhdyA9IGNvbXB1dGVFbGJvd1BvaW50cygKICAgICAgICAgICAgICAgIHBhcmFtcy5zdGFydFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLmVuZFdvcmxkLAogICAgICAgICAgICAgICAgcGFyYW1zLnN0YXJ0QmluZGluZywKICAgICAgICAgICAgICAgIHBhcmFtcy5lbmRCaW5kaW5nLAogICAgICAgICAgICAgICAgY2FjaGVkRWxlbWVudHMsCiAgICAgICAgICAgICAgICBwYXJhbXMubWluU3R1Ykxlbmd0aCwKICAgICAgICAgICAgKTsKICAgICAgICAgICAgY29uc3Qgc2ltcGxpZmllZCA9IHNpbXBsaWZ5RWxib3dQYXRoKHJhdyk7CiAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UoeyB0eXBlOiAncm91dGVSZXN1bHQnLCByZXF1ZXN0SWQsIHBvaW50czogc2ltcGxpZmllZCB9KTsKICAgICAgICB9IGNhdGNoIHsKICAgICAgICAgICAgLy8gT24gZXJyb3IsIHJldHVybiBhIHN0cmFpZ2h0IGxpbmUgZmFsbGJhY2sKICAgICAgICAgICAgc2VsZi5wb3N0TWVzc2FnZSh7CiAgICAgICAgICAgICAgICB0eXBlOiAncm91dGVSZXN1bHQnLAogICAgICAgICAgICAgICAgcmVxdWVzdElkLAogICAgICAgICAgICAgICAgcG9pbnRzOiBbMCwgMCwgcGFyYW1zLmVuZFdvcmxkLnggLSBwYXJhbXMuc3RhcnRXb3JsZC54LCBwYXJhbXMuZW5kV29ybGQueSAtIHBhcmFtcy5zdGFydFdvcmxkLnldLAogICAgICAgICAgICB9KTsKICAgICAgICB9CiAgICB9Cn07Cg==",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this.workerConfig),this.worker?(this.worker.onmessage=this.handleMessage,this.worker.onerror=()=>{this.workerSupported=!1,this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker failed"));this.pending.clear()},this.worker):(this.workerSupported=!1,null)}catch{return this.workerSupported=!1,null}}updateElements(e){this.cachedElements=e;const n=this._getWorker();n&&e.length>=Wr&&n.postMessage({type:"updateElements",elements:Pc(e)})}async computeRoute(e){const n=this._getWorker();if(!n||this.cachedElements.length<Wr)return this.computeSync(e);const o=++this.requestIdCounter;return new Promise((s,r)=>{const i=setTimeout(()=>{this.pending.has(o)&&(this.pending.delete(o),s(this.computeSync(e)))},100);this.pending.set(o,{resolve:s,reject:r,timerId:i}),n.postMessage({type:"computeRoute",requestId:o,params:e})})}computeSync(e){const n=on(e.startWorld,e.endWorld,e.startBinding,e.endBinding,this.cachedElements,e.minStubLength);return sn(n)}dispose(){this.worker&&(this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.timerId!==void 0&&clearTimeout(e.timerId),e.reject(new Error("Worker disposed"));this.pending.clear()}get isWorkerActive(){return this.workerSupported}}let ne=null,Go;function Do(t){return ne&&t&&JSON.stringify(t)!==JSON.stringify(Go)&&(ne.dispose(),ne=null),ne||(Go=t,ne=new Yc(t)),ne}function Tr(){ne&&(ne.dispose(),ne=null,Go=void 0)}const Xo=I.createContext(void 0);function Br(){return I.useContext(Xo)}function Zr(t,e,n,o){const[s,r]=I.useState(null),i=I.useRef(n),l=Br(),a=l==null?void 0:l.elbowWorkerConfig;return i.current=n,I.useEffect(()=>{Do(a).updateElements(n)},[o,a]),I.useEffect(()=>()=>{},[]),I.useEffect(()=>{if(!t){r(null);return}const c=Do(a);let d=!1;const h={startWorld:e.startWorld,endWorld:e.endWorld,startBinding:e.startBinding,endBinding:e.endBinding,minStubLength:e.minStubLength};if(c.isWorkerActive)c.computeRoute(h).then(u=>{d||r(u)});else{const u=on(e.startWorld,e.endWorld,e.startBinding,e.endBinding,i.current,e.minStubLength),f=sn(u);r(f)}return()=>{d=!0}},[t,e.startWorld.x,e.startWorld.y,e.endWorld.x,e.endWorld.y,e.startBinding,e.endBinding,e.minStubLength,o]),s}const Hc=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:m,endBinding:W,lineType:v,isLocked:D}=t,$=!D&&!o,T=I.useRef(null),O=y.roughness,ot=v==="curved",F=v==="elbow",{fingerprint:J,elementsRef:Y}=Er(c),Q=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),M=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),k=Zr(F,{startWorld:Q,endWorld:M,startBinding:m,endBinding:W},c??[],J),C=I.useMemo(()=>{if(!F)return f;const R=on(Q,M,m,W,Y.current);return sn(R)},[F,h,u,f,m,W,J]),w=F?k??C:f,S=I.useMemo(()=>{if(!F)return f;const R=[...w],K=f[0],et=f[1];if(K!==0||et!==0)for(let Ct=0;Ct<R.length;Ct+=2)R[Ct]+=K,R[Ct+1]+=et;return R},[F,w,f]),Z=I.useMemo(()=>{if(!ot)return null;const R={x:f[0],y:f[1]},K={x:f[f.length-2],y:f[f.length-1]},et=Jt(R,K,t.curvature??zt);return{start:R,end:K,cp:et}},[ot,f,t.curvature]),G=I.useCallback(()=>s(d),[s,d]),U=I.useCallback(()=>l==null?void 0:l(d),[l,d]),X=I.useCallback(R=>{let K=R.target.x(),et=R.target.y();a&&(K=At(K,a),et=At(et,a),R.target.x(K),R.target.y(et)),i==null||i(d,{x:K,y:et})},[d,a,i]),L=I.useCallback(R=>{let K=R.target.x(),et=R.target.y();a&&(K=At(K,a),et=At(et,a)),r(d,{x:K,y:et})},[d,a,r]),at=I.useCallback(R=>{const K=R.target,et=K.scaleX(),Ct=K.scaleY();K.setAttrs({scaleX:1,scaleY:1});const bt=f.map((st,pt)=>pt%2===0?st*et:st*Ct),rt=Tn(bt);r(d,{x:K.x(),y:K.y(),points:bt,rotation:K.rotation(),width:rt.width,height:rt.height})},[d,f,r]),tt=Oe(O),E=e?Tt.color:void 0,V=e?Tt.blur:0,dt=e?Tt.opacity:0;return g.jsx(gt.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:G,onTap:G,onDblClick:U,onDblTap:U,onDragMove:X,onDragEnd:L,onTransformEnd:at,children:F?g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:S,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:S,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]}):ot?g.jsx(gt.Shape,{sceneFunc:(R,K)=>{if(Z){if(R.beginPath(),O>0){const et=ye(d);vr(R,Z.start,Z.cp,Z.end,O,et,tt,y.strokeWidth)}else R.moveTo(Z.start.x,Z.start.y),R.quadraticCurveTo(Z.cp.x,Z.cp.y,Z.end.x,Z.end.y);R.fillStrokeShape(K)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):O>0?g.jsx(gt.Shape,{sceneFunc:(R,K)=>{const et=ye(d);R.beginPath(),Mo(R,f,O,et,tt,y.strokeWidth),R.fillStrokeShape(K)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:E,shadowBlur:V,shadowOpacity:dt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:E,shadowBlur:V,shadowOpacity:dt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})]})})},Oc=I.memo(Hc);function Nc(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function Uc(t){return{x:-t.y,y:t.x}}function Lo(t){return Math.max(10,t*4)}function oe(t,e,n,o,s,r,i){const l=Nc(n,o),a=Uc(l),c=s*.45,d=t._context;switch(d.save(),d.strokeStyle=r,d.fillStyle=r,d.lineWidth=i,d.lineJoin="round",d.lineCap="round",e){case"arrow":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(h.x,h.y),d.lineTo(n.x,n.y),d.lineTo(u.x,u.y),d.stroke();break}case"triangle":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"triangle_outline":{const h={x:n.x-l.x*s+a.x*c,y:n.y-l.y*s+a.y*c},u={x:n.x-l.x*s-a.x*c,y:n.y-l.y*s-a.y*c};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(h.x,h.y),d.lineTo(u.x,u.y),d.closePath(),d.fill(),d.stroke();break}case"circle":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"circle_outline":{const h=s*.35,u=n.x-l.x*h,f=n.y-l.y*h;d.fillStyle="#ffffff",d.beginPath(),d.arc(u,f,h,0,Math.PI*2),d.fill(),d.stroke();break}case"diamond":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"diamond_outline":{const h=c*.7,u=s*.55,f={x:n.x-l.x*u,y:n.y-l.y*u};d.fillStyle="#ffffff",d.beginPath(),d.moveTo(n.x,n.y),d.lineTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-l.x*u,f.y-l.y*u),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.closePath(),d.fill(),d.stroke();break}case"bar":{const h=c*1.2;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one":{const h=c*1,u=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(f.x+a.x*h,f.y+a.y*h),d.lineTo(f.x-a.x*h,f.y-a.y*h),d.stroke();break}case"crowfoot_many":{const h=c*1,u=s*.6;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const f={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(f.x,f.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}case"crowfoot_one_or_many":{const h=c*1,u=s*.6,f=s*.25;d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();const p={x:n.x-l.x*f,y:n.y-l.y*f};d.beginPath(),d.moveTo(p.x+a.x*h,p.y+a.y*h),d.lineTo(p.x-a.x*h,p.y-a.y*h),d.stroke();const y={x:n.x-l.x*u,y:n.y-l.y*u};d.beginPath(),d.moveTo(n.x+a.x*h,n.y+a.y*h),d.lineTo(y.x,y.y),d.lineTo(n.x-a.x*h,n.y-a.y*h),d.stroke();break}}d.restore()}function Dn(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Kc(t){let e=t.startArrowhead??null,n=t.endArrowhead??null;return e===null&&t.startArrow&&(e="arrow"),n===null&&t.endArrow&&(n="arrow"),{start:e,end:n}}const zc=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:a,allElements:c})=>{const{id:d,x:h,y:u,points:f,rotation:p,style:y,startBinding:m,endBinding:W,lineType:v,isLocked:D}=t,$=!D&&!o,T=I.useRef(null),O=y.roughness,{start:ot,end:F}=Kc(t),J=ot!=null||F!=null,Y=v==="curved",Q=v==="elbow",M=Lo(y.strokeWidth),k=Oe(O),{fingerprint:C,elementsRef:w}=Er(c),S=I.useMemo(()=>({x:h+f[0],y:u+f[1]}),[h,u,f[0],f[1]]),Z=I.useMemo(()=>({x:h+f[f.length-2],y:u+f[f.length-1]}),[h,u,f]),G=J?Math.ceil(M*1.5):void 0,U=Zr(Q,{startWorld:S,endWorld:Z,startBinding:m,endBinding:W,minStubLength:G},c??[],C),X=I.useMemo(()=>{if(!Q)return f;const rt=on(S,Z,m,W,w.current,G);return sn(rt)},[Q,h,u,f,m,W,C]),L=Q?U??X:f,at=I.useMemo(()=>{if(!Q)return f;const rt=[...L],st=f[0],pt=f[1];if(st!==0||pt!==0)for(let A=0;A<rt.length;A+=2)rt[A]+=st,rt[A+1]+=pt;return rt},[Q,L,f]),tt=I.useMemo(()=>{if(!Y)return null;const rt={x:f[0],y:f[1]},st={x:f[f.length-2],y:f[f.length-1]},pt=Jt(rt,st,t.curvature??zt);return{start:rt,end:st,cp:pt}},[Y,f,t.curvature]),E=I.useCallback(()=>s(d),[s,d]),V=I.useCallback(()=>l==null?void 0:l(d),[l,d]),dt=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a),rt.target.x(st),rt.target.y(pt)),i==null||i(d,{x:st,y:pt})},[d,a,i]),R=I.useCallback(rt=>{let st=rt.target.x(),pt=rt.target.y();a&&(st=At(st,a),pt=At(pt,a)),r(d,{x:st,y:pt})},[d,a,r]),K=I.useCallback(rt=>{const st=rt.target,pt=st.scaleX(),A=st.scaleY();st.setAttrs({scaleX:1,scaleY:1});const lt=f.map((j,Dt)=>Dt%2===0?j*pt:j*A),mt=Tn(lt);r(d,{x:st.x(),y:st.y(),points:lt,rotation:st.rotation(),width:mt.width,height:mt.height})},[d,f,r]),et=e?Tt.color:void 0,Ct=e?Tt.blur:0,bt=e?Tt.opacity:0;return g.jsx(gt.Group,{id:d,ref:T,x:h,y:u,rotation:p,transformsEnabled:p?"all":"position",draggable:$,onClick:E,onTap:E,onDblClick:V,onDblTap:V,onDragMove:dt,onDragEnd:R,onTransformEnd:K,children:Q?g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:at,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:at,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"square",lineJoin:"miter",shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(at);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):Y?g.jsxs(g.Fragment,{children:[g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{if(tt){if(rt.beginPath(),O>0){const pt=ye(d);vr(rt,tt.start,tt.cp,tt.end,O,pt,k,y.strokeWidth)}else rt.moveTo(tt.start.x,tt.start.y),rt.quadraticCurveTo(tt.cp.x,tt.cp.y,tt.end.x,tt.end.y);rt.fillStrokeShape(st)}},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&tt&&g.jsx(gt.Shape,{sceneFunc:rt=>{if(ot){const st=xo(tt.start,tt.cp,tt.end,!1);oe(rt,ot,tt.start,st,M,y.strokeColor,y.strokeWidth)}if(F){const st=xo(tt.start,tt.cp,tt.end,!0);oe(rt,F,tt.end,st,M,y.strokeColor,y.strokeWidth)}},listening:!1,opacity:y.opacity})]}):O>0?g.jsxs(g.Fragment,{children:[g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=ye(d);rt.beginPath(),Mo(rt,f,O,pt,k,y.strokeWidth),rt.fillStrokeShape(st)},stroke:y.strokeColor,strokeWidth:y.strokeWidth,hitStrokeWidth:Math.max(20,y.strokeWidth+16),dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",listening:!0,opacity:y.opacity,shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]}):g.jsxs(g.Fragment,{children:[g.jsx(gt.Line,{points:f,stroke:"transparent",strokeWidth:Math.max(20,y.strokeWidth+16),listening:!0,perfectDrawEnabled:!1}),g.jsx(gt.Line,{points:f,stroke:y.strokeColor,strokeWidth:y.strokeWidth,opacity:y.opacity,dash:_t(y.strokeStyle,y.strokeWidth),lineCap:"round",lineJoin:"round",shadowColor:et,shadowBlur:Ct,shadowOpacity:bt,listening:!1,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}),J&&g.jsx(gt.Shape,{sceneFunc:(rt,st)=>{const pt=Dn(f);if(!(pt.length<2)){if(ot&&oe(rt,ot,pt[0],pt[1],M,y.strokeColor,y.strokeWidth),F){const A=pt[pt.length-1],lt=pt[pt.length-2];oe(rt,F,A,lt,M,y.strokeColor,y.strokeWidth)}rt.fillStrokeShape(st)}},listening:!1,opacity:y.opacity})]})})},Jc=I.memo(zc),$c=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,points:u,rotation:f,style:p,isLocked:y}=t,m=!y&&!n,W=I.useCallback(()=>o(c),[o,c]),v=I.useCallback(()=>i==null?void 0:i(c),[i,c]),D=I.useCallback(G=>{let U=G.target.x(),X=G.target.y();if(l&&(U=At(U,l),X=At(X,l),G.target.x(U),G.target.y(X)),!l&&a){const{minX:L,minY:at,width:tt,height:E}=Bo(u),V=a(c,{x:U+L,y:X+at,width:tt,height:E});V&&(U=V.x-L,X=V.y-at,G.target.x(U),G.target.y(X))}r==null||r(c,{x:U,y:X})},[c,l,u,r,a]),$=I.useCallback(G=>{let U=G.target.x(),X=G.target.y();l&&(U=At(U,l),X=At(X,l)),s(c,{x:U,y:X})},[c,l,s]),T=I.useCallback(G=>{const U=G.target,X=U.scaleX(),L=U.scaleY();U.setAttrs({scaleX:1,scaleY:1});const at=u.map((tt,E)=>E%2===0?tt*X:tt*L);s(c,{x:U.x(),y:U.y(),points:at,rotation:U.rotation()})},[c,u,s]),O=e?Tt.color:void 0,ot=e?Tt.blur:0,F=e?Tt.opacity:0,J=p.freehandStyle||"standard",Y=t.isComplete===!1,Q=Y?0:d,M=Y?0:h,k=J==="pen"||J==="brush",C=J==="pencil",w=I.useMemo(()=>{if(!k)return"";const G=!Y;if(J==="brush"){const U=p.strokeWidth*4;return br(u,t.pressures,{size:U,thinning:.7,smoothing:.5,streamline:.5,simulatePressure:!0,last:G,start:{cap:!0},end:{cap:!0}})}return br(u,t.pressures,{size:p.strokeWidth*1.8,thinning:.6,smoothing:.5,streamline:.5,simulatePressure:!0,last:G,start:{cap:!0,taper:0},end:{cap:!0,taper:0}})},[u,t.pressures,k,J,p.strokeWidth,Y]),S=I.useMemo(()=>{if(!C||u.length===0)return[];const G=[u[0],u[1]];let U=u[0],X=u[1];for(let L=2;L<u.length;L+=2){const at=u[L],tt=u[L+1],E=at-U,V=tt-X;(E*E+V*V>2.25||L===u.length-2)&&(G.push(at,tt),U=at,X=tt)}return G},[C,u]),Z=I.useCallback((G,U)=>{const X=p.roughness,L=ye(c);G.beginPath(),Mo(G,S,X,L,Oe(X),p.strokeWidth),G.fillStrokeShape(U)},[c,S,p.roughness,p.strokeWidth]);return k&&w?g.jsx(gt.Path,{id:c,x:Q,y:M,data:w,rotation:f,transformsEnabled:f?"all":"position",fill:p.strokeColor,opacity:p.opacity,draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:20,onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):C?g.jsx(gt.Shape,{id:c,x:Q,y:M,width:Y?void 0:t.width,height:Y?void 0:t.height,rotation:f,transformsEnabled:f?"all":"position",sceneFunc:Z,stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:Math.max(20,p.strokeWidth+16),onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1}):g.jsx(gt.Line,{id:c,x:Q,y:M,points:u,rotation:f,transformsEnabled:f?"all":"position",stroke:p.strokeColor,strokeWidth:p.strokeWidth,opacity:p.opacity,lineCap:"round",lineJoin:"round",tension:.5,globalCompositeOperation:"source-over",draggable:m,onClick:W,onTap:W,onDblClick:v,onDblTap:v,shadowColor:O,shadowBlur:ot,shadowOpacity:F,hitStrokeWidth:20,onDragMove:D,onDragEnd:$,onTransformEnd:T,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})},Rc=I.memo($c),Xn=1.18,jc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,autoEdit:i,onEditStart:l,onEditEnd:a,allElements:c,gridSnap:d})=>{const{id:h,x:u,y:f,width:p,height:y,rotation:m,style:W,text:v,containerId:D,textAlign:$,verticalAlign:T,isLocked:O}=t,ot=I.useRef(null),F=I.useRef(!1),J=I.useRef(!1),Y=!!D,Q=!Y&&!O&&!n,M=I.useMemo(()=>!D||!c?null:c.find(X=>X.id===D)??null,[D,c]),k=I.useMemo(()=>{var dt,R;if(!M)return{x:u,y:f};if(M.type==="arrow"||M.type==="line"){const K=M,et=K.points,Ct={x:et[0],y:et[1]},bt={x:et[et.length-2],y:et[et.length-1]};let rt,st;if(K.lineType==="curved"){const lt=Jt(Ct,bt,K.curvature??zt),mt=Ye(Ct,lt,bt,.5);rt=K.x+mt.x,st=K.y+mt.y}else rt=K.x+(Ct.x+bt.x)/2,st=K.y+(Ct.y+bt.y)/2;const pt=Math.max(80,p||80),A=((dt=ot.current)==null?void 0:dt.height())??y;return{x:rt-pt/2,y:st-A/2,width:pt}}const X=4,L=M.width-X*2,at=Math.max(20,L),tt=M.x+X,E=((R=ot.current)==null?void 0:R.height())??y;let V;return T==="top"?V=M.y+X:T==="bottom"?V=M.y+M.height-E-X:V=M.y+(M.height-E)/2,{x:tt,y:V,width:at}},[M,u,f,y,T]),C=I.useCallback(()=>{const X=ot.current;if(!X||F.current)return;const L=X.height(),at={};let tt=!1;if(Math.abs(L-y)>1&&(at.height=L,tt=!0),!Y){const E=Math.ceil(X.getTextWidth());Math.abs(E-p)>1&&(at.width=E,tt=!0)}tt&&s(h,at)},[h,y,p,Y,s]);I.useEffect(()=>{requestAnimationFrame(C)},[v,W.fontSize,W.fontFamily,C]);const w=I.useCallback(()=>{const X=ot.current;if(!X||F.current)return;const L=X.getStage();if(!L)return;F.current=!0,l==null||l(h);const at=L.container(),E=X.getAbsoluteTransform().copy().point({x:0,y:0}),V=L.scaleX(),dt=W.fontSize*V,R=dt*(Xn-1.07)/2;let K=0,et=0,Ct=0,bt=0;const st=4*V;if(Y&&M){const Ft=L.getAbsoluteTransform().copy().point({x:M.x,y:M.y});K=Ft.x,et=Ft.y,Ct=M.width*V,bt=M.height*V}const pt=X.width(),A=Y?Ct-st*2:Math.max(pt,100)*V,lt=Y?K+st:E.x,mt=v,j=document.createElement("textarea");if(at.appendChild(j),j.value=v,j.style.position="absolute",Y&&M){const vt=T||"middle",Ft=X.height()*V;let Ut;vt==="top"?Ut=et+st-R:vt==="bottom"?Ut=et+bt-Ft-st-R:Ut=et+(bt-Ft)/2-R,j.style.top=`${Ut}px`}else j.style.top=`${E.y-R}px`;j.style.left=`${lt}px`,j.style.width=`${A}px`,j.style.fontSize=`${dt}px`,j.style.fontFamily=W.fontFamily,j.style.color=W.strokeColor,j.style.lineHeight=`${Xn}`,j.style.border="none",j.style.borderRadius="0",j.style.padding="0",j.style.margin="0",j.style.outline="none",j.style.resize="none",j.style.overflow="hidden",j.style.background="transparent",j.style.zIndex="1000",j.rows=1,j.style.minHeight=`${Math.max(20,dt*Xn)}px`,j.style.boxSizing="border-box",j.style.transformOrigin="left top",j.style.letterSpacing="normal",j.style.caretColor=W.strokeColor;const Dt=Y?$||"center":"left";j.style.textAlign=Dt,Y?(j.style.whiteSpace="pre-wrap",j.style.wordBreak="break-word"):(j.style.whiteSpace="pre",j.style.wordBreak="normal");const Gt=Y?(M==null?void 0:M.rotation)??m:m;Gt&&(j.style.transform=`rotateZ(${Gt}deg)`);const Ot=()=>{j.style.height="auto";const vt=j.scrollHeight;if(j.style.height=`${vt}px`,Y&&M){const Ft=T||"middle";let Ut;Ft==="top"?Ut=et+st-R:Ft==="bottom"?Ut=et+bt-vt-st-R:Ut=et+(bt-vt)/2-R,j.style.top=`${Ut}px`}Y||(j.style.width="auto",j.style.width=`${Math.max(j.scrollWidth,100*V)}px`)};j.addEventListener("input",Ot),requestAnimationFrame(Ot),X.hide(),L.batchDraw(),j.focus(),j.select();let Ge=!1;const jt=()=>{if(!F.current)return;F.current=!1;const vt=Ge?mt:j.value,Ft=vt.trim()==="";j.removeEventListener("input",Ot),j.removeEventListener("blur",mn),j.removeEventListener("keydown",Nt),j.parentNode&&j.parentNode.removeChild(j),X.show(),L.batchDraw(),Ge||s(h,{text:vt}),a==null||a(h,Ft)},mn=()=>{jt()},Nt=vt=>{vt.stopPropagation(),vt.key==="Escape"&&(Ge=!0,j.blur()),vt.key==="Enter"&&!vt.shiftKey&&(vt.preventDefault(),j.blur()),vt.key==="Tab"&&(vt.preventDefault(),j.blur())};j.addEventListener("blur",mn),j.addEventListener("keydown",Nt)},[h,v,m,W,Y,M,$,T,s,l,a]);I.useEffect(()=>{i||(J.current=!1)},[i]),I.useEffect(()=>{i&&!J.current&&ot.current&&(J.current=!0,w())},[i,w]);const S=Y?k.x:u,Z=Y?k.y:f,G=Y&&k.width?k.width:void 0,U=Y?$||"center":void 0;return g.jsx(gt.Text,{ref:ot,id:h,x:S,y:Z,text:v||(Y?"":"Double-click to edit"),fontSize:W.fontSize,fontFamily:W.fontFamily,fill:W.strokeColor,lineHeight:Xn,width:G,align:U,wrap:Y?"word":"none",rotation:Y?(M==null?void 0:M.rotation)??m:m,transformsEnabled:(Y?(M==null?void 0:M.rotation)??m:m)?"all":"position",visible:!(i&&!F.current&&!v),opacity:v?W.opacity:Y?0:.4,draggable:Q,listening:!Y,onClick:Y?void 0:()=>o(h),onTap:Y?void 0:()=>o(h),onDblClick:w,onDblTap:w,shadowColor:!Y&&e?"#4f8df7":void 0,shadowBlur:!Y&&e?6:0,shadowOpacity:!Y&&e?.5:0,hitStrokeWidth:Y?0:10,perfectDrawEnabled:!1,onDragMove:Y?void 0:X=>{let L=X.target.x(),at=X.target.y();d&&(L=At(L,d),at=At(at,d),X.target.x(L),X.target.y(at)),r==null||r(h,{x:L,y:at})},onDragEnd:Y?void 0:X=>{let L=X.target.x(),at=X.target.y();d&&(L=At(L,d),at=At(at,d)),s(h,{x:L,y:at})},onTransformEnd:Y?void 0:X=>{const L=X.target,at=L.scaleX(),tt=L.scaleY(),E=Math.max(Math.abs(at),Math.abs(tt)),V=Math.max(8,Math.round(W.fontSize*E));L.scaleX(1),L.scaleY(1),s(h,{x:L.x(),y:L.y(),rotation:L.rotation(),style:{...W,fontSize:V}})}})},Qc=I.memo(jc),qc=({element:t,isSelected:e,isGrouped:n,onSelect:o,onChange:s,onDragMove:r,onDoubleClick:i,gridSnap:l,onDragSnap:a})=>{const{id:c,x:d,y:h,width:u,height:f,rotation:p,src:y,style:m,crop:W,cornerRadius:v,scaleMode:D,isLocked:$}=t,[T,O]=I.useState(null),[ot,F]=I.useState(!1),[J,Y]=I.useState({w:u,h:f});I.useEffect(()=>{Y({w:u,h:f})},[u,f]);const Q=J.w,M=J.h;I.useEffect(()=>{if(!y){O(null),F(!0);return}const E=new window.Image;return E.crossOrigin="anonymous",E.onload=()=>{O(E),F(!1)},E.onerror=()=>{O(null),F(!0)},E.src=y,()=>{E.onload=null,E.onerror=null}},[y]);const k=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();if(l&&(V=At(V,l),dt=At(dt,l),E.target.x(V),E.target.y(dt)),!l&&a){const R=a(c,{x:V,y:dt,width:u,height:f});R&&(V=R.x,dt=R.y,E.target.x(V),E.target.y(dt))}r==null||r(c,{x:V,y:dt})},[c,u,f,l,a,r]),C=I.useCallback(E=>{let V=E.target.x(),dt=E.target.y();l&&(V=At(V,l),dt=At(dt,l)),s(c,{x:V,y:dt})},[c,l,s]),w=I.useCallback(E=>{const V=E.target,dt=V.scaleX(),R=V.scaleY(),K=Math.max(10,V.width()*dt),et=Math.max(10,V.height()*R);V.setAttrs({scaleX:1,scaleY:1,width:K,height:et}),Y({w:K,h:et}),r==null||r(c,{x:V.x(),y:V.y(),width:K,height:et})},[c,r]),S=I.useCallback(E=>{const V=E.target;s(c,{x:V.x(),y:V.y(),width:Math.max(10,V.width()),height:Math.max(10,V.height()),rotation:V.rotation()})},[c,s]);let Z=0,G=0,U=Q,X=M,L;if(W&&(L={x:W.x,y:W.y,width:W.width,height:W.height}),T){const E=W?W.width:T.naturalWidth,V=W?W.height:T.naturalHeight;if(D==="fit"){const dt=E/V,R=Q/M;dt>R?(U=Q,X=Q/dt,G=(M-X)/2):(X=M,U=M*dt,Z=(Q-U)/2)}else if(D==="fill"&&!W){const dt=T.naturalWidth,R=T.naturalHeight,K=dt/R,et=Q/M;if(K>et){const Ct=R*et;L={x:(dt-Ct)/2,y:0,width:Ct,height:R}}else{const Ct=dt/et;L={x:0,y:(R-Ct)/2,width:dt,height:Ct}}U=Q,X=M}}const at=v>0?E=>{const V=Math.min(v,Q/2,M/2);E.beginPath(),E.moveTo(V,0),E.lineTo(Q-V,0),E.arcTo(Q,0,Q,V,V),E.lineTo(Q,M-V),E.arcTo(Q,M,Q-V,M,V),E.lineTo(V,M),E.arcTo(0,M,0,M-V,V),E.lineTo(0,V),E.arcTo(0,0,V,0,V),E.closePath()}:void 0,tt={id:c,x:d,y:h,width:Q,height:M,rotation:p,transformsEnabled:p?"all":"position",draggable:!$&&!n,clipFunc:at,onClick:()=>o(c),onTap:()=>o(c),onDblClick:()=>i==null?void 0:i(c),onDblTap:()=>i==null?void 0:i(c),onDragMove:k,onDragEnd:C,onTransform:w,onTransformEnd:S};return!T||ot?g.jsx(gt.Group,{...tt,children:g.jsx(gt.Rect,{width:Q,height:M,fill:"#f0f0f0",stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,opacity:m.opacity,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1})}):g.jsxs(gt.Group,{...tt,shadowColor:e?"#4f8df7":void 0,shadowBlur:e?6:0,shadowOpacity:e?.5:0,children:[D==="fit"&&g.jsx(gt.Rect,{width:Q,height:M,fill:m.fillColor==="transparent"?void 0:m.fillColor,cornerRadius:v}),g.jsx(gt.Image,{image:T,x:Z,y:G,width:U,height:X,crop:L,opacity:m.opacity,listening:!1,perfectDrawEnabled:!1}),m.strokeWidth>0&&m.strokeColor!=="transparent"&&g.jsx(gt.Rect,{width:Q,height:M,stroke:m.strokeColor,strokeWidth:m.strokeWidth,cornerRadius:v,listening:!1})]})},ta=I.memo(qc),ea=.5,na=1,oa=({element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,autoEditText:a,onTextEditStart:c,onTextEditEnd:d,allElements:h,gridSnap:u,onDragSnap:f,viewportScale:p})=>{var m,W,v;const y=I.useCallback(()=>s(t.id),[s,t.id]);if(!t.isVisible)return null;if(p!==void 0&&!e&&!n){const D=Math.max(t.width,t.height)*p;if(D<ea)return null;if(D<na)return g.jsx(gt.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:((m=t.style)==null?void 0:m.fillColor)||"#e0e0e0",stroke:((W=t.style)==null?void 0:W.strokeColor)||"#999",strokeWidth:1/p,opacity:((v=t.style)==null?void 0:v.opacity)??1,onClick:y,onTap:y,perfectDrawEnabled:!1,shadowForStrokeEnabled:!1,transformsEnabled:"position"})}switch(t.type){case"rectangle":return g.jsx(_c,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"ellipse":return g.jsx(Gc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"diamond":return g.jsx(Xc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"line":return g.jsx(Oc,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"arrow":return g.jsx(Jc,{element:t,isSelected:e,isEditing:n,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,allElements:h});case"freedraw":return g.jsx(Rc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});case"text":return g.jsx(Qc,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,autoEdit:a,onEditStart:c,onEditEnd:d,allElements:h,gridSnap:u});case"image":return g.jsx(ta,{element:t,isSelected:e,isGrouped:o,onSelect:s,onChange:r,onDragMove:i,onDoubleClick:l,gridSnap:u,onDragSnap:f});default:return null}};function sa(t,e){return!(t.element!==e.element||t.isSelected!==e.isSelected||t.isEditing!==e.isEditing||t.isGrouped!==e.isGrouped||t.autoEditText!==e.autoEditText||t.viewportScale!==e.viewportScale||t.gridSnap!==e.gridSnap)}const Ln=I.memo(oa,sa);function ra(t,e){if(t.length===0)return"";const n=new Set(t),o=new Map;for(const r of e)if(n.has(r.id)&&(o.set(r.id,r),o.size===n.size))break;const s=[];for(const r of t){const i=o.get(r);i&&s.push(`${r}:${i.isLocked?1:0}:${i.type}`)}return s.join(",")}const ia=({selectedIds:t,selectionColor:e="#4f8df7"})=>{const n=I.useRef(null),o=B(c=>ra(t,c.elements)),{hasLocked:s,allLocked:r,allText:i}=I.useMemo(()=>{if(!o||t.length===0)return{hasLocked:!1,allLocked:!1,allText:!1};const c=o.split(",");let d=0,h=0;for(const u of c){const f=u.split(":");f[1]==="1"&&d++,f[2]==="text"&&h++}return{hasLocked:d>0,allLocked:d===c.length,allText:h===c.length}},[o,t.length]),l=i?["top-left","top-right","bottom-left","bottom-right"]:["top-left","top-right","bottom-left","bottom-right","middle-left","middle-right","top-center","bottom-center"];if(I.useEffect(()=>{var u;const c=n.current;if(!c)return;const d=c.getStage();if(!d)return;const h=t.map(f=>d.findOne(`#${f}`)).filter(Boolean);c.nodes(h),(u=c.getLayer())==null||u.batchDraw()},[t]),t.length===0)return null;const a=s?"#ff9500":e;return g.jsx(gt.Transformer,{ref:n,flipEnabled:!1,keepRatio:i,resizeEnabled:!r,rotateEnabled:!r,boundBoxFunc:(c,d)=>r||Math.abs(d.width)<5||Math.abs(d.height)<5?c:d,anchorFill:r?"#ff9500":"#ffffff",anchorStroke:a,anchorSize:r?0:8,anchorCornerRadius:2,borderStroke:a,borderStrokeWidth:1,borderDash:r?[6,3]:[4,4],rotateAnchorOffset:25,enabledAnchors:r?[]:l})},la=I.memo(ia),ca=({width:t,height:e,viewport:n,gridColor:o="#e5e5e5"})=>{const{x:s,y:r,scale:i}=n,l=xe,a=I.useMemo(()=>{const c=Math.floor((-s/i-l)/l)*l,d=Math.ceil((-s/i+t/i+l)/l)*l,h=Math.floor((-r/i-l)/l)*l,u=Math.ceil((-r/i+e/i+l)/l)*l;return{startX:c,endX:d,startY:h,endY:u}},[s,r,i,t,e,l]);return g.jsx(gt.Shape,{sceneFunc:c=>{const{startX:d,endX:h,startY:u,endY:f}=a,p=1/i,y=c._context;y.beginPath(),y.strokeStyle=o,y.lineWidth=p;for(let m=d;m<=h;m+=l)y.moveTo(m,u),y.lineTo(m,f);for(let m=u;m<=f;m+=l)y.moveTo(d,m),y.lineTo(h,m);y.stroke()},listening:!1,perfectDrawEnabled:!1})},aa=I.memo(ca),da=({box:t,selectionColor:e="#4f8df7",viewportScale:n=1})=>t?g.jsx(gt.Rect,{x:t.x,y:t.y,width:t.width,height:t.height,fill:`${e}14`,stroke:e,strokeWidth:1/n,dash:[4/n,4/n],listening:!1}):null,ua=I.memo(da),Ie=6,ga=({el:t,color:e,viewportScale:n})=>{const o=t.x+t.width/2,s=t.y+t.height/2,r=t.rotation||0;switch(t.type){case"ellipse":return g.jsx(gt.Ellipse,{x:o,y:s,radiusX:t.width/2+Ie,radiusY:t.height/2+Ie,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1});case"diamond":{const i=t.width+Ie*2,l=t.height+Ie*2,a=[i/2,0,i,l/2,i/2,l,0,l/2];return g.jsx(gt.Line,{x:o-i/2,y:s-l/2,points:a,closed:!0,rotation:r,offsetX:0,offsetY:0,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}default:return g.jsx(gt.Rect,{x:o,y:s,offsetX:t.width/2+Ie,offsetY:t.height/2+Ie,width:t.width+Ie*2,height:t.height+Ie*2,rotation:r,stroke:e,strokeWidth:2/n,dash:[8/n,4/n],cornerRadius:6,fill:e,opacity:.1,listening:!1,perfectDrawEnabled:!1})}},ha=({elements:t,snapTarget:e,visible:n,color:o="#4f8df7",viewportScale:s=1})=>{if(!n||!e)return null;const r=t.find(i=>i.id===e.elementId&&Io(i));return r?g.jsxs(g.Fragment,{children:[g.jsx(ga,{el:r,color:o,viewportScale:s}),g.jsx(gt.Circle,{x:e.position.x,y:e.position.y,radius:6/s,fill:o,stroke:"white",strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1}),!e.isPrecise&&(()=>{const i=r.rotation||0,l={x:r.x+r.width/2,y:r.y+r.height/2},a=i!==0?tr(l,{x:r.x,y:r.y},i*Math.PI/180):l;return g.jsx(gt.Circle,{x:a.x,y:a.y,radius:4/s,fill:"white",stroke:o,strokeWidth:2/s,listening:!1,perfectDrawEnabled:!1})})()]}):null},fa=I.memo(ha),_r=4,pa=3,ya="#ffffff",Ia="#4f8df7",Ca="#2563eb",ba="#4f8df7",ma=5,Aa="#ff6b35",wa="#ffffff";function xa(t){const e=[];for(let n=0;n<t.length;n+=2)e.push({x:t[n],y:t[n+1]});return e}function Mr(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}const ka=({element:t,allElements:e,onPointsChange:n,onPointDragMove:o,onSnapTargetChange:s,color:r="#4f8df7"})=>{const{selectedPointIndices:i,hoveredPointIndex:l,hoveredMidpointIndex:a,setSelectedPoints:c,togglePointSelection:d,setHoveredPoint:h,setHoveredMidpoint:u,setIsDraggingPoint:f}=dn(),{id:p,x:y,y:m,points:W}=t,v=xa(W),D=I.useRef(null),$=I.useRef(null),T=I.useRef(void 0),O="lineType"in t&&t.lineType==="curved",ot="lineType"in t&&t.lineType==="elbow",F=O||ot,J=I.useCallback(w=>w===0||w===v.length-1,[v.length]),Y=I.useCallback(w=>{f(!0),D.current={points:[...W],x:y,y:m},T.current=void 0,i.includes(w)||c([w])},[W,y,m,i,c,f]),Q=I.useCallback((w,S)=>{const Z=S.target,G=Z.x(),U=Z.y(),X=[...W];X[w*2]=G-y,X[w*2+1]=U-m;const L={};if(J(w)){const at=Z.getStage(),tt=at==null?void 0:at.getRelativePointerPosition(),E=(tt==null?void 0:tt.x)??G,V=(tt==null?void 0:tt.y)??U;$.current={x:E,y:V};const dt={x:E,y:V},R=new Set([p]),K=w===0?t.endBinding:t.startBinding;K&&R.add(K.elementId);const et=ce(t.style.strokeWidth??2),Ct=ke(dt,e,24,R,void 0,void 0,et,T.current);if(s==null||s(Ct),T.current=Ct==null?void 0:Ct.isPrecise,Ct){const bt=Ct.position;X[w*2]=bt.x-y,X[w*2+1]=bt.y-m,Z.x(bt.x),Z.y(bt.y);const rt={elementId:Ct.elementId,fixedPoint:Ct.fixedPoint,gap:et,isPrecise:Ct.isPrecise};w===0?L.startBinding=rt:L.endBinding=rt}else w===0?L.startBinding=null:L.endBinding=null}o==null||o(p,{points:X,x:y,y:m,...L})},[W,y,m,p,t,e,J,o,s]),M=I.useCallback((w,S)=>{f(!1);const Z=S.target;let G,U;J(w)&&$.current?(G=$.current.x,U=$.current.y):(G=Z.x(),U=Z.y()),$.current=null;const X=[...W];X[w*2]=G-y,X[w*2+1]=U-m;const L={points:X};if(J(w)){const R={x:G,y:U},K=new Set([p]),et=w===0?t.endBinding:t.startBinding;et&&K.add(et.elementId);const Ct=ce(t.style.strokeWidth??2),bt=ke(R,e,24,K,void 0,void 0,Ct,T.current);if(s==null||s(null),T.current=void 0,bt){const rt=ce(t.style.strokeWidth??2),st={elementId:bt.elementId,fixedPoint:bt.fixedPoint,gap:rt,isPrecise:bt.isPrecise};w===0?L.startBinding=st:L.endBinding=st,X[w*2]=bt.position.x-y,X[w*2+1]=bt.position.y-m,L.points=X}else w===0?L.startBinding=null:L.endBinding=null}const at=L.points??X,tt=at[0],E=at[1];if(tt!==0||E!==0){const R=[];for(let K=0;K<at.length;K+=2)R.push(at[K]-tt,at[K+1]-E);L.x=y+tt,L.y=m+E,L.points=R}const V=L.points??at,dt=Tn(V);L.width=dt.width,L.height=dt.height,n(p,L),D.current=null},[W,y,m,p,v,t,e,J,f,n,s]),k=I.useCallback((w,S)=>{S.cancelBubble=!0,S.evt.shiftKey?d(w):c([w])},[c,d]),C=I.useCallback((w,S)=>{S.cancelBubble=!0;const Z=v[w],G=v[w+1],U=Mr(Z,G),X=w+1,L=[];for(let tt=0;tt<v.length;tt++)L.push(v[tt].x,v[tt].y),tt===w&&L.push(U.x,U.y);const at=Tn(L);c([X]),u(null),n(p,{points:L,width:at.width,height:at.height})},[p,v,c,u,n]);return g.jsxs(gt.Group,{children:[!F&&v.length>=2&&v.slice(0,-1).map((w,S)=>{const Z=v[S+1],G=Mr(w,Z),U=a===S;return g.jsx(gt.Circle,{x:y+G.x,y:m+G.y,radius:pa,fill:U?Ca:Ia,opacity:U?.9:.5,stroke:"white",strokeWidth:1.5,onMouseEnter:()=>u(S),onMouseLeave:()=>u(null),onClick:X=>C(S,X),onTap:X=>C(S,X),hitStrokeWidth:10,perfectDrawEnabled:!1},`mid-${S}`)}),v.map((w,S)=>{const Z=J(S);if(F&&!Z)return null;const G=i.includes(S),U=l===S,X=Z?_r+1:_r;return g.jsx(gt.Circle,{x:y+w.x,y:m+w.y,radius:X,fill:G?ba:ya,stroke:U||G?"#2563eb":r,strokeWidth:G?2.5:2,draggable:!0,onMouseEnter:()=>h(S),onMouseLeave:()=>h(-1),onClick:L=>k(S,L),onTap:L=>k(S,L),onDragStart:()=>Y(S),onDragMove:L=>Q(S,L),onDragEnd:L=>M(S,L),hitStrokeWidth:10,perfectDrawEnabled:!1},`pt-${S}`)}),O&&v.length>=2&&(()=>{const w=v[0],S=v[v.length-1],Z=t.curvature??zt,G=Jt(w,S,Z),U=Ye(w,G,S,.5);return g.jsx(gt.Circle,{x:y+U.x,y:m+U.y,radius:ma,fill:Aa,stroke:wa,strokeWidth:2,draggable:!0,onDragStart:()=>f(!0),onDragMove:X=>{const L=X.target,at={x:y+w.x,y:m+w.y},tt={x:y+S.x,y:m+S.y},E={x:L.x(),y:L.y()},V=nr(at,tt,E),dt=Jt(w,S,V),R=Ye(w,dt,S,.5);L.x(y+R.x),L.y(m+R.y),o==null||o(p,{curvature:V})},onDragEnd:X=>{f(!1);const L=X.target,at={x:y+w.x,y:m+w.y},tt={x:y+S.x,y:m+S.y},E={x:L.x(),y:L.y()},V=nr(at,tt,E),dt=Jt(w,S,V),R=Ye(w,dt,S,.5);L.x(y+R.x),L.y(m+R.y),n(p,{curvature:V})},hitStrokeWidth:12,perfectDrawEnabled:!1},"curve-handle")})()]})},Sa=I.memo(ka),va={Hand:g.jsx(It.Hand,{size:18}),MousePointer2:g.jsx(It.MousePointer2,{size:18}),Square:g.jsx(It.Square,{size:18}),Circle:g.jsx(It.Circle,{size:18}),Diamond:g.jsx(It.Diamond,{size:18}),Minus:g.jsx(It.Minus,{size:18}),ArrowUpRight:g.jsx(It.ArrowUpRight,{size:18}),Pencil:g.jsx(It.Pencil,{size:18}),Type:g.jsx(It.Type,{size:18}),ImageIcon:g.jsx(It.ImageIcon,{size:18}),Eraser:g.jsx(It.Eraser,{size:18}),StickyNote:g.jsx(It.StickyNote,{size:18})},Ce=(t,e,n)=>({display:"flex",alignItems:"center",justifyContent:"center",width:34,height:34,borderRadius:8,border:"none",cursor:n?"not-allowed":"pointer",transition:"background 150ms, color 150ms",background:t?`${e.activeToolColor}20`:"transparent",color:t?e.activeToolColor:n?`${e.mutedTextColor}55`:e.mutedTextColor,outline:t?`1.5px solid ${e.activeToolColor}50`:"none",flexShrink:0,opacity:n?.45:1}),Fn=t=>({width:1,height:22,background:t.toolbarBorder,margin:"0 3px",flexShrink:0}),Gr=t=>({display:"flex",alignItems:"center",gap:1,background:t.toolbarBg,backdropFilter:"blur(10px)",WebkitBackdropFilter:"blur(10px)",boxShadow:"0 2px 10px rgba(0,0,0,0.08)",borderRadius:12,padding:"5px 8px",border:`1px solid ${t.toolbarBorder}`});function Ea(t,e,n){const[o,s]=I.useState(null),r=I.useRef(e);r.current=e;const i=I.useCallback(()=>{t.current&&s(r.current(t.current.getBoundingClientRect()))},[t]);return I.useEffect(()=>{if(!n){s(null);return}return i(),window.addEventListener("resize",i),window.addEventListener("scroll",i,!0),()=>{window.removeEventListener("resize",i),window.removeEventListener("scroll",i,!0)}},[n,i]),o}const Fo=({anchorRef:t,onClose:e,theme:n,placement:o,computePos:s,transform:r,dataAttribute:i,style:l,children:a,isOpen:c})=>{const d=Ea(t,h=>s(h,o),c);return I.useEffect(()=>{if(!c)return;const h=f=>{t.current&&t.current.contains(f.target)||f.target.closest(`[${i}]`)||e()},u=()=>e();return document.addEventListener("mousedown",h),window.addEventListener("resize",u),()=>{document.removeEventListener("mousedown",h),window.removeEventListener("resize",u)}},[c,e,i,t]),!c||!d?null:xs.createPortal(g.jsx("div",{[i]:"true",style:{position:"fixed",top:d.top,left:d.left,transform:r,background:n.toolbarBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",border:`1px solid ${n.toolbarBorder}`,borderRadius:12,boxShadow:"0 8px 28px rgba(0,0,0,0.12)",zIndex:9999,...l},children:a}),document.body)},Dr=({icon:t,label:e,disabled:n,isActive:o,onClick:s,theme:r,size:i=36})=>g.jsx("button",{title:e,disabled:n,onClick:n?void 0:s,style:{display:"flex",alignItems:"center",justifyContent:"center",width:i,height:i,borderRadius:8,border:`1px solid ${o?`${r.activeToolColor}50`:"transparent"}`,background:o?`${r.activeToolColor}18`:"transparent",cursor:n?"default":"pointer",color:o?r.activeToolColor:n?`${r.mutedTextColor}55`:r.mutedTextColor,opacity:n?.4:1,transition:"background 120ms, color 120ms, border-color 120ms"},onMouseEnter:l=>{!n&&!o&&(l.currentTarget.style.background=`${r.activeToolColor}14`,l.currentTarget.style.color=r.activeToolColor,l.currentTarget.style.borderColor=`${r.activeToolColor}30`)},onMouseLeave:l=>{o||(l.currentTarget.style.background="transparent",l.currentTarget.style.color=n?`${r.mutedTextColor}55`:r.mutedTextColor,l.currentTarget.style.borderColor="transparent")},children:t}),Wa=({actions:t,anchorRef:e,onClose:n,theme:o,placement:s="bottom"})=>g.jsx(Fo,{isOpen:!0,anchorRef:e,onClose:n,theme:o,placement:s,computePos:(r,i)=>i==="top"?{top:r.bottom+8,left:r.left+r.width/2}:{top:r.top-12,left:r.left+r.width/2},transform:s==="top"?"translate(-50%, 0)":"translate(-50%, -100%)",dataAttribute:"data-subtools-popup",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(4, 36px)",gap:4},children:t.map((r,i)=>g.jsx(Dr,{icon:r.icon,label:r.label,disabled:r.disabled,onClick:()=>{r.onClick(),n()},theme:o},i))}),Ta=({shapes:t,activeTool:e,anchorRef:n,onSelect:o,onClose:s,theme:r,placement:i="bottom"})=>g.jsx(Fo,{isOpen:!0,anchorRef:n,onClose:s,theme:r,placement:i,computePos:(l,a)=>a==="top"?{top:l.bottom+8,left:l.right}:{top:l.top-12,left:l.right},transform:i==="top"?"translate(-100%, 0)":"translate(-100%, -100%)",dataAttribute:"data-shape-picker",style:{padding:8,display:"grid",gridTemplateColumns:"repeat(5, 40px)",gap:4},children:t.filter(l=>l.tool!==null).map((l,a)=>g.jsx(Dr,{icon:l.icon,label:l.label,disabled:l.tool===null,isActive:l.tool!==null&&e===l.tool,onClick:()=>{l.tool&&(o(l.tool),s())},theme:r,size:40},a))}),Ba=({scale:t,theme:e,onZoomIn:n,onZoomOut:o,onReset:s,placement:r="bottom"})=>{const[i,l]=I.useState(!1),a=I.useRef(null);return g.jsxs("div",{ref:a,style:{position:"relative"},children:[g.jsxs("button",{style:{...Ce(i,e),width:"auto",padding:"0 6px",gap:2,fontSize:11,minWidth:52},onClick:()=>l(!i),title:"Zoom",children:[g.jsxs("span",{style:{minWidth:32,textAlign:"center",userSelect:"none"},children:[Math.round(t*100),"%"]}),g.jsx(It.ChevronDown,{size:12})]}),g.jsx(Fo,{isOpen:i,anchorRef:a,onClose:()=>l(!1),theme:e,placement:r,computePos:(c,d)=>d==="top"?{top:c.bottom+6,left:c.left}:{top:c.top-6,left:c.left},transform:r==="top"?"translateY(0)":"translateY(-100%)",dataAttribute:"data-zoom-dropdown",style:{padding:4,minWidth:130},children:[{icon:g.jsx(It.ZoomIn,{size:14}),label:"Zoom In",fn:()=>{n(),l(!1)}},{icon:g.jsx(It.ZoomOut,{size:14}),label:"Zoom Out",fn:()=>{o(),l(!1)}},{icon:g.jsx(It.Maximize,{size:14}),label:"Reset Zoom",fn:()=>{s(),l(!1)}}].map(({icon:c,label:d,fn:h})=>g.jsxs("button",{onClick:h,style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",border:"none",background:"transparent",color:e.textColor,cursor:"pointer",borderRadius:4,fontSize:12},onMouseEnter:u=>{u.currentTarget.style.background=`${e.activeToolColor}14`},onMouseLeave:u=>{u.currentTarget.style.background="transparent"},children:[c,g.jsx("span",{children:d})]},d))})]})},Za=({visibleTools:t,theme:e,position:n="bottom"})=>{const o=B(E=>E.activeTool),s=B(E=>E.setActiveTool),r=B(E=>E.undo),i=B(E=>E.redo),l=B(E=>E.selectedIds),a=B(E=>E.elements),c=B(E=>E.deleteElements),d=B(E=>E.duplicateElements),h=B(E=>E.bringToFront),u=B(E=>E.bringForward),f=B(E=>E.sendBackward),p=B(E=>E.sendToBack),y=B(E=>E.toggleLockElements),m=B(E=>E.ungroupElements),W=B(E=>E.pushHistory),v=B(E=>E.showGrid),D=B(E=>E.toggleGrid),$=B(E=>E.zoomIn),T=B(E=>E.zoomOut),O=B(E=>E.resetZoom),ot=B(E=>E.viewport.scale),[F,J]=I.useState(!1),Y=I.useRef(null),[Q,M]=I.useState(!1),k=I.useRef(null),C=l.length>0,w=l.length>1,S=C&&a.filter(E=>l.includes(E.id)).every(E=>E.isLocked),Z=()=>{const E=new Blob([JSON.stringify(a,null,2)],{type:"application/json"}),V=URL.createObjectURL(E),dt=Object.assign(document.createElement("a"),{href:V,download:"canvas.json"});document.body.appendChild(dt),dt.click(),document.body.removeChild(dt),URL.revokeObjectURL(V)},G=[{icon:g.jsx(It.AlignLeft,{size:16}),label:"Align Left",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignCenter,{size:16}),label:"Align Center H",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignRight,{size:16}),label:"Align Right",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignCenterVertical,{size:16}),label:"Align Center V",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignStartVertical,{size:16}),label:"Align Top",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.AlignEndVertical,{size:16}),label:"Align Bottom",disabled:!w,onClick:()=>{}},{icon:g.jsx(It.FlipHorizontal,{size:16}),label:"Flip H",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.FlipVertical,{size:16}),label:"Flip V",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.ChevronsUp,{size:16}),label:"Bring to Front",disabled:!C,onClick:()=>{h(l),W()}},{icon:g.jsx(It.ArrowUp,{size:16}),label:"Bring Forward",disabled:!C,onClick:()=>{u(l),W()}},{icon:g.jsx(It.ArrowDown,{size:16}),label:"Send Backward",disabled:!C,onClick:()=>{f(l),W()}},{icon:g.jsx(It.ChevronsDown,{size:16}),label:"Send to Back",disabled:!C,onClick:()=>{p(l),W()}},{icon:g.jsx(It.RotateCcw,{size:16}),label:"Rotate Left 90°",disabled:!C,onClick:()=>{}},{icon:g.jsx(It.RotateCw,{size:16}),label:"Rotate Right 90°",disabled:!C,onClick:()=>{}},{icon:S?g.jsx(It.Unlock,{size:16}):g.jsx(It.Lock,{size:16}),label:S?"Unlock":"Lock",disabled:!C,onClick:()=>{y(l),W()}},{icon:g.jsx(It.Ungroup,{size:16}),label:"Ungroup",disabled:!C,onClick:()=>{m(l),W()}},{icon:g.jsx(It.Grid3x3,{size:16}),label:v?"Hide Grid":"Show Grid",disabled:!1,onClick:D},{icon:g.jsx(It.Download,{size:16}),label:"Export JSON",disabled:!1,onClick:Z},{icon:g.jsx(It.Maximize,{size:16}),label:"Reset Zoom",disabled:!1,onClick:O},{icon:g.jsx(It.Group,{size:16}),label:"Select All",disabled:!1,onClick:()=>{}}],X=[{icon:g.jsx(It.Square,{size:16}),label:"Rectangle",tool:"rectangle"},{icon:g.jsx(It.Circle,{size:16}),label:"Ellipse",tool:"ellipse"},{icon:g.jsx(It.Diamond,{size:16}),label:"Diamond",tool:"diamond"},{icon:g.jsx(It.Minus,{size:16}),label:"Line",tool:"line"},{icon:g.jsx(It.ArrowUpRight,{size:16}),label:"Arrow",tool:"arrow"}].filter(E=>E.tool===null?!0:!t.some(V=>V.type===E.tool)),L=E=>s(E),at=G.filter(E=>!["Undo","Redo","Delete","Duplicate"].includes(E.label)),tt=n==="top";return g.jsx("div",{style:{position:"absolute",...tt?{top:16}:{bottom:16},left:0,right:0,zIndex:50,display:"flex",justifyContent:"center",alignItems:tt?"flex-start":"flex-end",pointerEvents:"none"},children:g.jsxs("div",{style:{display:"flex",flexDirection:tt?"column-reverse":"column",alignItems:"center",maxWidth:"calc(100% - 32px)",gap:0,pointerEvents:"none"},children:[g.jsxs("div",{style:{...Gr(e),pointerEvents:"auto",...tt?{borderRadius:"0 0 12px 12px",borderTop:"none"}:{borderRadius:"12px 12px 0 0",borderBottom:"none"}},children:[g.jsx("button",{style:Ce(!1,e),onClick:r,title:"Undo (⌘Z)",children:g.jsx(It.Undo2,{size:16})}),g.jsx("button",{style:Ce(!1,e),onClick:i,title:"Redo (⌘⇧Z)",children:g.jsx(It.Redo2,{size:16})}),g.jsx("div",{style:Fn(e)}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&c(l)},title:"Delete (⌫)",children:g.jsx(It.Trash2,{size:16})}),g.jsx("button",{style:Ce(!1,e,!C),disabled:!C,onClick:()=>{C&&d(l)},title:"Duplicate (⌘D)",children:g.jsx(It.Copy,{size:16})}),at.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:Fn(e)}),g.jsx("button",{ref:Y,style:Ce(F,e),onClick:()=>{J(!F),M(!1)},title:"More actions",children:g.jsx(It.MoreHorizontal,{size:16})})]})]}),g.jsxs("div",{style:{...Gr(e),pointerEvents:"auto",...tt?{borderRadius:"12px 12px 0 0",borderBottom:"none"}:{}},children:[t.map(E=>g.jsx("button",{style:Ce(o===E.type,e),onClick:()=>s(E.type),title:`${E.label} (${E.shortcut})`,children:va[E.icon]},E.type)),g.jsx("div",{style:Fn(e)}),g.jsx(Ba,{scale:ot,theme:e,onZoomIn:$,onZoomOut:T,onReset:O,placement:n}),X.length>0&&g.jsxs(g.Fragment,{children:[g.jsx("div",{style:Fn(e)}),g.jsx("button",{ref:k,style:Ce(Q,e),onClick:()=>{M(!Q),J(!1)},title:"More shapes",children:g.jsx(It.ChevronUp,{size:16})})]})]}),F&&at.length>0&&g.jsx(Wa,{actions:at,anchorRef:Y,onClose:()=>J(!1),theme:e,placement:n}),Q&&X.length>0&&g.jsx(Ta,{shapes:X,activeTool:o,anchorRef:k,onSelect:L,onClose:()=>M(!1),theme:e,placement:n})]})})},be=({theme:t,variant:e="toggle",isActive:n=!1,dangerHover:o=!1,onClick:s,title:r,disabled:i=!1,width:l=28,height:a=28,style:c,children:d})=>{const[h,u]=I.useState(!1),f=n||h,p=()=>e==="toggle"&&n?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",y=()=>e==="toggle"&&n?`${t.activeToolColor}10`:h?"#f3f4f6":"transparent";return g.jsx("button",{title:r,onClick:i?void 0:s,disabled:i,onMouseEnter:()=>!i&&u(!0),onMouseLeave:()=>u(!1),style:{width:l,height:a,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:5,border:p(),background:y(),cursor:i?"not-allowed":"pointer",color:n?t.activeToolColor:t.textColor,transition:"background 0.1s, border-color 0.1s",outline:"none",padding:0,opacity:i?.35:1,flexShrink:0,...c},children:typeof d=="function"?d(f):d})},Vo=({theme:t,isActive:e=!1,onClick:n,title:o,disabled:s,flex:r=1,width:i,children:l,style:a})=>g.jsx("button",{title:o,onClick:n,disabled:s,style:{flex:r,width:i,padding:"3px 0",borderRadius:4,border:e?`1.5px solid ${t.activeToolColor}`:"1px solid #e0e3e7",background:e?`${t.activeToolColor}10`:"transparent",cursor:"pointer",fontSize:10,fontWeight:500,color:e?t.activeToolColor:t.textColor,textAlign:"center",outline:"none",...a},children:l}),Mt=({theme:t,label:e,headerAction:n,children:o,style:s})=>g.jsxs("div",{style:{marginBottom:10,...s},children:[e&&g.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:n?"space-between":"flex-start",marginBottom:n?0:5},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:e}),n]}),o]}),Te=({children:t,gap:e=5,wrap:n=!1,columns:o=4,style:s})=>g.jsx("div",{style:{display:o?"grid":"flex",gridTemplateColumns:o?`repeat(${o}, 1fr)`:void 0,gap:e,justifyContent:o?void 0:"flex-start",flexWrap:!o&&n?"wrap":"nowrap",...s},children:t}),Vn=({options:t,value:e,onChange:n,theme:o,label:s,isOpen:r,onToggle:i,pickerRef:l,columns:a,style:c})=>{const d=t.find(p=>p.value===e)??t[0],h=I.useRef(null),[u,f]=I.useState(null);return I.useEffect(()=>{if(r&&h.current){const p=h.current.getBoundingClientRect();f({top:p.bottom+3,left:p.left})}else f(null)},[r]),g.jsxs("div",{ref:l,style:{position:"relative",display:"inline-flex",...c},children:[g.jsx("button",{ref:h,title:`${s}: ${d.label}`,onClick:i,style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",height:28,padding:"0 8px",borderRadius:6,border:r?`1.5px solid ${o.activeToolColor}`:"1px solid #e0e3e7",background:r?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:r?o.activeToolColor:o.textColor,outline:"none",transition:"background 0.15s, border-color 0.15s",boxShadow:r?`0 0 0 2px ${o.activeToolColor}20`:"none"},children:typeof d.icon=="function"?d.icon(r?o.activeToolColor:o.textColor):d.icon}),r&&u&&xs.createPortal(g.jsx("div",{"data-compact-dropdown":"true",style:{position:"fixed",top:u.top,left:u.left,background:o.panelBg,border:`1px solid ${o.toolbarBorder}`,borderRadius:6,padding:3,boxShadow:"0 3px 12px rgba(0,0,0,0.1)",zIndex:9999,display:"grid",gridTemplateColumns:a?`repeat(${a}, 26px)`:`repeat(${t.length}, 26px)`,gap:1},children:t.map(p=>{const y=p.value===e,m=y?o.activeToolColor:o.textColor;return g.jsx("button",{title:p.label,onClick:()=>{n(p.value),i()},style:{display:"flex",alignItems:"center",justifyContent:"center",width:26,height:26,borderRadius:4,border:y?`1.5px solid ${o.activeToolColor}`:"1px solid transparent",background:y?`${o.activeToolColor}10`:"transparent",cursor:"pointer",color:m,outline:"none"},children:typeof p.icon=="function"?p.icon(m):p.icon},String(p.value))})}),document.body)]})},Po=20,_a=4,Ma=6,Ga=[{value:1,label:"Thin",thickness:1},{value:2,label:"Normal",thickness:2},{value:4,label:"Bold",thickness:3.5},{value:6,label:"Extra Bold",thickness:5.5}],Da=[{value:"solid",label:"Solid"},{value:"dashed",label:"Dashed"},{value:"dotted",label:"Dotted"}],Xa=({thickness:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"2",y1:"7",x2:"12",y2:"7",stroke:e,strokeWidth:t,strokeLinecap:"round"})}),La=({style:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:g.jsx("line",{x1:"1",y1:"7",x2:"13",y2:"7",stroke:e,strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:t==="dashed"?"3.5 2.5":t==="dotted"?"1 2.5":void 0})}),Fa=({level:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t===0?g.jsx("path",{d:"M2,9 Q5,5 7,7 Q9,9 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):t===1?g.jsx("path",{d:"M2,9 Q3.5,3 6,8 Q8,13 10,6 Q11,3 12,5",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"}):g.jsx("path",{d:"M1,8 Q3,3 4.5,9 Q6,13 7,6 Q8.5,1 10,9 Q11.5,13 13,6",fill:"none",stroke:e,strokeWidth:"1.4",strokeLinecap:"round"})}),Va=({type:t,color:e})=>g.jsx("svg",{width:"12",height:"12",viewBox:"0 0 14 14",children:t==="sharp"?g.jsx("polyline",{points:"2,11 7,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}):t==="elbow"?g.jsx("polyline",{points:"2,11 2,3 12,3 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"square",strokeLinejoin:"miter"}):g.jsx("path",{d:"M2,11 Q7,0 12,11",fill:"none",stroke:e,strokeWidth:"1.3",strokeLinecap:"round"})}),Xr={standard:({size:t,color:e,strokeWidth:n})=>g.jsx(It.PenLine,{size:t,color:e,strokeWidth:n}),pen:({size:t,color:e,strokeWidth:n})=>g.jsx(It.PenTool,{size:t,color:e,strokeWidth:n}),pencil:({size:t,color:e,strokeWidth:n})=>g.jsx(It.Pencil,{size:t,color:e,strokeWidth:n}),brush:({size:t,color:e,strokeWidth:n})=>g.jsx(It.Brush,{size:t,color:e,strokeWidth:n})},Pa=({style:t,color:e})=>{const n=Xr[t]??Xr.standard;return g.jsx(n,{size:16,color:e,strokeWidth:1.5})},Lr=({arrowhead:t,end:e,color:n})=>{let l=18,a=null;switch(t){case null:break;case"arrow":l=16,a=g.jsx("path",{d:`M12,${6-3.5} L18,6 L12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"});break;case"triangle":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:n});break;case"triangle_outline":l=12,a=g.jsx("polygon",{points:`18,6 12,${6-3.5} 12,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinejoin:"round"});break;case"circle":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:n});break;case"circle_outline":l=11,a=g.jsx("circle",{cx:18-3.5,cy:6,r:3.5,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"diamond":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:n});break;case"diamond_outline":l=10,a=g.jsx("polygon",{points:`18,6 14,${6-3.5} 10,6 14,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3"});break;case"bar":a=g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"});break;case"crowfoot_one":l=14,a=g.jsxs(g.Fragment,{children:[g.jsx("line",{x1:14,y1:6-3.5,x2:14,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break;case"crowfoot_one_or_many":l=11,a=g.jsxs(g.Fragment,{children:[g.jsx("path",{d:`M18,${6-3.5} L11,6 L18,${6+3.5}`,fill:"none",stroke:n,strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"}),g.jsx("line",{x1:18-3.5,y1:6-3.5,x2:18-3.5,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"}),g.jsx("line",{x1:18,y1:6-3.5,x2:18,y2:6+3.5,stroke:n,strokeWidth:"1.3",strokeLinecap:"round"})]});break}const c=e==="start"?"scale(-1,1) translate(-20,0)":void 0;return g.jsx("svg",{width:14,height:12,viewBox:"0 0 20 12",fill:"none",children:g.jsxs("g",{transform:c,children:[g.jsx("line",{x1:2,y1:6,x2:l,y2:6,stroke:n,strokeWidth:"1.5",strokeLinecap:"round"}),a]})})},me=({children:t,color:e,size:n=12})=>g.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:e,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:t}),Pn={sendToBack:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 12 12 18"}),g.jsx("polyline",{points:"9 15 12 18 15 15"})]}),sendBackward:t=>g.jsxs(me,{color:t,children:[g.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),g.jsx("polyline",{points:"19 12 12 19 5 12"})]}),bringForward:t=>g.jsxs(me,{color:t,children:[g.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"5"}),g.jsx("polyline",{points:"5 12 12 5 19 12"})]}),bringToFront:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),g.jsx("path",{d:"M17 21H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7l5 5v11a2 2 0 0 1-2 2z",opacity:"0.3"}),g.jsx("polyline",{points:"12 18 12 12"}),g.jsx("polyline",{points:"9 15 12 12 15 15"})]})},Yn={duplicate:t=>g.jsxs(me,{color:t,children:[g.jsx("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"}),g.jsx("path",{d:"M16 8V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2"})]}),delete:t=>g.jsxs(me,{color:t,children:[g.jsx("polyline",{points:"3 6 5 6 21 6"}),g.jsx("path",{d:"M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"}),g.jsx("path",{d:"M10 11v6"}),g.jsx("path",{d:"M14 11v6"}),g.jsx("path",{d:"M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"})]}),link:t=>g.jsxs(me,{color:t,children:[g.jsx("path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}),g.jsx("path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"})]}),ungroup:t=>g.jsxs(me,{color:t,children:[g.jsx("rect",{x:"2",y:"2",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("rect",{x:"14",y:"14",width:"8",height:"8",rx:"1",strokeDasharray:"3 2"}),g.jsx("path",{d:"M14 2h4a2 2 0 0 1 2 2v4"}),g.jsx("path",{d:"M2 14v4a2 2 0 0 0 2 2h4"})]})},Ya=({theme:t})=>{const e=B(A=>A.currentStyle),n=B(A=>A.setCurrentStyle),o=B(A=>A.selectedIds),s=B(A=>A.elements),r=B(A=>A.updateElement),i=B(A=>A.pushHistory),l=B(A=>A.toggleLockElements),a=B(A=>A.deleteElements),c=B(A=>A.duplicateElements),d=B(A=>A.bringToFront),h=B(A=>A.sendToBack),u=B(A=>A.bringForward),f=B(A=>A.sendBackward),p=B(A=>A.activeTool),y=B(A=>A.currentLineType),m=B(A=>A.setCurrentLineType),W=B(A=>A.currentStartArrowhead),v=B(A=>A.setCurrentStartArrowhead),D=B(A=>A.currentEndArrowhead),$=B(A=>A.setCurrentEndArrowhead),[T,O]=I.useState(null),ot=I.useRef(null),F=I.useRef(null),[J,Y]=I.useState(null),Q=I.useRef(null),M=I.useRef(null),k=I.useRef(null),C=I.useRef(null);I.useEffect(()=>{if(!T)return;const A=lt=>{const mt=T==="start"?ot:F,j=mt.current&&mt.current.contains(lt.target),Dt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Dt&&O(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[T]),I.useEffect(()=>{if(!J)return;const A=lt=>{const mt=J==="sloppiness"?Q:M,j=mt.current&&mt.current.contains(lt.target),Dt=lt.target.closest('[data-compact-dropdown="true"]');!j&&!Dt&&Y(null)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[J]);const w=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(mt=>mt.id===A))==null?void 0:lt.type)==="text"}),[o,s]),S=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return A&&(A.type==="arrow"||A.type==="line")?A:null},[o,s]),Z=I.useMemo(()=>{const A=o.length===1?s.find(lt=>lt.id===o[0]):null;return!A||A.type!=="image"?null:A},[o,s]),G=I.useMemo(()=>{if(o.length===0)return null;const A=s.filter(j=>o.includes(j.id)),lt=A.every(j=>j.isLocked),mt=A.some(j=>j.isLocked);return{allLocked:lt,anyLocked:mt}},[o,s]),U=(S==null?void 0:S.type)==="arrow",X=S!=null,L=o.length>0,at=I.useMemo(()=>o.some(A=>{var lt;return((lt=s.find(mt=>mt.id===A))==null?void 0:lt.type)==="freedraw"}),[o,s]),tt=p==="arrow"||p==="line",E=p==="arrow",V=X||tt,dt=U||E,R=at||p==="freedraw",K=I.useMemo(()=>{if(o.length===0)return e;if(o.length===1){const lt=s.find(mt=>mt.id===o[0]);if(lt)return lt.style}const A=s.find(lt=>o.includes(lt.id));return A?A.style:e},[o,s,e]),et=A=>{n(A),o.length>0&&(o.forEach(lt=>{const mt=s.find(j=>j.id===lt);mt&&r(lt,{style:{...mt.style,...A}})}),i())},Ct=Math.round(K.opacity*100),bt={position:"absolute",left:12,top:64,zIndex:50,width:160,background:t.panelBg,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",boxShadow:"0 1px 4px rgba(0,0,0,0.05), 0 3px 12px rgba(0,0,0,0.07)",borderRadius:10,padding:"10px 10px 8px",border:`1px solid ${t.toolbarBorder}`,maxHeight:"calc(100vh - 90px)",overflowY:"auto",fontFamily:"system-ui, -apple-system, sans-serif"},rt=(A,lt)=>({width:Po,height:Po,borderRadius:4,border:lt?`2px solid ${t.activeToolColor}`:"1.5px solid #d5d8dc",cursor:"pointer",background:A==="transparent"?"repeating-conic-gradient(#d1d5db 0% 25%, transparent 0% 50%) 50%/6px 6px":A,boxShadow:lt?`0 0 0 1.5px ${t.activeToolColor}30`:"none",outline:"none",flexShrink:0,transition:"border-color 0.1s, box-shadow 0.1s",padding:0}),st={height:1,background:t.toolbarBorder,margin:"10px 0",border:"none"},pt={display:"grid",gridTemplateColumns:`repeat(${Ma}, ${Po}px)`,gap:_a};return g.jsxs("div",{style:bt,children:[g.jsx(Mt,{label:"Stroke",theme:t,children:g.jsxs("div",{style:pt,children:[tn.map(A=>g.jsx("button",{style:rt(A,K.strokeColor===A),onClick:()=>et({strokeColor:A}),title:A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=k.current)==null?void 0:A.click()},style:{...rt(K.strokeColor,!tn.includes(K.strokeColor)),background:tn.includes(K.strokeColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":K.strokeColor,border:tn.includes(K.strokeColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:k,type:"color",value:K.strokeColor.startsWith("#")?K.strokeColor:"#000000",onChange:A=>et({strokeColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),!X&&!tt&&!at&&p!=="freedraw"&&g.jsx(Mt,{label:"Background",theme:t,children:g.jsxs("div",{style:pt,children:[en.map(A=>g.jsx("button",{style:rt(A,K.fillColor===A),onClick:()=>et({fillColor:A}),title:A==="transparent"?"None":A},A)),g.jsx("button",{title:"Custom color",onClick:()=>{var A;return(A=C.current)==null?void 0:A.click()},style:{...rt(K.fillColor,!en.includes(K.fillColor)),background:en.includes(K.fillColor)?"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)":K.fillColor,border:en.includes(K.fillColor)?"1.5px solid #d5d8dc":`2px solid ${t.activeToolColor}`}}),g.jsx("input",{ref:C,type:"color",value:K.fillColor.startsWith("#")?K.fillColor:"#ffffff",onChange:A=>et({fillColor:A.target.value}),style:{position:"absolute",opacity:0,width:0,height:0,pointerEvents:"none"}})]})}),g.jsx(Mt,{label:"Stroke width",theme:t,children:g.jsx(Te,{columns:4,children:Ga.map(A=>g.jsx(be,{isActive:K.strokeWidth===A.value,theme:t,onClick:()=>et({strokeWidth:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Xa,{thickness:A.thickness,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(Mt,{label:"Stroke style",theme:t,children:g.jsx(Te,{columns:4,children:Da.map(A=>g.jsx(be,{isActive:K.strokeStyle===A.value,theme:t,onClick:()=>et({strokeStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(La,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),g.jsx(Mt,{label:"Sloppiness",theme:t,headerAction:g.jsx(Vn,{label:"Sloppiness",style:{width:32},value:K.roughness,options:Ss.map(A=>({value:A.value,label:A.label,icon:lt=>g.jsx(Fa,{level:A.value,color:lt})})),onChange:A=>{et({roughness:A})},theme:t,isOpen:J==="sloppiness",onToggle:()=>Y(J==="sloppiness"?null:"sloppiness"),pickerRef:Q})}),R&&g.jsx(Mt,{label:"Pen style",theme:t,children:g.jsx(Te,{columns:4,children:sl.map(A=>g.jsx(be,{isActive:(K.freehandStyle||"standard")===A.value,theme:t,onClick:()=>et({freehandStyle:A.value}),title:A.label,width:"100%",height:32,children:lt=>g.jsx(Pa,{style:A.value,color:lt?t.activeToolColor:t.textColor})},A.value))})}),V&&g.jsx(Mt,{label:U||E?"Arrow type":"Line type",theme:t,headerAction:g.jsx(Vn,{label:U||E?"Arrow type":"Line type",style:{width:32},value:S?S.lineType:y,options:uo.map(A=>({value:A.type,label:A.label,icon:lt=>g.jsx(Va,{type:A.type,color:lt})})),onChange:A=>{const lt=uo.find(mt=>mt.type===A);if(lt){if(S){const mt={lineType:lt.type};if(lt.type==="curved"||lt.type==="elbow"){const j=S;j.points.length>4&&(mt.points=[j.points[0],j.points[1],j.points[j.points.length-2],j.points[j.points.length-1]])}r(S.id,mt),i()}m(lt.type),Y(null)}},theme:t,isOpen:J==="lineType",onToggle:()=>Y(J==="lineType"?null:"lineType"),pickerRef:M})}),dt&&g.jsx(Mt,{label:"Arrows",theme:t,headerAction:g.jsxs("div",{style:{display:"flex",gap:4},children:[g.jsx(Vn,{label:"Start arrowhead",style:{width:32},value:(S?S.startArrowhead:W)??"__none__",options:ao.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(Lr,{arrowhead:A.type,end:"start",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{startArrowhead:lt}),i()),v(lt)},columns:4,theme:t,isOpen:T==="start",onToggle:()=>O(T==="start"?null:"start"),pickerRef:ot}),g.jsx(Vn,{label:"End arrowhead",style:{width:32},value:(S?S.endArrowhead:D)??"__none__",options:ao.map(A=>({value:A.type??"__none__",label:A.label,icon:lt=>g.jsx(Lr,{arrowhead:A.type,end:"end",color:lt})})),onChange:A=>{const lt=A==="__none__"?null:A;S&&(r(S.id,{endArrowhead:lt}),i()),$(lt)},columns:4,theme:t,isOpen:T==="end",onToggle:()=>O(T==="end"?null:"end"),pickerRef:F})]})}),g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsxs(Mt,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Opacity"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[Ct,"%"]})]}),g.jsx("input",{type:"range",min:"0",max:"100",step:"1",value:Ct,onChange:A=>et({opacity:parseInt(A.target.value)/100}),style:{width:"100%",accentColor:t.activeToolColor,height:4}})]})]}),w&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Font size",theme:t,children:g.jsx(Te,{columns:0,wrap:!0,gap:2,children:nl.map(A=>g.jsx(Vo,{isActive:K.fontSize===A,theme:t,onClick:()=>et({fontSize:A}),flex:"none",style:{width:28,padding:"2px 0"},children:A},A))})}),g.jsx(Mt,{label:"Font family",theme:t,children:g.jsx("select",{value:K.fontFamily,onChange:A=>et({fontFamily:A.target.value}),style:{width:"100%",padding:"4px 6px",borderRadius:4,border:`1px solid ${t.toolbarBorder}`,background:t.panelBg,color:t.textColor,fontSize:10,cursor:"pointer",outline:"none"},children:ol.map(A=>g.jsx("option",{value:A.value,children:A.label},A.value))})})]}),Z&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Scale mode",theme:t,children:g.jsx(Te,{columns:3,children:["stretch","fit","fill"].map(A=>g.jsx(Vo,{isActive:Z.scaleMode===A,theme:t,title:A==="stretch"?"Stretch to fill":A==="fit"?"Fit (contain)":"Fill (cover)",onClick:()=>{r(Z.id,{scaleMode:A}),i()},flex:"1",children:A.charAt(0).toUpperCase()+A.slice(1)},A))})}),g.jsxs(Mt,{theme:t,children:[g.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:3},children:[g.jsx("span",{style:{fontSize:10,fontWeight:600,color:t.mutedTextColor,letterSpacing:.2},children:"Corner radius"}),g.jsxs("span",{style:{fontSize:10,fontWeight:500,color:t.textColor},children:[Z.cornerRadius,"px"]})]}),g.jsx("input",{type:"range",min:"0",max:"50",step:"1",value:Z.cornerRadius,onChange:A=>{r(Z.id,{cornerRadius:parseInt(A.target.value)}),i()},style:{width:"100%",accentColor:t.activeToolColor,height:4}})]}),g.jsx(Mt,{theme:t,children:g.jsx(Vo,{theme:t,style:{width:"100%",padding:"5px 0",borderRadius:4},onClick:()=>{const A=document.createElement("input");A.type="file",A.accept="image/*",A.onchange=async()=>{var j;const lt=(j=A.files)==null?void 0:j[0];if(!lt)return;const mt=new FileReader;mt.onload=()=>{const Dt=mt.result,Gt=new window.Image;Gt.onload=()=>{r(Z.id,{src:Dt,naturalWidth:Gt.naturalWidth,naturalHeight:Gt.naturalHeight}),i()},Gt.src=Dt},mt.readAsDataURL(lt)},A.click()},children:"Replace Image…"})})]}),L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx(Mt,{label:"Layers",theme:t,children:g.jsx(Te,{columns:4,children:[{fn:h,icon:Pn.sendToBack,tip:"Send to back"},{fn:f,icon:Pn.sendBackward,tip:"Send backward"},{fn:u,icon:Pn.bringForward,tip:"Bring forward"},{fn:d,icon:Pn.bringToFront,tip:"Bring to front"}].map(({fn:A,icon:lt,tip:mt})=>g.jsx(be,{variant:"action",theme:t,title:mt,width:"100%",height:32,onClick:()=>{A(o),i()},children:j=>lt(j?t.activeToolColor:t.textColor)},mt))})}),g.jsx(Mt,{label:"Actions",theme:t,children:g.jsxs(Te,{columns:4,children:[g.jsx(be,{variant:"action",theme:t,title:"Duplicate (⌘D)",width:"100%",height:32,onClick:()=>c(o),children:A=>Yn.duplicate(A?t.activeToolColor:t.textColor)}),g.jsx(be,{variant:"action",theme:t,title:"Delete (⌫)",dangerHover:!0,width:"100%",height:32,onClick:()=>{a(o),i()},children:A=>Yn.delete(A?"#e03131":t.textColor)}),g.jsx(be,{variant:"action",theme:t,title:"Add link (coming soon)",width:"100%",height:32,disabled:!0,children:Yn.link(t.mutedTextColor)}),g.jsx(be,{variant:"action",theme:t,title:"Ungroup",width:"100%",height:32,onClick:()=>{B.getState().ungroupElements(o),i()},children:A=>Yn.ungroup(A?t.activeToolColor:t.textColor)})]})})]}),G&&L&&g.jsxs(g.Fragment,{children:[g.jsx("hr",{style:st}),g.jsx("button",{style:{display:"flex",alignItems:"center",justifyContent:"center",gap:4,width:"100%",padding:"5px 0",borderRadius:6,border:G.allLocked?"1.5px solid #ff9500":`1px solid ${t.toolbarBorder}`,background:G.allLocked?"#ff950010":"transparent",cursor:"pointer",fontSize:10,fontWeight:600,color:G.allLocked?"#ff9500":t.textColor,letterSpacing:.2,transition:"all 0.1s ease",outline:"none",marginBottom:2},title:G.allLocked?"Unlock position (⌘⇧L)":"Lock position (⌘⇧L)",onClick:()=>l(o),children:G.allLocked?g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 9.9-1"})]}),"Unlock"]}):g.jsxs(g.Fragment,{children:[g.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[g.jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),g.jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),"Lock Position"]})})]})]})},Ha=({x:t,y:e,items:n,onClose:o,theme:s})=>{const r=I.useRef(null),[i,l]=I.useState({x:t,y:e}),[a,c]=I.useState(!1),d=I.useRef(o);d.current=o,I.useEffect(()=>{const u=r.current;if(!u)return;const f=u.getBoundingClientRect(),p=u.parentElement;if(!p)return;const y=p.getBoundingClientRect();let m=t,W=e;t+f.width>y.width&&(m=Math.max(0,t-f.width)),e+f.height>y.height&&(W=Math.max(0,e-f.height)),l({x:m,y:W}),requestAnimationFrame(()=>c(!0))},[t,e]);const h=I.useCallback(()=>{d.current()},[]);return I.useEffect(()=>{const u=m=>{r.current&&!r.current.contains(m.target)&&h()},f=m=>{m.key==="Escape"&&h()},p=()=>h(),y=requestAnimationFrame(()=>{document.addEventListener("pointerdown",u,!0),document.addEventListener("keydown",f,!0),window.addEventListener("scroll",p,!0)});return()=>{cancelAnimationFrame(y),document.removeEventListener("pointerdown",u,!0),document.removeEventListener("keydown",f,!0),window.removeEventListener("scroll",p,!0)}},[h]),g.jsx("div",{ref:r,style:{position:"absolute",left:i.x,top:i.y,zIndex:1e3,background:s.panelBg,border:`1px solid ${s.toolbarBorder}`,borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.12)",padding:"4px 0",minWidth:180,backdropFilter:"blur(8px)",userSelect:"none",opacity:a?1:0,transform:a?"scale(1)":"scale(0.95)",transformOrigin:"top left",transition:"opacity 0.12s ease-out, transform 0.12s ease-out"},onContextMenu:u=>u.preventDefault(),children:n.map((u,f)=>g.jsxs(I.Fragment,{children:[u.divider&&g.jsx("div",{style:{height:1,background:s.toolbarBorder,margin:"4px 0"}}),g.jsxs("button",{onClick:()=>{u.disabled||(u.action(),o())},disabled:u.disabled,style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%",padding:"6px 12px",border:"none",background:"transparent",color:u.disabled?s.mutedTextColor:s.textColor,fontSize:13,cursor:u.disabled?"default":"pointer",textAlign:"left",fontFamily:"inherit",lineHeight:"20px"},onMouseEnter:p=>{u.disabled||(p.currentTarget.style.background=s.activeToolColor+"18")},onMouseLeave:p=>{p.currentTarget.style.background="transparent"},children:[g.jsx("span",{children:u.label}),u.shortcut&&g.jsx("span",{style:{color:s.mutedTextColor,fontSize:11,marginLeft:24,opacity:.8},children:u.shortcut})]})]},f))})},Oa=I.memo(Ha);let Yo=[];function yn(t){Yo=structuredClone(t)}function Ho(){return structuredClone(Yo)}function Na(){return Yo.length>0}function Fr(t){return t.toDataURL({pixelRatio:2})}function Ua(t,e="canvas.png"){const n=Fr(t),o=document.createElement("a");o.download=e,o.href=n,document.body.appendChild(o),o.click(),document.body.removeChild(o)}function Vr(t){return JSON.stringify(t,null,2)}function Ka(t,e="canvas.json"){const n=Vr(t),o=new Blob([n],{type:"application/json"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const Hn=20;function St(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function In(t,e){const n=_t(t,e);return n.length>0?n.join(","):"none"}function Oo(t){const{strokeColor:e,fillColor:n,strokeWidth:o,opacity:s,strokeStyle:r}=t.style,i=In(r,o),l=[`fill="${St(n==="transparent"?"none":n)}"`,`stroke="${St(e)}"`,`stroke-width="${o}"`,`opacity="${s}"`];return i!=="none"&&l.push(`stroke-dasharray="${i}"`),l.join(" ")}function On(t,e,n,o){return e.rotation?`<g transform="rotate(${e.rotation} ${n} ${o})">${t}</g>`:t}function za(t){const{x:e,y:n,width:o,height:s,cornerRadius:r}=t,i=r?` rx="${r}" ry="${r}"`:"",l=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${i} ${Oo(t)} />`;return On(l,t,e+o/2,n+s/2)}function Ja(t){const e=t.x+t.width/2,n=t.y+t.height/2,o=`<ellipse cx="${e}" cy="${n}" rx="${t.width/2}" ry="${t.height/2}" ${Oo(t)} />`;return On(o,t,e,n)}function $a(t){const e=un(t.width,t.height),n=[];for(let s=0;s<e.length;s+=2)n.push(`${t.x+e[s]},${t.y+e[s+1]}`);const o=`<polygon points="${n.join(" ")}" ${Oo(t)} />`;return On(o,t,t.x+t.width/2,t.y+t.height/2)}function Ra(t){const n=t.points.map((s,r)=>`${r%2===0?t.x+s:t.y+s}`),o=[];for(let s=0;s<n.length;s+=2)o.push(`${n[s]},${n[s+1]}`);return`<polyline points="${o.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round"${In(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${In(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function ja(t){const e=t.points,n={x:e[0],y:e[1]},o={x:e[e.length-2],y:e[e.length-1]},s=Jt(n,o,t.curvature??zt),r=t.x+n.x,i=t.y+n.y,l=t.x+s.x,a=t.y+s.y,c=t.x+o.x,d=t.y+o.y;return`<path d="M ${r} ${i} Q ${l} ${a} ${c} ${d}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round"${In(t.style.strokeStyle,t.style.strokeWidth)!=="none"?` stroke-dasharray="${In(t.style.strokeStyle,t.style.strokeWidth)}"`:""} />`}function Qa(t,e){const n=t.x-e.x,o=t.y-e.y,s=Math.sqrt(n*n+o*o)||1;return{x:n/s,y:o/s}}function qa(t){return{x:-t.y,y:t.x}}function Nn(t,e,n,o,s,r){const i=Qa(e,n),l=qa(i),a=o*.45;switch(t){case"arrow":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polyline points="${c.x},${c.y} ${e.x},${e.y} ${d.x},${d.y}" fill="none" stroke="${St(s)}" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round" />`}case"triangle":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"triangle_outline":{const c={x:e.x-i.x*o+l.x*a,y:e.y-i.y*o+l.y*a},d={x:e.x-i.x*o-l.x*a,y:e.y-i.y*o-l.y*a};return`<polygon points="${e.x},${e.y} ${c.x},${c.y} ${d.x},${d.y}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"circle":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="${St(s)}" stroke="${St(s)}" stroke-width="${r}" />`}case"circle_outline":{const c=o*.35,d=e.x-i.x*c,h=e.y-i.y*c;return`<circle cx="${d}" cy="${h}" r="${c}" fill="#ffffff" stroke="${St(s)}" stroke-width="${r}" />`}case"bar":{const c=a*1.2;return`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`}case"diamond":case"diamond_outline":{const c=a*.7,d=o*.55,h={x:e.x-i.x*d,y:e.y-i.y*d},u=t==="diamond"?St(s):"#ffffff";return`<polygon points="${e.x},${e.y} ${h.x+l.x*c},${h.y+l.y*c} ${h.x-i.x*d},${h.y-i.y*d} ${h.x-l.x*c},${h.y-l.y*c}" fill="${u}" stroke="${St(s)}" stroke-width="${r}" />`}case"crowfoot_one":{const c=a*1,d=o*.25,h={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<line x1="${h.x+l.x*c}" y1="${h.y+l.y*c}" x2="${h.x-l.x*c}" y2="${h.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`].join(`
|
|
2
|
+
`)}case"crowfoot_many":{const c=a*1,d=o*.6,h={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<polyline points="${e.x+l.x*c},${e.y+l.y*c} ${h.x},${h.y} ${e.x-l.x*c},${e.y-l.y*c}" fill="none" stroke="${St(s)}" stroke-width="${r}" />`].join(`
|
|
3
|
+
`)}case"crowfoot_one_or_many":{const c=a*1,d=o*.6,h=o*.25,u={x:e.x-i.x*h,y:e.y-i.y*h},f={x:e.x-i.x*d,y:e.y-i.y*d};return[`<line x1="${e.x+l.x*c}" y1="${e.y+l.y*c}" x2="${e.x-l.x*c}" y2="${e.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<line x1="${u.x+l.x*c}" y1="${u.y+l.y*c}" x2="${u.x-l.x*c}" y2="${u.y-l.y*c}" stroke="${St(s)}" stroke-width="${r}" />`,`<polyline points="${e.x+l.x*c},${e.y+l.y*c} ${f.x},${f.y} ${e.x-l.x*c},${e.y-l.y*c}" fill="none" stroke="${St(s)}" stroke-width="${r}" />`].join(`
|
|
4
|
+
`)}default:return""}}function td(t){const e=[],n=t.lineType==="curved";if(e.push(n?ja(t):Ra(t)),t.type==="arrow"){const o=t,s=o.startArrowhead??(o.startArrow?"arrow":null),r=o.endArrowhead??(o.endArrow?"arrow":null),i=Lo(t.style.strokeWidth),l=t.points;if(n){const a={x:l[0],y:l[1]},c={x:l[l.length-2],y:l[l.length-1]},d=Jt(a,c,o.curvature??zt),h={x:t.x+a.x,y:t.y+a.y},u={x:t.x+c.x,y:t.y+c.y},f={x:t.x+d.x*.1+a.x*.9,y:t.y+d.y*.1+a.y*.9},p={x:t.x+d.x*.1+c.x*.9,y:t.y+d.y*.1+c.y*.9};s&&e.push(Nn(s,h,f,i,t.style.strokeColor,t.style.strokeWidth)),r&&e.push(Nn(r,u,p,i,t.style.strokeColor,t.style.strokeWidth))}else{if(s&&l.length>=4){const a={x:t.x+l[0],y:t.y+l[1]},c={x:t.x+l[2],y:t.y+l[3]};e.push(Nn(s,a,c,i,t.style.strokeColor,t.style.strokeWidth))}if(r&&l.length>=4){const a={x:t.x+l[l.length-2],y:t.y+l[l.length-1]},c={x:t.x+l[l.length-4],y:t.y+l[l.length-3]};e.push(Nn(r,a,c,i,t.style.strokeColor,t.style.strokeWidth))}}}return e.join(`
|
|
5
|
+
`)}function ed(t){if(t.points.length<4)return"";const e=[];for(let n=0;n<t.points.length;n+=2)e.push(`${t.x+t.points[n]},${t.y+t.points[n+1]}`);return`<polyline points="${e.join(" ")}" fill="none" stroke="${St(t.style.strokeColor)}" stroke-width="${t.style.strokeWidth}" opacity="${t.style.opacity}" stroke-linecap="round" stroke-linejoin="round" />`}function nd(t){if(!t.text)return"";const{style:e,x:n,y:o,text:s,textAlign:r}=t,i=s.split(`
|
|
6
|
+
`),l=e.fontSize*1.18;let a="start",c=0;r==="center"?(a="middle",c=t.width/2):r==="right"&&(a="end",c=t.width);const d=i.map((u,f)=>`<tspan x="${n+c}" dy="${f===0?0:l}">${St(u)}</tspan>`).join(""),h=[`font-family="${St(e.fontFamily)}"`,`font-size="${e.fontSize}"`,`fill="${St(e.strokeColor)}"`,`opacity="${e.opacity}"`,`text-anchor="${a}"`];return`<text x="${n+c}" y="${o+e.fontSize}" ${h.join(" ")}>${d}</text>`}function od(t){const{x:e,y:n,width:o,height:s,src:r,cornerRadius:i,style:l}=t,a=[],c=i>0?`clip-${t.id}`:"";c&&a.push(`<defs><clipPath id="${c}"><rect x="${e}" y="${n}" width="${o}" height="${s}" rx="${i}" ry="${i}" /></clipPath></defs>`);const d=`<image href="${St(r)}" x="${e}" y="${n}" width="${o}" height="${s}" opacity="${l.opacity}" preserveAspectRatio="none"${c?` clip-path="url(#${c})"`:""} />`;let h="";if(l.strokeWidth>0&&l.strokeColor!=="transparent"){const f=i?` rx="${i}" ry="${i}"`:"";h=`<rect x="${e}" y="${n}" width="${o}" height="${s}"${f} fill="none" stroke="${St(l.strokeColor)}" stroke-width="${l.strokeWidth}" opacity="${l.opacity}" />`}const u=a.join("")+d+h;return On(u,t,e+o/2,n+s/2)}function sd(t){switch(t.type){case"rectangle":return za(t);case"ellipse":return Ja(t);case"diamond":return $a(t);case"line":case"arrow":return td(t);case"freedraw":return ed(t);case"text":return nd(t);case"image":return od(t);default:return""}}function Ne(t){if(t.length===0)return'<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"></svg>';let e=1/0,n=1/0,o=-1/0,s=-1/0;for(const d of t)if(d.isVisible)if(d.type==="line"||d.type==="arrow"||d.type==="freedraw"){const h=d.points;for(let u=0;u<h.length;u+=2){const f=d.x+h[u],p=d.y+h[u+1];e=Math.min(e,f),n=Math.min(n,p),o=Math.max(o,f),s=Math.max(s,p)}}else e=Math.min(e,d.x),n=Math.min(n,d.y),o=Math.max(o,d.x+d.width),s=Math.max(s,d.y+d.height);const r=o-e+Hn*2,i=s-n+Hn*2,l=-e+Hn,a=-n+Hn,c=t.filter(d=>d.isVisible).map(d=>sd(d)).filter(Boolean).join(`
|
|
7
7
|
`);return[`<svg xmlns="http://www.w3.org/2000/svg" width="${r}" height="${i}" viewBox="0 0 ${r} ${i}">`,` <g transform="translate(${l} ${a})">`,` ${c}`," </g>","</svg>"].join(`
|
|
8
|
-
`)}function $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
|
|
8
|
+
`)}function rd(t,e="canvas.svg"){const n=Ne(t),o=new Blob([n],{type:"image/svg+xml"}),s=URL.createObjectURL(o),r=document.createElement("a");r.download=e,r.href=s,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(s)}const id=5;function ld(t){if((t.type==="line"||t.type==="arrow"||t.type==="freedraw")&&"points"in t){const e=t.points;let n=1/0,o=-1/0,s=1/0,r=-1/0;for(let i=0;i<e.length;i+=2){const l=t.x+e[i],a=t.y+e[i+1];n=Math.min(n,l),o=Math.max(o,l),s=Math.min(s,a),r=Math.max(r,a)}return{left:n,right:o,top:s,bottom:r,cx:(n+o)/2,cy:(s+r)/2}}return{left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2}}function cd(t,e,n,o=id){const s={left:t.x,right:t.x+t.width,top:t.y,bottom:t.y+t.height,cx:t.x+t.width/2,cy:t.y+t.height/2},r=[],i=[];for(const a of e){if(n.has(a.id)||!a.isVisible||a.type==="text"&&a.containerId)continue;const c=ld(a),d=[[s.left,"left",c.left],[s.left,"left",c.right],[s.right,"right",c.left],[s.right,"right",c.right],[s.cx,"cx",c.cx],[s.left,"left",c.cx],[s.right,"right",c.cx],[s.cx,"cx",c.left],[s.cx,"cx",c.right]];for(const[u,f,p]of d)Math.abs(u-p)<o&&r.push({value:p,edge:f,other:c});const h=[[s.top,"top",c.top],[s.top,"top",c.bottom],[s.bottom,"bottom",c.top],[s.bottom,"bottom",c.bottom],[s.cy,"cy",c.cy],[s.top,"top",c.cy],[s.bottom,"bottom",c.cy],[s.cy,"cy",c.top],[s.cy,"cy",c.bottom]];for(const[u,f,p]of h)Math.abs(u-p)<o&&i.push({value:p,edge:f,other:c})}const l={guides:[]};if(r.length>0){r.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=r[0],c=a.value-s[a.edge];l.x=t.x+c;const d=a.value,h=r.filter(p=>Math.abs(p.value-d)<1);let u=s.top+(l.y!==void 0?l.y-t.y:0),f=s.bottom+(l.y!==void 0?l.y-t.y:0);for(const p of h)u=Math.min(u,p.other.top),f=Math.max(f,p.other.bottom);l.guides.push({orientation:"v",position:d,start:u-10,end:f+10})}if(i.length>0){i.sort((p,y)=>Math.abs(p.value-s[p.edge])-Math.abs(y.value-s[y.edge]));const a=i[0],c=a.value-s[a.edge];l.y=t.y+c;const d=a.value,h=i.filter(p=>Math.abs(p.value-d)<1);let u=s.left+(l.x!==void 0?l.x-t.x:0),f=s.right+(l.x!==void 0?l.x-t.x:0);for(const p of h)u=Math.min(u,p.other.left),f=Math.max(f,p.other.right);l.guides.push({orientation:"h",position:d,start:u-10,end:f+10})}return l}function ad(t=!0,e){const n=B(k=>k.setActiveTool),o=B(k=>k.undo),s=B(k=>k.redo),r=B(k=>k.selectedIds),i=B(k=>k.elements),l=B(k=>k.deleteElements),a=B(k=>k.duplicateElements),c=B(k=>k.bringToFront),d=B(k=>k.sendToBack),h=B(k=>k.bringForward),u=B(k=>k.sendBackward),f=B(k=>k.toggleGrid),p=B(k=>k.showGrid),y=B(k=>k.zoomIn),m=B(k=>k.zoomOut),W=B(k=>k.resetZoom),v=B(k=>k.zoomToFit),D=B(k=>k.zoomToSelection),$=B(k=>k.clearSelection),T=B(k=>k.updateElement),O=B(k=>k.addElement),ot=B(k=>k.setSelectedIds),F=B(k=>k.pushHistory),J=dn(),Y=I.useCallback(()=>{r.length!==0&&yn(Us(r,i))},[r,i]),Q=I.useCallback(()=>{const k=Ho();if(k.length===0)return;const C=20,{clones:w,selectedCloneIds:S}=En(k,k,C);w.forEach(Z=>O(Z)),ot(S.length>0?S:w.map(Z=>Z.id)),F(),yn(k.map(Z=>({...Z,x:Z.x+C,y:Z.y+C})))},[O,ot,F]),M=I.useCallback((k,C)=>{r.length!==0&&(r.forEach(w=>{const S=i.find(Z=>Z.id===w);S&&!S.isLocked&&T(w,{x:S.x+k,y:S.y+C})}),F())},[r,i,T,F]);I.useEffect(()=>{if(!t)return;const k=C=>{const w=C.target.tagName;if(w==="INPUT"||w==="TEXTAREA"||w==="SELECT")return;const S=C.metaKey||C.ctrlKey;if(!S&&!C.shiftKey){const G={v:"select",h:"hand",r:"rectangle",o:"ellipse",d:"diamond",l:"line",a:"arrow",p:"freedraw",t:"text",i:"image",e:"eraser"}[C.key.toLowerCase()];if(G){C.preventDefault(),n(G);return}}if(S&&C.key==="z"&&!C.shiftKey){C.preventDefault(),o();return}if(S&&C.key==="z"&&C.shiftKey){C.preventDefault(),s();return}if(S&&C.key==="y"){C.preventDefault(),s();return}if((C.key==="Delete"||C.key==="Backspace")&&!S){if(J.isEditing&&J.selectedPointIndices.length>0){C.preventDefault();const{elements:Z,updateElement:G,pushHistory:U}=B.getState(),X=Z.find(L=>L.id===J.elementId);if(X){const L=X.points.length/2,at=new Set(J.selectedPointIndices);if(L-at.size>=2){const E=[];for(let st=0;st<L;st++)at.has(st)||E.push(X.points[st*2],X.points[st*2+1]);const V=E[0],dt=E[1],R=[];for(let st=0;st<E.length;st+=2)R.push(E[st]-V,E[st+1]-dt);let K=0,et=0,Ct=0,bt=0;for(let st=0;st<R.length;st+=2)K=Math.min(K,R[st]),et=Math.max(et,R[st]),Ct=Math.min(Ct,R[st+1]),bt=Math.max(bt,R[st+1]);const rt={x:X.x+V,y:X.y+dt,points:R,width:et-K,height:bt-Ct};at.has(0)&&(rt.startBinding=null),at.has(L-1)&&(rt.endBinding=null),G(X.id,rt),U(),J.setSelectedPoints([])}}return}if(r.length>0){C.preventDefault();const Z=r.filter(G=>{const U=i.find(X=>X.id===G);return U&&!U.isLocked});Z.length>0&&l(Z)}return}if(S&&C.key==="d"){C.preventDefault(),r.length>0&&a(r);return}if(C.key==="]"&&S&&C.shiftKey){C.preventDefault(),c(r);return}if(C.key==="["&&S&&C.shiftKey){C.preventDefault(),d(r);return}if(C.key==="]"&&S&&!C.shiftKey){C.preventDefault(),h(r);return}if(C.key==="["&&S&&!C.shiftKey){C.preventDefault(),u(r);return}if(C.key==="g"&&!S){C.preventDefault(),f();return}if(S&&(C.key==="="||C.key==="+")){C.preventDefault(),y();return}if(S&&C.key==="-"){C.preventDefault(),m();return}if(S&&C.key==="0"){C.preventDefault(),W();return}if(S&&C.shiftKey&&C.key==="1"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();v(Z.width,Z.height,void 0,{animate:!0})}return}if(S&&C.shiftKey&&C.key==="2"){if(C.preventDefault(),e!=null&&e.current){const Z=e.current.getBoundingClientRect();D(Z.width,Z.height,{animate:!0})}return}if(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(C.key)&&!S&&r.length>0&&!J.isEditing){C.preventDefault();const Z=p?xe:1,G=C.shiftKey?Z*10:Z,U=C.key==="ArrowLeft"?-G:C.key==="ArrowRight"?G:0,X=C.key==="ArrowUp"?-G:C.key==="ArrowDown"?G:0;M(U,X);return}if(S&&C.key==="c"){r.length>0&&(C.preventDefault(),Y());return}if(!(S&&C.key==="v")){if(S&&C.key==="x"){r.length>0&&(C.preventDefault(),Y(),l(r));return}if(S&&C.key==="g"&&!C.shiftKey){if(C.preventDefault(),r.length>=2){const{groupElements:Z}=B.getState();Z(r)}return}if(S&&C.key==="g"&&C.shiftKey){if(C.preventDefault(),r.length>0){const{ungroupElements:Z}=B.getState();Z(r)}return}if(S&&C.shiftKey&&C.key==="l"){if(C.preventDefault(),r.length>0){const{toggleLockElements:Z}=B.getState();Z(r)}return}if(C.key==="Escape"){if(C.preventDefault(),J.isEditing){J.exitEditMode();return}$(),n("select");return}if(S&&C.key==="a"){C.preventDefault();const{elements:Z,setSelectedIds:G}=B.getState();G(Z.map(U=>U.id));return}}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[t,n,o,s,r,i,l,a,c,d,h,u,f,p,y,m,W,v,D,e,$,J,M,Y,Q])}function No(t){if((t.type==="line"||t.type==="arrow")&&"points"in t){const e=t.points;let n=0,o=0,s=0,r=0;for(let i=0;i<e.length;i+=2){const l=e[i],a=e[i+1];l<n&&(n=l),l>o&&(o=l),a<s&&(s=a),a>r&&(r=a)}return{minX:t.x+n,minY:t.y+s,maxX:t.x+o,maxY:t.y+r,id:t.id}}return t.type==="freedraw"?{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}:{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,id:t.id}}class Uo{constructor(e=9){ct(this,"tree");ct(this,"_elementMap",new Map);ct(this,"_fattenedMap",new Map);ct(this,"_margin",50);this.tree=new Qi(e)}get margin(){return this._margin}set margin(e){this._margin=Math.max(0,e)}rebuild(e){this._elementMap.clear(),this._fattenedMap.clear();const n=this._margin,o=new Array(e.length);for(let s=0;s<e.length;s++){const r=e[s];this._elementMap.set(r.id,r);const i=No(r),l={minX:i.minX-n,minY:i.minY-n,maxX:i.maxX+n,maxY:i.maxY+n,id:r.id};this._fattenedMap.set(r.id,{trueMinX:i.minX,trueMinY:i.minY,trueMaxX:i.maxX,trueMaxY:i.maxY,item:l}),o[s]=l}this.tree.clear(),this.tree.load(o)}update(e){this._elementMap.set(e.id,e);const n=No(e),o=this._fattenedMap.get(e.id);if(o){const{item:i}=o;if(n.minX>=i.minX&&n.minY>=i.minY&&n.maxX<=i.maxX&&n.maxY<=i.maxY)return o.trueMinX=n.minX,o.trueMinY=n.minY,o.trueMaxX=n.maxX,o.trueMaxY=n.maxY,!1;this.tree.remove(i,(l,a)=>l.id===a.id)}const s=this._margin,r={minX:n.minX-s,minY:n.minY-s,maxX:n.maxX+s,maxY:n.maxY+s,id:e.id};return this._fattenedMap.set(e.id,{trueMinX:n.minX,trueMinY:n.minY,trueMaxX:n.maxX,trueMaxY:n.maxY,item:r}),this.tree.insert(r),!0}remove(e){const n=this._fattenedMap.get(e);n&&this.tree.remove(n.item,(o,s)=>o.id===s.id),this._elementMap.delete(e),this._fattenedMap.delete(e)}queryViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,u=this.tree.search({minX:a,minY:c,maxX:d,maxY:h}),f=new Array(u.length);for(let p=0;p<u.length;p++)f[p]=u[p].id;return f}queryRect(e,n,o,s){return this.tree.search({minX:e,minY:n,maxX:o,maxY:s})}queryPoint(e,n){return this.tree.search({minX:e,minY:n,maxX:e,maxY:n}).map(o=>o.id)}getElementById(e){return this._elementMap.get(e)}get elementMap(){return this._elementMap}get size(){return this._elementMap.size}getTrueAABB(e){const n=this._fattenedMap.get(e);if(n)return{minX:n.trueMinX,minY:n.trueMinY,maxX:n.trueMaxX,maxY:n.trueMaxY}}clear(){this.tree.clear(),this._elementMap.clear(),this._fattenedMap.clear()}}let Ko=null;function dd(){return Ko||(Ko=new Uo),Ko}const Pr=200;function ud(t,e,n,o,s,r){const i=I.useRef(new Uo),l=I.useMemo(()=>Rs(s),[s]),a=I.useRef([]),c=I.useRef([]),d=I.useRef(0);if(t!==c.current){const h=c.current;if(c.current=t,t.length>Pr)if(t.length!==d.current)i.current.rebuild(t);else{const f=i.current;for(let p=0;p<t.length;p++)t[p]!==h[p]&&f.update(t[p])}d.current=t.length}return I.useMemo(()=>{if(t.length<=Pr)return Js(t,e,n,o,l,r);const u=i.current.queryViewport(e,n,o,r),f=new Set(u);for(const m of s)f.add(m);const p=[];for(const m of t)f.has(m.id)&&p.push(m);const y=a.current;if(p.length===y.length){let m=!0;for(let W=0;W<p.length;W++)if(p[W]!==y[W]){m=!1;break}if(m)return y}return a.current=p,p},[t,e.x,e.y,e.scale,n,o,l,s,r])}const gd=[.0625,.125,.25,.5,1,2,4,8];function Yr(t){const e=gd;if(t<=e[0])return e[0];if(t>=e[e.length-1])return e[e.length-1];for(let n=0;n<e.length-1;n++){const o=(e[n]+e[n+1])/2;if(t<=o)return e[n]}return e[e.length-1]}function Hr(t){return I.useMemo(()=>Yr(t),[t])}const hd=500,fd=500;function Or(t,e={}){const{batchSize:n=fd,threshold:o=hd,enabled:s=!0}=e,r=I.useRef(0),[i,l]=I.useState(0),a=I.useRef([]),c=I.useRef(!1),d=I.useRef(0);t!==a.current&&(a.current=t);const u=s&&t.length>o;I.useEffect(()=>{if(!u){l(t.length),c.current=!0,d.current=t.length;return}const m=d.current;if(c.current&&Math.abs(t.length-m)<n){l(t.length),d.current=t.length;return}const W=++r.current;c.current=!1,d.current=t.length,l(Math.min(n,t.length));let v=n;function D(){r.current===W&&(v=Math.min(v+n,t.length),l(v),v<t.length?requestAnimationFrame(D):c.current=!0)}return n<t.length?requestAnimationFrame(D):c.current=!0,()=>{r.current++}},[t,u,n]);const f=I.useMemo(()=>!u||i>=t.length?t:t.slice(0,i),[t,i,u]),p=u&&i<t.length,y=t.length>0?Math.min(i/t.length,1):1;return{visibleElements:f,isLoading:p,progress:y}}function Nr(t,e){const n=(e==null?void 0:e.timeout)??1e3;"requestIdleCallback"in window?window.requestIdleCallback(o=>{o.timeRemaining()>5?t():Nr(t,e)},{timeout:n}):setTimeout(t,100)}function pd(){return new Promise(t=>setTimeout(t,0))}const yd=200,Id=1e4;class Ur{constructor(e){ct(this,"_worker",null);ct(this,"_pending",new Map);ct(this,"_workerSupported",!0);ct(this,"_workerConfig");ct(this,"_onMessage",e=>{const n=e.data;if(!n||!n.requestId)return;const o=this._pending.get(n.requestId);o&&(this._pending.delete(n.requestId),n.type==="svgResult"?o.resolve(n.svg):n.type==="error"&&o.reject(new Error(n.message)))});this._workerConfig=e}_getWorker(){if(!this._workerSupported)return null;if(this._worker)return this._worker;try{return this._worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGV4cG9ydFdvcmtlci50cyDigJQgV2ViIFdvcmtlciBmb3Igb2ZmLW1haW4tdGhyZWFkIFNWRyBleHBvcnQuCiAqCiAqIEdlbmVyYXRlcyBTVkcgc3RyaW5ncyBmcm9tIHNlcmlhbGl6ZWQgZWxlbWVudCBkYXRhIGluIGEgYmFja2dyb3VuZAogKiB0aHJlYWQsIGtlZXBpbmcgdGhlIG1haW4gdGhyZWFkIHJlc3BvbnNpdmUgZHVyaW5nIGV4cG9ydCBvZiBsYXJnZQogKiBjYW52YXNlcyAoMTBLKyBlbGVtZW50cykuCiAqCiAqIENvbW11bmljYXRpb24gcHJvdG9jb2w6CiAqICAgTWFpbiDihpIgV29ya2VyOgogKiAgICAgeyB0eXBlOiAnZXhwb3J0U1ZHJywgcmVxdWVzdElkOiBzdHJpbmcsIGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10gfQogKiAgIFdvcmtlciDihpIgTWFpbjoKICogICAgIHsgdHlwZTogJ3N2Z1Jlc3VsdCcsIHJlcXVlc3RJZDogc3RyaW5nLCBzdmc6IHN0cmluZyB9CiAqICAgICB7IHR5cGU6ICdlcnJvcicsIHJlcXVlc3RJZDogc3RyaW5nLCBtZXNzYWdlOiBzdHJpbmcgfQogKgogKiBVc2VzIFZpdGUncyBuYXRpdmUgV29ya2VyIG1vZHVsZSBzdXBwb3J0IOKAlCBpbXBvcnRlZCB3aXRoOgogKiAgIG5ldyBXb3JrZXIobmV3IFVSTCgnLi9leHBvcnRXb3JrZXIudHMnLCBpbXBvcnQubWV0YS51cmwpLCB7IHR5cGU6ICdtb2R1bGUnIH0pCiAqLwoKaW1wb3J0IHsgZXhwb3J0VG9TVkcgfSBmcm9tICdAL3V0aWxzL2V4cG9ydCc7CmltcG9ydCB0eXBlIHsgQ2FudmFzRWxlbWVudCB9IGZyb20gJ0AvdHlwZXMnOwoKLy8g4pSA4pSA4pSAIE1lc3NhZ2UgVHlwZXMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgppbnRlcmZhY2UgRXhwb3J0U1ZHTWVzc2FnZSB7CiAgICB0eXBlOiAnZXhwb3J0U1ZHJzsKICAgIHJlcXVlc3RJZDogc3RyaW5nOwogICAgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXTsKfQoKdHlwZSBJbmNvbWluZ01lc3NhZ2UgPSBFeHBvcnRTVkdNZXNzYWdlOwoKaW50ZXJmYWNlIFNWR1Jlc3VsdE1lc3NhZ2UgewogICAgdHlwZTogJ3N2Z1Jlc3VsdCc7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIHN2Zzogc3RyaW5nOwp9CgppbnRlcmZhY2UgRXJyb3JNZXNzYWdlIHsKICAgIHR5cGU6ICdlcnJvcic7CiAgICByZXF1ZXN0SWQ6IHN0cmluZzsKICAgIG1lc3NhZ2U6IHN0cmluZzsKfQoKdHlwZSBPdXRnb2luZ01lc3NhZ2UgPSBTVkdSZXN1bHRNZXNzYWdlIHwgRXJyb3JNZXNzYWdlOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBtYWluIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKc2VsZi5vbm1lc3NhZ2UgPSAoZXY6IE1lc3NhZ2VFdmVudDxJbmNvbWluZ01lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBldi5kYXRhOwoKICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICBjYXNlICdleHBvcnRTVkcnOiB7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBjb25zdCBzdmcgPSBleHBvcnRUb1NWRyhtc2cuZWxlbWVudHMpOwogICAgICAgICAgICAgICAgY29uc3QgcmVzcG9uc2U6IE91dGdvaW5nTWVzc2FnZSA9IHsKICAgICAgICAgICAgICAgICAgICB0eXBlOiAnc3ZnUmVzdWx0JywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgc3ZnLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9IGNhdGNoIChlcnIpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHJlc3BvbnNlOiBPdXRnb2luZ01lc3NhZ2UgPSB7CiAgICAgICAgICAgICAgICAgICAgdHlwZTogJ2Vycm9yJywKICAgICAgICAgICAgICAgICAgICByZXF1ZXN0SWQ6IG1zZy5yZXF1ZXN0SWQsCiAgICAgICAgICAgICAgICAgICAgbWVzc2FnZTogZXJyIGluc3RhbmNlb2YgRXJyb3IgPyBlcnIubWVzc2FnZSA6IFN0cmluZyhlcnIpLAogICAgICAgICAgICAgICAgfTsKICAgICAgICAgICAgICAgIHNlbGYucG9zdE1lc3NhZ2UocmVzcG9uc2UpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBkZWZhdWx0OgogICAgICAgICAgICBicmVhazsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href),this._workerConfig),this._worker?(this._worker.onmessage=this._onMessage,this._worker.onerror=e=>{console.warn("[ExportWorkerManager] Worker error, falling back to sync:",e.message),this._workerSupported=!1,this._rejectAll(new Error("Export Worker failed")),this._worker&&(this._worker.terminate(),this._worker=null)},this._worker):(this._workerSupported=!1,null)}catch{return this._workerSupported=!1,null}}_rejectAll(e){for(const[,n]of this._pending)n.reject(e);this._pending.clear()}async exportSVG(e){if(e.length<=yd)return Ne(e);const n=this._getWorker();if(!n)return Ne(e);const o=Pt();return new Promise((s,r)=>{this._pending.set(o,{resolve:s,reject:r});const i=setTimeout(()=>{if(this._pending.has(o)){this._pending.delete(o),console.warn("[ExportWorkerManager] Timeout, falling back to sync export");try{s(Ne(e))}catch(d){r(d)}}},Id),l=s,a=r,c=this._pending.get(o);c&&(c.resolve=d=>{clearTimeout(i),l(d)},c.reject=d=>{clearTimeout(i),a(d)}),n.postMessage({type:"exportSVG",requestId:o,elements:e})})}async downloadSVG(e,n="canvas.svg"){const o=await this.exportSVG(e),s=new Blob([o],{type:"image/svg+xml"}),r=URL.createObjectURL(s),i=document.createElement("a");i.download=n,i.href=r,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}dispose(){var e;this._rejectAll(new Error("ExportWorkerManager disposed")),(e=this._worker)==null||e.terminate(),this._worker=null}}let se=null,zo;function Cd(t){return se&&t&&JSON.stringify(t)!==JSON.stringify(zo)&&(se.dispose(),se=null),se||(zo=t,se=new Ur(t)),se}function Kr(){se&&(se.dispose(),se=null,zo=void 0)}const zr={canvasBackground:"#f8f9fa",gridColor:"#e5e5e5",selectionColor:"#4f8df7",toolbarBg:"rgba(255, 255, 255, 0.95)",toolbarBorder:"#e5e7eb",panelBg:"rgba(255, 255, 255, 0.95)",activeToolColor:"#4f46e5",textColor:"#374151",mutedTextColor:"#9ca3af"};let Rt=null,Wt=null,Jo=new Set;function Jr(t){return Wt&&Un(),Rt=new Kt.Doc,Wt=new ks.WebsocketProvider(t.serverUrl,t.roomName,Rt,{connect:!0,params:t.authToken?{token:t.authToken}:void 0}),Wt.awareness.setLocalState({user:t.user,cursor:null,selectedIds:[]}),Wt.on("status",e=>{const n=e.status;for(const o of Jo)o(n)}),{doc:Rt,provider:Wt}}function Un(){Wt&&(Wt.awareness.setLocalState(null),Wt.disconnect(),Wt.destroy(),Wt=null),Rt&&(Rt.destroy(),Rt=null)}function $r(){return Rt}function $o(){return Wt}function Rr(){return Rt==null?void 0:Rt.getMap("elements")}function bd(){return Wt!==null&&Wt.wsconnected}function jr(t){return Jo.add(t),()=>{Jo.delete(t)}}function Kn(t){if(!Wt)return;const e=Wt.awareness.getLocalState();Wt.awareness.setLocalState({...e,...t})}function Qr(){if(!Wt)return new Map;const t=Wt.awareness.getStates(),e=Wt.awareness.clientID,n=new Map;for(const[o,s]of t)o!==e&&s&&s.user&&n.set(o,s);return n}const Ro=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],zn=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"];function Cn(t,e){const n=t;for(const o of Ro){const s=n[o];s!==void 0&&e.set(o,s)}if(t.style)for(const o of zn)e.set(`style.${o}`,t.style[o]);switch(t.boundElements?e.set("boundElements",JSON.stringify(t.boundElements)):e.set("boundElements",null),t.groupIds&&e.set("groupIds",JSON.stringify(t.groupIds)),t.type){case"rectangle":e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":e.set("points",JSON.stringify(t.points)),e.set("lineType",t.lineType),t.curvature!==void 0&&e.set("curvature",t.curvature),e.set("startBinding",t.startBinding?JSON.stringify(t.startBinding):null),e.set("endBinding",t.endBinding?JSON.stringify(t.endBinding):null),t.type==="arrow"&&(e.set("startArrowhead",t.startArrowhead),e.set("endArrowhead",t.endArrowhead));break;case"freedraw":e.set("points",JSON.stringify(t.points));break;case"text":e.set("text",t.text),e.set("containerId",t.containerId),e.set("textAlign",t.textAlign),e.set("verticalAlign",t.verticalAlign);break;case"image":e.set("src",t.src),e.set("naturalWidth",t.naturalWidth),e.set("naturalHeight",t.naturalHeight),e.set("scaleMode",t.scaleMode),e.set("crop",t.crop?JSON.stringify(t.crop):null),e.set("cornerRadius",t.cornerRadius),e.set("alt",t.alt);break}}function Be(t){const e=t.get("type"),n=t.get("id");if(!e||!n)return null;const o={};for(const r of zn){const i=t.get(`style.${r}`);i!==void 0&&(o[r]=i)}const s={id:n,type:e,x:t.get("x")??0,y:t.get("y")??0,width:t.get("width")??100,height:t.get("height")??100,rotation:t.get("rotation")??0,isLocked:t.get("isLocked")??!1,isVisible:t.get("isVisible")??!0,style:o,boundElements:Ze(t.get("boundElements"))??null,groupIds:Ze(t.get("groupIds"))??void 0,sortOrder:t.get("sortOrder")??void 0};switch(e){case"rectangle":s.cornerRadius=t.get("cornerRadius")??0;break;case"line":case"arrow":s.points=Ze(t.get("points"))??[0,0,100,0],s.lineType=t.get("lineType")??"sharp",s.curvature=t.get("curvature")??void 0,s.startBinding=Ze(t.get("startBinding")),s.endBinding=Ze(t.get("endBinding")),e==="arrow"&&(s.startArrowhead=t.get("startArrowhead")??null,s.endArrowhead=t.get("endArrowhead")??"arrow");break;case"freedraw":s.points=Ze(t.get("points"))??[];break;case"text":s.text=t.get("text")??"",s.containerId=t.get("containerId")??null,s.textAlign=t.get("textAlign")??"center",s.verticalAlign=t.get("verticalAlign")??"middle";break;case"image":s.src=t.get("src")??"",s.naturalWidth=t.get("naturalWidth")??0,s.naturalHeight=t.get("naturalHeight")??0,s.scaleMode=t.get("scaleMode")??"fit",s.crop=Ze(t.get("crop"))??null,s.cornerRadius=t.get("cornerRadius")??0,s.alt=t.get("alt")??"";break}return s}function Ze(t){if(t==null)return null;try{return JSON.parse(t)}catch{return null}}let _e=!1,Me=!1,Jn=null,$n=null,Ue=null,re=[];function qr(t=50){const e=$r(),n=Rr();if(!e||!n){console.warn("[SyncBridge] Cannot start sync — no Yjs doc");return}if(Rn(),n.size>0){_e=!0;const l=wd(n);B.getState().setElements(l),re=l,_e=!1}else{const l=B.getState().elements;l.length>0&&(Me=!0,e.transact(()=>{for(const a of l){const c=new Kt.Map;Cn(a,c),n.set(a.id,c)}},"local-init"),Me=!1),re=l}const o=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||Me)return;_e=!0;const c=B.getState();let d=[...re],h=!1;for(const[u,f]of l.keys)if(f.action==="add"||f.action==="update"){const p=n.get(u);if(p){const y=Be(p);if(y){const m=d.findIndex(W=>W.id===u);m>=0?d[m]=y:d.push(y),h=!0}}}else f.action==="delete"&&(d=d.filter(p=>p.id!==u),h=!0);h&&(d.sort((u,f)=>u.sortOrder&&f.sortOrder?u.sortOrder<f.sortOrder?-1:u.sortOrder>f.sortOrder?1:0:0),c.setElements(d),re=d),_e=!1};let s=null;const r=new Set,i=l=>{if(!Me){for(const a of l){let c=a.target;for(;c&&!(c instanceof Kt.Map&&c.parent===n);)c=c.parent;if(c instanceof Kt.Map){const d=c.get("id");d&&r.add(d)}}s&&clearTimeout(s),s=setTimeout(()=>{if(r.size===0||Me)return;_e=!0;let a=[...re],c=!1;for(const d of r){const h=n.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}r.clear(),c&&(B.getState().setElements(a),re=a),_e=!1},16)}};n.observe(o),n.observeDeep(i),$n=()=>{n.unobserve(o),n.unobserveDeep(i),s&&clearTimeout(s),r.clear()},Jn=B.subscribe(l=>{_e||l.elements!==re&&(Ue&&clearTimeout(Ue),Ue=setTimeout(()=>{md(l.elements,n,e)},t))})}function Rn(){Jn&&(Jn(),Jn=null),$n&&($n(),$n=null),Ue&&(clearTimeout(Ue),Ue=null),re=[]}function md(t,e,n){Me=!0,re=t;const o=new Map;for(const s of t)o.set(s.id,s);n.transact(()=>{for(const[s]of e.entries())o.has(s)||e.delete(s);for(const s of t){let r=e.get(s.id);r?Ad(s,r):(r=new Kt.Map,Cn(s,r),e.set(s.id,r))}},"local-sync"),Me=!1}function Ad(t,e){const n=t;for(const s of Ro){const r=n[s];r!==e.get(s)&&e.set(s,r)}if(t.style)for(const s of zn){const r=t.style[s];r!==e.get(`style.${s}`)&&e.set(`style.${s}`,r)}const o=t.boundElements?JSON.stringify(t.boundElements):null;switch(o!==e.get("boundElements")&&e.set("boundElements",o),t.type){case"rectangle":t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius);break;case"line":case"arrow":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r),t.lineType!==e.get("lineType")&&e.set("lineType",t.lineType),t.curvature!==e.get("curvature")&&e.set("curvature",t.curvature);const i=t.startBinding?JSON.stringify(t.startBinding):null;i!==e.get("startBinding")&&e.set("startBinding",i);const l=t.endBinding?JSON.stringify(t.endBinding):null;l!==e.get("endBinding")&&e.set("endBinding",l),t.type==="arrow"&&(t.startArrowhead!==e.get("startArrowhead")&&e.set("startArrowhead",t.startArrowhead),t.endArrowhead!==e.get("endArrowhead")&&e.set("endArrowhead",t.endArrowhead));break}case"freedraw":{const r=JSON.stringify(t.points);r!==e.get("points")&&e.set("points",r);break}case"text":t.text!==e.get("text")&&e.set("text",t.text),t.containerId!==e.get("containerId")&&e.set("containerId",t.containerId),t.textAlign!==e.get("textAlign")&&e.set("textAlign",t.textAlign),t.verticalAlign!==e.get("verticalAlign")&&e.set("verticalAlign",t.verticalAlign);break;case"image":t.src!==e.get("src")&&e.set("src",t.src),t.naturalWidth!==e.get("naturalWidth")&&e.set("naturalWidth",t.naturalWidth),t.naturalHeight!==e.get("naturalHeight")&&e.set("naturalHeight",t.naturalHeight),t.scaleMode!==e.get("scaleMode")&&e.set("scaleMode",t.scaleMode);const s=t.crop?JSON.stringify(t.crop):null;s!==e.get("crop")&&e.set("crop",s),t.cornerRadius!==e.get("cornerRadius")&&e.set("cornerRadius",t.cornerRadius),t.alt!==e.get("alt")&&e.set("alt",t.alt);break}}function wd(t){const e=[];for(const[,n]of t.entries()){const o=Be(n);o&&e.push(o)}return e.sort((n,o)=>n.sortOrder&&o.sortOrder?n.sortOrder<o.sortOrder?-1:n.sortOrder>o.sortOrder?1:0:0),e}function ti(t){const[e,n]=I.useState("disconnected"),[o,s]=I.useState([]),r=I.useRef(t);r.current=t;const i=I.useRef((t==null?void 0:t.awarenessThrottleMs)??100),l=I.useRef(0);I.useEffect(()=>{if(!t){Un(),Rn(),n("disconnected"),s([]);return}const{provider:h}=Jr(t);qr(t.syncDebounceMs??50);const u=jr(n),f=()=>{const y=Qr();s(Array.from(y.values()))};h.awareness.on("change",f);const p=B.subscribe((y,m)=>{y.selectedIds!==m.selectedIds&&Kn({selectedIds:y.selectedIds}),y.activeTool!==m.activeTool&&Kn({activeTool:y.activeTool})});return()=>{u(),p(),h.awareness.off("change",f),Rn(),Un(),n("disconnected"),s([])}},[t==null?void 0:t.serverUrl,t==null?void 0:t.roomName,t==null?void 0:t.user.id,t==null?void 0:t.syncDebounceMs]);const a=I.useCallback(h=>{const u=Date.now();u-l.current<i.current||(l.current=u,Kn({cursor:h}))},[]),c=I.useCallback(()=>{const h=$o();h&&h.disconnect()},[]),d=I.useCallback(()=>{const h=$o();h&&h.connect()},[]);return{isConnected:e==="connected",connectionStatus:e,peers:o,disconnect:c,reconnect:d,updateCursor:a}}const xd=[0,0,0,18,4.5,14.5,9,20,12,18,7.5,12.5,14,12.5,0,0],jo=12,ei="system-ui, -apple-system, sans-serif",ni=6,oi=4,si=14,ri=18,ie={ctx:null,cache:new Map};function kd(t){const e=ie.cache.get(t);if(e!==void 0)return e;if(!ie.ctx)try{const o=document.createElement("canvas");ie.ctx=o.getContext("2d")}catch{}let n;return ie.ctx?(ie.ctx.font=`${jo}px ${ei}`,n=ie.ctx.measureText(t).width):n=t.length*7,ie.cache.size>200&&ie.cache.clear(),ie.cache.set(t,n),n}function ii(t,e,n,o,s,r){const i=(t-n.x)*n.scale,l=(e-n.y)*n.scale;return i>=-r&&i<=o+r&&l>=-r&&l<=s+r}function Sd(t,e,n,o,s){const r=t.x+t.width/2,i=t.y+t.height/2,l=Math.sqrt(t.width*t.width+t.height*t.height)/2;return ii(r,i,e,n,o,s+l*e.scale)}const vd=({peers:t,viewport:e,stageWidth:n,stageHeight:o,elements:s})=>{const r=I.useMemo(()=>{const a=new Map;for(const c of s)a.set(c.id,c);return a},[s]),i=1/e.scale,l=150;return g.jsx(g.Fragment,{children:t.map(a=>{if(!a.cursor&&a.selectedIds.length===0)return null;const{user:c}=a;return g.jsxs(gt.Group,{children:[a.selectedIds.map(d=>{const h=r.get(d);if(!h||!Sd(h,e,n,o,l))return null;const u=3*i;return g.jsx(gt.Rect,{x:h.x+h.width/2,y:h.y+h.height/2,offsetX:h.width/2+u,offsetY:h.height/2+u,width:h.width+u*2,height:h.height+u*2,rotation:h.rotation??0,stroke:c.color,strokeWidth:2*i,dash:[6*i,4*i],cornerRadius:3*i,listening:!1,perfectDrawEnabled:!1},d)}),a.cursor&&ii(a.cursor.x,a.cursor.y,e,n,o,l)&&g.jsxs(gt.Group,{x:a.cursor.x,y:a.cursor.y,scaleX:i,scaleY:i,listening:!1,children:[g.jsx(gt.Line,{points:xd,fill:c.color,stroke:"#ffffff",strokeWidth:1,closed:!0,perfectDrawEnabled:!1}),g.jsx(gt.Rect,{x:si,y:ri,width:kd(c.name)+ni*2,height:jo+oi*2,fill:c.color,cornerRadius:4,listening:!1,perfectDrawEnabled:!1}),g.jsx(gt.Text,{x:si+ni,y:ri+oi,text:c.name,fontSize:jo,fontFamily:ei,fill:"#ffffff",listening:!1,perfectDrawEnabled:!1})]})]},c.id)})})},li=I.memo(vd);qe.showWarnings=!1;function ci(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}const ai=10,Ed=({elements:t,listening:e,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditTextId:i,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u,onGroupDragEnd:f})=>{const p=I.useRef(null);I.useEffect(()=>{const v=p.current;if(!v||t.length===0)return;const $=(window.devicePixelRatio||1)*Math.max(1,u),T=requestAnimationFrame(()=>{if(!p.current)return;const O=v.getClientRect({skipTransform:!0}),ot=8192,F=O.width*$,J=O.height*$;if(F>ot||J>ot||O.width<=0||O.height<=0){v.clearCache(),v.batchDraw();return}v.cache({pixelRatio:$}),v.batchDraw()});return()=>{cancelAnimationFrame(T),v.clearCache()}},[t,u,i]);const{ungrouped:y,groups:m}=I.useMemo(()=>{var $;const v=[],D=new Map;for(const T of t)if(($=T.groupIds)!=null&&$.length){const O=T.groupIds[T.groupIds.length-1];D.has(O)||D.set(O,[]),D.get(O).push(T)}else v.push(T);return{ungrouped:v,groups:D}},[t]),W=I.useCallback(v=>{var D;(D=p.current)==null||D.clearCache()},[]);return g.jsxs(gt.Layer,{ref:p,listening:e,children:[y.map(v=>g.jsx(Ln,{element:v,isSelected:!1,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===v.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},v.id)),Array.from(m.entries()).map(([v,D])=>{const $=D.some(T=>T.isLocked);return g.jsx(gt.Group,{draggable:!$,onDragStart:W,onDragEnd:T=>{const O=T.target.x(),ot=T.target.y();T.target.x(0),T.target.y(0),f==null||f(v,O,ot)},children:D.map(T=>g.jsx(Ln,{element:T,isSelected:!1,isGrouped:!0,onSelect:n,onChange:o,onDragMove:s,onDoubleClick:r,autoEditText:i===T.id,onTextEditStart:l,onTextEditEnd:a,allElements:c,gridSnap:d,onDragSnap:h,viewportScale:u},T.id))},v)})]})},Wd=I.memo(Ed,(t,e)=>!(t.elements!==e.elements||t.listening!==e.listening||t.autoEditTextId!==e.autoEditTextId||t.gridSnap!==e.gridSnap||t.viewportScale!==e.viewportScale)),Td=({element:t,scale:e})=>{const n=20/e,o=n/24;return g.jsxs(gt.Group,{x:t.x-n/2,y:t.y-n/2,listening:!1,children:[g.jsx(gt.Rect,{width:n,height:n,fill:"#ff9500",cornerRadius:n/4,opacity:.9}),g.jsx(gt.Path,{x:n*.12,y:n*.08,data:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z",fill:"white",scaleX:o*.78,scaleY:o*.78,listening:!1})]})},di=I.forwardRef((t,e)=>{const{initialElements:n,elements:o,onChange:s,onSelectionChange:r,onElementCreate:i,onElementDelete:l,onElementDoubleClick:a,width:c="100%",height:d="100%",tools:h,defaultStyle:u,showToolbar:f=!0,toolbarPosition:p="bottom",defaultTool:y,showStylePanel:m=!0,showStatusBar:W=!0,showGrid:v=!1,enableShortcuts:D=!0,theme:$,readOnly:T=!1,className:O,contextMenuItems:ot,renderContextMenu:F,collaboration:J,workerConfig:Y}=t,Q={...zr,...$},M=I.useMemo(()=>({elbowWorkerConfig:Y!=null&&Y.disabled?{disabled:!0}:Y!=null&&Y.elbowWorkerUrl?{url:Y.elbowWorkerUrl}:void 0,exportWorkerConfig:Y!=null&&Y.disabled?{disabled:!0}:Y!=null&&Y.exportWorkerUrl?{url:Y.exportWorkerUrl}:void 0}),[Y]),k=B(),{elements:C,selectedIds:w,activeTool:S,currentStyle:Z,viewport:G,showGrid:U,isDrawing:X,setIsDrawing:L,setDrawStart:at,drawStart:tt,addElement:E,updateElement:V,setSelectedIds:dt,clearSelection:R,setActiveTool:K,setViewport:et,deleteElements:Ct,pushHistory:bt,setElements:rt,setCurrentStyle:st,undo:pt,redo:A,toggleGrid:lt}=k,mt=I.useMemo(()=>Rs(w),[w]),{peers:j,updateCursor:Dt}=ti(J??null),Gt=I.useRef(null),Ot=I.useRef(null),Ge=I.useRef(null),jt=dn(),mn=jt.isEditing,[Nt,vt]=I.useState({width:800,height:600}),[Ft,Ut]=I.useState(null),[ou,Gi]=I.useState(null),su=I.useRef(null),[ru,Di]=I.useState(null),[Xi,$e]=I.useState(null),[Re,os]=I.useState(null),[le,je]=I.useState(null),[iu,ss]=I.useState([]),rs=I.useRef(!1),to=I.useRef(!1),[De,is]=I.useState(!1),Ae=I.useRef(!1),{isDraggingPoint:ls,elementId:Li}=jt,Fi=I.useRef([]),Qt=I.useMemo(()=>{let b=null;for(let P=0;P<C.length;P++){const nt=C[P];if(nt.type!=="line"&&nt.type!=="arrow"){b&&(b[P]=nt);continue}const it=nt;if(!it.startBinding&&!it.endBinding){b&&(b[P]=nt);continue}if(ls&&Li===nt.id){b&&(b[P]=nt);continue}const N=Se(it,C);N?(b||(b=C.slice(0,P)),b[P]={...it,...N}):b&&(b[P]=nt)}const _=b??C,z=Fi.current;if(_.length===z.length){let P=!0;for(let nt=0;nt<_.length;nt++)if(_[nt]!==z[nt]){P=!1;break}if(P)return z}return Fi.current=_,_},[C,ls,Li]),cs=I.useMemo(()=>{const b=new Map;for(const _ of Qt)b.set(_.id,_);return b},[Qt]),eo=ud(Qt,G,Nt.width,Nt.height,w),lu=Hr(G.scale),as=I.useRef([]),ds=I.useRef([]),{staticElements:cu,interactiveElements:au}=I.useMemo(()=>{var it,N;let b=Re?new Set([...mt,Re]):mt;if(b.size>0){const H=new Set(b);for(const q of eo)if(H.has(q.id)&&((it=q.groupIds)!=null&&it.length)){const ht=q.groupIds[q.groupIds.length-1];for(const ut of eo)(N=ut.groupIds)!=null&&N.includes(ht)&&H.add(ut.id)}H.size!==b.size&&(b=H)}const _=[],z=[];for(const H of eo)b.has(H.id)?z.push(H):_.push(H);const P=ci(_,as.current)?as.current:_,nt=ci(z,ds.current)?ds.current:z;return as.current=P,ds.current=nt,{staticElements:P,interactiveElements:nt}},[eo,mt,Re]),{visibleElements:du}=Or(cu,{batchSize:500,threshold:500,enabled:!0});ad(D&&!T,Ot),I.useEffect(()=>{u&&st({...wn,...u})},[]),I.useEffect(()=>{n&&n.length>0&&(rt(n),bt())},[]),I.useEffect(()=>{v!==U&<()},[]),I.useEffect(()=>{y&&K(y)},[]),I.useEffect(()=>{o&&rt(o)},[o,rt]);const Vi=I.useRef(C);I.useEffect(()=>{s&&C!==Vi.current&&s(C),Vi.current=C},[C,s]),I.useEffect(()=>{r&&r(w)},[w,r]),I.useEffect(()=>{const b=dn.getState();if(!b.isEditing)return;if(S!=="select"){b.exitEditMode();return}if(w.length!==1||w[0]!==b.elementId){b.exitEditMode();return}const _=C.find(z=>z.id===w[0]);_&&(_.type==="line"||_.type==="arrow")&&(!b.isEditing||b.elementId!==_.id)&&b.enterEditMode(_.id)},[w,S,C]),I.useEffect(()=>{const b=z=>{z.key==="Shift"&&(rs.current=!0)},_=z=>{z.key==="Shift"&&(rs.current=!1)};return window.addEventListener("keydown",b),window.addEventListener("keyup",_),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",_)}},[]),I.useEffect(()=>{const b=P=>{const nt=P.target.tagName;nt==="INPUT"||nt==="TEXTAREA"||nt==="SELECT"||P.code==="Space"&&!Ae.current&&(P.preventDefault(),Ae.current=!0,is(!0))},_=P=>{P.code==="Space"&&(Ae.current=!1,is(!1))},z=()=>{Ae.current&&(Ae.current=!1,is(!1))};return window.addEventListener("keydown",b),window.addEventListener("keyup",_),window.addEventListener("blur",z),()=>{window.removeEventListener("keydown",b),window.removeEventListener("keyup",_),window.removeEventListener("blur",z)}},[]),I.useEffect(()=>{const b=Ot.current;if(!b||T)return;const _=P=>{P.preventDefault(),P.stopPropagation(),P.dataTransfer&&(P.dataTransfer.dropEffect="copy")},z=async P=>{if(P.preventDefault(),P.stopPropagation(),!P.dataTransfer)return;const nt=Zo(P.dataTransfer);if(nt.length===0)return;const it=b.getBoundingClientRect();Gt.current;const N=B.getState().viewport,H=(P.clientX-it.left-N.x)/N.scale,q=(P.clientY-it.top-N.y)/N.scale,ht=B.getState().currentStyle;for(const ut of nt)try{const ft=await Zn(ut),yt=await hn(ft),xt=_n(ft,yt.naturalWidth,yt.naturalHeight,H,q,{...ht});E(xt),i==null||i(xt),dt([xt.id]),bt()}catch{}K("select")};return b.addEventListener("dragover",_),b.addEventListener("drop",z),()=>{b.removeEventListener("dragover",_),b.removeEventListener("drop",z)}},[T,E,dt,bt,K,i]),I.useEffect(()=>{if(T)return;const b=_=>{const z=_.target.tagName;if(z==="INPUT"||z==="TEXTAREA"||z==="SELECT")return;const P=_o(_);if(P.file||P.imgUrl)_.preventDefault(),_.stopPropagation(),(async()=>{try{const nt=await Ar(P);if(!nt)return;const it=await hn(nt),N=B.getState().viewport,H=Ot.current,q=H==null?void 0:H.getBoundingClientRect(),ht=q?(q.width/2-N.x)/N.scale:400,ut=q?(q.height/2-N.y)/N.scale:300,ft=B.getState().currentStyle,yt=_n(nt,it.naturalWidth,it.naturalHeight,ht,ut,{...ft});E(yt),i==null||i(yt),dt([yt.id]),bt(),K("select")}catch{}})();else{_.preventDefault(),_.stopPropagation();const nt=Ho();if(nt.length===0)return;const it=20,{clones:N,selectedCloneIds:H}=En(nt,nt,it);N.forEach(q=>E(q)),dt(H.length>0?H:N.map(q=>q.id)),bt(),yn(nt.map(q=>({...q,x:q.x+it,y:q.y+it})))}};return window.addEventListener("paste",b,!0),()=>window.removeEventListener("paste",b,!0)},[T,E,dt,bt,K,i]),I.useEffect(()=>{const b=Ot.current;if(!b)return;const _=new ResizeObserver(z=>{for(const P of z){const{width:nt,height:it}=P.contentRect;vt({width:Math.floor(nt),height:Math.floor(it)})}});return _.observe(b),()=>_.disconnect()},[]);const uu=I.useCallback(()=>{const b=Gt.current;if(!b)return null;const _=b.getPointerPosition();return _?{x:(_.x-G.x)/G.scale,y:(_.y-G.y)/G.scale}:null},[G]),gu=I.useCallback(b=>U?{x:At(b.x,xe),y:At(b.y,xe)}:b,[U]),no=I.useRef(null);no.current={elements:C,selectedIds:w,activeTool:S,currentStyle:Z,isDrawing:X,drawStart:tt,showGrid:U,addElement:E,updateElement:V,deleteElements:Ct,setSelectedIds:dt,clearSelection:R,setActiveTool:K,setIsDrawing:L,setDrawStart:at,pushHistory:bt,getPointerPos:uu,snapPos:gu,currentElementIdRef:Ge,shiftKeyRef:rs,startBindingRef:su,setSnapTarget:Gi,selectionBox:Ft,setSelectionBox:Ut,setAutoEditTextId:$e,linearEdit:{isEditing:jt.isEditing,elementId:jt.elementId,exitEditMode:jt.exitEditMode,enterEditMode:jt.enterEditMode},onElementCreate:i,onElementDelete:l};const Pi=I.useCallback(b=>{if(T||Ae.current)return;if(b.evt.button===2){to.current=!0,le&&je(null);return}to.current=!1;const z=no.current,P=z.getPointerPos();if(!P||(le&&je(null),z.activeTool==="hand"||De))return;const nt=fn(z.activeTool);nt==null||nt.onMouseDown(b,P,z),Ge.current&&os(Ge.current)},[T,le,De]),Yi=I.useCallback(b=>{if(Ae.current||T)return;const _=no.current,z=_.getPointerPos();if(!z)return;Dt(z);const P=fn(_.activeTool);P==null||P.onMouseMove(b,z,_)},[T,Dt]),us=I.useRef(null),Hi=I.useRef(Yi);Hi.current=Yi;const Oi=I.useMemo(()=>{var _,z;(z=(_=us.current)==null?void 0:_.cancel)==null||z.call(_);const b=$s(P=>{Hi.current(P)});return us.current=b,b},[]);I.useEffect(()=>()=>{var b,_;(_=(b=us.current)==null?void 0:b.cancel)==null||_.call(b),Tr(),Kr()},[]);const Ni=I.useCallback(()=>{const b=no.current,_=fn(b.activeTool);_==null||_.onMouseUp(b),requestAnimationFrame(()=>{os(null)})},[os]),hu=I.useCallback(b=>{b.evt.preventDefault();const _=Gt.current;if(!_)return;const z=_.getPointerPosition();if(!z)return;const P=1.05,nt=b.evt.deltaY>0?-1:1,it=Math.min(Le,Math.max(Xe,nt>0?G.scale*P:G.scale/P));et(Wn({viewport:G,point:z,targetScale:it}))},[G,et]),fu=I.useCallback(b=>{S!=="hand"&&!Ae.current&&!De||et({x:b.target.x(),y:b.target.y()})},[S,et,De]),gs=I.useCallback(b=>{var q;const{activeTool:_,elements:z,selectedIds:P,setSelectedIds:nt}=B.getState();if(_!=="select"||T)return;if(to.current){to.current=!1;return}const it=z.find(ht=>ht.id===b),N=it&&(it.type==="line"||it.type==="arrow"),H=dn.getState();if(N?(!H.isEditing||H.elementId!==b)&&H.enterEditMode(b):H.isEditing&&H.exitEditMode(),(q=it==null?void 0:it.groupIds)!=null&&q.length){const ht=it.groupIds[it.groupIds.length-1],ut=z.filter(ft=>{var yt;return(yt=ft.groupIds)==null?void 0:yt.includes(ht)}).map(ft=>ft.id);nt(ut)}else nt([b])},[T]),oo=I.useRef(null),hs=I.useRef(!1),fs=I.useRef(!1),we=I.useRef(null),Ui=I.useCallback(()=>{hs.current=!1;const b=oo.current;if(!b||b.size===0)return;const _=Array.from(b,([z,P])=>({id:z,updates:P}));b.clear(),B.getState().batchUpdateElements(_)},[]),so=I.useRef(new Set),ps=I.useCallback((b,_)=>{if(T)return;we.current===null&&(we.current=qe.pixelRatio,qe.pixelRatio=1);const{elements:z,selectedIds:P}=B.getState();if(P.length>ai){fs.current=!0;return}fs.current=!1;const nt=z.find(it=>it.id===b);if(nt&&(nt.type==="line"||nt.type==="arrow")&&!so.current.has(b)){const it=nt;if(it.startBinding||it.endBinding){so.current.add(b);const N={},H=it.type;if(it.startBinding){const q=B.getState().elements;ve(b,H,it.startBinding,null,q,B.getState().updateElement),N.startBinding=null}if(it.endBinding){const q=B.getState().elements;ve(b,H,it.endBinding,null,q,B.getState().updateElement),N.endBinding=null}B.getState().updateElement(b,{..._,...N});return}}oo.current||(oo.current=new Map),oo.current.set(b,_),hs.current||(hs.current=!0,queueMicrotask(Ui))},[T,Ui]),Ki=I.useCallback((b,_)=>{const{elements:z,selectedIds:P}=B.getState();if(P.length>1)return null;const nt=new Set(P),it=cd(_,z,nt);return ss(it.guides),it.x!==void 0||it.y!==void 0?{x:it.x??_.x,y:it.y??_.y}:null},[]),ro=I.useRef(null),ys=I.useRef(!1),zi=I.useCallback(()=>{ys.current=!1;const b=ro.current;if(!b||b.size===0)return;const _=Array.from(b);b.clear(),fs.current=!1,B.getState().batchUpdateElements(_.map(([H,q])=>({id:H,updates:q}))),ss([]);const P=B.getState().elements,nt=new Map;for(const H of P)nt.set(H.id,H);const it=[],N=new Set;for(const[H]of _){so.current.delete(H);const q=ln(H,P);for(const ut of q){if(N.has(ut.id))continue;N.add(ut.id);const ft=nt.get(ut.id);if(!ft)continue;const yt=Se(ft,P);yt&&it.push({id:ft.id,updates:yt})}const ht=nt.get(H);if(ht!=null&&ht.boundElements&&["rectangle","ellipse","diamond","image"].includes(ht.type))for(const ft of ht.boundElements){if(ft.type!=="text")continue;const yt=nt.get(ft.id);if(!yt)continue;const xt=Math.max(20,ht.width-8);let wt;yt.verticalAlign==="top"?wt=ht.y+4:yt.verticalAlign==="bottom"?wt=ht.y+ht.height-yt.height-4:wt=ht.y+(ht.height-yt.height)/2,it.push({id:ft.id,updates:{x:ht.x+4,y:wt,width:xt}})}}it.length>0&&B.getState().batchUpdateElements(it),B.getState().pushHistory(),we.current!==null&&(qe.pixelRatio=we.current,we.current=null)},[]),Is=I.useCallback((b,_)=>{if(T)return;const{selectedIds:z}=B.getState();if(z.length>ai){ro.current||(ro.current=new Map),ro.current.set(b,_),ys.current||(ys.current=!0,queueMicrotask(zi));return}V(b,_),ss([]),so.current.delete(b);const P=B.getState().elements,nt=new Map;for(const H of P)nt.set(H.id,H);const it=ln(b,P);for(const H of it){const q=nt.get(H.id);if(!q)continue;const ht=Se(q,P);ht&&V(q.id,ht)}const N=nt.get(b);if(N!=null&&N.boundElements&&["rectangle","ellipse","diamond","image"].includes(N.type))for(const q of N.boundElements){if(q.type!=="text")continue;const ht=nt.get(q.id);if(!ht)continue;const ut=Math.max(20,N.width-8);let ft;ht.verticalAlign==="top"?ft=N.y+4:ht.verticalAlign==="bottom"?ft=N.y+N.height-ht.height-4:ft=N.y+(N.height-ht.height)/2,V(q.id,{x:N.x+4,y:ft,width:ut})}if((N==null?void 0:N.type)==="text"){const H=N;if(H.containerId){const q=nt.get(H.containerId);if(q&&["rectangle","ellipse","diamond","image"].includes(q.type)){const ut=H.height+8;if(q.height<ut){V(q.id,{height:ut});const ft=B.getState().elements;for(const yt of ln(q.id,ft)){const xt=ft.find(Et=>Et.id===yt.id);if(!xt)continue;const wt=Se(xt,ft);wt&&V(xt.id,wt)}}}}}bt(),we.current!==null&&(qe.pixelRatio=we.current,we.current=null)},[V,bt,T,zi]),pu=I.useCallback((b,_,z)=>{if(T||_===0&&z===0)return;const P=B.getState(),it=P.elements.filter(yt=>{var xt;return(xt=yt.groupIds)==null?void 0:xt.includes(b)});if(it.length===0)return;const N=it.map(yt=>({id:yt.id,updates:{x:yt.x+_,y:yt.y+z}}));P.batchUpdateElements(N);const H=B.getState().elements,q=new Map;for(const yt of H)q.set(yt.id,yt);const ht=new Set(it.map(yt=>yt.id)),ut=[],ft=new Set;for(const yt of it){const xt=ln(yt.id,H);for(const Et of xt){if(ft.has(Et.id)||(ft.add(Et.id),ht.has(Et.id)))continue;const Bt=q.get(Et.id);if(!Bt)continue;const kt=Se(Bt,H);kt&&ut.push({id:Bt.id,updates:kt})}const wt=q.get(yt.id);if(wt!=null&&wt.boundElements&&["rectangle","ellipse","diamond","image"].includes(wt.type))for(const Bt of wt.boundElements){if(Bt.type!=="text"||ht.has(Bt.id))continue;const kt=q.get(Bt.id);if(!kt)continue;const Vt=Math.max(20,wt.width-8);let Xt;kt.verticalAlign==="top"?Xt=wt.y+4:kt.verticalAlign==="bottom"?Xt=wt.y+wt.height-kt.height-4:Xt=wt.y+(wt.height-kt.height)/2,ut.push({id:Bt.id,updates:{x:wt.x+4,y:Xt,width:Vt}})}}ut.length>0&&B.getState().batchUpdateElements(ut),P.pushHistory()},[T]),Cs=I.useCallback(b=>{var q,ht;if(T)return;const{activeTool:_,elements:z,currentStyle:P,addElement:nt,updateElement:it,setSelectedIds:N}=B.getState();if(_!=="select")return;const H=z.find(ut=>ut.id===b);if(H&&(a==null?void 0:a(b,H))!==!0){if(H.type==="line"||H.type==="arrow"){const ut=(q=H.boundElements)==null?void 0:q.find(Qe=>Qe.type==="text");if(ut){N([ut.id]),$e(ut.id);return}const ft=Pt(),yt=H,xt=yt.points,wt={x:xt[0],y:xt[1]},Et={x:xt[xt.length-2],y:xt[xt.length-1]};let Bt,kt;if(yt.lineType==="curved"){const Qe=Jt(wt,Et,yt.curvature??zt),An=Ye(wt,Qe,Et,.5);Bt=yt.x+An.x,kt=yt.y+An.y}else Bt=yt.x+(wt.x+Et.x)/2,kt=yt.y+(wt.y+Et.y)/2;const Vt={id:ft,type:"text",x:Bt,y:kt,width:100,height:30,rotation:0,style:{...P,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:b,textAlign:"center",verticalAlign:"middle"};nt(Vt),i==null||i(Vt);const Xt=H.boundElements??[];it(b,{boundElements:[...Xt,{id:ft,type:"text"}]}),N([ft]),$e(ft);return}if(H.type==="rectangle"||H.type==="ellipse"||H.type==="diamond"||H.type==="image"){const ut=(ht=H.boundElements)==null?void 0:ht.find(wt=>wt.type==="text");if(ut){N([ut.id]),$e(ut.id);return}const ft=Pt(),yt={id:ft,type:"text",x:H.x,y:H.y,width:H.width,height:30,rotation:0,style:{...P,fillColor:"transparent"},isLocked:!1,isVisible:!0,boundElements:null,text:"",containerId:b,textAlign:"center",verticalAlign:"middle"};nt(yt),i==null||i(yt);const xt=H.boundElements??[];it(b,{boundElements:[...xt,{id:ft,type:"text"}]}),N([ft]),$e(ft);return}}},[T,a,i]),yu=I.useCallback((b,_)=>{if(T)return;const{elements:z,updateElement:P,pushHistory:nt}=B.getState(),it=z.find(N=>N.id===b);if(P(b,_),it&&(_.startBinding!==void 0||_.endBinding!==void 0)){const N=it.type;if(_.startBinding!==void 0){const H=B.getState().elements;ve(b,N,it.startBinding,_.startBinding??null,H,B.getState().updateElement)}if(_.endBinding!==void 0){const H=B.getState().elements;ve(b,N,it.endBinding,_.endBinding??null,H,B.getState().updateElement)}}nt()},[T]),Iu=I.useCallback((b,_)=>{T||B.getState().updateElement(b,_)},[T]),Cu=I.useCallback(b=>{Gi(b)},[]),Ji=I.useCallback(b=>{Di(b)},[]),$i=I.useCallback((b,_)=>{if(Di(null),$e(null),_){const{elements:z,updateElement:P,deleteElements:nt,pushHistory:it}=B.getState(),N=z.find(H=>H.id===b);if((N==null?void 0:N.type)==="text"&&N.containerId){const H=N.containerId,q=z.find(ht=>ht.id===H);q!=null&&q.boundElements&&P(H,{boundElements:q.boundElements.filter(ht=>ht.id!==b)})}nt([b]),l==null||l([b])}else B.getState().pushHistory()},[l]),bu=I.useCallback(b=>{var nt,it;if(T)return;b.preventDefault();const _=Ot.current;if(!_)return;const z=_.getBoundingClientRect(),P=Gt.current;if(P){const N=P.getPointerPosition(),H=(N==null?void 0:N.x)??b.clientX-z.left,q=(N==null?void 0:N.y)??b.clientY-z.top,ht=B.getState().viewport,ut=(H-ht.x)/ht.scale,ft=(q-ht.y)/ht.scale,{elements:yt,selectedIds:xt,setSelectedIds:wt}=B.getState();let Et=null;for(let Bt=yt.length-1;Bt>=0;Bt--){const kt=yt[Bt];if(kt.type==="text"&&kt.containerId)continue;let Vt=kt.x,Xt=kt.y,Qe=kt.width,An=kt.height;if((kt.type==="arrow"||kt.type==="line")&&"points"in kt){const bs=kt.points,ms=[],As=[];for(let lo=0;lo<bs.length;lo+=2)ms.push(kt.x+bs[lo]),As.push(kt.y+bs[lo+1]);Vt=Math.min(...ms),Xt=Math.min(...As),Qe=Math.max(...ms)-Vt,An=Math.max(...As)-Xt}const io=Math.max(4,((nt=kt.style)==null?void 0:nt.strokeWidth)??2);if(ut>=Vt-io&&ut<=Vt+Qe+io&&ft>=Xt-io&&ft<=Xt+An+io){Et=kt;break}}if(Et&&!xt.includes(Et.id))if((it=Et.groupIds)!=null&&it.length){const Bt=Et.groupIds[Et.groupIds.length-1],kt=yt.filter(Vt=>{var Xt;return(Xt=Vt.groupIds)==null?void 0:Xt.includes(Bt)}).map(Vt=>Vt.id);wt(kt)}else wt([Et.id])}je({x:b.clientX-z.left,y:b.clientY-z.top})},[T]),mu=I.useMemo(()=>{var it;const b=w.length>0,z=navigator.platform.includes("Mac")?"⌘":"Ctrl+",P=[];P.push({label:"Copy",shortcut:`${z}C`,disabled:!b,action:()=>{b&&yn(Us(w,C))}}),P.push({label:"Paste",shortcut:`${z}V`,disabled:!Na(),action:()=>{const N=Ho();if(N.length===0)return;const H=20,{clones:q,selectedCloneIds:ht}=En(N,N,H);q.forEach(ut=>E(ut)),dt(ht.length>0?ht:q.map(ut=>ut.id)),bt(),yn(N.map(ut=>({...ut,x:ut.x+H,y:ut.y+H})))}}),P.push({label:"Duplicate",shortcut:`${z}D`,disabled:!b,action:()=>{b&&k.duplicateElements(w)}}),P.push({label:"Delete",shortcut:"Del",disabled:!b,divider:!0,action:()=>{b&&(Ct(w),l==null||l(w))}}),P.push({label:"Bring to Front",shortcut:`${z}⇧]`,disabled:!b,divider:!0,action:()=>{b&&k.bringToFront(w)}}),P.push({label:"Send to Back",shortcut:`${z}⇧[`,disabled:!b,action:()=>{b&&k.sendToBack(w)}});let nt=!1;if(w.length>=2){const N=C.filter(ut=>w.includes(ut.id)),H=new Set(N.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length}).map(ut=>ut.groupIds[ut.groupIds.length-1]));N.every(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.length})&&H.size===1||(P.push({label:"Group",shortcut:`${z}G`,divider:!0,action:()=>k.groupElements(w)}),nt=!0)}if(b){const N=C.filter(q=>w.includes(q.id));if(N.some(q=>{var ht;return(ht=q.groupIds)==null?void 0:ht.length})){const q=new Set;for(const ut of N)(it=ut.groupIds)!=null&&it.length&&q.add(ut.groupIds[ut.groupIds.length-1]);const ht=C.filter(ut=>{var ft;return(ft=ut.groupIds)==null?void 0:ft.some(yt=>q.has(yt))}).map(ut=>ut.id);P.push({label:"Ungroup",shortcut:`${z}⇧G`,divider:!nt,action:()=>k.ungroupElements(ht)})}}if(P.push({label:"Select All",shortcut:`${z}A`,divider:!0,action:()=>dt(C.map(N=>N.id))}),b){const N=C.filter(ht=>w.includes(ht.id)),H=N.every(ht=>ht.isLocked),q=N.some(ht=>ht.isLocked);P.push({label:H?"Unlock":q?"Unlock All":"Lock",shortcut:`${z}⇧L`,divider:!0,action:()=>k.toggleLockElements(w)})}if(b){const N=new Set(["rectangle","ellipse","diamond"]),H=C.filter(q=>w.includes(q.id)&&N.has(q.type));if(H.length>0){const q=new Set(H.map(ft=>ft.type)),ut=[{label:"Rectangle",type:"rectangle"},{label:"Ellipse",type:"ellipse"},{label:"Diamond",type:"diamond"}].filter(ft=>!q.has(ft.type)||q.size>1);ut.length>0&&ut.forEach((ft,yt)=>{P.push({label:`Convert to ${ft.label}`,divider:yt===0,action:()=>k.convertElementType(H.map(xt=>xt.id),ft.type)})})}}if(ot){const N=typeof ot=="function"?ot({selectedIds:w,elements:C,position:le??{x:0,y:0},close:()=>je(null)}):ot;if(N.length>0){P.push({...N[0],divider:!0});for(let H=1;H<N.length;H++)P.push(N[H])}}return P},[w,C,k,E,Ct,dt,bt,l,ot,le]);I.useImperativeHandle(e,()=>({getElements:()=>B.getState().elements,setElements:b=>{rt(b),bt()},addElement:b=>{E(b)},deleteElements:b=>{Ct(b)},getSelectedIds:()=>B.getState().selectedIds,setSelectedIds:b=>{dt(b)},clearSelection:()=>{R()},setActiveTool:b=>{K(b)},getActiveTool:()=>B.getState().activeTool,undo:()=>{pt()},redo:()=>{A()},zoomTo:b=>{et({scale:Math.min(Le,Math.max(Xe,b))})},resetView:()=>{et({x:0,y:0,scale:1})},scrollToElement:(b,_)=>{const z=B.getState().elements.find(wt=>wt.id===b);if(!z)return;const P=Ot.current;if(!P)return;const nt=P.getBoundingClientRect(),it=nt.width,N=nt.height,H=(_==null?void 0:_.zoom)??Math.max(B.getState().viewport.scale,1),q=Math.min(Le,Math.max(Xe,H)),ht=z.x+(z.width??0)/2,ut=z.y+(z.height??0)/2,ft=it/2-ht*q,yt=N/2-ut*q,xt={x:ft,y:yt,scale:q};_!=null&&_.animate?Ee(B.getState().viewport,xt,et):et(xt)},zoomToFit:(b,_)=>{const z=Ot.current;if(!z)return;const P=z.getBoundingClientRect(),nt=P.width,it=P.height;B.getState().zoomToFit(nt,it,b,{padding:_==null?void 0:_.padding,maxZoom:_==null?void 0:_.maxZoom,animate:_==null?void 0:_.animate})},exportPNG:()=>{var b;return((b=Gt.current)==null?void 0:b.toDataURL({pixelRatio:2}))??null},exportJSON:()=>JSON.stringify(B.getState().elements,null,2),exportSVG:()=>Ne(B.getState().elements),importJSON:b=>{try{const _=JSON.parse(b);Array.isArray(_)&&(rt(_),bt())}catch{}},getStage:()=>Gt.current}));const Au=()=>{var _;if(T)return"default";if(De||S==="hand")return"grab";const b=fn(S);return((_=b==null?void 0:b.getCursor)==null?void 0:_.call(b))??"default"},wu=h?co.filter(b=>h.includes(b.type)):co,xu=m&&!T&&(!["hand","select","eraser"].includes(S)||S==="select"&&w.length>0),Ri=!De&&["select","eraser","image"].includes(S);return g.jsx(Xo.Provider,{value:M,children:g.jsxs("div",{ref:Ot,className:O,onContextMenu:bu,onMouseLeave:()=>Dt(null),style:{position:"relative",width:c,height:d,overflow:"hidden",background:Q.canvasBackground},children:[f&&!T&&p!=="hidden"&&g.jsx(Za,{visibleTools:wu,theme:Q,position:p}),xu&&g.jsx(Ya,{theme:Q}),g.jsx("div",{style:{cursor:Au(),position:"absolute",top:0,left:0,right:0,bottom:0},children:g.jsxs(gt.Stage,{ref:Gt,width:Nt.width,height:Nt.height,x:G.x,y:G.y,scaleX:G.scale,scaleY:G.scale,draggable:(S==="hand"||De)&&!T,onMouseDown:Pi,onMouseMove:Oi,onMouseUp:Ni,onWheel:hu,onDragEnd:fu,onTouchStart:Pi,onTouchMove:Oi,onTouchEnd:Ni,children:[U&&g.jsx(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(aa,{width:Nt.width,height:Nt.height,viewport:G,gridColor:Q.gridColor})}),g.jsx(Wd,{elements:du,listening:Ri,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,autoEditTextId:Xi,onTextEditStart:Ji,onTextEditEnd:$i,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:Ki,viewportScale:G.scale,onGroupDragEnd:pu}),g.jsxs(gt.Layer,{listening:Ri,children:[au.filter(b=>b.id!==Re).map(b=>g.jsx(Ln,{element:b,isSelected:!0,isEditing:mn&&jt.elementId===b.id,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,autoEditText:Xi===b.id,onTextEditStart:Ji,onTextEditEnd:$i,allElements:Qt,gridSnap:U?xe:void 0,onDragSnap:U?void 0:Ki,viewportScale:lu},b.id)),S==="select"&&!T&&(()=>{const b=w.filter(_=>{const z=cs.get(_);return!(!z||z.type==="line"||z.type==="arrow"||z.type==="text"&&z.containerId||_===ru)});return b.length===0?null:g.jsx(la,{selectedIds:b,selectionColor:Q.selectionColor})})(),mn&&(()=>{const b=cs.get(jt.elementId??"");return b?g.jsx(Sa,{element:b,allElements:Qt,onPointsChange:yu,onPointDragMove:Iu,onSnapTargetChange:Cu,color:Q.selectionColor}):null})()]}),Re&&(()=>{const b=cs.get(Re);return b?g.jsx(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:g.jsx(Ln,{element:b,isSelected:!1,onSelect:gs,onChange:Is,onDragMove:ps,onDoubleClick:Cs,allElements:Qt,gridSnap:U?xe:void 0,viewportScale:G.scale},b.id)}):null})(),g.jsxs(gt.Layer,{listening:!1,hitGraphEnabled:!1,children:[g.jsx(ua,{box:Ft,selectionColor:Q.selectionColor,viewportScale:G.scale}),g.jsx(fa,{elements:Qt,snapTarget:ou,visible:(S==="line"||S==="arrow"||ls)&&!T,color:Q.selectionColor,viewportScale:G.scale}),iu.map((b,_)=>b.orientation==="v"?g.jsx(gt.Line,{points:[b.position,b.start,b.position,b.end],stroke:Q.selectionColor,strokeWidth:1/G.scale,dash:[4/G.scale,4/G.scale],listening:!1,perfectDrawEnabled:!1},`ag-${_}`):g.jsx(gt.Line,{points:[b.start,b.position,b.end,b.position],stroke:Q.selectionColor,strokeWidth:1/G.scale,dash:[4/G.scale,4/G.scale],listening:!1,perfectDrawEnabled:!1},`ag-${_}`)),Qt.filter(b=>b.isLocked&&mt.has(b.id)).map(b=>g.jsx(Td,{element:b,scale:G.scale},`lock-${b.id}`)),j.length>0&&g.jsx(li,{peers:j,viewport:G,stageWidth:Nt.width,stageHeight:Nt.height,elements:Qt})]})]})}),le&&(F?F({selectedIds:w,elements:C,position:le,close:()=>je(null)}):g.jsx(Oa,{x:le.x,y:le.y,items:mu,onClose:()=>je(null),theme:Q})),W&&g.jsx(Bd,{theme:Q})]})})});di.displayName="FlowCanvas";const Bd=I.memo(({theme:t})=>{const e=B(s=>s.elements.length),n=B(s=>s.activeTool),o=B(s=>s.selectedIds.length);return g.jsxs("div",{style:{position:"absolute",bottom:16,left:12,zIndex:50,display:"flex",alignItems:"center",gap:10,background:t.toolbarBg,backdropFilter:"blur(8px)",boxShadow:"0 1px 3px rgba(0,0,0,0.08)",borderRadius:8,padding:"4px 12px",border:`1px solid ${t.toolbarBorder}`,fontSize:11,color:t.mutedTextColor,userSelect:"none"},children:[g.jsxs("span",{children:["Tool: ",g.jsx("strong",{style:{color:t.textColor,textTransform:"capitalize"},children:n})]}),g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Elements: ",g.jsx("strong",{style:{color:t.textColor},children:e})]}),o>0&&g.jsxs(g.Fragment,{children:[g.jsx("span",{style:{opacity:.4},children:"|"}),g.jsxs("span",{children:["Selected: ",g.jsx("strong",{style:{color:t.activeToolColor},children:o})]})]})]})}),ui={rectangle:0,ellipse:1,diamond:2,line:3,arrow:4,freedraw:5,text:6,image:7};class gi{constructor(e=1024){ct(this,"_data");ct(this,"_capacity",0);ct(this,"_indexMap",new Map);this._data=this._allocate(e),this._capacity=e}get length(){return this._data.length}get data(){return this._data}_allocate(e){return{ids:new Array(e),x:new Float64Array(e),y:new Float64Array(e),w:new Float64Array(e),h:new Float64Array(e),types:new Uint8Array(e),length:0}}_ensureCapacity(e){if(e<=this._capacity)return;const n=Math.max(e,this._capacity*2),o=this._data,s=this._allocate(n);s.x.set(o.x.subarray(0,o.length)),s.y.set(o.y.subarray(0,o.length)),s.w.set(o.w.subarray(0,o.length)),s.h.set(o.h.subarray(0,o.length)),s.types.set(o.types.subarray(0,o.length));for(let r=0;r<o.length;r++)s.ids[r]=o.ids[r];s.length=o.length,this._data=s,this._capacity=n}rebuild(e){const n=e.length;this._ensureCapacity(n),this._indexMap.clear();const{ids:o,x:s,y:r,w:i,h:l,types:a}=this._data;for(let c=0;c<n;c++){const d=e[c];o[c]=d.id,s[c]=d.x,r[c]=d.y,i[c]=d.width,l[c]=d.height,a[c]=ui[d.type]??0,this._indexMap.set(d.id,c)}this._data.length=n}updateElement(e){const n=this._indexMap.get(e.id);return n===void 0?!1:(this._data.x[n]=e.x,this._data.y[n]=e.y,this._data.w[n]=e.width,this._data.h[n]=e.height,!0)}cullViewport(e,n,o,s=200){const{x:r,y:i,scale:l}=e,a=-r/l-s,c=-i/l-s,d=(-r+n)/l+s,h=(-i+o)/l+s,{ids:u,x:f,y:p,w:y,h:m,length:W}=this._data,v=[];for(let D=0;D<W;D++){const $=f[D],T=p[D],O=y[D],ot=m[D];$+O>=a&&$<=d&&T+ot>=c&&T<=h&&v.push(u[D])}return v}queryRect(e,n,o,s){const{ids:r,x:i,y:l,w:a,h:c,length:d}=this._data,h=[];for(let u=0;u<d;u++){const f=i[u],p=l[u],y=a[u],m=c[u];f+y>=e&&f<=o&&p+m>=n&&p<=s&&h.push(r[u])}return h}queryPoint(e,n){const{ids:o,x:s,y:r,w:i,h:l,length:a}=this._data,c=[];for(let d=0;d<a;d++)e>=s[d]&&e<=s[d]+i[d]&&n>=r[d]&&n<=r[d]+l[d]&&c.push(o[d]);return c}clear(){this._data.length=0,this._indexMap.clear()}}let Qo=null;function Zd(){return Qo||(Qo=new gi),Qo}const Lt="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qo=Lt.length,Ke=Lt[0],_d=Lt[qo-1];function Md(t,e){const n=Lt.indexOf(t),o=Lt.indexOf(e);if(o-n<=1)return null;const s=Math.floor((n+o)/2);return Lt[s]}function ts(t,e){return t===null&&e===null?"a0":e===null?hi(t):t===null?Gd(e):Dd(t,e)}function es(t,e,n){if(n===0)return[];if(n===1)return[ts(t,e)];const o=Math.floor(n/2),s=ts(t,e),r=es(t,s,o),i=es(s,e,n-o-1);return[...r,s,...i]}function hi(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o<qo-1)return e[n]=Lt[o+1],e.join("");e[n]=Ke}return t+Lt[1]}function Gd(t){const e=t.split("");for(let n=e.length-1;n>=0;n--){const o=Lt.indexOf(e[n]);if(o>0){e[n]=Lt[o-1];let s=e.join("");for(;s.length>1&&s.endsWith(Ke);)s=s.slice(0,-1);return s}e[n]=_d}return Ke+t}function Dd(t,e){const n=Math.max(t.length,e.length),o=t.padEnd(n,Ke),s=e.padEnd(n,Ke);let r="";for(let i=0;i<n;i++){if(o[i]===s[i]){r+=o[i];continue}const l=Md(o[i],s[i]);return l!==null?r+l:r+o[i]+hi(o.slice(i+1).replace(/0+$/,"")||Ke)}return t+Lt[Math.floor(qo/2)]}function Xd(t){if(!t||t.length===0)return!1;for(const e of t)if(Lt.indexOf(e)===-1)return!1;return!0}function Ld(t,e){return t===e?0:t<e?-1:1}class Fd{constructor(e=1e4){ct(this,"_entries",[]);ct(this,"_maxEntries");this._maxEntries=e}push(e){this._entries.push(e),this._entries.length>this._maxEntries&&(this._entries=this._entries.slice(this._entries.length-this._maxEntries))}get entries(){return this._entries}entriesSince(e){return this._entries.filter(n=>n.timestamp>=e)}entriesByClient(e){return this._entries.filter(n=>n.clientId===e)}clear(){this._entries=[]}get length(){return this._entries.length}}function fi(t){return{type:"add",element:t}}function pi(t){return{type:"delete",elementId:t}}function yi(t,e,n){return{type:"move",elementId:t,dx:e,dy:n}}function Ii(t,e,n,o,s){return{type:"resize",elementId:t,width:e,height:n,x:o,y:s}}function Ci(t,e){return{type:"style",elementId:t,changes:e}}function bi(t,e){return{type:"rotate",elementId:t,rotation:e}}function mi(t,e){return{type:"reorder",elementId:t,sortOrder:e}}function Ai(t,e){return{type:"updatePoints",elementId:t,points:e}}function wi(t,e){return{type:"setText",elementId:t,text:e}}function Vd(...t){return{type:"batch",operations:t}}function xi(t,e){switch(e.type){case"add":return[...t,e.element];case"delete":return t.filter(n=>n.id!==e.elementId);case"move":return t.map(n=>n.id===e.elementId?{...n,x:n.x+e.dx,y:n.y+e.dy}:n);case"resize":return t.map(n=>n.id===e.elementId?{...n,width:e.width,height:e.height,...e.x!==void 0?{x:e.x}:{},...e.y!==void 0?{y:e.y}:{}}:n);case"style":return t.map(n=>n.id===e.elementId?{...n,style:{...n.style,...e.changes}}:n);case"rotate":return t.map(n=>n.id===e.elementId?{...n,rotation:e.rotation}:n);case"reorder":return t.map(n=>n.id===e.elementId?{...n,sortOrder:e.sortOrder}:n);case"updatePoints":return t.map(n=>n.id!==e.elementId?n:"points"in n?{...n,points:e.points}:n);case"setText":return t.map(n=>n.id!==e.elementId?n:n.type==="text"?{...n,text:e.text}:n);case"batch":{let n=t;for(const o of e.operations)n=xi(n,o);return n}default:return t}}function Pd(t,e){const n=[],o=new Map,s=new Map;for(const r of t)o.set(r.id,r);for(const r of e)s.set(r.id,r);for(const r of e)o.has(r.id)||n.push(fi(r));for(const r of t)s.has(r.id)||n.push(pi(r.id));for(const r of e){const i=o.get(r.id);if(!i||i===r)continue;(i.x!==r.x||i.y!==r.y)&&n.push(yi(r.id,r.x-i.x,r.y-i.y)),(i.width!==r.width||i.height!==r.height)&&n.push(Ii(r.id,r.width,r.height)),i.rotation!==r.rotation&&n.push(bi(r.id,r.rotation));const l={};let a=!1;for(const c of Object.keys(r.style))i.style[c]!==r.style[c]&&(l[c]=r.style[c],a=!0);if(a&&n.push(Ci(r.id,l)),r.type==="text"&&i.type==="text"&&r.text!==i.text&&n.push(wi(r.id,r.text)),(r.type==="line"||r.type==="arrow"||r.type==="freedraw")&&(i.type==="line"||i.type==="arrow"||i.type==="freedraw")){const c=r.points,d=i.points;(c.length!==d.length||c.some((h,u)=>h!==d[u]))&&n.push(Ai(r.id,c))}i.sortOrder!==r.sortOrder&&r.sortOrder!==void 0&&n.push(mi(r.id,r.sortOrder))}return n}class Yd{constructor(){ct(this,"_doc",null);ct(this,"_provider",null);ct(this,"_config",null);ct(this,"_isApplyingRemote",!1);ct(this,"_isApplyingLocal",!1);ct(this,"_lastElements",[]);ct(this,"_syncTimer",null);ct(this,"_deepTimer",null);ct(this,"_dirtyIds",new Set);ct(this,"_storeUnsub",null);ct(this,"_yObserverCleanup",null);ct(this,"_statusListeners",new Set)}get doc(){return this._doc}get provider(){return this._provider}get config(){return this._config}get isActive(){return this._provider!==null&&this._provider.wsconnected}connect(e){return this.dispose(),this._config=e,this._doc=new Kt.Doc,this._provider=new ks.WebsocketProvider(e.serverUrl,e.roomName,this._doc,{connect:!0,params:e.authToken?{token:e.authToken}:void 0}),this._provider.awareness.setLocalState({user:e.user,cursor:null,selectedIds:[]}),this._provider.on("status",n=>{const o=n.status;for(const s of this._statusListeners)s(o)}),{doc:this._doc,provider:this._provider}}getYElements(){var e;return(e=this._doc)==null?void 0:e.getMap("elements")}updateAwareness(e){if(!this._provider)return;const n=this._provider.awareness.getLocalState();this._provider.awareness.setLocalState({...n,...e})}getRemoteAwareness(){if(!this._provider)return new Map;const e=this._provider.awareness.getStates(),n=this._provider.awareness.clientID,o=new Map;for(const[s,r]of e)s!==n&&r&&r.user&&o.set(s,r);return o}onStatusChange(e){return this._statusListeners.add(e),()=>{this._statusListeners.delete(e)}}startSync(e,n=50){const o=this._doc,s=this.getYElements();if(!o||!s){console.warn("[CollaborationManager] Cannot start sync — not connected");return}if(this.stopSync(),s.size>0){this._isApplyingRemote=!0;const l=this._yMapCollectionToElements(s);e.setElements(l),this._lastElements=l,this._isApplyingRemote=!1}else{const l=e.getState().elements;l.length>0&&(this._isApplyingLocal=!0,o.transact(()=>{for(const a of l){const c=new Kt.Map;Cn(a,c),s.set(a.id,c)}},"local-init"),this._isApplyingLocal=!1),this._lastElements=l}const r=(l,a)=>{if(a.origin==="local-sync"||a.origin==="local-init"||this._isApplyingLocal)return;this._isApplyingRemote=!0;let c=[...this._lastElements],d=!1;for(const[h,u]of l.keys)if(u.action==="add"||u.action==="update"){const f=s.get(h);if(f){const p=Be(f);if(p){const y=c.findIndex(m=>m.id===h);y>=0?c[y]=p:c.push(p),d=!0}}}else u.action==="delete"&&(c=c.filter(f=>f.id!==h),d=!0);d&&(c.sort((h,u)=>h.sortOrder&&u.sortOrder?h.sortOrder<u.sortOrder?-1:h.sortOrder>u.sortOrder?1:0:0),e.setElements(c),this._lastElements=c),this._isApplyingRemote=!1},i=l=>{if(!this._isApplyingLocal){for(const a of l){let c=a.target;for(;c&&!(c instanceof Kt.Map&&c.parent===s);)c=c.parent;if(c instanceof Kt.Map){const d=c.get("id");d&&this._dirtyIds.add(d)}}this._deepTimer&&clearTimeout(this._deepTimer),this._deepTimer=setTimeout(()=>{if(this._dirtyIds.size===0||this._isApplyingLocal)return;this._isApplyingRemote=!0;let a=[...this._lastElements],c=!1;for(const d of this._dirtyIds){const h=s.get(d);if(!h)continue;const u=Be(h);if(!u)continue;const f=a.findIndex(p=>p.id===d);f>=0&&(a[f]=u,c=!0)}this._dirtyIds.clear(),c&&(e.setElements(a),this._lastElements=a),this._isApplyingRemote=!1},16)}};s.observe(r),s.observeDeep(i),this._yObserverCleanup=()=>{s.unobserve(r),s.unobserveDeep(i),this._deepTimer&&clearTimeout(this._deepTimer),this._dirtyIds.clear()},this._storeUnsub=e.subscribe(l=>{this._isApplyingRemote||l.elements!==this._lastElements&&(this._syncTimer&&clearTimeout(this._syncTimer),this._syncTimer=setTimeout(()=>{this._syncLocalToYjs(l.elements,s,o)},n))})}stopSync(){var e,n;(e=this._storeUnsub)==null||e.call(this),this._storeUnsub=null,(n=this._yObserverCleanup)==null||n.call(this),this._yObserverCleanup=null,this._syncTimer&&(clearTimeout(this._syncTimer),this._syncTimer=null),this._lastElements=[]}dispose(){this.stopSync(),this._provider&&(this._provider.awareness.setLocalState(null),this._provider.disconnect(),this._provider.destroy(),this._provider=null),this._doc&&(this._doc.destroy(),this._doc=null),this._config=null,this._statusListeners.clear()}_syncLocalToYjs(e,n,o){this._isApplyingLocal=!0,this._lastElements=e;const s=new Map;for(const r of e)s.set(r.id,r);o.transact(()=>{for(const[r]of n.entries())s.has(r)||n.delete(r);for(const r of e){let i=n.get(r.id);i?this._updateYMapFromElement(r,i):(i=new Kt.Map,Cn(r,i),n.set(r.id,i))}},"local-sync"),this._isApplyingLocal=!1}_updateYMapFromElement(e,n){const o=["id","type","x","y","width","height","rotation","isLocked","isVisible","sortOrder"],s=["strokeColor","fillColor","strokeWidth","opacity","strokeStyle","roughness","fontSize","fontFamily"],r=e;for(const l of o){const a=r[l];a!==n.get(l)&&n.set(l,a)}if(e.style)for(const l of s){const a=e.style[l];a!==n.get(`style.${l}`)&&n.set(`style.${l}`,a)}const i=e.boundElements?JSON.stringify(e.boundElements):null;switch(i!==n.get("boundElements")&&n.set("boundElements",i),e.type){case"rectangle":e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius);break;case"line":case"arrow":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a),e.lineType!==n.get("lineType")&&n.set("lineType",e.lineType),e.curvature!==n.get("curvature")&&n.set("curvature",e.curvature);const c=e.startBinding?JSON.stringify(e.startBinding):null;c!==n.get("startBinding")&&n.set("startBinding",c);const d=e.endBinding?JSON.stringify(e.endBinding):null;d!==n.get("endBinding")&&n.set("endBinding",d),e.type==="arrow"&&(e.startArrowhead!==n.get("startArrowhead")&&n.set("startArrowhead",e.startArrowhead),e.endArrowhead!==n.get("endArrowhead")&&n.set("endArrowhead",e.endArrowhead));break}case"freedraw":{const a=JSON.stringify(e.points);a!==n.get("points")&&n.set("points",a);break}case"text":e.text!==n.get("text")&&n.set("text",e.text),e.containerId!==n.get("containerId")&&n.set("containerId",e.containerId),e.textAlign!==n.get("textAlign")&&n.set("textAlign",e.textAlign),e.verticalAlign!==n.get("verticalAlign")&&n.set("verticalAlign",e.verticalAlign);break;case"image":e.src!==n.get("src")&&n.set("src",e.src),e.naturalWidth!==n.get("naturalWidth")&&n.set("naturalWidth",e.naturalWidth),e.naturalHeight!==n.get("naturalHeight")&&n.set("naturalHeight",e.naturalHeight),e.scaleMode!==n.get("scaleMode")&&n.set("scaleMode",e.scaleMode);const l=e.crop?JSON.stringify(e.crop):null;l!==n.get("crop")&&n.set("crop",l),e.cornerRadius!==n.get("cornerRadius")&&n.set("cornerRadius",e.cornerRadius),e.alt!==n.get("alt")&&n.set("alt",e.alt);break}}_yMapCollectionToElements(e){const n=[];for(const[,o]of e.entries()){const s=Be(o);s&&n.push(s)}return n.sort((o,s)=>o.sortOrder&&s.sortOrder?o.sortOrder<s.sortOrder?-1:o.sortOrder>s.sortOrder?1:0:0),n}}class Hd{constructor(e){ct(this,"_worker",null);ct(this,"_callbacks");this._callbacks=e}connect(e,n){if(this.dispose(),this._worker=Gn(()=>new URL("data:video/mp2t;base64,LyoqCiAqIGNvbGxhYm9yYXRpb24vc3luY1dvcmtlci53b3JrZXIudHMg4oCUIFdlYiBXb3JrZXIgaW1wbGVtZW50YXRpb24uCiAqCiAqIFJ1bnMgWWpzIGRvY3VtZW50ICsgV2ViU29ja2V0IHByb3ZpZGVyICsgc3luYyBsb2dpYyBlbnRpcmVseSBvZmYgdGhlCiAqIG1haW4gdGhyZWFkLiBDb21tdW5pY2F0ZXMgd2l0aCB0aGUgbWFpbiB0aHJlYWQgdmlhIHBvc3RNZXNzYWdlLgogKgogKiBUaGlzIGZpbGUgaXMgZGVzaWduZWQgdG8gYmUgaW1wb3J0ZWQgdmlhIFZpdGUncyBgbmV3IFdvcmtlcihuZXcgVVJMKC4uLikpYC4KICovCgovLyBJbXBvcnQgWWpzICh5anMgYW5kIHktd2Vic29ja2V0IGFyZSBwdXJlIEpTIOKAlCBubyBET00gZGVwZW5kZW5jeSkKaW1wb3J0ICogYXMgWSBmcm9tICd5anMnOwppbXBvcnQgeyBXZWJzb2NrZXRQcm92aWRlciB9IGZyb20gJ3ktd2Vic29ja2V0JzsKaW1wb3J0IHR5cGUgeyBXb3JrZXJJbk1lc3NhZ2UsIFdvcmtlck91dE1lc3NhZ2UgfSBmcm9tICcuL3N5bmNXb3JrZXInOwppbXBvcnQgdHlwZSB7IENhbnZhc0VsZW1lbnQgfSBmcm9tICdAL3R5cGVzJzsKaW1wb3J0IHR5cGUgeyBBd2FyZW5lc3NTdGF0ZSwgQ29sbGFib3JhdGlvbkNvbmZpZyB9IGZyb20gJy4vdHlwZXMnOwppbXBvcnQgeyBlbGVtZW50VG9ZTWFwLCB5TWFwVG9FbGVtZW50LCBTWU5DX0ZJRUxEUywgU1RZTEVfRklFTERTIH0gZnJvbSAnLi9zeW5jQnJpZGdlQ29kZWMnOwoKLy8g4pSA4pSA4pSAIFdvcmtlciBTdGF0ZSDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmxldCBfZG9jOiBZLkRvYyB8IG51bGwgPSBudWxsOwpsZXQgX3Byb3ZpZGVyOiBXZWJzb2NrZXRQcm92aWRlciB8IG51bGwgPSBudWxsOwpsZXQgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKbGV0IF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKbGV0IF9sYXN0RWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwpsZXQgX3N5bmNUaW1lcjogUmV0dXJuVHlwZTx0eXBlb2Ygc2V0VGltZW91dD4gfCBudWxsID0gbnVsbDsKbGV0IF9kZWVwVGltZXI6IFJldHVyblR5cGU8dHlwZW9mIHNldFRpbWVvdXQ+IHwgbnVsbCA9IG51bGw7CmNvbnN0IF9kaXJ0eUlkcyA9IG5ldyBTZXQ8c3RyaW5nPigpOwpsZXQgX3N5bmNEZWJvdW5jZU1zID0gNTA7CgovLyDilIDilIDilIAgUG9zdCBNZXNzYWdlIEhlbHBlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIHBvc3QobXNnOiBXb3JrZXJPdXRNZXNzYWdlKTogdm9pZCB7CiAgICBzZWxmLnBvc3RNZXNzYWdlKG1zZyk7Cn0KCi8vIOKUgOKUgOKUgCBZLk1hcCBDb2xsZWN0aW9uIEhlbHBlcnMg4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSA4pSACgpmdW5jdGlvbiB5TWFwQ29sbGVjdGlvblRvRWxlbWVudHMoeUVsZW1lbnRzOiBZLk1hcDxZLk1hcDx1bmtub3duPj4pOiBDYW52YXNFbGVtZW50W10gewogICAgY29uc3QgZWxlbWVudHM6IENhbnZhc0VsZW1lbnRbXSA9IFtdOwogICAgZm9yIChjb25zdCBbLCB5TWFwXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgY29uc3QgZWwgPSB5TWFwVG9FbGVtZW50KHlNYXApOwogICAgICAgIGlmIChlbCkgZWxlbWVudHMucHVzaChlbCk7CiAgICB9CiAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgaWYgKGEuc29ydE9yZGVyICYmIGIuc29ydE9yZGVyKSB7CiAgICAgICAgICAgIHJldHVybiBhLnNvcnRPcmRlciA8IGIuc29ydE9yZGVyID8gLTEgOiBhLnNvcnRPcmRlciA+IGIuc29ydE9yZGVyID8gMSA6IDA7CiAgICAgICAgfQogICAgICAgIHJldHVybiAwOwogICAgfSk7CiAgICByZXR1cm4gZWxlbWVudHM7Cn0KCmZ1bmN0aW9uIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbDogQ2FudmFzRWxlbWVudCwgeU1hcDogWS5NYXA8dW5rbm93bj4pOiB2b2lkIHsKICAgIGNvbnN0IGVsUmVjb3JkID0gZWwgYXMgdW5rbm93biBhcyBSZWNvcmQ8c3RyaW5nLCB1bmtub3duPjsKICAgIGZvciAoY29uc3QgZmllbGQgb2YgU1lOQ19GSUVMRFMpIHsKICAgICAgICBjb25zdCB2YWx1ZSA9IGVsUmVjb3JkW2ZpZWxkXTsKICAgICAgICBpZiAodmFsdWUgIT09IHlNYXAuZ2V0KGZpZWxkKSkgeU1hcC5zZXQoZmllbGQsIHZhbHVlKTsKICAgIH0KCiAgICBpZiAoZWwuc3R5bGUpIHsKICAgICAgICBmb3IgKGNvbnN0IHNmIG9mIFNUWUxFX0ZJRUxEUykgewogICAgICAgICAgICBjb25zdCB2YWwgPSBlbC5zdHlsZVtzZl07CiAgICAgICAgICAgIGlmICh2YWwgIT09IHlNYXAuZ2V0KGBzdHlsZS4ke3NmfWApKSB5TWFwLnNldChgc3R5bGUuJHtzZn1gLCB2YWwpOwogICAgICAgIH0KICAgIH0KCiAgICBjb25zdCBiZUpzb24gPSBlbC5ib3VuZEVsZW1lbnRzID8gSlNPTi5zdHJpbmdpZnkoZWwuYm91bmRFbGVtZW50cykgOiBudWxsOwogICAgaWYgKGJlSnNvbiAhPT0geU1hcC5nZXQoJ2JvdW5kRWxlbWVudHMnKSkgeU1hcC5zZXQoJ2JvdW5kRWxlbWVudHMnLCBiZUpzb24pOwoKICAgIHN3aXRjaCAoZWwudHlwZSkgewogICAgICAgIGNhc2UgJ3JlY3RhbmdsZSc6CiAgICAgICAgICAgIGlmIChlbC5jb3JuZXJSYWRpdXMgIT09IHlNYXAuZ2V0KCdjb3JuZXJSYWRpdXMnKSkgeU1hcC5zZXQoJ2Nvcm5lclJhZGl1cycsIGVsLmNvcm5lclJhZGl1cyk7CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIGNhc2UgJ2xpbmUnOgogICAgICAgIGNhc2UgJ2Fycm93JzogewogICAgICAgICAgICBjb25zdCBwdHNKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKHB0c0pzb24gIT09IHlNYXAuZ2V0KCdwb2ludHMnKSkgeU1hcC5zZXQoJ3BvaW50cycsIHB0c0pzb24pOwogICAgICAgICAgICBpZiAoZWwubGluZVR5cGUgIT09IHlNYXAuZ2V0KCdsaW5lVHlwZScpKSB5TWFwLnNldCgnbGluZVR5cGUnLCBlbC5saW5lVHlwZSk7CiAgICAgICAgICAgIGlmIChlbC5jdXJ2YXR1cmUgIT09IHlNYXAuZ2V0KCdjdXJ2YXR1cmUnKSkgeU1hcC5zZXQoJ2N1cnZhdHVyZScsIGVsLmN1cnZhdHVyZSk7CiAgICAgICAgICAgIGNvbnN0IHNiSnNvbiA9IGVsLnN0YXJ0QmluZGluZyA/IEpTT04uc3RyaW5naWZ5KGVsLnN0YXJ0QmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoc2JKc29uICE9PSB5TWFwLmdldCgnc3RhcnRCaW5kaW5nJykpIHlNYXAuc2V0KCdzdGFydEJpbmRpbmcnLCBzYkpzb24pOwogICAgICAgICAgICBjb25zdCBlYkpzb24gPSBlbC5lbmRCaW5kaW5nID8gSlNPTi5zdHJpbmdpZnkoZWwuZW5kQmluZGluZykgOiBudWxsOwogICAgICAgICAgICBpZiAoZWJKc29uICE9PSB5TWFwLmdldCgnZW5kQmluZGluZycpKSB5TWFwLnNldCgnZW5kQmluZGluZycsIGViSnNvbik7CiAgICAgICAgICAgIGlmIChlbC50eXBlID09PSAnYXJyb3cnKSB7CiAgICAgICAgICAgICAgICBpZiAoZWwuc3RhcnRBcnJvd2hlYWQgIT09IHlNYXAuZ2V0KCdzdGFydEFycm93aGVhZCcpKSB5TWFwLnNldCgnc3RhcnRBcnJvd2hlYWQnLCBlbC5zdGFydEFycm93aGVhZCk7CiAgICAgICAgICAgICAgICBpZiAoZWwuZW5kQXJyb3doZWFkICE9PSB5TWFwLmdldCgnZW5kQXJyb3doZWFkJykpIHlNYXAuc2V0KCdlbmRBcnJvd2hlYWQnLCBlbC5lbmRBcnJvd2hlYWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGJyZWFrOwogICAgICAgIH0KICAgICAgICBjYXNlICdmcmVlZHJhdyc6IHsKICAgICAgICAgICAgY29uc3QgZnBKc29uID0gSlNPTi5zdHJpbmdpZnkoZWwucG9pbnRzKTsKICAgICAgICAgICAgaWYgKGZwSnNvbiAhPT0geU1hcC5nZXQoJ3BvaW50cycpKSB5TWFwLnNldCgncG9pbnRzJywgZnBKc29uKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgICAgIGNhc2UgJ3RleHQnOgogICAgICAgICAgICBpZiAoZWwudGV4dCAhPT0geU1hcC5nZXQoJ3RleHQnKSkgeU1hcC5zZXQoJ3RleHQnLCBlbC50ZXh0KTsKICAgICAgICAgICAgaWYgKGVsLmNvbnRhaW5lcklkICE9PSB5TWFwLmdldCgnY29udGFpbmVySWQnKSkgeU1hcC5zZXQoJ2NvbnRhaW5lcklkJywgZWwuY29udGFpbmVySWQpOwogICAgICAgICAgICBpZiAoZWwudGV4dEFsaWduICE9PSB5TWFwLmdldCgndGV4dEFsaWduJykpIHlNYXAuc2V0KCd0ZXh0QWxpZ24nLCBlbC50ZXh0QWxpZ24pOwogICAgICAgICAgICBpZiAoZWwudmVydGljYWxBbGlnbiAhPT0geU1hcC5nZXQoJ3ZlcnRpY2FsQWxpZ24nKSkgeU1hcC5zZXQoJ3ZlcnRpY2FsQWxpZ24nLCBlbC52ZXJ0aWNhbEFsaWduKTsKICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgY2FzZSAnaW1hZ2UnOgogICAgICAgICAgICBpZiAoZWwuc3JjICE9PSB5TWFwLmdldCgnc3JjJykpIHlNYXAuc2V0KCdzcmMnLCBlbC5zcmMpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbFdpZHRoICE9PSB5TWFwLmdldCgnbmF0dXJhbFdpZHRoJykpIHlNYXAuc2V0KCduYXR1cmFsV2lkdGgnLCBlbC5uYXR1cmFsV2lkdGgpOwogICAgICAgICAgICBpZiAoZWwubmF0dXJhbEhlaWdodCAhPT0geU1hcC5nZXQoJ25hdHVyYWxIZWlnaHQnKSkgeU1hcC5zZXQoJ25hdHVyYWxIZWlnaHQnLCBlbC5uYXR1cmFsSGVpZ2h0KTsKICAgICAgICAgICAgaWYgKGVsLnNjYWxlTW9kZSAhPT0geU1hcC5nZXQoJ3NjYWxlTW9kZScpKSB5TWFwLnNldCgnc2NhbGVNb2RlJywgZWwuc2NhbGVNb2RlKTsKICAgICAgICAgICAgY29uc3QgY3JvcEpzb24gPSBlbC5jcm9wID8gSlNPTi5zdHJpbmdpZnkoZWwuY3JvcCkgOiBudWxsOwogICAgICAgICAgICBpZiAoY3JvcEpzb24gIT09IHlNYXAuZ2V0KCdjcm9wJykpIHlNYXAuc2V0KCdjcm9wJywgY3JvcEpzb24pOwogICAgICAgICAgICBpZiAoZWwuY29ybmVyUmFkaXVzICE9PSB5TWFwLmdldCgnY29ybmVyUmFkaXVzJykpIHlNYXAuc2V0KCdjb3JuZXJSYWRpdXMnLCBlbC5jb3JuZXJSYWRpdXMpOwogICAgICAgICAgICBpZiAoZWwuYWx0ICE9PSB5TWFwLmdldCgnYWx0JykpIHlNYXAuc2V0KCdhbHQnLCBlbC5hbHQpOwogICAgICAgICAgICBicmVhazsKICAgIH0KfQoKLy8g4pSA4pSA4pSAIENvbm5lY3QgLyBEaXNjb25uZWN0IOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gY29ubmVjdChjb25maWc6IENvbGxhYm9yYXRpb25Db25maWcsIHN5bmNEZWJvdW5jZU1zOiBudW1iZXIpOiB2b2lkIHsKICAgIGRpc2Nvbm5lY3QoKTsKCiAgICBfc3luY0RlYm91bmNlTXMgPSBzeW5jRGVib3VuY2VNczsKICAgIF9kb2MgPSBuZXcgWS5Eb2MoKTsKCiAgICBfcHJvdmlkZXIgPSBuZXcgV2Vic29ja2V0UHJvdmlkZXIoCiAgICAgICAgY29uZmlnLnNlcnZlclVybCwKICAgICAgICBjb25maWcucm9vbU5hbWUsCiAgICAgICAgX2RvYywKICAgICAgICB7CiAgICAgICAgICAgIGNvbm5lY3Q6IHRydWUsCiAgICAgICAgICAgIHBhcmFtczogY29uZmlnLmF1dGhUb2tlbiA/IHsgdG9rZW46IGNvbmZpZy5hdXRoVG9rZW4gfSA6IHVuZGVmaW5lZCwKICAgICAgICB9LAogICAgKTsKCiAgICAvLyBBd2FyZW5lc3MKICAgIF9wcm92aWRlci5hd2FyZW5lc3Muc2V0TG9jYWxTdGF0ZSh7CiAgICAgICAgdXNlcjogY29uZmlnLnVzZXIsCiAgICAgICAgY3Vyc29yOiBudWxsLAogICAgICAgIHNlbGVjdGVkSWRzOiBbXSwKICAgIH0gc2F0aXNmaWVzIEF3YXJlbmVzc1N0YXRlKTsKCiAgICAvLyBTdGF0dXMgZXZlbnRzCiAgICBfcHJvdmlkZXIub24oJ3N0YXR1cycsIChldmVudDogeyBzdGF0dXM6IHN0cmluZyB9KSA9PiB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdzdGF0dXMnLCBzdGF0dXM6IGV2ZW50LnN0YXR1cyBhcyBXb3JrZXJPdXRNZXNzYWdlIGV4dGVuZHMgeyB0eXBlOiAnc3RhdHVzJzsgc3RhdHVzOiBpbmZlciBTIH0gPyBTIDogbmV2ZXIgfSk7CiAgICB9KTsKCiAgICAvLyBBd2FyZW5lc3MgY2hhbmdlcyDihpIgcGVlcnMKICAgIF9wcm92aWRlci5hd2FyZW5lc3Mub24oJ2NoYW5nZScsICgpID0+IHsKICAgICAgICBpZiAoIV9wcm92aWRlcikgcmV0dXJuOwogICAgICAgIGNvbnN0IGFsbCA9IF9wcm92aWRlci5hd2FyZW5lc3MuZ2V0U3RhdGVzKCk7CiAgICAgICAgY29uc3QgbG9jYWxJZCA9IF9wcm92aWRlci5hd2FyZW5lc3MuY2xpZW50SUQ7CiAgICAgICAgY29uc3QgcGVlcnM6IEF3YXJlbmVzc1N0YXRlW10gPSBbXTsKICAgICAgICBmb3IgKGNvbnN0IFtjbGllbnRJZCwgc3RhdGVdIG9mIGFsbCkgewogICAgICAgICAgICBpZiAoY2xpZW50SWQgIT09IGxvY2FsSWQgJiYgc3RhdGUgJiYgKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKS51c2VyKSB7CiAgICAgICAgICAgICAgICBwZWVycy5wdXNoKHN0YXRlIGFzIEF3YXJlbmVzc1N0YXRlKTsKICAgICAgICAgICAgfQogICAgICAgIH0KICAgICAgICBwb3N0KHsgdHlwZTogJ3BlZXJzJywgcGVlcnMgfSk7CiAgICB9KTsKCiAgICAvLyBTdGFydCBzeW5jCiAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgLy8gSW5pdGlhbCBzeW5jOiBpZiBZanMgaGFzIGRhdGEsIHNlbmQgdG8gbWFpbiB0aHJlYWQKICAgIGlmICh5RWxlbWVudHMuc2l6ZSA+IDApIHsKICAgICAgICBjb25zdCBlbGVtZW50cyA9IHlNYXBDb2xsZWN0aW9uVG9FbGVtZW50cyh5RWxlbWVudHMpOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKICAgICAgICBwb3N0KHsgdHlwZTogJ3JlbW90ZS11cGRhdGUnLCBlbGVtZW50cyB9KTsKICAgIH0KCiAgICAvLyBZanMgb2JzZXJ2ZXJzIOKGkiBwb3N0IHJlbW90ZS11cGRhdGUKICAgIHlFbGVtZW50cy5vYnNlcnZlKChldmVudHMsIHRyYW5zYWN0aW9uKSA9PiB7CiAgICAgICAgaWYgKHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLXN5bmMnIHx8IHRyYW5zYWN0aW9uLm9yaWdpbiA9PT0gJ2xvY2FsLWluaXQnKSByZXR1cm47CiAgICAgICAgaWYgKF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSB0cnVlOwogICAgICAgIGxldCBlbGVtZW50cyA9IFsuLi5fbGFzdEVsZW1lbnRzXTsKICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICBmb3IgKGNvbnN0IFtrZXksIGNoYW5nZV0gb2YgZXZlbnRzLmtleXMpIHsKICAgICAgICAgICAgaWYgKGNoYW5nZS5hY3Rpb24gPT09ICdhZGQnIHx8IGNoYW5nZS5hY3Rpb24gPT09ICd1cGRhdGUnKSB7CiAgICAgICAgICAgICAgICBjb25zdCB5TWFwID0geUVsZW1lbnRzLmdldChrZXkpOwogICAgICAgICAgICAgICAgaWYgKHlNYXApIHsKICAgICAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgaWYgKGVsKSB7CiAgICAgICAgICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGtleSk7CiAgICAgICAgICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgZWxlbWVudHNbaWR4XSA9IGVsOwogICAgICAgICAgICAgICAgICAgICAgICBlbHNlIGVsZW1lbnRzLnB1c2goZWwpOwogICAgICAgICAgICAgICAgICAgICAgICBjaGFuZ2VkID0gdHJ1ZTsKICAgICAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0gZWxzZSBpZiAoY2hhbmdlLmFjdGlvbiA9PT0gJ2RlbGV0ZScpIHsKICAgICAgICAgICAgICAgIGVsZW1lbnRzID0gZWxlbWVudHMuZmlsdGVyKGUgPT4gZS5pZCAhPT0ga2V5KTsKICAgICAgICAgICAgICAgIGNoYW5nZWQgPSB0cnVlOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICBlbGVtZW50cy5zb3J0KChhLCBiKSA9PiB7CiAgICAgICAgICAgICAgICBpZiAoYS5zb3J0T3JkZXIgJiYgYi5zb3J0T3JkZXIpIHsKICAgICAgICAgICAgICAgICAgICByZXR1cm4gYS5zb3J0T3JkZXIgPCBiLnNvcnRPcmRlciA/IC0xIDogYS5zb3J0T3JkZXIgPiBiLnNvcnRPcmRlciA/IDEgOiAwOwogICAgICAgICAgICAgICAgfQogICAgICAgICAgICAgICAgcmV0dXJuIDA7CiAgICAgICAgICAgIH0pOwogICAgICAgICAgICBfbGFzdEVsZW1lbnRzID0gZWxlbWVudHM7CiAgICAgICAgICAgIHBvc3QoeyB0eXBlOiAncmVtb3RlLXVwZGF0ZScsIGVsZW1lbnRzIH0pOwogICAgICAgIH0KICAgICAgICBfaXNBcHBseWluZ1JlbW90ZSA9IGZhbHNlOwogICAgfSk7CgogICAgeUVsZW1lbnRzLm9ic2VydmVEZWVwKChldmVudHMpID0+IHsKICAgICAgICBpZiAoX2lzQXBwbHlpbmdMb2NhbCkgcmV0dXJuOwoKICAgICAgICBmb3IgKGNvbnN0IGV2ZW50IG9mIGV2ZW50cykgewogICAgICAgICAgICBsZXQgdGFyZ2V0OiBZLkFic3RyYWN0VHlwZTx1bmtub3duPiB8IG51bGwgPSBldmVudC50YXJnZXQ7CiAgICAgICAgICAgIHdoaWxlICh0YXJnZXQgJiYgISh0YXJnZXQgaW5zdGFuY2VvZiBZLk1hcCAmJiB0YXJnZXQucGFyZW50ID09PSB5RWxlbWVudHMpKSB7CiAgICAgICAgICAgICAgICB0YXJnZXQgPSB0YXJnZXQucGFyZW50IGFzIFkuQWJzdHJhY3RUeXBlPHVua25vd24+IHwgbnVsbDsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiAodGFyZ2V0IGluc3RhbmNlb2YgWS5NYXApIHsKICAgICAgICAgICAgICAgIGNvbnN0IGlkID0gdGFyZ2V0LmdldCgnaWQnKSBhcyBzdHJpbmc7CiAgICAgICAgICAgICAgICBpZiAoaWQpIF9kaXJ0eUlkcy5hZGQoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgfQoKICAgICAgICBpZiAoX2RlZXBUaW1lcikgY2xlYXJUaW1lb3V0KF9kZWVwVGltZXIpOwogICAgICAgIF9kZWVwVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICAgICAgaWYgKF9kaXJ0eUlkcy5zaXplID09PSAwIHx8IF9pc0FwcGx5aW5nTG9jYWwpIHJldHVybjsKCiAgICAgICAgICAgIF9pc0FwcGx5aW5nUmVtb3RlID0gdHJ1ZTsKICAgICAgICAgICAgbGV0IGVsZW1lbnRzID0gWy4uLl9sYXN0RWxlbWVudHNdOwogICAgICAgICAgICBsZXQgY2hhbmdlZCA9IGZhbHNlOwoKICAgICAgICAgICAgZm9yIChjb25zdCBpZCBvZiBfZGlydHlJZHMpIHsKICAgICAgICAgICAgICAgIGNvbnN0IHlNYXAgPSB5RWxlbWVudHMuZ2V0KGlkKTsKICAgICAgICAgICAgICAgIGlmICgheU1hcCkgY29udGludWU7CiAgICAgICAgICAgICAgICBjb25zdCBlbCA9IHlNYXBUb0VsZW1lbnQoeU1hcCk7CiAgICAgICAgICAgICAgICBpZiAoIWVsKSBjb250aW51ZTsKICAgICAgICAgICAgICAgIGNvbnN0IGlkeCA9IGVsZW1lbnRzLmZpbmRJbmRleChlID0+IGUuaWQgPT09IGlkKTsKICAgICAgICAgICAgICAgIGlmIChpZHggPj0gMCkgeyBlbGVtZW50c1tpZHhdID0gZWw7IGNoYW5nZWQgPSB0cnVlOyB9CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2RpcnR5SWRzLmNsZWFyKCk7CgogICAgICAgICAgICBpZiAoY2hhbmdlZCkgewogICAgICAgICAgICAgICAgX2xhc3RFbGVtZW50cyA9IGVsZW1lbnRzOwogICAgICAgICAgICAgICAgcG9zdCh7IHR5cGU6ICdyZW1vdGUtdXBkYXRlJywgZWxlbWVudHMgfSk7CiAgICAgICAgICAgIH0KICAgICAgICAgICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgICAgICB9LCAxNik7CiAgICB9KTsKfQoKZnVuY3Rpb24gZGlzY29ubmVjdCgpOiB2b2lkIHsKICAgIGlmIChfc3luY1RpbWVyKSB7IGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsgX3N5bmNUaW1lciA9IG51bGw7IH0KICAgIGlmIChfZGVlcFRpbWVyKSB7IGNsZWFyVGltZW91dChfZGVlcFRpbWVyKTsgX2RlZXBUaW1lciA9IG51bGw7IH0KICAgIF9kaXJ0eUlkcy5jbGVhcigpOwoKICAgIGlmIChfcHJvdmlkZXIpIHsKICAgICAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUobnVsbCk7CiAgICAgICAgX3Byb3ZpZGVyLmRpc2Nvbm5lY3QoKTsKICAgICAgICBfcHJvdmlkZXIuZGVzdHJveSgpOwogICAgICAgIF9wcm92aWRlciA9IG51bGw7CiAgICB9CiAgICBpZiAoX2RvYykgewogICAgICAgIF9kb2MuZGVzdHJveSgpOwogICAgICAgIF9kb2MgPSBudWxsOwogICAgfQogICAgX2xhc3RFbGVtZW50cyA9IFtdOwogICAgX2lzQXBwbHlpbmdSZW1vdGUgPSBmYWxzZTsKICAgIF9pc0FwcGx5aW5nTG9jYWwgPSBmYWxzZTsKCiAgICBwb3N0KHsgdHlwZTogJ3N0YXR1cycsIHN0YXR1czogJ2Rpc2Nvbm5lY3RlZCcgfSk7Cn0KCi8vIOKUgOKUgOKUgCBMb2NhbCBVcGRhdGUgSGFuZGxlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmZ1bmN0aW9uIGhhbmRsZUxvY2FsVXBkYXRlKGVsZW1lbnRzOiBDYW52YXNFbGVtZW50W10pOiB2b2lkIHsKICAgIGlmICghX2RvYyB8fCBfaXNBcHBseWluZ1JlbW90ZSkgcmV0dXJuOwogICAgaWYgKGVsZW1lbnRzID09PSBfbGFzdEVsZW1lbnRzKSByZXR1cm47CgogICAgaWYgKF9zeW5jVGltZXIpIGNsZWFyVGltZW91dChfc3luY1RpbWVyKTsKICAgIF9zeW5jVGltZXIgPSBzZXRUaW1lb3V0KCgpID0+IHsKICAgICAgICBpZiAoIV9kb2MpIHJldHVybjsKICAgICAgICBjb25zdCB5RWxlbWVudHMgPSBfZG9jLmdldE1hcCgnZWxlbWVudHMnKSBhcyBZLk1hcDxZLk1hcDx1bmtub3duPj47CgogICAgICAgIF9pc0FwcGx5aW5nTG9jYWwgPSB0cnVlOwogICAgICAgIF9sYXN0RWxlbWVudHMgPSBlbGVtZW50czsKCiAgICAgICAgY29uc3QgbG9jYWxNYXAgPSBuZXcgTWFwPHN0cmluZywgQ2FudmFzRWxlbWVudD4oKTsKICAgICAgICBmb3IgKGNvbnN0IGVsIG9mIGVsZW1lbnRzKSBsb2NhbE1hcC5zZXQoZWwuaWQsIGVsKTsKCiAgICAgICAgX2RvYy50cmFuc2FjdCgoKSA9PiB7CiAgICAgICAgICAgIGZvciAoY29uc3QgW2lkXSBvZiB5RWxlbWVudHMuZW50cmllcygpKSB7CiAgICAgICAgICAgICAgICBpZiAoIWxvY2FsTWFwLmhhcyhpZCkpIHlFbGVtZW50cy5kZWxldGUoaWQpOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGZvciAoY29uc3QgZWwgb2YgZWxlbWVudHMpIHsKICAgICAgICAgICAgICAgIGxldCB5TWFwID0geUVsZW1lbnRzLmdldChlbC5pZCk7CiAgICAgICAgICAgICAgICBpZiAoIXlNYXApIHsKICAgICAgICAgICAgICAgICAgICB5TWFwID0gbmV3IFkuTWFwPHVua25vd24+KCk7CiAgICAgICAgICAgICAgICAgICAgZWxlbWVudFRvWU1hcChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICAgICAgeUVsZW1lbnRzLnNldChlbC5pZCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9IGVsc2UgewogICAgICAgICAgICAgICAgICAgIHVwZGF0ZVlNYXBGcm9tRWxlbWVudChlbCwgeU1hcCk7CiAgICAgICAgICAgICAgICB9CiAgICAgICAgICAgIH0KICAgICAgICB9LCAnbG9jYWwtc3luYycpOwoKICAgICAgICBfaXNBcHBseWluZ0xvY2FsID0gZmFsc2U7CiAgICB9LCBfc3luY0RlYm91bmNlTXMpOwp9CgovLyDilIDilIDilIAgQXdhcmVuZXNzIFVwZGF0ZSBIYW5kbGVyIOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgAoKZnVuY3Rpb24gaGFuZGxlQXdhcmVuZXNzKG1zZzogRXh0cmFjdDxXb3JrZXJJbk1lc3NhZ2UsIHsgdHlwZTogJ2F3YXJlbmVzcycgfT4pOiB2b2lkIHsKICAgIGlmICghX3Byb3ZpZGVyKSByZXR1cm47CiAgICBjb25zdCBjdXJyZW50ID0gX3Byb3ZpZGVyLmF3YXJlbmVzcy5nZXRMb2NhbFN0YXRlKCkgYXMgQXdhcmVuZXNzU3RhdGUgfCBudWxsOwogICAgY29uc3QgdXBkYXRlOiBQYXJ0aWFsPEF3YXJlbmVzc1N0YXRlPiA9IHsgY3Vyc29yOiBtc2cuY3Vyc29yIH07CiAgICBpZiAobXNnLnNlbGVjdGVkSWRzKSB1cGRhdGUuc2VsZWN0ZWRJZHMgPSBtc2cuc2VsZWN0ZWRJZHM7CiAgICBpZiAobXNnLmFjdGl2ZVRvb2wpIHVwZGF0ZS5hY3RpdmVUb29sID0gbXNnLmFjdGl2ZVRvb2w7CiAgICBfcHJvdmlkZXIuYXdhcmVuZXNzLnNldExvY2FsU3RhdGUoeyAuLi5jdXJyZW50LCAuLi51cGRhdGUgfSk7Cn0KCi8vIOKUgOKUgOKUgCBNZXNzYWdlIFJvdXRlciDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCnNlbGYub25tZXNzYWdlID0gKGU6IE1lc3NhZ2VFdmVudDxXb3JrZXJJbk1lc3NhZ2U+KSA9PiB7CiAgICBjb25zdCBtc2cgPSBlLmRhdGE7CiAgICB0cnkgewogICAgICAgIHN3aXRjaCAobXNnLnR5cGUpIHsKICAgICAgICAgICAgY2FzZSAnY29ubmVjdCc6CiAgICAgICAgICAgICAgICBjb25uZWN0KG1zZy5jb25maWcsIG1zZy5zeW5jRGVib3VuY2VNcyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnZGlzY29ubmVjdCc6CiAgICAgICAgICAgICAgICBkaXNjb25uZWN0KCk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnbG9jYWwtdXBkYXRlJzoKICAgICAgICAgICAgICAgIGhhbmRsZUxvY2FsVXBkYXRlKG1zZy5lbGVtZW50cyk7CiAgICAgICAgICAgICAgICBicmVhazsKICAgICAgICAgICAgY2FzZSAnYXdhcmVuZXNzJzoKICAgICAgICAgICAgICAgIGhhbmRsZUF3YXJlbmVzcyhtc2cpOwogICAgICAgICAgICAgICAgYnJlYWs7CiAgICAgICAgfQogICAgfSBjYXRjaCAoZXJyKSB7CiAgICAgICAgcG9zdCh7IHR5cGU6ICdlcnJvcicsIG1lc3NhZ2U6IGVyciBpbnN0YW5jZW9mIEVycm9yID8gZXJyLm1lc3NhZ2UgOiBTdHJpbmcoZXJyKSB9KTsKICAgIH0KfTsK",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:qt&&qt.tagName.toUpperCase()==="SCRIPT"&&qt.src||new URL("f1ow.umd.cjs",document.baseURI).href)),!this._worker){console.warn("[SyncWorkerBridge] Worker creation failed, collaboration disabled"),this._callbacks.onStatus("disconnected");return}this._worker.onmessage=o=>{const s=o.data;switch(s.type){case"status":this._callbacks.onStatus(s.status);break;case"remote-update":this._callbacks.onRemoteUpdate(s.elements);break;case"peers":this._callbacks.onPeers(s.peers);break;case"error":this._callbacks.onError(s.message);break}},this._worker.onerror=o=>{this._callbacks.onError(`Worker error: ${o.message}`)},this._post({type:"connect",config:e,syncDebounceMs:n})}disconnect(){this._post({type:"disconnect"})}sendLocalUpdate(e){this._post({type:"local-update",elements:e})}sendAwareness(e){this._post({type:"awareness",cursor:e.cursor??null,selectedIds:e.selectedIds,activeTool:e.activeTool})}dispose(){this._worker&&(this._worker.terminate(),this._worker=null)}_post(e){var n;(n=this._worker)==null||n.postMessage(e)}}function ze(t){return`${t.zoom}:${t.col}:${t.row}`}class ki{constructor(e=200){ct(this,"_cache",new Map);ct(this,"_accessCounter",0);ct(this,"_maxTiles");this._maxTiles=e}get(e){const n=this._cache.get(ze(e));return n?(n.accessOrder=++this._accessCounter,n.bitmap):null}set(e,n,o=0){const s=ze(e),r=this._cache.get(s);r&&r.bitmap.close(),this._cache.set(s,{key:s,bitmap:n,accessOrder:++this._accessCounter,generation:o}),this._evict()}isFresh(e,n){const o=this._cache.get(ze(e));return o!=null&&o.generation>=n}invalidate(e){const n=ze(e),o=this._cache.get(n);o&&(o.bitmap.close(),this._cache.delete(n))}clear(){for(const e of this._cache.values())e.bitmap.close();this._cache.clear()}get size(){return this._cache.size}dispose(){this.clear()}_evict(){if(this._cache.size<=this._maxTiles)return;const e=Array.from(this._cache.values()).sort((o,s)=>o.accessOrder-s.accessOrder),n=e.length-this._maxTiles;for(let o=0;o<n;o++)e[o].bitmap.close(),this._cache.delete(e[o].key)}}const bn=256,jn=[.1,.15,.2,.25,.33,.5,.67,.75,1,1.25,1.5,2,2.5,3,4,5];function Si(t){let e=jn[0],n=Math.abs(t-e);for(let o=1;o<jn.length;o++){const s=Math.abs(t-jn[o]);s<n&&(e=jn[o],n=s)}return e}function Je(t){return bn/t}function vi(t,e,n,o=1){const s=Si(t.scale),r=Je(s),i=-t.x/t.scale,l=-t.y/t.scale,a=i+e/t.scale,c=l+n/t.scale,d=Math.floor(i/r)-o,h=Math.ceil(a/r)+o,u=Math.floor(l/r)-o,f=Math.ceil(c/r)+o,p=[];for(let y=d;y<=h;y++)for(let m=u;m<=f;m++)p.push({col:y,row:m,zoom:s});return{tiles:p,zoom:s}}function Ei(t){const e=Je(t.zoom);return{minX:t.col*e,minY:t.row*e,maxX:(t.col+1)*e,maxY:(t.row+1)*e}}function Od(t,e){return t.minX<=e.maxX&&t.maxX>=e.minX&&t.minY<=e.maxY&&t.maxY>=e.minY}function Nd(t,e){const n=cn(t),o=Je(e),s=[],r=Math.floor(n.minX/o),i=Math.floor(n.maxX/o),l=Math.floor(n.minY/o),a=Math.floor(n.maxY/o);for(let c=r;c<=i;c++)for(let d=l;d<=a;d++)s.push({col:c,row:d,zoom:e});return s}class Wi{constructor(e={}){ct(this,"_cache");ct(this,"_drawFn");ct(this,"_elementTiles",new Map);ct(this,"_generation",0);this._cache=new ki(e.maxCachedTiles??200),this._drawFn=e.drawFn??Ud}getTiles(e,n,o,s){const{tiles:r,zoom:i}=vi(e,n,o),l=[];for(const a of r){let c=this._cache.get(a);c||(c=this._rasterise(a,s),this._cache.set(a,c,this._generation));const d=Je(i);l.push({coord:a,bitmap:c,worldX:a.col*d,worldY:a.row*d,worldSize:d})}return l}invalidateElements(e){const n=new Set;for(const o of e){const s=this._elementTiles.get(o);if(s){for(const r of s)n.add(r);this._elementTiles.delete(o)}}for(const o of n){const[s,r,i]=o.split(":").map(Number);this._cache.invalidate({zoom:s,col:r,row:i})}}invalidateAll(){this._generation++,this._cache.clear(),this._elementTiles.clear()}dispose(){this._cache.dispose(),this._elementTiles.clear()}get cacheSize(){return this._cache.size}_rasterise(e,n){const o=Ei(e),s=Je(e.zoom),r=[];for(const c of n){const d=cn(c);if(Od(d,o)){r.push(c);const h=ze(e),u=this._elementTiles.get(c.id);u?u.includes(h)||u.push(h):this._elementTiles.set(c.id,[h])}}const i=new OffscreenCanvas(bn,bn),l=i.getContext("2d"),a=bn/s;return l.scale(a,a),l.translate(-o.minX,-o.minY),this._drawFn(l,r,o),i.transferToImageBitmap()}}function Ud(t,e,n){var o,s,r,i,l,a,c;for(const d of e){if(t.save(),d.rotation){const p=d.x+d.width/2,y=d.y+d.height/2;t.translate(p,y),t.rotate(d.rotation*Math.PI/180),t.translate(-p,-y)}t.globalAlpha=((o=d.style)==null?void 0:o.opacity)??1;const h=((s=d.style)==null?void 0:s.strokeColor)??"#000000",u=((r=d.style)==null?void 0:r.fillColor)??"transparent",f=((i=d.style)==null?void 0:i.strokeWidth)??2;switch(t.strokeStyle=h,t.fillStyle=u,t.lineWidth=f,d.type){case"rectangle":t.beginPath(),t.rect(d.x,d.y,d.width,d.height),u!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(d.x+d.width/2,d.y+d.height/2,d.width/2,d.height/2,0,0,Math.PI*2),u!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{const p=d.x+d.width/2,y=d.y+d.height/2;t.beginPath(),t.moveTo(p,d.y),t.lineTo(d.x+d.width,y),t.lineTo(p,d.y+d.height),t.lineTo(d.x,y),t.closePath(),u!=="transparent"&&t.fill(),t.stroke();break}case"line":case"arrow":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"freedraw":{const p=d.points;if(p.length>=4){t.beginPath(),t.moveTo(d.x+p[0],d.y+p[1]);for(let y=2;y<p.length;y+=2)t.lineTo(d.x+p[y],d.y+p[y+1]);t.stroke()}break}case"text":{const p=d;t.font=`${((l=p.style)==null?void 0:l.fontSize)??16}px ${((a=p.style)==null?void 0:a.fontFamily)??"sans-serif"}`,t.fillStyle=h,t.fillText(p.text,d.x,d.y+(((c=p.style)==null?void 0:c.fontSize)??16));break}case"image":t.strokeStyle="#ccc",t.setLineDash([4,4]),t.strokeRect(d.x,d.y,d.width,d.height);break}t.restore()}}function Kd(t,e,n,o,s={}){var p;const{enabled:r=!1,maxCachedTiles:i=200,drawFn:l,elementThreshold:a=500}=s,c=I.useRef(null);I.useEffect(()=>(c.current=new Wi({maxCachedTiles:i,drawFn:l}),()=>{var y;(y=c.current)==null||y.dispose(),c.current=null}),[i,l]);const d=r&&t.length>=a,h=I.useMemo(()=>!d||!c.current||n===0||o===0?[]:c.current.getTiles(e,n,o,t).map(m=>({key:`${m.coord.zoom}:${m.coord.col}:${m.coord.row}`,bitmap:m.bitmap,worldX:m.worldX,worldY:m.worldY,worldSize:m.worldSize})),[d,e.x,e.y,e.scale,n,o,t]),u=I.useCallback(y=>{var m;(m=c.current)==null||m.invalidateElements(y)},[]),f=I.useCallback(()=>{var y;(y=c.current)==null||y.invalidateAll()},[]);return{isActive:d,tiles:h,invalidateElements:u,invalidateAll:f,cacheSize:((p=c.current)==null?void 0:p.cacheSize)??0}}const Ht=4096,Qn=1024,qn=16,Ti=2;class zd{constructor(e=Ht,n=Ht){ct(this,"_shelves",[]);ct(this,"_atlasWidth");ct(this,"_atlasHeight");this._atlasWidth=e,this._atlasHeight=n}pack(e,n){const o=e+Ti,s=n+Ti;for(const l of this._shelves)if(l.height>=s&&l.x+o<=this._atlasWidth){const a={x:l.x,y:l.y};return l.x+=o,a}const r=this._shelves.length>0?this._shelves[this._shelves.length-1].y+this._shelves[this._shelves.length-1].height:0;if(r+s>this._atlasHeight)return null;const i={y:r,height:s,x:o};return this._shelves.push(i),{x:0,y:r}}reset(){this._shelves=[]}}class Bi{constructor(e){ct(this,"_entries",new Map);ct(this,"_packer");ct(this,"_canvas");ct(this,"_ctx");ct(this,"_drawFn");ct(this,"_dirty",!1);ct(this,"_generation",0);this._packer=new zd(Ht,Ht),this._canvas=new OffscreenCanvas(Ht,Ht),this._ctx=this._canvas.getContext("2d"),this._drawFn=e??$d}addOrUpdate(e,n){const o=this._entries.get(e.id);if(o&&o.generation>=n)return o.region;const{pw:s,ph:r}=Jd(e),i=this._packer.pack(s,r);if(!i)return null;this._ctx.save(),this._ctx.clearRect(i.x,i.y,s,r),this._ctx.translate(i.x,i.y);const l=s/Math.max(e.width,1),a=r/Math.max(e.height,1);this._ctx.scale(l,a),this._drawFn(this._ctx,e,e.width,e.height),this._ctx.restore();const c={atlasIndex:0,u:i.x/Ht,v:i.y/Ht,uWidth:s/Ht,vHeight:r/Ht,pixelWidth:s,pixelHeight:r};return this._entries.set(e.id,{elementId:e.id,region:c,generation:n}),this._dirty=!0,c}getRegion(e){var n;return((n=this._entries.get(e))==null?void 0:n.region)??null}remove(e){this._entries.delete(e)}rebuild(e){this._generation++,this._packer.reset(),this._entries.clear(),this._ctx.clearRect(0,0,Ht,Ht);for(const n of e)this.addOrUpdate(n,this._generation);this._dirty=!0}get isDirty(){return this._dirty}getCanvas(){return this._dirty=!1,this._canvas}get generation(){return this._generation}get size(){return this._entries.size}dispose(){this._entries.clear()}}function Jd(t){const e=Math.max(t.width,1)/Math.max(t.height,1);let n,o;return t.width>=t.height?(n=Math.min(Math.max(Math.ceil(t.width),qn),Qn),o=Math.min(Math.max(Math.ceil(n/e),qn),Qn)):(o=Math.min(Math.max(Math.ceil(t.height),qn),Qn),n=Math.min(Math.max(Math.ceil(o*e),qn),Qn)),{pw:n,ph:o}}function $d(t,e,n,o){var l,a,c,d,h,u,f;const s=((l=e.style)==null?void 0:l.strokeColor)??"#000000",r=((a=e.style)==null?void 0:a.fillColor)??"transparent",i=((c=e.style)==null?void 0:c.strokeWidth)??2;switch(t.strokeStyle=s,t.fillStyle=r,t.lineWidth=i,t.globalAlpha=((d=e.style)==null?void 0:d.opacity)??1,e.type){case"rectangle":t.beginPath(),t.rect(0,0,n,o),r!=="transparent"&&t.fill(),t.stroke();break;case"ellipse":t.beginPath(),t.ellipse(n/2,o/2,n/2,o/2,0,0,Math.PI*2),r!=="transparent"&&t.fill(),t.stroke();break;case"diamond":{t.beginPath(),t.moveTo(n/2,0),t.lineTo(n,o/2),t.lineTo(n/2,o),t.lineTo(0,o/2),t.closePath(),r!=="transparent"&&t.fill(),t.stroke();break}case"text":{const p=e;t.font=`${((h=p.style)==null?void 0:h.fontSize)??16}px ${((u=p.style)==null?void 0:u.fontFamily)??"sans-serif"}`,t.fillStyle=s,t.fillText(p.text,0,((f=p.style)==null?void 0:f.fontSize)??16);break}default:t.strokeStyle="#aaa",t.strokeRect(0,0,n,o);break}}const Rd=`#version 300 es
|
|
9
9
|
precision highp float;
|
|
10
10
|
|
|
11
11
|
// Shared unit-quad corners (0=bottom-left, 1=top-right)
|
|
@@ -49,7 +49,7 @@ void main() {
|
|
|
49
49
|
v_texCoord = a_texRect.xy + a_position * a_texRect.zw;
|
|
50
50
|
v_opacity = a_opacity;
|
|
51
51
|
}
|
|
52
|
-
`,
|
|
52
|
+
`,jd=`#version 300 es
|
|
53
53
|
precision mediump float;
|
|
54
54
|
|
|
55
55
|
in vec2 v_texCoord;
|
|
@@ -63,4 +63,4 @@ void main() {
|
|
|
63
63
|
vec4 texColor = texture(u_atlas, v_texCoord);
|
|
64
64
|
fragColor = texColor * v_opacity;
|
|
65
65
|
}
|
|
66
|
-
`;function 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 Zi(t,e,n){const o=t.createShader(e);if(!o)throw new Error("Failed to create shader");if(t.shaderSource(o,n),t.compileShader(o),!t.getShaderParameter(o,t.COMPILE_STATUS)){const s=t.getShaderInfoLog(o)??"Unknown error";throw t.deleteShader(o),new Error(`Shader compile error: ${s}`)}return o}function Qd(t,e,n){const o=t.createProgram();if(!o)throw new Error("Failed to create program");if(t.attachShader(o,e),t.attachShader(o,n),t.linkProgram(o),!t.getProgramParameter(o,t.LINK_STATUS)){const s=t.getProgramInfoLog(o)??"Unknown error";throw t.deleteProgram(o),new Error(`Program link error: ${s}`)}return o}function qd(t,e,n){const o=Zi(t,t.VERTEX_SHADER,e),s=Zi(t,t.FRAGMENT_SHADER,n),r=Qd(t,o,s);return t.deleteShader(o),t.deleteShader(s),r}function tu(t,e,n=t.STATIC_DRAW){const o=t.createBuffer();if(!o)throw new Error("Failed to create buffer");return t.bindBuffer(t.ARRAY_BUFFER,o),t.bufferData(t.ARRAY_BUFFER,e,n),o}function eu(t,e,n){const o=n??t.createTexture();if(!o)throw new Error("Failed to create texture");return t.bindTexture(t.TEXTURE_2D,o),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e),o}function _i(t,e,n,o,s){const r=2*n/o,i=-2*n/s,l=2*t/o-1,a=-2*e/s+1;return new Float32Array([r,0,0,0,i,0,l,a,1])}const ns=10;class Mi{constructor(e={}){ct(this,"_canvas",null);ct(this,"_gl",null);ct(this,"_program",null);ct(this,"_vao",null);ct(this,"_quadVBO",null);ct(this,"_instanceVBO",null);ct(this,"_atlasTexture",null);ct(this,"_atlas");ct(this,"_viewMatrixLoc",null);ct(this,"_atlasLoc",null);ct(this,"_instanceData",new Float32Array(0));ct(this,"_instanceCount",0);ct(this,"_elementThreshold");ct(this,"_generation",0);ct(this,"_staticIds",new Set);ct(this,"_isInitialised",!1);ct(this,"_width",0);ct(this,"_height",0);this._atlas=new Bi(e.rasterFn),this._elementThreshold=e.elementThreshold??1e3}init(e){if(this._isInitialised)return!0;const n=e.getContext("webgl2",{alpha:!0,premultipliedAlpha:!0,antialias:!0,desynchronized:!0});if(!n)return console.warn("[WebGLHybrid] WebGL2 not available"),!1;this._canvas=e,this._gl=n;try{this._program=qd(n,Rd,jd)}catch(d){return console.warn("[WebGLHybrid] Shader compilation failed:",d),!1}this._viewMatrixLoc=n.getUniformLocation(this._program,"u_viewMatrix"),this._atlasLoc=n.getUniformLocation(this._program,"u_atlas"),this._vao=n.createVertexArray(),n.bindVertexArray(this._vao);const o=new Float32Array([0,0,1,0,0,1,0,1,1,0,1,1]);this._quadVBO=tu(n,o,n.STATIC_DRAW);const s=n.getAttribLocation(this._program,"a_position");n.bindBuffer(n.ARRAY_BUFFER,this._quadVBO),n.enableVertexAttribArray(s),n.vertexAttribPointer(s,2,n.FLOAT,!1,0,0),this._instanceVBO=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,this._instanceVBO),n.bufferData(n.ARRAY_BUFFER,0,n.DYNAMIC_DRAW);const r=ns*4,i=n.getAttribLocation(this._program,"a_worldRect"),l=n.getAttribLocation(this._program,"a_texRect"),a=n.getAttribLocation(this._program,"a_opacity"),c=n.getAttribLocation(this._program,"a_rotation");return i>=0&&(n.enableVertexAttribArray(i),n.vertexAttribPointer(i,4,n.FLOAT,!1,r,0),n.vertexAttribDivisor(i,1)),l>=0&&(n.enableVertexAttribArray(l),n.vertexAttribPointer(l,4,n.FLOAT,!1,r,16),n.vertexAttribDivisor(l,1)),a>=0&&(n.enableVertexAttribArray(a),n.vertexAttribPointer(a,1,n.FLOAT,!1,r,32),n.vertexAttribDivisor(a,1)),c>=0&&(n.enableVertexAttribArray(c),n.vertexAttribPointer(c,1,n.FLOAT,!1,r,36),n.vertexAttribDivisor(c,1)),n.bindVertexArray(null),n.enable(n.BLEND),n.blendFunc(n.ONE,n.ONE_MINUS_SRC_ALPHA),this._isInitialised=!0,!0}render(e,n,o){if(!this._isInitialised||!this._gl||!this._canvas||e.length<this._elementThreshold)return;const s=this._gl;(this._canvas.width!==this._width||this._canvas.height!==this._height)&&(this._canvas.width=this._width,this._canvas.height=this._height),s.viewport(0,0,this._width,this._height),s.clearColor(0,0,0,0),s.clear(s.COLOR_BUFFER_BIT);const r=[];for(const l of e)n.has(l.id)||r.push(l);if(r.length===0)return;this._generation++;for(const l of r)this._atlas.addOrUpdate(l,this._generation);this._atlas.isDirty&&(this._atlasTexture=eu(s,this._atlas.getCanvas(),this._atlasTexture)),this._buildInstanceData(r),s.bindBuffer(s.ARRAY_BUFFER,this._instanceVBO),s.bufferData(s.ARRAY_BUFFER,this._instanceData,s.DYNAMIC_DRAW),s.useProgram(this._program);const i=_i(o.x,o.y,o.scale,this._width,this._height);s.uniformMatrix3fv(this._viewMatrixLoc,!1,i),s.activeTexture(s.TEXTURE0),s.bindTexture(s.TEXTURE_2D,this._atlasTexture),s.uniform1i(this._atlasLoc,0),s.bindVertexArray(this._vao),s.drawArraysInstanced(s.TRIANGLES,0,6,this._instanceCount),s.bindVertexArray(null)}setSize(e,n){this._width=e,this._height=n}get isActive(){return this._isInitialised}get instanceCount(){return this._instanceCount}get elementThreshold(){return this._elementThreshold}invalidateElements(e){for(const n of e)this._atlas.remove(n)}invalidateAll(){this._atlas.rebuild([])}dispose(){const e=this._gl;e&&(this._program&&e.deleteProgram(this._program),this._vao&&e.deleteVertexArray(this._vao),this._quadVBO&&e.deleteBuffer(this._quadVBO),this._instanceVBO&&e.deleteBuffer(this._instanceVBO),this._atlasTexture&&e.deleteTexture(this._atlasTexture)),this._atlas.dispose(),this._isInitialised=!1,this._gl=null,this._canvas=null}_buildInstanceData(e){var i;const o=e.length*ns;this._instanceData.length<o&&(this._instanceData=new Float32Array(o));let s=0,r=0;for(const l of e){const a=this._atlas.getRegion(l.id);a&&(this._instanceData[s+0]=l.x,this._instanceData[s+1]=l.y,this._instanceData[s+2]=l.width,this._instanceData[s+3]=l.height,this._instanceData[s+4]=a.u,this._instanceData[s+5]=a.v,this._instanceData[s+6]=a.uWidth,this._instanceData[s+7]=a.vHeight,this._instanceData[s+8]=((i=l.style)==null?void 0:i.opacity)??1,this._instanceData[s+9]=(l.rotation??0)*Math.PI/180,s+=ns,r++)}this._instanceCount=r}}function nu(t,e,n,o,s={}){const{enabled:r=!1,rasterFn:i,elementThreshold:l}=s,a=I.useRef(null),c=I.useRef(null),d=I.useRef(!1);I.useEffect(()=>{var p;if(!r){(p=a.current)==null||p.dispose(),a.current=null,d.current=!1;return}return a.current=new Mi({rasterFn:i,elementThreshold:l}),()=>{var y;(y=a.current)==null||y.dispose(),a.current=null,d.current=!1}},[r,i,l]);const h=I.useCallback(p=>{c.current=p,p&&a.current&&(d.current=a.current.init(p))},[]);I.useEffect(()=>{var p;(p=a.current)==null||p.setSize(o.width,o.height)},[o.width,o.height]),I.useEffect(()=>{!a.current||!d.current||a.current.render(t,e,n)});const u=I.useCallback(p=>{var y;(y=a.current)==null||y.invalidateElements(p)},[]),f=I.useCallback(()=>{var p;(p=a.current)==null||p.invalidateAll()},[]);return I.useMemo(()=>{var p;return{webglCanvasRef:h,isActive:d.current,invalidateElements:u,invalidateAll:f,instanceCount:((p=a.current)==null?void 0:p.instanceCount)??0}},[h,u,f])}x.ARROWHEAD_TYPES=ao,x.CURVE_RATIO=zt,x.CollaborationManager=Yd,x.CursorOverlay=li,x.DEFAULT_ANIMATION_DURATION=js,x.DEFAULT_STYLE=wn,x.DEFAULT_THEME=zr,x.ELEMENT_TYPE_MAP=ui,x.ExportWorkerManager=Ur,x.FILL_COLORS=en,x.FlowCanvas=di,x.LINE_TYPES=uo,x.OperationLog=Fd,x.ROUGHNESS_CONFIGS=Ss,x.STROKE_COLORS=tn,x.STROKE_WIDTHS=el,x.STYLE_FIELDS=zn,x.SYNC_FIELDS=Ro,x.SpatialIndex=Uo,x.SpatialSoA=gi,x.SyncWorkerAdapter=Hd,x.TILE_SIZE=bn,x.TOOLS=co,x.TextureAtlas=Bi,x.TileCache=ki,x.TileRenderer=Wi,x.WebGLHybridRenderer=Mi,x.WorkerConfigContext=Xo,x.ZOOM_STEPS=an,x.aabbOverlaps=zs,x.addBoundElement=Os,x.animateViewport=Ee,x.applyOperation=xi,x.arrowheadSize=Lo,x.batchElementUpdates=Dl,x.buildElementMap=Ml,x.buildViewMatrix=_i,x.cancelViewportAnimation=We,x.clearElbowRouteCache=kl,x.clipboardHasImage=Ac,x.cloneElementsForHistory=Gl,x.compareFractionalKeys=Ld,x.computeCurveControlPoint=Jt,x.computeEfficientZoom=Yr,x.computeElbowPoints=on,x.computeElbowRoute=Ds,x.computeFixedPoint=Ys,x.computeImageElementDimensions=mr,x.computeZoomToFit=bo,x.createCollaborationProvider=Jr,x.createImageElement=_n,x.createWorker=Gn,x.cullToViewport=Js,x.curveArrowPrev=xo,x.destroyCollaborationProvider=Un,x.detectOperations=Pd,x.directionFromEdgePoint=il,x.directionFromFixedPoint=go,x.directionFromPoints=nn,x.directionFromShapeToPoint=ho,x.discreteZoom=Si,x.disposeElbowWorkerManager=Tr,x.disposeExportWorkerManager=Kr,x.distance=Fl,x.downloadJSON=Ka,x.downloadPNG=Ua,x.downloadSVG=rd,x.drawArrowhead=oe,x.elementToSpatialItem=No,x.elementToYMap=Cn,x.exportToDataURL=Fr,x.exportToJSON=Vr,x.exportToSVG=Ne,x.extractImageDataFromClipboard=_o,x.fileToDataURL=Zn,x.findConnectorsForElement=ln,x.findNearestSnapTarget=ke,x.flatToPoints=Dn,x.generateId=Pt,x.generateKeyBetween=ts,x.generateNKeysBetween=es,x.getAnchorPosition=vl,x.getConnectionPoints=Vs,x.getDiamondPoints=un,x.getEdgePoint=de,x.getEdgePointFromFixedPoint=ae,x.getElbowPreferredDirection=Sn,x.getElbowWorkerManager=Do,x.getElementAABB=cn,x.getElementTiles=Nd,x.getElementsBounds=Co,x.getExportWorkerManager=Cd,x.getImageFilesFromDataTransfer=Zo,x.getNextZoomStep=Qs,x.getPrevZoomStep=qs,x.getRemoteAwareness=Qr,x.getSharedSpatialIndex=dd,x.getSharedSpatialSoA=Zd,x.getStrokeDash=_t,x.getToolHandler=fn,x.getVisibleBounds=Ks,x.getVisibleTiles=vi,x.getYDoc=$r,x.getYElements=Rr,x.getYProvider=$o,x.isCollaborationActive=bd,x.isConnectable=Io,x.isPointInRect=Vl,x.isValidFractionalIndex=Xd,x.isWorkerSupported=Vc,x.loadImage=hn,x.normalizeRect=Ao,x.onStatusChange=jr,x.opAdd=fi,x.opBatch=Vd,x.opDelete=pi,x.opMove=yi,x.opReorder=mi,x.opResize=Ii,x.opRotate=bi,x.opSetText=wi,x.opStyle=Ci,x.opUpdatePoints=Ai,x.openImageFilePicker=wr,x.quadBezierAt=Ye,x.quadBezierTangent=wo,x.rafThrottle=$s,x.recomputeBoundPoints=Se,x.removeBoundElement=Ns,x.resolveImageSource=Ar,x.rotatePoint=tr,x.scheduleIdleWork=Nr,x.simplifyElbowPath=sn,x.startSync=qr,x.stopSync=Rn,x.syncBoundElements=ve,x.tileBounds=Ei,x.tileKey=ze,x.updateAwareness=Kn,x.useCanvasStore=B,x.useCollaboration=ti,x.useEfficientZoom=Hr,x.useProgressiveRender=Or,x.useTileRenderer=Kd,x.useWebGLHybrid=nu,x.useWorkerConfig=Br,x.worldTileSize=Je,x.yMapToElement=Be,x.yieldToMain=pd,x.zoomAtPoint=Wn,Object.defineProperty(x,Symbol.toStringTag,{value:"Module"})}));
|